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: mobile responsive redesign and clear failed runs

Adam Eivya9b5e96fd419
diff --git a/PLAN.md b/PLAN.md
index 369e58a9de..d52b7aa3c6 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -45,6 +45,8 @@ pm2 logs
- [~] M16: Memory System (semantic memory, LM Studio embeddings, auto-extraction, agent context injection)
- [x] M17: PM2 Ecosystem Config Enhancement (per-process port detection, CDP_PORT support, refresh button)
- [x] M18: PM2 Standardization (LLM-powered config refactoring, import integration, button trigger)
+- [x] M19: CoS Agent Runner (isolated PM2 process for agent spawning, prevents orphaned processes)
+- [x] M20: AI Provider Error Handling (error extraction, categorization, CoS investigation tasks)
### Documentation
- [Contributing Guide](./docs/CONTRIBUTING.md) - Code guidelines, git workflow
@@ -420,6 +422,17 @@ Autonomous agent manager that watches task files, spawns sub-agents, and maintai
| autoStart | false | Start on server boot |
| selfImprovementEnabled | true | Allow self-analysis |
+### Model Selection Rules
+The `selectModelForTask` function in `subAgentSpawner.js` routes tasks to appropriate model tiers:
+
+| Tier | Trigger | Example Tasks |
+|------|---------|---------------|
+| **heavy** | Critical priority, visual analysis, complex reasoning | Architect, refactor, security audit, long context |
+| **medium** | Standard development tasks, default | Most coding tasks, bug fixes, feature implementation |
+| **light** | Documentation-only tasks | Update README, write docs, format text |
+
+**Important**: Light model (haiku) is NEVER used for coding tasks. Tasks containing keywords like `fix`, `bug`, `implement`, `test`, `feature`, `api`, `component`, etc. are automatically routed to medium tier or higher.
+
---
## M15: Graceful Error Handling
@@ -700,3 +713,163 @@ LLM-powered refactoring to standardize app configurations to follow PM2 best pra
| `server/services/socket.js` | Socket event handlers |
| `client/src/pages/Apps.jsx` | Standardize PM2 button |
| `client/src/services/api.js` | API functions |
+
+---
+
+## M19: CoS Agent Runner
+
+Isolated PM2 process for spawning Claude CLI agents, preventing orphaned processes when portos-server restarts.
+
+### Problem
+When multiple CoS agents are running and the main portos-server restarts (due to code changes, crashes, or manual restart), child processes spawned via `child_process.spawn()` become orphaned. The parent loses track of them because the `activeAgents` Map is in memory.
+
+### Solution
+A separate `portos-cos` PM2 process that:
+1. Runs independently from `portos-server`
+2. Manages agent spawning via HTTP/Socket.IO bridge
+3. Doesn't restart when `portos-server` restarts
+4. Maintains its own state file for PID tracking
+
+### Architecture
+```
+┌─────────────────┐ HTTP/Socket.IO ┌─────────────────┐
+│ portos-server │ ──────────────────► │ portos-cos │
+│ (5554) │ spawn/terminate │ (5558) │
+│ │ ◄────────────────── │ │
+│ subAgentSpawner│ events/output │ cos-runner │
+└─────────────────┘ └────────┬────────┘
+ │
+ │ spawn
+ ▼
+ ┌───────────────┐
+ │ Claude CLI │
+ │ Processes │
+ └───────────────┘
+```
+
+### Features
+1. **Isolated Process**: portos-cos runs as separate PM2 app, unaffected by portos-server restarts
+2. **Fallback Mode**: If portos-cos is unavailable, falls back to direct spawning
+3. **Event Bridge**: Socket.IO connection forwards agent output/completion events
+4. **PID Tracking**: Runner maintains state file with active PIDs for orphan cleanup
+5. **Graceful Shutdown**: 30-second kill timeout to allow agents to complete
+
+### Configuration
+| Setting | Value | Description |
+|---------|-------|-------------|
+| Port | 5558 | HTTP/Socket.IO API port |
+| kill_timeout | 30s | Grace period for agent shutdown |
+| max_restarts | 5 | Limit restarts to prevent loops |
+| min_uptime | 30s | Minimum runtime before healthy |
+
+### API Endpoints (portos-cos)
+| Route | Description |
+|-------|-------------|
+| GET /health | Health check with active agent count |
+| GET /agents | List active agents |
+| POST /spawn | Spawn a new agent |
+| POST /terminate/:agentId | Terminate specific agent |
+| POST /terminate-all | Terminate all agents |
+| GET /agents/:agentId/output | Get agent output buffer |
+
+### Socket.IO Events
+| Event | Direction | Payload |
+|-------|-----------|---------|
+| agent:output | Runner → Server | agentId, text |
+| agent:completed | Runner → Server | agentId, taskId, exitCode, success, duration |
+| agent:error | Runner → Server | agentId, error |
+
+### Implementation Files
+| File | Purpose |
+|------|---------|
+| `server/cos-runner/index.js` | Standalone Express server for agent management |
+| `server/services/cosRunnerClient.js` | Client library for portos-server to communicate with runner |
+| `server/services/subAgentSpawner.js` | Updated to use runner when available |
+| `ecosystem.config.cjs` | Added portos-cos PM2 configuration |
+
+### Data Storage
+```
+./data/cos/
+├── runner-state.json # Active agent PIDs and stats
+└── agents/{agentId}/ # Agent prompts and outputs (shared)
+```
+
+---
+
+## M20: AI Provider Error Handling
+
+Enhanced error extraction and display for AI provider execution failures, with automatic CoS investigation task creation.
+
+### Problem
+When AI provider executions fail (e.g., invalid model, API errors), the devtools/runner UI only showed exit codes without meaningful error information, making debugging difficult.
+
+### Solution
+1. **Error Extraction**: Extract meaningful error details from CLI output
+2. **Error Categorization**: Classify errors by type (model_not_found, auth_error, rate_limit, etc.)
+3. **Suggested Fixes**: Provide actionable suggestions for each error category
+4. **CoS Integration**: Create investigation tasks for actionable failures
+5. **UI Enhancement**: Display error details, category, and suggestions in history list
+
+### Error Categories
+| Category | Description | Actionable |
+|----------|-------------|------------|
+| model_not_found | Model doesn't exist in provider | Yes |
+| auth_error | API key invalid or unauthorized | Yes |
+| api_error | Generic API request failure | Yes |
+| rate_limit | Rate limiting triggered | No (transient) |
+| quota_exceeded | Billing/quota issue | Yes |
+| network_error | Connection refused/timeout | No (transient) |
+| timeout | Process timeout (SIGTERM) | No |
+| command_not_found | CLI tool not installed | Yes |
+| permission_denied | File/directory access denied | Yes |
+| unknown | Unrecognized error pattern | No |
+
+### Error Data Flow
+1. **Extraction** (`runner.js::extractErrorDetails`): Parse CLI output for error messages
+2. **Categorization** (`runner.js::categorizeError`): Match against known patterns
+3. **Emission** (`runner.js::emitProviderError`): Emit to errorEvents EventEmitter
+4. **Auto-fix** (`autoFixer.js::handleAIProviderError`): Create CoS investigation task
+5. **Display** (`DevTools.jsx`): Show in history with error details, category, and fix suggestion
+
+### Metadata Schema Enhancement
+Failed runs now include additional fields:
+```javascript
+{
+ // Existing fields
+ exitCode: number,
+ success: boolean,
+ error: string, // Primary error message
+
+ // New fields
+ errorDetails: string, // Additional error context
+ errorCategory: string, // e.g., 'model_not_found'
+ suggestedFix: string // Actionable suggestion
+}
+```
+
+### CoS Investigation Tasks
+When actionable errors occur, a CoS task is created:
+```markdown
+## Pending
+- [ ] #task-XXX | HIGH | APPROVAL | [Auto] Investigate agent failure: Model not found
+ - Context: # AI Provider Execution Failure
+ - Provider: Claude Code CLI
+ - Model: codex
+ - Error: model: codex
+ - Suggested Fix: Update model configuration
+```
+
+### Implementation Files
+| File | Changes |
+|------|---------|
+| `server/services/runner.js` | Added `extractErrorDetails`, `categorizeError`, `emitProviderError` |
+| `server/services/autoFixer.js` | Added `handleAIProviderError`, `buildAIProviderErrorContext` |
+| `server/services/subAgentSpawner.js` | Added `analyzeAgentFailure`, `createInvestigationTask` |
+| `client/src/pages/DevTools.jsx` | Display `errorCategory`, `errorDetails`, `suggestedFix` |
+
+### UI Display
+In the DevTools history, failed runs now show:
+- **Error Category Badge**: Colored tag showing the error type
+- **Error Message**: Extracted error details
+- **Suggested Fix Panel**: Yellow-bordered box with actionable advice
+- **Additional Details**: Expandable section with raw error context
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 7f1d0d2b1a..ec72053276 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -304,18 +304,18 @@ export default function Layout() {
{/* Main area */}
<div className={`flex-1 flex flex-col min-w-0 transition-all duration-300 ${collapsed ? 'lg:ml-16' : 'lg:ml-56'}`}>
{/* Mobile header */}
- <header className="lg:hidden flex items-center justify-between p-4 border-b border-port-border bg-port-card">
+ <header className="lg:hidden flex items-center justify-between px-3 py-2 border-b border-port-border bg-port-card">
<button
onClick={() => setMobileOpen(true)}
- className="p-2 -ml-2 text-gray-400 hover:text-white"
+ className="p-1.5 -ml-1 text-gray-400 hover:text-white"
>
- <Menu size={24} />
+ <Menu size={20} />
</button>
- <div className="flex items-center gap-2">
- <Logo size={24} className="text-port-accent" />
- <span className="font-bold text-port-accent">PortOS</span>
+ <div className="flex items-center gap-1.5">
+ <Logo size={18} className="text-port-accent" />
+ <span className="font-bold text-sm text-port-accent">PortOS</span>
</div>
- <div className="w-10" /> {/* Spacer for centering */}
+ <div className="w-8" /> {/* Spacer for centering */}
</header>
{/* Main content */}
diff --git a/client/src/components/cos/CoSCharacter.jsx b/client/src/components/cos/CoSCharacter.jsx
index 109af01cc7..7d6e8a52a0 100644
--- a/client/src/components/cos/CoSCharacter.jsx
+++ b/client/src/components/cos/CoSCharacter.jsx
@@ -4,7 +4,7 @@ export default function CoSCharacter({ state, speaking }) {
const stateConfig = AGENT_STATES[state] || AGENT_STATES.sleeping;
return (
- <div className="relative w-44 h-56 md:w-56 md:h-72">
+ <div className="relative w-16 h-20 sm:w-28 sm:h-36 md:w-44 md:h-56 lg:w-56 lg:h-72">
<svg viewBox="0 0 200 240" className="cos-character w-full h-auto">
<defs>
<linearGradient id="bodyGrad" x1="0%" y1="0%" x2="100%" y2="100%">
diff --git a/client/src/components/cos/StatCard.jsx b/client/src/components/cos/StatCard.jsx
index bed0fc81c5..77368bb434 100644
--- a/client/src/components/cos/StatCard.jsx
+++ b/client/src/components/cos/StatCard.jsx
@@ -1,17 +1,49 @@
-export default function StatCard({ label, value, icon, active, activeLabel }) {
+export default function StatCard({ label, value, icon, active, activeLabel, compact, mini }) {
+ if (compact) {
+ return (
+ <div className={`bg-port-card/80 border rounded-lg px-3 py-2 flex items-center gap-3 ${
+ active ? 'border-port-accent shadow-md shadow-port-accent/20' : 'border-port-border'
+ }`}>
+ <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`}>
+ {icon}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="text-xs text-gray-500 truncate">{label}</div>
+ <div className="text-base font-bold text-white">{value}</div>
+ </div>
+ </div>
+ );
+ }
+
+ if (mini) {
+ return (
+ <div className={`bg-port-card border rounded p-1.5 sm:p-2 lg:p-3 transition-all ${
+ active ? 'border-port-accent shadow-md shadow-port-accent/20' : 'border-port-border'
+ }`}>
+ <div className="flex items-center justify-between mb-0.5">
+ <span className="text-[10px] sm:text-xs text-gray-500 truncate">{label}</span>
+ <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`}>
+ {icon}
+ </div>
+ </div>
+ <div className="text-sm sm:text-base lg:text-xl font-bold text-white">{value}</div>
+ </div>
+ );
+ }
+
return (
- <div className={`bg-port-card border rounded-lg p-4 transition-all ${
+ <div className={`bg-port-card border rounded-lg p-2 sm:p-3 lg:p-4 transition-all ${
active ? 'border-port-accent shadow-lg shadow-port-accent/20' : 'border-port-border'
}`}>
- <div className="flex items-center justify-between mb-2">
- <span className="text-sm text-gray-500">{label}</span>
- <div className={active ? 'animate-pulse' : ''}>
+ <div className="flex items-center justify-between mb-0.5 sm:mb-1 lg:mb-2">
+ <span className="text-xs sm:text-sm text-gray-500 truncate mr-1">{label}</span>
+ <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`}>
{icon}
</div>
</div>
- <div className="text-2xl font-bold text-white">{value}</div>
+ <div className="text-lg sm:text-xl lg:text-2xl font-bold text-white">{value}</div>
{active && activeLabel && (
- <div className="text-xs text-port-accent mt-1 truncate animate-pulse">
+ <div className="text-xs text-port-accent mt-0.5 sm:mt-1 truncate animate-pulse">
{activeLabel}
</div>
)}
diff --git a/client/src/components/cos/TerminalCoSPanel.jsx b/client/src/components/cos/TerminalCoSPanel.jsx
index ab868af816..c59d285d5e 100644
--- a/client/src/components/cos/TerminalCoSPanel.jsx
+++ b/client/src/components/cos/TerminalCoSPanel.jsx
@@ -83,7 +83,7 @@ export default function TerminalCoSPanel({ state, speaking, statusMessage, event
};
return (
- <div className="relative flex flex-col p-4 font-mono text-sm bg-[#0d1117] border-b lg:border-b-0 lg:border-r border-gray-700/50 h-full overflow-y-auto scrollbar-hide">
+ <div className="relative flex flex-col p-3 lg:p-4 font-mono text-sm bg-[#0d1117] border-b lg:border-b-0 lg:border-r border-gray-700/50 shrink-0 lg:h-full overflow-hidden lg:overflow-y-auto scrollbar-hide max-h-[50vh] lg:max-h-none">
{/* Scanline effect */}
<div
className="absolute inset-0 pointer-events-none opacity-[0.02]"
@@ -93,37 +93,65 @@ export default function TerminalCoSPanel({ state, speaking, statusMessage, event
/>
{/* Terminal header */}
- <div className="flex items-center gap-3 mb-4 pb-2 border-b border-gray-700/50">
+ <div className="flex items-center gap-3 mb-2 lg:mb-4 pb-2 border-b border-gray-700/50">
<div className="flex gap-1.5">
- <span className="w-3 h-3 rounded-full bg-red-500/80"></span>
- <span className="w-3 h-3 rounded-full bg-yellow-500/80"></span>
- <span className="w-3 h-3 rounded-full bg-green-500/80"></span>
+ <span className="w-2.5 h-2.5 lg:w-3 lg:h-3 rounded-full bg-red-500/80"></span>
+ <span className="w-2.5 h-2.5 lg:w-3 lg:h-3 rounded-full bg-yellow-500/80"></span>
+ <span className="w-2.5 h-2.5 lg:w-3 lg:h-3 rounded-full bg-green-500/80"></span>
</div>
<span className="text-gray-500 text-xs">cos-terminal</span>
+ {/* Mobile-only status indicator */}
+ <div className="flex items-center gap-2 ml-auto lg:hidden">
+ <span className={`w-2 h-2 rounded-full ${running ? 'bg-green-400 animate-pulse' : 'bg-gray-600'}`}></span>
+ <span className={`text-xs ${running ? 'text-green-400' : 'text-gray-500'}`}>
+ {running ? 'ACTIVE' : 'IDLE'}
+ </span>
+ </div>
</div>
- {/* ASCII Art + Info */}
- <div className="flex items-start gap-4 mb-4">
- <div className="flex-shrink-0">
+ {/* ASCII Art + Info + Controls in row on mobile */}
+ <div className="flex items-center lg:items-start gap-3 lg:gap-4 mb-1 lg:mb-4">
+ {/* ASCII Art - smaller on mobile */}
+ <div className="flex-shrink-0 scale-75 lg:scale-100 origin-top-left -mr-3 lg:mr-0">
{ascii.map((line, i) => (
<div
key={i}
- className={`whitespace-pre leading-tight ${speaking && [0, 1].includes(i) ? 'animate-pulse' : ''}`}
+ className={`whitespace-pre leading-tight text-xs lg:text-sm ${speaking && [0, 1].includes(i) ? 'animate-pulse' : ''}`}
style={{ color: stateConfig.color }}
>
{line}
</div>
))}
</div>
- <div className="flex flex-col text-xs pt-1">
- <span className="text-white font-bold">CoS Agent v1.0</span>
- <span className="text-gray-400">PortOS · {stateConfig.label}</span>
- <span className="text-gray-500">~/portos/cos</span>
+ <div className="flex flex-col text-xs pt-0 lg:pt-1 flex-1 min-w-0">
+ <span className="text-white font-bold text-xs lg:text-sm">CoS Agent v1.0</span>
+ <span className="text-gray-400 truncate">PortOS · {stateConfig.label}</span>
+ <span className="text-gray-500 hidden lg:block">~/portos/cos</span>
+ </div>
+ {/* Mobile control buttons */}
+ <div className="flex lg:hidden gap-2 shrink-0">
+ {running ? (
+ <button
+ onClick={onStop}
+ className="flex items-center gap-1 px-2 py-1 bg-red-900/30 hover:bg-red-900/50 text-red-400 rounded border border-red-700/50 text-xs transition-colors"
+ >
+ <Square size={10} />
+ stop
+ </button>
+ ) : (
+ <button
+ onClick={onStart}
+ className="flex items-center gap-1 px-2 py-1 bg-green-900/30 hover:bg-green-900/50 text-green-400 rounded border border-green-700/50 text-xs transition-colors"
+ >
+ <Play size={10} />
+ start
+ </button>
+ )}
</div>
</div>
- {/* Status line */}
- <div className="flex items-center gap-2 mb-3 text-xs">
+ {/* Status line - desktop only */}
+ <div className="hidden lg:flex items-center gap-2 mb-3 text-xs">
<span className={`w-2 h-2 rounded-full ${running ? 'bg-green-400 animate-pulse' : 'bg-gray-600'}`}></span>
<span className={running ? 'text-green-400' : 'text-gray-500'}>
{running ? 'ACTIVE' : 'IDLE'}
@@ -133,19 +161,21 @@ export default function TerminalCoSPanel({ state, speaking, statusMessage, event
</div>
{/* Message bubble as terminal output */}
- <div className="mb-4 px-2 py-1.5 bg-gray-800/50 rounded border-l-2 border-cyan-500/50">
- <span className="text-cyan-400">$</span>
- <span className="text-gray-300 ml-2">{statusMessage}</span>
- {evalCountdown && (
- <div className="text-xs text-cyan-500/60 mt-1 font-mono">
- # next_check: {evalCountdown.formatted}
- </div>
- )}
+ <div className="mb-1 lg:mb-4 px-2 py-1 lg:py-1.5 bg-gray-800/50 rounded border-l-2 border-cyan-500/50">
+ <div className="flex items-center gap-1 lg:block">
+ <span className="text-cyan-400 text-xs">$</span>
+ <span className="text-gray-300 text-xs lg:ml-2 truncate lg:line-clamp-none flex-1">{statusMessage}</span>
+ {evalCountdown && (
+ <span className="text-[10px] lg:text-xs text-cyan-500/60 font-mono whitespace-nowrap lg:block lg:mt-1">
+ <span className="hidden lg:inline"># next: </span>({evalCountdown.formatted})
+ </span>
+ )}
+ </div>
</div>
- {/* Stats as terminal output */}
+ {/* Stats as terminal output - desktop only */}
{stats && (
- <div className="mb-4 text-xs space-y-1">
+ <div className="hidden lg:block mb-4 text-xs space-y-1">
<div className="text-gray-500">┌─ stats ──────────────────┐</div>
<div className="text-gray-400 pl-2">│ tasks_completed: <span className="text-green-400">{stats.tasksCompleted || 0}</span></div>
<div className="text-gray-400 pl-2">│ agents_spawned: <span className="text-cyan-400">{stats.agentsSpawned || 0}</span></div>
@@ -154,8 +184,8 @@ export default function TerminalCoSPanel({ state, speaking, statusMessage, event
</div>
)}
- {/* Event logs as terminal output */}
- <div className="flex-1 mb-4 flex flex-col min-h-0">
+ {/* Event logs as terminal output - desktop only */}
+ <div className="hidden lg:flex flex-1 mb-4 flex-col min-h-0">
<div className="text-gray-500 text-xs mb-1">// event_log</div>
<div className="flex-1 bg-black/30 rounded p-2 overflow-y-auto scrollbar-hide">
{(!eventLogs || eventLogs.length === 0) ? (
@@ -174,8 +204,8 @@ export default function TerminalCoSPanel({ state, speaking, statusMessage, event
</div>
</div>
- {/* Control buttons as terminal commands */}
- <div className="mt-auto pt-3 border-t border-gray-700/50">
+ {/* Control buttons as terminal commands - desktop only */}
+ <div className="hidden lg:block mt-auto pt-3 border-t border-gray-700/50">
<div className="flex gap-2">
{running ? (
<button
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 9da4897c20..847e5e0b6e 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -6,15 +6,19 @@ import {
CheckCircle,
AlertCircle,
RotateCcw,
- Loader2
+ Loader2,
+ Skull,
+ Activity
} from 'lucide-react';
import * as api from '../../../services/api';
-export default function AgentCard({ agent, onTerminate, onDelete, onResume, completed, liveOutput }) {
+export default function AgentCard({ agent, onTerminate, onKill, onDelete, onResume, completed, liveOutput }) {
const [expanded, setExpanded] = useState(false);
const [now, setNow] = useState(Date.now());
const [fullOutput, setFullOutput] = useState(null);
const [loadingOutput, setLoadingOutput] = useState(false);
+ const [processStats, setProcessStats] = useState(null);
+ const [killing, setKilling] = useState(false);
// Determine if this is a system agent (health check, etc.)
const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');
@@ -26,6 +30,27 @@ export default function AgentCard({ agent, onTerminate, onDelete, onResume, comp
return () => clearInterval(interval);
}, [completed]);
+ // Fetch process stats for running agents
+ useEffect(() => {
+ if (completed) return;
+
+ const fetchStats = async () => {
+ const stats = await api.getCosAgentStats(agent.id).catch(() => null);
+ setProcessStats(stats);
+ };
+
+ fetchStats();
+ const interval = setInterval(fetchStats, 5000); // Update every 5 seconds
+ return () => clearInterval(interval);
+ }, [completed, agent.id]);
+
+ const handleKill = async () => {
+ if (!onKill) return;
+ setKilling(true);
+ await onKill(agent.id);
+ setKilling(false);
+ };
+
// Fetch full output when expanded for completed agents
useEffect(() => {
if (expanded && completed && !fullOutput && !loadingOutput) {
@@ -85,12 +110,25 @@ export default function AgentCard({ agent, onTerminate, onDelete, onResume, comp
{!completed && (
<span className={`px-2 py-0.5 text-xs rounded animate-pulse ${
agent.metadata?.phase === 'initializing' ? 'bg-yellow-500/20 text-yellow-400' :
- agent.metadata?.phase === 'working' ? 'bg-port-accent/20 text-port-accent' :
'bg-port-accent/20 text-port-accent'
}`}>
- {agent.metadata?.phase === 'initializing' ? 'Initializing' :
- agent.metadata?.phase === 'working' ? 'Working' :
- 'Running'}
+ {agent.metadata?.phase === 'initializing' ? 'Initializing' : 'Working'}
+ </span>
+ )}
+ {/* Process stats for running agents */}
+ {!completed && processStats?.active && (
+ <span className="flex items-center gap-1 px-2 py-0.5 text-xs rounded bg-port-success/20 text-port-success"
+ title={`PID: ${processStats.pid} | State: ${processStats.state}`}>
+ <Activity size={10} />
+ PID {processStats.pid} | {processStats.cpu?.toFixed(1)}% | {processStats.memoryMb}MB
+ </span>
+ )}
+ {/* Show zombie warning if PID exists but process is dead */}
+ {!completed && agent.pid && processStats && !processStats.active && (
+ <span className="flex items-center gap-1 px-2 py-0.5 text-xs rounded bg-port-error/20 text-port-error"
+ title="Process is not running - zombie agent">
+ <Skull size={10} />
+ PID {agent.pid} ZOMBIE
</span>
)}
</div>
@@ -104,15 +142,27 @@ export default function AgentCard({ agent, onTerminate, onDelete, onResume, comp
{expanded ? 'Hide' : 'Show'} Output
</button>
)}
+ {/* Terminate button (graceful) */}
{!completed && onTerminate && (
<button
onClick={() => onTerminate(agent.id)}
- className="text-gray-500 hover:text-port-error transition-colors"
- title="Terminate"
+ className="text-gray-500 hover:text-port-warning transition-colors"
+ title="Terminate (graceful SIGTERM)"
>
<Square size={14} />
</button>
)}
+ {/* Kill button (force SIGKILL) */}
+ {!completed && onKill && (
+ <button
+ onClick={handleKill}
+ disabled={killing}
+ className="text-gray-500 hover:text-port-error transition-colors disabled:opacity-50"
+ title="Force Kill (SIGKILL)"
+ >
+ {killing ? <Loader2 size={14} className="animate-spin" /> : <Skull size={14} />}
+ </button>
+ )}
{completed && !isSystemAgent && onResume && (
<button
onClick={() => onResume(agent)}
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index 666244b566..da951561c9 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -14,6 +14,12 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
onRefresh();
};
+ const handleKill = async (agentId) => {
+ await api.killCosAgent(agentId).catch(err => toast.error(err.message));
+ toast.success('Agent force killed');
+ onRefresh();
+ };
+
const handleDelete = async (agentId) => {
await api.deleteCosAgent(agentId).catch(err => toast.error(err.message));
toast.success('Agent removed');
@@ -75,6 +81,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
key={agent.id}
agent={agent}
onTerminate={handleTerminate}
+ onKill={handleKill}
liveOutput={liveOutputs[agent.id]}
/>
))}
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index 7b3970c102..0386154eab 100644
--- a/client/src/components/cos/tabs/TasksTab.jsx
+++ b/client/src/components/cos/tabs/TasksTab.jsx
@@ -1,5 +1,5 @@
-import { useState, useEffect } from 'react';
-import { Plus, RefreshCw } from 'lucide-react';
+import { useState, useEffect, useRef } from 'react';
+import { Plus, RefreshCw, Image, X } from 'lucide-react';
import toast from 'react-hot-toast';
import {
DndContext,
@@ -23,6 +23,8 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
const [showAddTask, setShowAddTask] = useState(false);
const [newTask, setNewTask] = useState({ id: '', description: '', context: '', model: '', provider: '', app: '' });
const [userTasksLocal, setUserTasksLocal] = useState([]);
+ const [screenshots, setScreenshots] = useState([]);
+ const fileInputRef = useRef(null);
const userTasks = tasks.user?.tasks || [];
const cosTasks = tasks.cos?.tasks || [];
@@ -65,6 +67,52 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
}
};
+ // Screenshot handling
+ 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 result = ev?.target?.result;
+ if (typeof result !== 'string') {
+ console.error('❌ Failed to read file: unexpected FileReader result type');
+ return;
+ }
+
+ const parts = result.split(',');
+ if (parts.length < 2) {
+ console.error('❌ Failed to read file: unexpected data URL format');
+ return;
+ }
+
+ const base64 = parts[1];
+ const uploaded = await api.uploadScreenshot(base64, file.name, file.type).catch((err) => {
+ console.error(`❌ Failed to upload screenshot: ${err.message}`);
+ return null;
+ });
+ if (uploaded) {
+ setScreenshots(prev => [...prev, {
+ id: uploaded.id,
+ filename: uploaded.filename,
+ preview: result,
+ path: uploaded.path
+ }]);
+ }
+ };
+ reader.onerror = (err) => {
+ console.error(`❌ FileReader failed to read file: ${err.message}`);
+ };
+ reader.readAsDataURL(file);
+ }
+ e.target.value = '';
+ };
+
+ const removeScreenshot = (id) => {
+ setScreenshots(prev => prev.filter(s => s.id !== id));
+ };
+
// Get models for selected provider
const selectedProvider = providers?.find(p => p.id === newTask.provider);
const availableModels = selectedProvider?.models || [];
@@ -82,7 +130,8 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
context: newTask.context,
model: newTask.model || undefined,
provider: newTask.provider || undefined,
- app: newTask.app || undefined
+ app: newTask.app || undefined,
+ screenshots: screenshots.length > 0 ? screenshots.map(s => s.path) : undefined
}).catch(err => {
toast.error(err.message);
return;
@@ -90,6 +139,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
toast.success('Task added');
setNewTask({ id: '', description: '', context: '', model: '', provider: '', app: '' });
+ setScreenshots([]);
setShowAddTask(false);
onRefresh();
};
@@ -177,9 +227,55 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
))}
</select>
</div>
+ {/* Screenshot Upload */}
+ <div className="flex items-center gap-3">
+ <button
+ type="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 transition-colors"
+ >
+ <Image size={16} />
+ Add Screenshot
+ </button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ multiple
+ onChange={handleFileSelect}
+ className="hidden"
+ />
+ {screenshots.length > 0 && (
+ <span className="text-xs text-gray-500">{screenshots.length} screenshot{screenshots.length > 1 ? 's' : ''} attached</span>
+ )}
+ </div>
+ {/* Screenshot Previews */}
+ {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
+ type="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>
+ )}
<div className="flex justify-end gap-2">
<button
- onClick={() => setShowAddTask(false)}
+ onClick={() => {
+ setShowAddTask(false);
+ setScreenshots([]);
+ }}
className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"
>
Cancel
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 705136a035..60880632ee 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -125,18 +125,18 @@ export default function AIProviders() {
return (
<div className="space-y-6">
- <div className="flex items-center justify-between">
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<h1 className="text-2xl font-bold text-white">AI Providers</h1>
- <div className="flex gap-2">
+ <div className="flex flex-wrap gap-2">
<button
onClick={() => setShowRunPanel(!showRunPanel)}
- className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors text-sm sm:text-base"
>
{showRunPanel ? 'Hide Runner' : 'Run Prompt'}
</button>
<button
onClick={() => { setEditingProvider(null); setShowForm(true); }}
- className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"
+ className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors text-sm sm:text-base"
>
Add Provider
</button>
@@ -146,11 +146,11 @@ export default function AIProviders() {
{/* Run Panel */}
{showRunPanel && (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-4">
- <div className="flex items-center gap-4">
+ <div className="flex flex-col sm:flex-row gap-2 sm:gap-4">
<select
value={activeProviderId || ''}
onChange={(e) => handleSetActive(e.target.value)}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white w-full sm:w-auto"
>
<option value="">Select Provider</option>
{providers.filter(p => p.enabled).map(p => (
@@ -161,7 +161,7 @@ export default function AIProviders() {
<select
value={selectedWorkspace}
onChange={(e) => setSelectedWorkspace(e.target.value)}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white w-full sm:w-auto"
>
<option value="">No workspace</option>
{apps.map(app => (
@@ -214,9 +214,9 @@ export default function AIProviders() {
provider.id === activeProviderId ? 'border-port-accent' : 'border-port-border'
}`}
>
- <div className="flex items-start justify-between">
- <div className="flex-1">
- <div className="flex items-center gap-3">
+ <div className="flex flex-col lg:flex-row lg:items-start justify-between gap-4">
+ <div className="flex-1 min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
<h3 className="text-lg font-semibold text-white">{provider.name}</h3>
<span className={`text-xs px-2 py-0.5 rounded ${
provider.type === 'cli' ? 'bg-blue-500/20 text-blue-400' : 'bg-purple-500/20 text-purple-400'
@@ -237,16 +237,16 @@ export default function AIProviders() {
<div className="mt-2 text-sm text-gray-400 space-y-1">
{provider.type === 'cli' && (
- <p>Command: <code className="text-gray-300">{provider.command} {provider.args?.join(' ')}</code></p>
+ <p className="break-words">Command: <code className="text-gray-300 break-all">{provider.command} {provider.args?.join(' ')}</code></p>
)}
{provider.type === 'api' && (
- <p>Endpoint: <code className="text-gray-300">{provider.endpoint}</code></p>
+ <p className="break-words">Endpoint: <code className="text-gray-300 break-all">{provider.endpoint}</code></p>
)}
{provider.models?.length > 0 && (
<p>Models: {provider.models.slice(0, 3).join(', ')}{provider.models.length > 3 ? ` +${provider.models.length - 3}` : ''}</p>
)}
{provider.defaultModel && (
- <p>Default: <code className="text-gray-300">{provider.defaultModel}</code></p>
+ <p className="break-words">Default: <code className="text-gray-300 break-all">{provider.defaultModel}</code></p>
)}
{(provider.lightModel || provider.mediumModel || provider.heavyModel) && (
<p className="text-xs">
@@ -268,11 +268,11 @@ export default function AIProviders() {
)}
</div>
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
<button
onClick={() => handleTest(provider.id)}
disabled={testResults[provider.id]?.testing}
- className="px-3 py-1 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50"
+ className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50"
>
{testResults[provider.id]?.testing ? 'Testing...' : 'Test'}
</button>
@@ -280,7 +280,7 @@ export default function AIProviders() {
{provider.type === 'api' && (
<button
onClick={() => handleRefreshModels(provider.id)}
- className="px-3 py-1 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"
+ className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"
title="Refresh models from API"
>
Refresh
@@ -289,7 +289,7 @@ export default function AIProviders() {
<button
onClick={() => handleToggleEnabled(provider)}
- className={`px-3 py-1 text-sm rounded transition-colors ${
+ className={`px-3 py-1.5 text-sm rounded transition-colors ${
provider.enabled
? 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30'
: 'bg-port-success/20 text-port-success hover:bg-port-success/30'
@@ -301,7 +301,7 @@ export default function AIProviders() {
{provider.id !== activeProviderId && provider.enabled && (
<button
onClick={() => handleSetActive(provider.id)}
- className="px-3 py-1 text-sm bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded transition-colors"
+ className="px-3 py-1.5 text-sm bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded transition-colors"
>
Set Default
</button>
@@ -309,14 +309,14 @@ export default function AIProviders() {
<button
onClick={() => { setEditingProvider(provider); setShowForm(true); }}
- className="px-3 py-1 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"
+ className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"
>
Edit
</button>
<button
onClick={() => handleDelete(provider.id)}
- className="px-3 py-1 text-sm bg-port-error/20 text-port-error hover:bg-port-error/30 rounded transition-colors"
+ className="px-3 py-1.5 text-sm bg-port-error/20 text-port-error hover:bg-port-error/30 rounded transition-colors"
>
Delete
</button>
@@ -340,22 +340,22 @@ export default function AIProviders() {
{runs.map(run => (
<div
key={run.id}
- className="bg-port-card border border-port-border rounded-lg p-3 flex items-center justify-between"
+ className="bg-port-card border border-port-border rounded-lg p-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2"
>
- <div className="flex items-center gap-4">
- <span className={`w-2 h-2 rounded-full ${
+ <div className="flex items-start sm:items-center gap-3 min-w-0">
+ <span className={`w-2 h-2 rounded-full flex-shrink-0 mt-1.5 sm:mt-0 ${
run.success === true ? 'bg-port-success' :
run.success === false ? 'bg-port-error' :
'bg-port-warning animate-pulse'
}`} />
- <div>
- <p className="text-sm text-white">{run.prompt}</p>
- <p className="text-xs text-gray-500">
+ <div className="min-w-0">
+ <p className="text-sm text-white break-words">{run.prompt}</p>
+ <p className="text-xs text-gray-500 break-words">
{run.providerName} • {run.workspaceName || 'No workspace'} • {new Date(run.startTime).toLocaleString()}
</p>
</div>
</div>
- <div className="text-sm text-gray-400">
+ <div className="text-sm text-gray-400 flex-shrink-0 pl-5 sm:pl-0">
{run.duration ? `${(run.duration / 1000).toFixed(1)}s` : 'Running...'}
</div>
</div>
@@ -411,8 +411,8 @@ function ProviderForm({ provider, onClose, onSave }) {
};
return (
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
- <div className="bg-port-card border border-port-border rounded-xl p-6 w-full max-w-lg">
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 w-full max-w-lg max-h-[90vh] overflow-y-auto">
<h2 className="text-xl font-bold text-white mb-4">
{provider ? 'Edit Provider' : 'Add Provider'}
</h2>
@@ -509,7 +509,7 @@ function ProviderForm({ provider, onClose, onSave }) {
{/* 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 className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div>
<label className="block text-xs text-gray-400 mb-1">Light (fast)</label>
<input
diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsx
index 10e7b50559..0b1b8b0953 100644
--- a/client/src/pages/Apps.jsx
+++ b/client/src/pages/Apps.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, Fragment } from 'react';
+import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { ExternalLink, Play, Square, RotateCcw, FolderOpen, Terminal, Code, RefreshCw, Wrench } from 'lucide-react';
import toast from 'react-hot-toast';
@@ -114,20 +114,20 @@ export default function Apps() {
return (
<div>
{/* Header */}
- <div className="flex items-center justify-between mb-6">
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
<div>
<h2 className="text-2xl font-bold text-white">Apps</h2>
- <p className="text-gray-500">Manage registered applications</p>
+ <p className="text-gray-500 text-sm sm:text-base">Manage registered applications</p>
</div>
<Link
to="/apps/create"
- className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors text-center"
>
+ Add App
</Link>
</div>
- {/* Table */}
+ {/* App List */}
{apps.length === 0 ? (
<div className="bg-port-card border border-port-border rounded-xl p-12 text-center">
<div className="text-4xl mb-4">📦</div>
@@ -141,264 +141,251 @@ export default function Apps() {
</Link>
</div>
) : (
- <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
- <div className="overflow-x-auto">
- <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">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 => (
- <Fragment key={app.id}>
- <tr className="hover:bg-port-border/30">
- <td className="px-4 py-3">
+ <div className="space-y-4">
+ {apps.map(app => (
+ <div
+ key={app.id}
+ className="bg-port-card border border-port-border rounded-xl overflow-hidden"
+ >
+ {/* Main App Row */}
+ <div className="p-4">
+ <div className="flex flex-col sm:flex-row sm:items-center gap-4">
+ {/* Expand + Name + Status */}
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <button
+ onClick={() => toggleExpand(app.id)}
+ className="text-gray-400 hover:text-white transition-transform flex-shrink-0"
+ >
+ <span className={`inline-block transition-transform ${expandedId === app.id ? 'rotate-90' : ''}`}>▶</span>
+ </button>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium text-white">{app.name}</span>
+ <StatusBadge status={app.overallStatus} size="sm" />
+ </div>
+ <div className="text-xs text-gray-500 flex flex-wrap gap-x-2 mt-1">
+ {(app.pm2ProcessNames || []).map((procName, i) => {
+ const procInfo = app.processes?.find(p => p.name === procName);
+ const ports = procInfo?.ports || {};
+ const portEntries = Object.entries(ports);
+ const portDisplay = portEntries.length > 1
+ ? ` (${portEntries.map(([label, port]) => `${label}:${port}`).join(', ')})`
+ : portEntries.length === 1
+ ? `:${portEntries[0][1]}`
+ : '';
+ return (
+ <span key={i}>
+ {procName}<span className="text-cyan-500">{portDisplay}</span>
+ {i < (app.pm2ProcessNames?.length || 0) - 1 ? ',' : ''}
+ </span>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+
+ {/* Controls */}
+ <div className="flex flex-wrap items-center gap-2">
+ {/* Start/Stop/Restart Button Group */}
+ <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={() => toggleExpand(app.id)}
- className="text-gray-400 hover:text-white transition-transform"
+ 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"
>
- <span className={`inline-block transition-transform ${expandedId === app.id ? 'rotate-90' : ''}`}>▶</span>
+ <Play size={14} />
+ <span className="text-xs">{actionLoading[app.id] === 'start' ? 'Starting...' : 'Start'}</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 flex flex-wrap gap-x-2">
- {/* Show process names with ports - filter to only this app's processes */}
- {(app.pm2ProcessNames || []).map((procName, i) => {
- const procInfo = app.processes?.find(p => p.name === procName);
- const ports = procInfo?.ports || {};
- const portEntries = Object.entries(ports);
- const portDisplay = portEntries.length > 1
- ? ` (${portEntries.map(([label, port]) => `${label}:${port}`).join(', ')})`
- : portEntries.length === 1
- ? `:${portEntries[0][1]}`
- : '';
- return (
- <span key={i}>
- {procName}<span className="text-cyan-500">{portDisplay}</span>
- {i < (app.pm2ProcessNames?.length || 0) - 1 ? ',' : ''}
- </span>
- );
- })}
+ )}
+ </div>
+
+ {/* Launch button */}
+ {app.uiPort && app.overallStatus === 'online' && (
+ <button
+ onClick={() => window.open(`${window.location.protocol}//${window.location.hostname}:${app.uiPort}`, '_blank')}
+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors rounded-lg border border-port-border flex items-center gap-1"
+ title={`Open ${window.location.hostname}:${app.uiPort}`}
+ >
+ <ExternalLink size={14} />
+ <span className="text-xs">Launch</span>
+ </button>
+ )}
+
+ {/* Edit/Delete Actions */}
+ {confirmingDelete === app.id ? (
+ <div className="flex items-center 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>
- </td>
- <td className="px-4 py-3">
- <StatusBadge status={app.overallStatus} size="sm" />
- </td>
- <td className="px-4 py-3">
- {/* Start/Stop/Restart/Launch Button Group */}
- <div className="flex justify-center gap-2">
- <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>
- {/* Launch button - only show when online and has UI port */}
- {app.uiPort && app.overallStatus === 'online' && (
- <button
- onClick={() => window.open(`${window.location.protocol}//${window.location.hostname}:${app.uiPort}`, '_blank')}
- className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors rounded-lg border border-port-border flex items-center gap-1"
- title={`Open ${window.location.hostname}:${app.uiPort}`}
- >
- <ExternalLink size={14} />
- <span className="text-xs">Launch</span>
- </button>
- )}
+ </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>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Expanded Details */}
+ {expandedId === app.id && (
+ <div className="bg-port-bg border-t border-port-border">
+ <div className="p-4 sm:px-6 sm:py-4 space-y-4">
+ {/* Details Grid */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Repository Path</div>
+ <div className="flex items-start gap-2">
+ <FolderOpen size={16} className="text-yellow-400 flex-shrink-0 mt-0.5" />
+ <code className="text-sm text-gray-300 font-mono break-all">{app.repoPath}</code>
</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="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 flex-shrink-0" />
+ <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-start gap-2 py-1">
+ <Terminal size={14} className="text-green-400 flex-shrink-0 mt-0.5" />
+ <code className="text-sm text-cyan-300 font-mono break-all">{cmd}</code>
</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={5} 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>
+ ))}
+ </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) => {
- // Find port for this process from the processes array
- const processConfig = app.processes?.find(p => p.name === proc.name);
- return (
- <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>
- {processConfig?.ports && Object.keys(processConfig.ports).length > 0 && (
- <span className="text-xs text-cyan-400 font-mono">
- {Object.entries(processConfig.ports).length > 1
- ? ` (${Object.entries(processConfig.ports).map(([label, port]) => `${label}:${port}`).join(', ')})`
- : `:${Object.values(processConfig.ports)[0]}`}
- </span>
- )}
- <span className="text-xs text-gray-500">{proc.status}</span>
- {proc.cpu !== undefined && (
- <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={() => api.openAppInEditor(app.id).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={() => api.openAppFolder(app.id).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>
- <button
- onClick={() => handleRefreshConfig(app)}
- disabled={refreshingConfig[app.id]}
- 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 disabled:opacity-50"
- title="Re-scan ecosystem config for PM2 processes and ports"
- >
- <RefreshCw size={14} className={refreshingConfig[app.id] ? 'animate-spin' : ''} />
- Refresh Config
- </button>
- <button
- onClick={() => handleStandardize(app)}
- disabled={standardizing[app.id]}
- className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"
- title="Standardize PM2 config: move all ports to ecosystem.config.cjs"
- >
- <Wrench size={14} className={standardizing[app.id] ? 'animate-spin' : ''} />
- {standardizing[app.id] ? 'Standardizing...' : 'Standardize PM2'}
- </button>
+ {/* 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) => {
+ const processConfig = app.processes?.find(p => p.name === proc.name);
+ return (
+ <div
+ key={i}
+ className="flex flex-wrap 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 flex-shrink-0 ${
+ 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>
+ {processConfig?.ports && Object.keys(processConfig.ports).length > 0 && (
+ <span className="text-xs text-cyan-400 font-mono">
+ {Object.entries(processConfig.ports).length > 1
+ ? ` (${Object.entries(processConfig.ports).map(([label, port]) => `${label}:${port}`).join(', ')})`
+ : `:${Object.values(processConfig.ports)[0]}`}
+ </span>
+ )}
+ <span className="text-xs text-gray-500">{proc.status}</span>
+ {proc.cpu !== undefined && (
+ <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>
- </td>
- </tr>
+ );
+ })}
+ </div>
+ </div>
)}
- </Fragment>
- ))}
- </tbody>
- </table>
- </div>
+
+ {/* Quick Actions */}
+ <div className="flex flex-wrap gap-2 pt-2">
+ <button
+ onClick={() => api.openAppInEditor(app.id).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={() => api.openAppFolder(app.id).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>
+ <button
+ onClick={() => handleRefreshConfig(app)}
+ disabled={refreshingConfig[app.id]}
+ 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 disabled:opacity-50"
+ title="Re-scan ecosystem config for PM2 processes and ports"
+ >
+ <RefreshCw size={14} className={refreshingConfig[app.id] ? 'animate-spin' : ''} />
+ Refresh Config
+ </button>
+ <button
+ onClick={() => handleStandardize(app)}
+ disabled={standardizing[app.id]}
+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"
+ title="Standardize PM2 config: move all ports to ecosystem.config.cjs"
+ >
+ <Wrench size={14} className={standardizing[app.id] ? 'animate-spin' : ''} />
+ {standardizing[app.id] ? 'Standardizing...' : 'Standardize PM2'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ ))}
</div>
)}
@@ -457,8 +444,8 @@ function EditAppModal({ app, onClose, onSave }) {
};
return (
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
- <div className="bg-port-card border border-port-border rounded-xl p-6 w-full max-w-lg max-h-[90vh] overflow-auto">
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 w-full max-w-lg max-h-[90vh] overflow-auto">
<h2 className="text-xl font-bold text-white mb-4">Edit App</h2>
{error && (
@@ -468,7 +455,7 @@ function EditAppModal({ app, onClose, onSave }) {
)}
<form onSubmit={handleSubmit} className="space-y-4">
- <div className="grid grid-cols-[1fr_auto] gap-4">
+ <div className="grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-4">
<div>
<label className="block text-sm text-gray-400 mb-1">Name</label>
<input
@@ -479,7 +466,7 @@ function EditAppModal({ app, onClose, onSave }) {
required
/>
</div>
- <div className="w-32">
+ <div className="w-full sm:w-32">
<IconPicker value={formData.icon} onChange={icon => setFormData({ ...formData, icon })} />
</div>
</div>
@@ -495,7 +482,7 @@ function EditAppModal({ app, onClose, onSave }) {
/>
</div>
- <div className="grid grid-cols-2 gap-4">
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm text-gray-400 mb-1">UI Port</label>
<input
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 0699391bd4..fd6924ebce 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -144,6 +144,13 @@ export default function ChiefOfStaff() {
fetchData();
});
+ socket.on('cos:agent:updated', (updatedAgent) => {
+ // Update the specific agent in the agents list without fetching all data
+ setAgents(prev => prev.map(agent =>
+ agent.id === updatedAgent.id ? updatedAgent : agent
+ ));
+ });
+
socket.on('cos:agent:output', (data) => {
if (data?.agentId && data?.line) {
setLiveOutputs(prev => ({
@@ -273,7 +280,7 @@ export default function ChiefOfStaff() {
const hasIssues = (health?.issues?.length || 0) > 0;
return (
- <div className="flex flex-col lg:grid lg:grid-cols-[320px_1fr] h-screen">
+ <div className="flex flex-col lg:grid lg:grid-cols-[320px_1fr] h-screen overflow-hidden">
{/* Agent Panel */}
{avatarStyle === 'ascii' ? (
<TerminalCoSPanel
@@ -288,7 +295,7 @@ export default function ChiefOfStaff() {
evalCountdown={evalCountdown}
/>
) : (
- <div className="relative flex flex-col items-center p-6 lg:p-8 border-b lg:border-b-0 lg:border-r border-indigo-500/20 bg-gradient-to-b from-slate-900/80 to-slate-900/40 h-full overflow-y-auto scrollbar-hide">
+ <div className="relative flex border-b lg:border-b-0 lg:border-r border-indigo-500/20 bg-gradient-to-b from-slate-900/80 to-slate-900/40 shrink-0 lg:h-full lg:overflow-y-auto scrollbar-hide">
{/* Background Effects */}
<div
className="absolute inset-0 pointer-events-none"
@@ -300,12 +307,13 @@ export default function ChiefOfStaff() {
}}
/>
- <div className="relative z-10 flex flex-col items-center">
- <div className="text-sm font-semibold tracking-widest uppercase text-slate-400 mb-1 font-mono">
+ {/* Avatar Column - half width on mobile, full on desktop */}
+ <div className="flex-1 lg:flex-none flex flex-col items-center p-4 lg:p-8 relative z-10">
+ <div className="hidden lg:block text-sm font-semibold tracking-widest uppercase text-slate-400 mb-1 font-mono">
Digital Assistant
</div>
<h1
- className="text-2xl lg:text-3xl font-bold mb-4 lg:mb-8"
+ className="text-lg sm:text-xl lg:text-3xl font-bold mb-2 lg:mb-8"
style={{
background: 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)',
WebkitBackgroundClip: 'text',
@@ -318,59 +326,96 @@ export default function ChiefOfStaff() {
<CoSCharacter state={agentState} speaking={speaking} />
<StateLabel state={agentState} />
- <StatusBubble message={statusMessage} countdown={evalCountdown} />
- {status?.running && <EventLog logs={eventLogs} />}
+ <div className="hidden sm:block">
+ <StatusBubble message={statusMessage} countdown={evalCountdown} />
+ </div>
+ <div className="hidden lg:block">
+ {status?.running && <EventLog logs={eventLogs} />}
+ </div>
{/* Control Buttons */}
- <div className="flex items-center gap-3 mt-6">
+ <div className="flex items-center gap-2 sm:gap-3 mt-3 lg:mt-6">
{status?.running ? (
<button
onClick={handleStop}
- className="flex items-center gap-2 px-4 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg transition-colors"
+ className="flex items-center gap-1 sm:gap-2 px-2 sm:px-4 py-1.5 sm:py-2 text-sm sm:text-base bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg transition-colors"
>
- <Square size={16} />
+ <Square size={14} className="sm:w-4 sm:h-4" />
Stop
</button>
) : (
<button
onClick={handleStart}
- className="flex items-center gap-2 px-4 py-2 bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 rounded-lg transition-colors"
+ className="flex items-center gap-1 sm:gap-2 px-2 sm:px-4 py-1.5 sm:py-2 text-sm sm:text-base bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 rounded-lg transition-colors"
>
- <Play size={16} />
+ <Play size={14} className="sm:w-4 sm:h-4" />
Start
</button>
)}
<StatusIndicator running={status?.running} />
</div>
</div>
+
+ {/* Mobile Stats Column - only visible on mobile */}
+ <div className="flex-1 flex flex-col justify-center gap-2 p-3 lg:hidden relative z-10">
+ <StatCard
+ label="Active"
+ value={activeAgentCount}
+ icon={<Cpu className="w-4 h-4 text-port-accent" />}
+ active={activeAgentCount > 0}
+ compact
+ />
+ <StatCard
+ label="Pending"
+ value={(tasks.user?.grouped?.pending?.length || 0) + (tasks.cos?.grouped?.pending?.length || 0)}
+ icon={<Clock className="w-4 h-4 text-yellow-500" />}
+ compact
+ />
+ <StatCard
+ label="Done"
+ value={status?.stats?.tasksCompleted || 0}
+ icon={<CheckCircle className="w-4 h-4 text-port-success" />}
+ compact
+ />
+ <StatCard
+ label="Issues"
+ value={health?.issues?.length || 0}
+ icon={<AlertCircle className={`w-4 h-4 ${hasIssues ? 'text-port-error' : 'text-gray-500'}`} />}
+ compact
+ />
+ </div>
</div>
)}
{/* Content Panel */}
- <div className="flex-1 p-3 lg:p-4 overflow-y-auto">
- {/* Stats Bar */}
- <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
+ <div className="flex-1 min-h-0 flex flex-col overflow-hidden">
+ <div className="overflow-y-auto p-3 lg:p-4">
+ {/* Stats Bar - hidden on mobile for SVG mode (shown in avatar panel instead) */}
+ <div className={`grid grid-cols-4 gap-1.5 sm:gap-2 lg:gap-3 mb-3 sm:mb-4 lg:mb-6 ${avatarStyle !== 'ascii' ? 'hidden lg:grid' : ''}`}>
<StatCard
- label="Active Agents"
+ label="Active"
value={activeAgentCount}
- icon={<Cpu className="w-5 h-5 text-port-accent" />}
+ icon={<Cpu className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5 text-port-accent" />}
active={activeAgentCount > 0}
- activeLabel={activeAgentCount > 0 ? agents.find(a => a.status === 'running')?.taskId : null}
+ mini
/>
<StatCard
- label="Pending Tasks"
+ label="Pending"
value={(tasks.user?.grouped?.pending?.length || 0) + (tasks.cos?.grouped?.pending?.length || 0)}
- icon={<Clock className="w-5 h-5 text-yellow-500" />}
+ icon={<Clock className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5 text-yellow-500" />}
+ mini
/>
<StatCard
- label="Completed"
+ label="Done"
value={status?.stats?.tasksCompleted || 0}
- icon={<CheckCircle className="w-5 h-5 text-port-success" />}
+ icon={<CheckCircle className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5 text-port-success" />}
+ mini
/>
<StatCard
- label="Health Issues"
+ label="Issues"
value={health?.issues?.length || 0}
- icon={<AlertCircle className={`w-5 h-5 ${hasIssues ? 'text-port-error' : 'text-gray-500'}`} />}
+ icon={<AlertCircle className={`w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5 ${hasIssues ? 'text-port-error' : 'text-gray-500'}`} />}
+ mini
/>
</div>
@@ -382,14 +427,14 @@ export default function ChiefOfStaff() {
<button
key={tabItem.id}
onClick={() => navigate(`/cos/${tabItem.id}`)}
- className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px whitespace-nowrap ${
+ className={`flex items-center gap-2 px-3 sm:px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px whitespace-nowrap ${
activeTab === tabItem.id
? 'text-port-accent border-port-accent'
: 'text-gray-500 border-transparent hover:text-white'
}`}
>
<Icon size={16} />
- {tabItem.label}
+ <span className="hidden sm:inline">{tabItem.label}</span>
</button>
);
})}
@@ -414,6 +459,7 @@ export default function ChiefOfStaff() {
{activeTab === 'config' && (
<ConfigTab config={status?.config} onUpdate={fetchData} onEvaluate={handleForceEvaluate} avatarStyle={avatarStyle} setAvatarStyle={setAvatarStyle} evalCountdown={evalCountdown} />
)}
+ </div>
</div>
</div>
);
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index ee2c401981..e3087c00ff 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -37,10 +37,10 @@ export default function Dashboard() {
return (
<div>
{/* Header */}
- <div className="flex items-center justify-between mb-6">
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4 mb-6">
<div>
<h2 className="text-2xl font-bold text-white">Dashboard</h2>
- <p className="text-gray-500">
+ <p className="text-gray-500 text-sm sm:text-base">
{apps.length} app{apps.length !== 1 ? 's' : ''} registered
</p>
</div>
diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsx
index 6b66c10385..523f2c1faf 100644
--- a/client/src/pages/DevTools.jsx
+++ b/client/src/pages/DevTools.jsx
@@ -91,7 +91,7 @@ export function HistoryPage() {
{/* Stats */}
{stats && (
- <div className="grid grid-cols-4 gap-4">
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
<div className="bg-port-card border border-port-border rounded-lg p-4 text-center">
<div className="text-2xl font-bold text-white">{stats.total}</div>
<div className="text-sm text-gray-400">Total Actions</div>
@@ -112,33 +112,35 @@ export function HistoryPage() {
)}
{/* Filters */}
- <div className="flex gap-4 items-center">
- <select
- value={filter.action}
- onChange={(e) => setFilter(prev => ({ ...prev, action: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
- >
- <option value="">All Actions</option>
- {actions.map(action => (
- <option key={action} value={action}>{action}</option>
- ))}
- </select>
+ <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 sm:items-center">
+ <div className="flex flex-wrap gap-2 sm:gap-4">
+ <select
+ value={filter.action}
+ onChange={(e) => setFilter(prev => ({ ...prev, action: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ <option value="">All Actions</option>
+ {actions.map(action => (
+ <option key={action} value={action}>{action}</option>
+ ))}
+ </select>
- <select
- value={filter.success}
- onChange={(e) => setFilter(prev => ({ ...prev, success: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
- >
- <option value="">All Results</option>
- <option value="true">Success</option>
- <option value="false">Failed</option>
- </select>
+ <select
+ value={filter.success}
+ onChange={(e) => setFilter(prev => ({ ...prev, success: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ <option value="">All Results</option>
+ <option value="true">Success</option>
+ <option value="false">Failed</option>
+ </select>
+ </div>
<div className="flex-1" />
{confirmingClear ? (
<div className="flex items-center gap-2">
- <span className="text-sm text-gray-400">Clear all history?</span>
+ <span className="text-sm text-gray-400">Clear all?</span>
<button
onClick={handleClear}
className="px-3 py-1.5 bg-port-error/20 text-port-error hover:bg-port-error/30 rounded-lg transition-colors"
@@ -171,37 +173,41 @@ export function HistoryPage() {
{history.map(entry => (
<div key={entry.id}>
<div
- className="p-4 hover:bg-port-border/20 cursor-pointer group"
+ className="p-3 sm:p-4 hover:bg-port-border/20 cursor-pointer group"
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 className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <button className="text-gray-400 hover:text-white flex-shrink-0">
+ <span className={`inline-block transition-transform ${expandedId === entry.id ? 'rotate-90' : ''}`}>▶</span>
+ </button>
+ <span className="text-xl flex-shrink-0">{getActionIcon(entry.action)}</span>
+ <div className="flex-1 min-w-0">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="font-medium text-white">{entry.action}</span>
+ {entry.targetName && (
+ <span className="text-gray-400 text-sm sm:text-base">→ {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 mt-1">{entry.details.command}</code>
)}
</div>
- {entry.details?.command && (
- <code className="text-xs text-gray-500 font-mono truncate block">{entry.details.command}</code>
- )}
</div>
- <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>
- <button
- onClick={(e) => handleDelete(entry.id, e)}
- className="p-1 text-gray-500 hover:text-port-error transition-colors opacity-0 group-hover:opacity-100"
- title="Delete entry"
- >
- <Trash2 size={14} />
- </button>
+ <div className="flex items-center gap-3 pl-8 sm:pl-0">
+ <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>
+ <button
+ onClick={(e) => handleDelete(entry.id, e)}
+ className="p-1 text-gray-500 hover:text-port-error transition-colors sm:opacity-0 sm:group-hover:opacity-100"
+ title="Delete entry"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
</div>
</div>
@@ -210,7 +216,7 @@ export function HistoryPage() {
<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 className="grid grid-cols-2 sm: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>
@@ -384,33 +390,59 @@ export function RunsHistoryPage() {
return `${(ms / 60000).toFixed(1)}m`;
};
+ const getExitCodeInfo = (exitCode) => {
+ const codeInfo = {
+ 1: { label: 'Error', description: 'Generic error - check the output for details' },
+ 2: { label: 'Misuse', description: 'Incorrect command usage or invalid arguments' },
+ 126: { label: 'Not Executable', description: 'Command found but not executable' },
+ 127: { label: 'Not Found', description: 'Command not found - check if CLI is installed' },
+ 128: { label: 'Invalid Exit', description: 'Invalid exit argument' },
+ 130: { label: 'Interrupted', description: 'Process interrupted (Ctrl+C / SIGINT)' },
+ 137: { label: 'Killed', description: 'Process killed (SIGKILL) - likely out of memory' },
+ 143: { label: 'Terminated', description: 'Process terminated (SIGTERM) - likely hit timeout' }
+ };
+ return codeInfo[exitCode] || { label: 'Unknown', description: `Exit code ${exitCode}` };
+ };
+
if (loading) {
return <div className="text-center py-8 text-gray-400">Loading runs history...</div>;
}
+ const failedCount = runs.filter(r => r.success === false).length;
+
+ const handleClearFailed = async () => {
+ const result = await api.deleteFailedRuns().catch(() => null);
+ if (result) {
+ loadRuns();
+ }
+ };
+
return (
- <div className="space-y-6">
- <div className="flex items-center justify-between">
- <h1 className="text-2xl font-bold text-white">AI Runs History</h1>
- <button
- onClick={loadRuns}
- className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white"
- >
- <RefreshCw size={16} /> Refresh
- </button>
+ <div className="space-y-4 lg:space-y-6">
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
+ <h1 className="text-lg sm:text-2xl font-bold text-white">AI Runs History</h1>
+ {failedCount > 0 && (
+ <button
+ onClick={handleClearFailed}
+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-error/20 hover:bg-port-error/30 text-port-error rounded-lg transition-colors self-end sm:self-auto"
+ >
+ <Trash2 size={14} />
+ Clear Failed ({failedCount})
+ </button>
+ )}
</div>
{/* Source Filter */}
- <div className="flex gap-2">
+ <div className="flex flex-wrap gap-1.5 sm:gap-2">
{[
- { value: 'all', label: 'All Runs' },
+ { value: 'all', label: 'All' },
{ value: 'devtools', label: 'DevTools' },
- { value: 'cos-agent', label: 'CoS Agents' }
+ { value: 'cos-agent', label: 'CoS' }
].map(filter => (
<button
key={filter.value}
onClick={() => setSourceFilter(filter.value)}
- className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
+ className={`px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg text-xs sm:text-sm font-medium transition-colors ${
sourceFilter === filter.value
? 'bg-port-accent text-white'
: 'bg-port-card text-gray-400 hover:text-white border border-port-border'
@@ -422,7 +454,7 @@ export function RunsHistoryPage() {
</div>
{/* Runs List */}
- <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl overflow-hidden">
{runs.length === 0 ? (
<div className="text-center py-12 text-gray-500">No AI runs yet</div>
) : (
@@ -430,47 +462,61 @@ export function RunsHistoryPage() {
{runs.map(run => (
<div key={run.id}>
<div
- className="p-4 hover:bg-port-border/20 cursor-pointer group"
+ className="p-3 sm:p-4 hover:bg-port-border/20 cursor-pointer group"
onClick={() => toggleExpand(run.id)}
data-testid={`run-row-${run.id}`}
>
- <div className="flex items-center gap-4">
- <button className="text-gray-400 hover:text-white">
- <span className={`inline-block transition-transform ${expandedId === run.id ? 'rotate-90' : ''}`}>▶</span>
- </button>
- <span className="text-xl">🤖</span>
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="font-medium text-white">{run.providerName}</span>
- <span className="text-gray-500 text-sm">{run.model}</span>
- {run.source === 'cos-agent' && (
- <span className="text-xs text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded">
- CoS
- </span>
- )}
- {run.workspaceName && (
- <span className="text-xs text-port-accent bg-port-accent/10 px-2 py-0.5 rounded">
- {run.workspaceName}
- </span>
- )}
- {run.duration && (
- <span className="text-xs text-cyan-400 font-mono">{formatRuntime(run.duration)}</span>
+ <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <button className="text-gray-400 hover:text-white flex-shrink-0">
+ <span className={`inline-block transition-transform ${expandedId === run.id ? 'rotate-90' : ''}`}>▶</span>
+ </button>
+ <span className="text-xl flex-shrink-0">🤖</span>
+ <div className="flex-1 min-w-0">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="font-medium text-white">{run.providerName}</span>
+ <span className="text-gray-500 text-sm">{run.model}</span>
+ {run.source === 'cos-agent' && (
+ <span className="text-xs text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded">
+ CoS
+ </span>
+ )}
+ {run.workspaceName && (
+ <span className="text-xs text-port-accent bg-port-accent/10 px-2 py-0.5 rounded">
+ {run.workspaceName}
+ </span>
+ )}
+ {run.duration && (
+ <span className="text-xs text-cyan-400 font-mono">{formatRuntime(run.duration)}</span>
+ )}
+ </div>
+ <div className="text-xs text-gray-500 font-mono truncate mt-1">
+ {run.prompt?.substring(0, 100)}{run.prompt?.length > 100 ? '...' : ''}
+ </div>
+ {/* Show error preview for failed runs in collapsed view */}
+ {run.success === false && expandedId !== run.id && (
+ <div className="text-xs text-port-error/80 font-mono truncate mt-1">
+ ⚠ {run.error
+ ? `${run.error.split('\n')[0]?.substring(0, 80)}${run.error.length > 80 ? '...' : ''}`
+ : run.errorCategory && run.errorCategory !== 'unknown'
+ ? `${run.errorCategory}: ${run.suggestedFix || 'See details'}`
+ : `${getExitCodeInfo(run.exitCode).label}: ${getExitCodeInfo(run.exitCode).description}`}
+ </div>
)}
</div>
- <div className="text-xs text-gray-500 font-mono truncate mt-1">
- {run.prompt?.substring(0, 100)}{run.prompt?.length > 100 ? '...' : ''}
- </div>
</div>
- <span className={`w-2 h-2 rounded-full flex-shrink-0 ${run.success ? 'bg-port-success' : run.success === false ? 'bg-port-error' : 'bg-port-warning'}`} />
- <span className="text-sm text-gray-500 flex-shrink-0">{formatTime(run.startTime)}</span>
- <button
- onClick={(e) => handleDelete(run.id, e)}
- className="p-1 text-gray-500 hover:text-port-error transition-colors opacity-0 group-hover:opacity-100"
- title="Delete run"
- data-testid={`delete-run-${run.id}`}
- >
- <Trash2 size={14} />
- </button>
+ <div className="flex items-center gap-3 pl-8 sm:pl-0">
+ <span className={`w-2 h-2 rounded-full flex-shrink-0 ${run.success ? 'bg-port-success' : run.success === false ? 'bg-port-error' : 'bg-port-warning'}`} />
+ <span className="text-sm text-gray-500 flex-shrink-0">{formatTime(run.startTime)}</span>
+ <button
+ onClick={(e) => handleDelete(run.id, e)}
+ className="p-1 text-gray-500 hover:text-port-error transition-colors sm:opacity-0 sm:group-hover:opacity-100"
+ title="Delete run"
+ data-testid={`delete-run-${run.id}`}
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
</div>
</div>
@@ -479,7 +525,7 @@ export function RunsHistoryPage() {
<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-5 gap-4 text-sm">
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4 text-sm">
<div>
<div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Started</div>
<div className="text-gray-300">{new Date(run.startTime).toLocaleString()}</div>
@@ -522,29 +568,64 @@ export function RunsHistoryPage() {
</div>
</div>
- {/* Output */}
- {expandedDetails[run.id]?.output && (
+ {/* Output - show for successful runs with output OR for failed runs */}
+ {(expandedDetails[run.id]?.output || run.success === false) && (
<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">
- {expandedDetails[run.id].output}
+ {expandedDetails[run.id]?.output || (run.success === false ? 'Loading output...' : '')}
</pre>
</div>
</div>
)}
- {/* Error */}
- {run.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">
- {run.error}
- </pre>
+ {/* Error - show for failed runs with error message OR exit code */}
+ {(run.error || (run.success === false && run.exitCode !== 0)) && (() => {
+ const exitInfo = getExitCodeInfo(run.exitCode);
+ return (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2 flex items-center gap-2">
+ Error
+ {run.exitCode !== undefined && run.exitCode !== null && run.exitCode !== 0 && (
+ <span className="text-port-error/70">(exit code: {run.exitCode})</span>
+ )}
+ {run.errorCategory && run.errorCategory !== 'unknown' ? (
+ <span className="px-1.5 py-0.5 bg-port-error/20 text-port-error/80 rounded text-xs">
+ {run.errorCategory}
+ </span>
+ ) : run.exitCode !== 0 && exitInfo.label !== 'Unknown' && (
+ <span className="px-1.5 py-0.5 bg-port-error/20 text-port-error/80 rounded text-xs">
+ {exitInfo.label}
+ </span>
+ )}
+ </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 break-all">
+ {run.error || exitInfo.description}
+ </pre>
+ </div>
+ {/* Show additional error details if available and different from error */}
+ {run.errorDetails && run.errorDetails !== run.error && (
+ <div className="mt-2 bg-port-error/5 border border-port-error/20 rounded-lg p-3">
+ <div className="text-xs text-gray-500 mb-1">Additional Details</div>
+ <pre className="text-xs text-port-error/80 font-mono whitespace-pre-wrap break-all">
+ {run.errorDetails}
+ </pre>
+ </div>
+ )}
+ {/* Show suggested fix if available, or fallback to exit code info */}
+ {(run.suggestedFix || (!run.error && exitInfo.description)) && (
+ <div className="mt-2 bg-port-warning/10 border border-port-warning/30 rounded-lg p-3">
+ <div className="text-xs text-port-warning mb-1 font-medium">Suggested Fix</div>
+ <div className="text-sm text-gray-300">
+ {run.suggestedFix || 'Check the output above for specific error details. If the output is empty, the process may have been terminated before producing output.'}
+ </div>
+ </div>
+ )}
</div>
- </div>
- )}
+ );
+ })()}
{/* Continue Button */}
{run.success && expandedDetails[run.id]?.output && (
@@ -985,18 +1066,18 @@ ${prompt.trim()}`;
{/* Input Area */}
{mode === 'ai' ? (
- <div className="flex gap-2">
+ <div className="flex flex-col sm:flex-row 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"
+ className="flex-1 px-3 sm:px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none resize-none text-sm sm:text-base"
/>
{running ? (
<button
onClick={handleStop}
- className="px-6 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"
+ className="px-6 py-3 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"
>
Stop
</button>
@@ -1004,7 +1085,7 @@ ${prompt.trim()}`;
<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"
+ className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
>
Run
</button>
@@ -1012,14 +1093,14 @@ ${prompt.trim()}`;
</div>
) : (
<>
- <div className="flex gap-2">
+ <div className="flex flex-col sm:flex-row 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"
+ className="flex-1 px-3 sm:px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white font-mono focus:border-port-accent focus:outline-none text-sm sm:text-base"
/>
{running ? (
<button
@@ -1038,7 +1119,7 @@ ${prompt.trim()}`;
</button>
)}
</div>
- <div className="text-xs text-gray-500">
+ <div className="text-xs text-gray-500 break-words">
Allowed: {allowedCommands.slice(0, 10).join(', ')}{allowedCommands.length > 10 ? `, +${allowedCommands.length - 10} more` : ''}
</div>
</>
@@ -1049,7 +1130,7 @@ ${prompt.trim()}`;
<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"
+ className="bg-port-bg border border-port-border rounded-lg p-3 sm:p-4 h-64 sm:h-80 overflow-auto font-mono text-xs sm:text-sm"
>
{output ? (
<pre className="text-gray-300 whitespace-pre-wrap">{output}</pre>
@@ -1247,31 +1328,32 @@ export function ProcessesPage() {
return (
<div className="space-y-6">
- <div className="flex justify-between items-center">
+ <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div>
<h1 className="text-2xl font-bold text-white">PM2 Processes</h1>
- <p className="text-gray-500">PortOS-managed processes ({managedProcesses.length} of {processes.length} total)</p>
+ <p className="text-gray-500 text-sm sm:text-base">PortOS-managed processes ({managedProcesses.length} of {processes.length} total)</p>
</div>
<div className="flex gap-2">
<button
onClick={handlePm2Save}
disabled={saving}
- className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
+ className="px-3 sm:px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 text-sm sm:text-base"
>
<Save size={16} className={saving ? 'animate-pulse' : ''} />
- {saving ? 'Saving...' : 'PM2 Save'}
+ <span className="hidden sm:inline">{saving ? 'Saving...' : 'PM2 Save'}</span>
+ <span className="sm:hidden">{saving ? '...' : 'Save'}</span>
</button>
<button
onClick={loadProcesses}
- className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"
+ className="px-3 sm:px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors text-sm sm:text-base"
>
Refresh
</button>
</div>
</div>
- <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
- <table className="w-full">
+ <div className="bg-port-card border border-port-border rounded-xl overflow-hidden overflow-x-auto">
+ <table className="w-full min-w-[700px]">
<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>
@@ -1588,7 +1670,7 @@ export function GitPage() {
{loading ? (
<div className="text-center py-8 text-gray-400">Loading...</div>
) : gitInfo && gitInfo.isRepo ? (
- <div className="grid grid-cols-2 gap-6">
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Status Panel */}
<div className="space-y-4">
{/* Branch Info */}
@@ -1933,54 +2015,143 @@ export function AgentsPage() {
}
return (
- <div className="space-y-6">
+ <div className="space-y-4 lg: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 className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
+ <div className="flex items-center gap-2 sm:gap-3">
+ <Activity size={24} className="sm:w-7 sm:h-7 text-purple-400" />
+ <h1 className="text-lg sm:text-2xl font-bold text-white font-mono">AI Agent Processes</h1>
+ <span className="hidden sm:inline text-gray-500 text-sm">({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"
+ className="flex items-center justify-center gap-2 px-3 py-1.5 sm:px-4 sm:py-2 bg-port-card border border-port-border hover:border-gray-500 text-white text-sm rounded-lg transition-colors"
>
- <RefreshCw size={16} />
- Refresh
+ <RefreshCw size={14} className="sm:w-4 sm:h-4" />
+ <span className="sm:inline">Refresh</span>
</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 className="grid grid-cols-3 gap-2 sm:gap-4">
+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm: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 className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">Processes</div>
+ <div className="text-lg sm:text-3xl font-bold text-white font-mono">{agents.length}</div>
</div>
- <Terminal size={32} className="text-purple-400" />
+ <Terminal size={20} className="sm:w-8 sm:h-8 text-purple-400" />
</div>
- <div className="bg-port-card border border-port-border rounded-xl p-5 flex items-center justify-between">
+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm: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 className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">CPU</div>
+ <div className="text-lg sm:text-3xl font-bold text-white font-mono">{totalCpu.toFixed(1)}%</div>
</div>
- <Cpu size={32} className="text-blue-400" />
+ <Cpu size={20} className="sm:w-8 sm:h-8 text-blue-400" />
</div>
- <div className="bg-port-card border border-port-border rounded-xl p-5 flex items-center justify-between">
+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm: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 className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">Memory</div>
+ <div className="text-lg sm:text-3xl font-bold text-white font-mono">{totalMemory.toFixed(1)}%</div>
</div>
- <MemoryStick size={32} className="text-green-400" />
+ <MemoryStick size={20} className="sm:w-8 sm:h-8 text-green-400" />
</div>
</div>
- {/* Running Processes Table */}
- <div className="bg-port-card border border-port-border rounded-xl">
- <div className="px-6 py-4 border-b border-port-border">
- <h2 className="text-lg font-semibold text-white">Running Processes</h2>
+ {/* Running Processes */}
+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl">
+ <div className="px-3 sm:px-6 py-3 sm:py-4 border-b border-port-border">
+ <h2 className="text-base sm:text-lg font-semibold text-white">Running Processes</h2>
</div>
- <div className="overflow-x-auto">
+
+ {/* Mobile Card View */}
+ <div className="sm:hidden divide-y divide-port-border">
+ {agents.map(agent => (
+ <div key={agent.pid} className="p-3">
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-white text-sm">{agent.agentName.toLowerCase()}</span>
+ {agent.source === 'cos' && (
+ <span className="px-1.5 py-0.5 text-[10px] bg-purple-500/20 text-purple-400 rounded">CoS</span>
+ )}
+ </div>
+ <button
+ onClick={() => handleKill(agent.pid)}
+ disabled={killing[agent.pid]}
+ className="text-red-400 hover:text-red-300 disabled:opacity-50 p-1"
+ >
+ <XCircle size={18} className={killing[agent.pid] ? 'animate-pulse' : ''} />
+ </button>
+ </div>
+ <div className="grid grid-cols-4 gap-2 text-xs">
+ <div>
+ <div className="text-gray-500">PID</div>
+ <div className="font-mono text-white">{agent.pid}</div>
+ </div>
+ <div>
+ <div className="text-gray-500">Time</div>
+ <div className="font-mono text-cyan-400">{agent.runtimeFormatted}</div>
+ </div>
+ <div>
+ <div className="text-gray-500">CPU</div>
+ <div className="font-mono text-green-400">{agent.cpu?.toFixed(1)}%</div>
+ </div>
+ <div>
+ <div className="text-gray-500">Mem</div>
+ <div className="font-mono text-blue-400">{agent.memory?.toFixed(1)}%</div>
+ </div>
+ </div>
+ <button
+ onClick={() => toggleExpand(agent.pid)}
+ className="mt-2 text-xs text-gray-500 hover:text-white flex items-center gap-1"
+ >
+ <span className={`inline-block transition-transform ${expandedPid === agent.pid ? 'rotate-90' : ''}`}>▶</span>
+ {expandedPid === agent.pid ? 'Hide details' : 'Show details'}
+ </button>
+ {expandedPid === agent.pid && (
+ <div className="mt-3 pt-3 border-t border-port-border space-y-3">
+ <div className="grid grid-cols-2 gap-3 text-xs">
+ <div>
+ <div className="text-gray-500 uppercase tracking-wide mb-0.5">Agent Type</div>
+ <div className="text-purple-400">{agent.agentName}</div>
+ </div>
+ <div>
+ <div className="text-gray-500 uppercase tracking-wide mb-0.5">Parent PID</div>
+ <div className="text-gray-300 font-mono">{agent.ppid}</div>
+ </div>
+ {agent.model && (
+ <div>
+ <div className="text-gray-500 uppercase tracking-wide mb-0.5">Model</div>
+ <div className="text-yellow-400 font-mono">{agent.model}</div>
+ </div>
+ )}
+ {agent.taskId && (
+ <div>
+ <div className="text-gray-500 uppercase tracking-wide mb-0.5">Task ID</div>
+ <div className="text-gray-300 font-mono truncate">{agent.taskId}</div>
+ </div>
+ )}
+ </div>
+ {agent.prompt && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Task</div>
+ <div className="bg-port-bg border border-port-border rounded p-2 text-xs text-gray-300 line-clamp-3">
+ {agent.prompt}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ ))}
+ {agents.length === 0 && (
+ <div className="px-3 py-8 text-center text-gray-500 text-sm">
+ No AI agents currently running
+ </div>
+ )}
+ </div>
+
+ {/* Desktop Table View */}
+ <div className="hidden sm:block overflow-x-auto">
<table className="w-full min-w-[600px]">
<thead>
<tr className="border-b border-port-border">
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index a13699ffe1..504a1e46d7 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -108,14 +108,14 @@ export default function PromptManager() {
return (
<div>
{/* Header */}
- <div className="flex items-center justify-between mb-6">
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
<div>
<h1 className="text-2xl font-bold text-white">Prompt Manager</h1>
- <p className="text-gray-500">Customize AI prompts for backend operations</p>
+ <p className="text-gray-500 text-sm sm:text-base">Customize AI prompts for backend operations</p>
</div>
<button
onClick={loadData}
- className="p-2 text-gray-400 hover:text-white"
+ className="p-2 text-gray-400 hover:text-white self-end sm:self-auto"
title="Reload"
>
<RefreshCw size={20} />
@@ -123,10 +123,10 @@ export default function PromptManager() {
</div>
{/* Tabs */}
- <div className="flex gap-2 mb-6">
+ <div className="flex flex-wrap gap-2 mb-6">
<button
onClick={() => setTab('stages')}
- className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
+ className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
tab === 'stages' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
}`}
>
@@ -134,7 +134,7 @@ export default function PromptManager() {
</button>
<button
onClick={() => setTab('variables')}
- className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
+ className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
tab === 'variables' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
}`}
>
@@ -144,7 +144,7 @@ export default function PromptManager() {
{/* Stages Tab */}
{tab === 'stages' && (
- <div className="grid grid-cols-3 gap-6">
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Stage List */}
<div className="bg-port-card border border-port-border rounded-xl p-4">
<h3 className="text-sm font-medium text-gray-400 mb-3">Prompt Stages</h3>
@@ -167,7 +167,7 @@ export default function PromptManager() {
</div>
{/* Stage Editor */}
- <div className="col-span-2 space-y-4">
+ <div className="lg:col-span-2 space-y-4">
{selectedStage ? (
<>
<div className="bg-port-card border border-port-border rounded-xl p-4">
@@ -202,7 +202,7 @@ export default function PromptManager() {
</p>
</div>
- <div className="grid grid-cols-2 gap-4">
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm text-gray-400 mb-1">Model</label>
<select
@@ -256,7 +256,7 @@ export default function PromptManager() {
{/* Variables Tab */}
{tab === 'variables' && (
- <div className="grid grid-cols-3 gap-6">
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Variable List */}
<div className="bg-port-card border border-port-border rounded-xl p-4">
<div className="flex items-center justify-between mb-3">
@@ -297,7 +297,7 @@ export default function PromptManager() {
</div>
{/* Variable Editor */}
- <div className="col-span-2">
+ <div className="lg:col-span-2">
<div className="bg-port-card border border-port-border rounded-xl p-4">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-medium text-white">
@@ -313,7 +313,7 @@ export default function PromptManager() {
</div>
<div className="space-y-4">
- <div className="grid grid-cols-2 gap-4">
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm text-gray-400 mb-1">Key *</label>
<input
diff --git a/client/src/pages/Templates.jsx b/client/src/pages/Templates.jsx
index 55ebac6193..2912c75a7b 100644
--- a/client/src/pages/Templates.jsx
+++ b/client/src/pages/Templates.jsx
@@ -72,14 +72,14 @@ export default function Templates() {
return (
<div className="max-w-4xl mx-auto">
- <div className="flex items-center justify-between mb-6">
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-6">
<div>
<h1 className="text-2xl font-bold text-white">App Templates</h1>
- <p className="text-gray-500">Create new apps from pre-configured templates</p>
+ <p className="text-gray-500 text-sm sm:text-base">Create new apps from pre-configured templates</p>
</div>
<button
onClick={() => navigate('/apps/create')}
- className="px-4 py-2 text-gray-400 hover:text-white"
+ className="px-4 py-2 text-gray-400 hover:text-white text-sm sm:text-base self-start sm:self-auto"
>
← Back to Import
</button>
@@ -151,7 +151,7 @@ export default function Templates() {
</form>
</div>
) : (
- <div className="grid gap-4 md:grid-cols-2">
+ <div className="grid gap-4 grid-cols-1 md:grid-cols-2">
{templates.map(template => {
const Icon = ICONS[template.icon] || Layers;
return (
diff --git a/client/src/services/api.js b/client/src/services/api.js
index e6ce2ebfc3..456de5cd65 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -136,6 +136,7 @@ export const getRunOutput = (id) => request(`/runs/${id}/output`);
export const getRunPrompt = (id) => request(`/runs/${id}/prompt`);
export const stopRun = (id) => request(`/runs/${id}/stop`, { method: 'POST' });
export const deleteRun = (id) => request(`/runs/${id}`, { method: 'DELETE' });
+export const deleteFailedRuns = () => request('/runs', { method: 'DELETE' });
// History
export const getHistory = (options = {}) => {
@@ -244,6 +245,8 @@ export const forceHealthCheck = () => request('/cos/health/check', { method: 'PO
export const getCosAgents = () => request('/cos/agents');
export const getCosAgent = (id) => request(`/cos/agents/${id}`);
export const terminateCosAgent = (id) => request(`/cos/agents/${id}/terminate`, { method: 'POST' });
+export const killCosAgent = (id) => request(`/cos/agents/${id}/kill`, { method: 'POST' });
+export const getCosAgentStats = (id) => request(`/cos/agents/${id}/stats`);
export const deleteCosAgent = (id) => request(`/cos/agents/${id}`, { method: 'DELETE' });
export const clearCompletedCosAgents = () => request('/cos/agents/completed', { method: 'DELETE' });
export const getCosReports = () => request('/cos/reports');
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index 0ded62fefd..05b2ab189f 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -15,6 +15,29 @@ module.exports = {
watch: false,
max_memory_restart: '500M'
},
+ {
+ name: 'portos-cos',
+ script: 'server/cos-runner/index.js',
+ cwd: __dirname,
+ interpreter: 'node',
+ // CoS Agent Runner - isolated process for spawning Claude CLI agents
+ // Does NOT restart when portos-server restarts, preventing orphaned agents
+ ports: { api: 5558 },
+ env: {
+ NODE_ENV: 'development',
+ PORT: 5558,
+ HOST: '0.0.0.0'
+ },
+ watch: false,
+ autorestart: true,
+ max_restarts: 5,
+ min_uptime: '30s',
+ restart_delay: 10000,
+ max_memory_restart: '1G',
+ // Important: This process manages long-running agent processes
+ // Keep kill_timeout high to allow graceful shutdown of agents
+ kill_timeout: 30000
+ },
{
name: 'portos-client',
script: 'node_modules/.bin/vite',
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
new file mode 100644
index 0000000000..45c59aa8e0
--- /dev/null
+++ b/server/cos-runner/index.js
@@ -0,0 +1,690 @@
+/**
+ * CoS Agent Runner - Standalone PM2 Process
+ *
+ * This service runs as a separate PM2 app (portos-cos) that doesn't restart
+ * when portos-server restarts. It manages Claude CLI agent spawning and
+ * prevents orphaned processes when the main server cycles.
+ *
+ * Communication with portos-server happens via HTTP on port 5558.
+ */
+
+import express from 'express';
+import { spawn } from 'child_process';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { writeFile, mkdir, readFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { v4 as uuidv4 } from 'uuid';
+import http from 'http';
+import { Server as SocketServer } from 'socket.io';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const ROOT_DIR = join(__dirname, '../../');
+const STATE_FILE = join(ROOT_DIR, 'data/cos/runner-state.json');
+const AGENTS_DIR = join(ROOT_DIR, 'data/cos/agents');
+
+const PORT = process.env.PORT || 5558;
+const HOST = process.env.HOST || '0.0.0.0';
+const RUNS_DIR = join(ROOT_DIR, 'data/runs');
+
+// Active agent processes (in memory)
+const activeAgents = new Map();
+
+// Active devtools runs (in memory)
+const activeRuns = new Map();
+
+// Express app setup
+const app = express();
+app.use(express.json({ limit: '10mb' }));
+
+const server = http.createServer(app);
+const io = new SocketServer(server, {
+ cors: { origin: '*' }
+});
+
+/**
+ * Load runner state from disk
+ */
+async function loadState() {
+ if (!existsSync(STATE_FILE)) {
+ return { agents: {}, stats: { spawned: 0, completed: 0, failed: 0 } };
+ }
+ const content = await readFile(STATE_FILE, 'utf-8');
+ return JSON.parse(content);
+}
+
+/**
+ * Save runner state to disk
+ */
+async function saveState(state) {
+ const dir = dirname(STATE_FILE);
+ if (!existsSync(dir)) {
+ await mkdir(dir, { recursive: true });
+ }
+ await writeFile(STATE_FILE, JSON.stringify(state, null, 2));
+}
+
+/**
+ * Emit event to connected portos-server instances
+ */
+function emitToServer(event, data) {
+ io.emit(event, data);
+ console.log(`📡 Emitted ${event}`);
+}
+
+/**
+ * Ensure runs directory exists
+ */
+async function ensureRunsDir() {
+ if (!existsSync(RUNS_DIR)) {
+ await mkdir(RUNS_DIR, { recursive: true });
+ }
+}
+
+/**
+ * Health check endpoint
+ */
+app.get('/health', (req, res) => {
+ res.json({
+ status: 'ok',
+ activeAgents: activeAgents.size,
+ activeRuns: activeRuns.size,
+ uptime: process.uptime()
+ });
+});
+
+/**
+ * Get process stats (CPU, memory) for a PID
+ */
+async function getProcessStats(pid) {
+ const { exec } = await import('child_process');
+ const { promisify } = await import('util');
+ const execAsync = promisify(exec);
+
+ // Get process stats using ps command
+ // %cpu = CPU percentage, rss = resident set size in KB
+ const result = await execAsync(`ps -p ${pid} -o pid=,pcpu=,rss=,state= 2>/dev/null`).catch(() => ({ stdout: '' }));
+ const line = result.stdout.trim();
+
+ if (!line) {
+ return { active: false, pid, cpu: 0, memoryKb: 0, state: 'dead' };
+ }
+
+ const parts = line.split(/\s+/).filter(Boolean);
+ if (parts.length >= 3) {
+ return {
+ active: true,
+ pid: parseInt(parts[0], 10),
+ cpu: parseFloat(parts[1]) || 0,
+ memoryKb: parseInt(parts[2], 10) || 0,
+ memoryMb: Math.round((parseInt(parts[2], 10) || 0) / 1024 * 10) / 10,
+ state: parts[3] || 'unknown'
+ };
+ }
+
+ return { active: true, pid, cpu: 0, memoryKb: 0, state: 'unknown' };
+}
+
+/**
+ * Get list of active agents with process stats
+ */
+app.get('/agents', async (req, res) => {
+ const agents = [];
+ for (const [agentId, agent] of activeAgents) {
+ const stats = await getProcessStats(agent.pid);
+ agents.push({
+ id: agentId,
+ taskId: agent.taskId,
+ pid: agent.pid,
+ startedAt: agent.startedAt,
+ runningTime: Date.now() - agent.startedAt,
+ processActive: stats.active,
+ cpu: stats.cpu,
+ memoryMb: stats.memoryMb,
+ state: stats.state
+ });
+ }
+ res.json(agents);
+});
+
+/**
+ * Get process stats for a specific agent
+ */
+app.get('/agents/:agentId/stats', async (req, res) => {
+ const { agentId } = req.params;
+ const agent = activeAgents.get(agentId);
+
+ if (!agent) {
+ return res.status(404).json({ error: 'Agent not found or not running' });
+ }
+
+ const stats = await getProcessStats(agent.pid);
+ res.json({ agentId, pid: agent.pid, ...stats });
+});
+
+/**
+ * Spawn a new agent
+ */
+app.post('/spawn', async (req, res) => {
+ const {
+ agentId,
+ taskId,
+ prompt,
+ workspacePath,
+ model,
+ envVars = {},
+ claudePath = '/Users/antic/.nvm/versions/node/v25.2.1/bin/claude'
+ } = req.body;
+
+ if (!agentId || !taskId || !prompt) {
+ return res.status(400).json({ error: 'Missing required fields: agentId, taskId, prompt' });
+ }
+
+ // Build spawn arguments
+ const spawnArgs = [
+ '--dangerously-skip-permissions',
+ '--print'
+ ];
+
+ if (model) {
+ spawnArgs.push('--model', model);
+ }
+
+ console.log(`🤖 Spawning agent ${agentId} for task ${taskId}`);
+
+ // Ensure workspacePath is valid
+ const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;
+
+ // Spawn the Claude CLI process
+ const claudeProcess = spawn(claudePath, spawnArgs, {
+ cwd,
+ shell: false,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: { ...process.env, ...envVars }
+ });
+
+ // Store in memory
+ activeAgents.set(agentId, {
+ process: claudeProcess,
+ taskId,
+ pid: claudeProcess.pid,
+ startedAt: Date.now(),
+ outputBuffer: ''
+ });
+
+ // Send prompt via stdin
+ claudeProcess.stdin.write(prompt);
+ claudeProcess.stdin.end();
+
+ // Handle stdout
+ claudeProcess.stdout.on('data', (data) => {
+ const text = data.toString();
+ const agent = activeAgents.get(agentId);
+ if (agent) {
+ agent.outputBuffer += text;
+ }
+ emitToServer('agent:output', { agentId, text });
+ });
+
+ // Handle stderr
+ claudeProcess.stderr.on('data', (data) => {
+ const text = `[stderr] ${data.toString()}`;
+ const agent = activeAgents.get(agentId);
+ if (agent) {
+ agent.outputBuffer += text;
+ }
+ emitToServer('agent:output', { agentId, text });
+ });
+
+ // Handle errors
+ claudeProcess.on('error', (err) => {
+ console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);
+ emitToServer('agent:error', { agentId, error: err.message });
+ activeAgents.delete(agentId);
+ });
+
+ // Handle process exit
+ claudeProcess.on('close', async (code) => {
+ const agent = activeAgents.get(agentId);
+ const duration = Date.now() - (agent?.startedAt || Date.now());
+ const output = agent?.outputBuffer || '';
+
+ console.log(`${code === 0 ? '✅' : '❌'} Agent ${agentId} exited with code ${code}`);
+
+ // Save output to agent directory
+ const agentDir = join(AGENTS_DIR, agentId);
+ if (!existsSync(agentDir)) {
+ await mkdir(agentDir, { recursive: true });
+ }
+ await writeFile(join(agentDir, 'output.txt'), output).catch(() => {});
+
+ // Persist completion status to disk BEFORE emitting event
+ // This ensures recovery is possible even if the socket event is lost
+ const metadataPath = join(agentDir, 'metadata.json');
+ const existingMetadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+ const completionMetadata = {
+ ...existingMetadata,
+ agentId,
+ taskId,
+ completedAt: new Date().toISOString(),
+ exitCode: code,
+ success: code === 0,
+ duration,
+ outputSize: Buffer.byteLength(output)
+ };
+ await writeFile(metadataPath, JSON.stringify(completionMetadata, null, 2)).catch(() => {});
+
+ // Emit completion event
+ emitToServer('agent:completed', {
+ agentId,
+ taskId,
+ exitCode: code,
+ success: code === 0,
+ duration,
+ outputLength: output.length
+ });
+
+ // Update state
+ const state = await loadState();
+ state.stats.completed++;
+ if (code !== 0) state.stats.failed++;
+ await saveState(state);
+
+ activeAgents.delete(agentId);
+ });
+
+ // Update state
+ const state = await loadState();
+ state.agents[agentId] = {
+ pid: claudeProcess.pid,
+ taskId,
+ startedAt: Date.now()
+ };
+ state.stats.spawned++;
+ await saveState(state);
+
+ res.json({
+ success: true,
+ agentId,
+ pid: claudeProcess.pid
+ });
+});
+
+/**
+ * Terminate an agent (graceful with SIGTERM, then SIGKILL after timeout)
+ */
+app.post('/terminate/:agentId', (req, res) => {
+ const { agentId } = req.params;
+ const agent = activeAgents.get(agentId);
+
+ if (!agent) {
+ return res.status(404).json({ error: 'Agent not found or not running' });
+ }
+
+ console.log(`🔪 Terminating agent ${agentId}`);
+
+ agent.process.kill('SIGTERM');
+
+ // Force kill after timeout
+ setTimeout(() => {
+ if (activeAgents.has(agentId)) {
+ agent.process.kill('SIGKILL');
+ activeAgents.delete(agentId);
+ }
+ }, 5000);
+
+ res.json({ success: true, agentId });
+});
+
+/**
+ * Force kill an agent immediately with SIGKILL (no graceful shutdown)
+ */
+app.post('/kill/:agentId', async (req, res) => {
+ const { agentId } = req.params;
+ const agent = activeAgents.get(agentId);
+
+ if (!agent) {
+ return res.status(404).json({ error: 'Agent not found or not running' });
+ }
+
+ console.log(`💀 Force killing agent ${agentId} (PID: ${agent.pid})`);
+
+ // Use SIGKILL for immediate termination
+ agent.process.kill('SIGKILL');
+
+ // Clean up immediately
+ activeAgents.delete(agentId);
+
+ // Update state
+ const state = await loadState();
+ delete state.agents[agentId];
+ await saveState(state);
+
+ res.json({ success: true, agentId, pid: agent.pid, signal: 'SIGKILL' });
+});
+
+/**
+ * Kill all agents
+ */
+app.post('/terminate-all', async (req, res) => {
+ const agentIds = Array.from(activeAgents.keys());
+
+ for (const agentId of agentIds) {
+ const agent = activeAgents.get(agentId);
+ if (agent) {
+ agent.process.kill('SIGTERM');
+ }
+ }
+
+ // Force kill after timeout
+ setTimeout(() => {
+ for (const agentId of agentIds) {
+ const agent = activeAgents.get(agentId);
+ if (agent) {
+ agent.process.kill('SIGKILL');
+ activeAgents.delete(agentId);
+ }
+ }
+ }, 5000);
+
+ res.json({ success: true, killed: agentIds.length });
+});
+
+/**
+ * Get agent output
+ */
+app.get('/agents/:agentId/output', (req, res) => {
+ const { agentId } = req.params;
+ const agent = activeAgents.get(agentId);
+
+ if (!agent) {
+ return res.status(404).json({ error: 'Agent not found' });
+ }
+
+ res.json({ agentId, output: agent.outputBuffer });
+});
+
+// ============================================
+// DEVTOOLS RUNS - CLI execution for devtools
+// ============================================
+
+/**
+ * Execute a CLI run (devtools runner)
+ */
+app.post('/run', async (req, res) => {
+ const {
+ runId,
+ command,
+ args = [],
+ prompt,
+ workspacePath,
+ envVars = {},
+ timeout
+ } = req.body;
+
+ if (!runId || !command || !prompt) {
+ return res.status(400).json({ error: 'Missing required fields: runId, command, prompt' });
+ }
+
+ await ensureRunsDir();
+
+ console.log(`🔧 Starting devtools run ${runId}: ${command} ${args.join(' ')}`);
+
+ // Build command args - add prompt at the end
+ const spawnArgs = [...args, prompt];
+
+ // Ensure workspacePath is valid
+ const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;
+
+ // Spawn the CLI process
+ const childProcess = spawn(command, spawnArgs, {
+ cwd,
+ shell: false,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: { ...process.env, ...envVars }
+ });
+
+ const startTime = Date.now();
+
+ // Store in memory
+ activeRuns.set(runId, {
+ process: childProcess,
+ pid: childProcess.pid,
+ startedAt: startTime,
+ outputBuffer: ''
+ });
+
+ // Handle stdout
+ childProcess.stdout.on('data', (data) => {
+ const text = data.toString();
+ const run = activeRuns.get(runId);
+ if (run) {
+ run.outputBuffer += text;
+ }
+ emitToServer('run:data', { runId, text });
+ });
+
+ // Handle stderr
+ childProcess.stderr.on('data', (data) => {
+ const text = data.toString();
+ const run = activeRuns.get(runId);
+ if (run) {
+ run.outputBuffer += text;
+ }
+ emitToServer('run:data', { runId, text });
+ });
+
+ // Handle errors
+ childProcess.on('error', (err) => {
+ console.error(`❌ Run ${runId} spawn error: ${err.message}`);
+ emitToServer('run:error', { runId, error: err.message });
+ activeRuns.delete(runId);
+ });
+
+ // Handle process exit
+ childProcess.on('close', async (code) => {
+ const run = activeRuns.get(runId);
+ const duration = Date.now() - startTime;
+ const output = run?.outputBuffer || '';
+
+ console.log(`${code === 0 ? '✅' : '❌'} Run ${runId} exited with code ${code} (${duration}ms)`);
+
+ // Save output to run directory
+ const runDir = join(RUNS_DIR, runId);
+ if (!existsSync(runDir)) {
+ await mkdir(runDir, { recursive: true });
+ }
+ await writeFile(join(runDir, 'output.txt'), output).catch(() => {});
+
+ // Persist completion status to disk BEFORE emitting event
+ // This ensures recovery is possible even if the socket event is lost
+ const metadataPath = join(runDir, 'metadata.json');
+ const existingMetadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+ const updatedMetadata = {
+ ...existingMetadata,
+ endTime: new Date().toISOString(),
+ exitCode: code,
+ success: code === 0,
+ duration,
+ outputSize: Buffer.byteLength(output)
+ };
+ await writeFile(metadataPath, JSON.stringify(updatedMetadata, null, 2)).catch(() => {});
+
+ // Emit completion event
+ emitToServer('run:complete', {
+ runId,
+ exitCode: code,
+ success: code === 0,
+ duration,
+ outputLength: output.length
+ });
+
+ activeRuns.delete(runId);
+ });
+
+ // Set timeout if specified
+ if (timeout) {
+ setTimeout(() => {
+ if (activeRuns.has(runId)) {
+ console.log(`⏰ Run ${runId} timed out after ${timeout}ms`);
+ childProcess.kill('SIGTERM');
+ }
+ }, timeout);
+ }
+
+ res.json({
+ success: true,
+ runId,
+ pid: childProcess.pid
+ });
+});
+
+/**
+ * Get list of active runs
+ */
+app.get('/runs', (req, res) => {
+ const runs = [];
+ for (const [runId, run] of activeRuns) {
+ runs.push({
+ id: runId,
+ pid: run.pid,
+ startedAt: run.startedAt,
+ runningTime: Date.now() - run.startedAt
+ });
+ }
+ res.json(runs);
+});
+
+/**
+ * Get run output
+ */
+app.get('/runs/:runId/output', (req, res) => {
+ const { runId } = req.params;
+ const run = activeRuns.get(runId);
+
+ if (!run) {
+ return res.status(404).json({ error: 'Run not found or not active' });
+ }
+
+ res.json({ runId, output: run.outputBuffer });
+});
+
+/**
+ * Check if a run is active
+ */
+app.get('/runs/:runId/active', (req, res) => {
+ const { runId } = req.params;
+ res.json({ runId, active: activeRuns.has(runId) });
+});
+
+/**
+ * Stop a run
+ */
+app.post('/runs/:runId/stop', (req, res) => {
+ const { runId } = req.params;
+ const run = activeRuns.get(runId);
+
+ if (!run) {
+ return res.status(404).json({ error: 'Run not found or not active' });
+ }
+
+ console.log(`🛑 Stopping run ${runId}`);
+
+ run.process.kill('SIGTERM');
+
+ // Force kill after timeout
+ setTimeout(() => {
+ if (activeRuns.has(runId)) {
+ run.process.kill('SIGKILL');
+ activeRuns.delete(runId);
+ }
+ }, 5000);
+
+ res.json({ success: true, runId });
+});
+
+/**
+ * Socket.IO connection handling
+ */
+io.on('connection', (socket) => {
+ console.log(`🔌 Client connected: ${socket.id}`);
+
+ socket.on('disconnect', () => {
+ console.log(`🔌 Client disconnected: ${socket.id}`);
+ });
+});
+
+/**
+ * Cleanup orphaned agents on startup
+ * Checks if PIDs from state are still running
+ */
+async function cleanupOrphanedAgents() {
+ const state = await loadState();
+ const orphaned = [];
+
+ for (const [agentId, agentInfo] of Object.entries(state.agents)) {
+ // Check if process is still running
+ const isRunning = await checkProcessRunning(agentInfo.pid);
+ if (!isRunning) {
+ orphaned.push(agentId);
+ delete state.agents[agentId];
+ }
+ }
+
+ if (orphaned.length > 0) {
+ console.log(`🧹 Cleaned up ${orphaned.length} orphaned agents from state`);
+ await saveState(state);
+ }
+
+ return orphaned;
+}
+
+/**
+ * Check if a process is running by PID
+ */
+async function checkProcessRunning(pid) {
+ const { exec } = await import('child_process');
+ const { promisify } = await import('util');
+ const execAsync = promisify(exec);
+
+ const result = await execAsync(`ps -p ${pid} -o pid=`).catch(() => ({ stdout: '' }));
+ return result.stdout.trim() !== '';
+}
+
+/**
+ * Start the server
+ */
+server.listen(PORT, HOST, async () => {
+ console.log(`🤖 CoS Agent Runner started on http://${HOST}:${PORT}`);
+
+ // Cleanup orphaned agents
+ const orphaned = await cleanupOrphanedAgents();
+ if (orphaned.length > 0) {
+ console.log(`🧹 Cleaned ${orphaned.length} orphaned agent(s)`);
+ }
+
+ // Ensure agents directory exists
+ if (!existsSync(AGENTS_DIR)) {
+ await mkdir(AGENTS_DIR, { recursive: true });
+ }
+});
+
+// Graceful shutdown
+process.on('SIGTERM', async () => {
+ console.log('📴 Received SIGTERM, shutting down gracefully...');
+
+ // Terminate all agents
+ for (const [agentId, agent] of activeAgents) {
+ console.log(`🔪 Terminating agent ${agentId}`);
+ agent.process.kill('SIGTERM');
+ }
+
+ // Wait for agents to terminate
+ await new Promise(resolve => setTimeout(resolve, 5000));
+
+ server.close(() => {
+ console.log('👋 CoS Agent Runner stopped');
+ process.exit(0);
+ });
+});
diff --git a/server/cos-runner/package.json b/server/cos-runner/package.json
new file mode 100644
index 0000000000..cd9476d281
--- /dev/null
+++ b/server/cos-runner/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "portos-cos-runner",
+ "type": "module",
+ "private": true,
+ "description": "Isolated PM2 process for CoS agent spawning"
+}
diff --git a/server/package-lock.json b/server/package-lock.json
index 731502be13..5eb07e61db 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -1,17 +1,18 @@
{
"name": "portos-server",
- "version": "0.5.5",
+ "version": "0.5.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos-server",
- "version": "0.5.5",
+ "version": "0.5.7",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
"pm2": "^5.4.3",
"socket.io": "^4.8.3",
+ "socket.io-client": "^4.8.3",
"uuid": "^11.0.3",
"zod": "^3.24.1"
},
@@ -1751,6 +1752,63 @@
"node": ">=10.2.0"
}
},
+ "node_modules/engine.io-client": {
+ "version": "6.6.4",
+ "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.4.tgz",
+ "integrity": "sha512-+kjUJnZGwzewFDw951CDWcwj35vMNf2fcj7xQWOctq1F2i1jkDdVvdFG9kM/BEChymCH36KgjnW0NsL58JYRxw==",
+ "license": "MIT",
+ "dependencies": {
+ "@socket.io/component-emitter": "~3.1.0",
+ "debug": "~4.4.1",
+ "engine.io-parser": "~5.2.1",
+ "ws": "~8.18.3",
+ "xmlhttprequest-ssl": "~2.1.1"
+ }
+ },
+ "node_modules/engine.io-client/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/engine.io-client/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/engine.io-client/node_modules/ws": {
+ "version": "8.18.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
@@ -3772,6 +3830,44 @@
}
}
},
+ "node_modules/socket.io-client": {
+ "version": "4.8.3",
+ "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
+ "integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
+ "license": "MIT",
+ "dependencies": {
+ "@socket.io/component-emitter": "~3.1.0",
+ "debug": "~4.4.1",
+ "engine.io-client": "~6.6.1",
+ "socket.io-parser": "~4.2.4"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/socket.io-client/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/socket.io-client/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
"node_modules/socket.io-parser": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.5.tgz",
@@ -4491,6 +4587,14 @@
}
}
},
+ "node_modules/xmlhttprequest-ssl": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
+ "integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
diff --git a/server/package.json b/server/package.json
index 869a4f1a8d..91837e48e3 100644
--- a/server/package.json
+++ b/server/package.json
@@ -14,6 +14,7 @@
"express": "^4.21.2",
"pm2": "^5.4.3",
"socket.io": "^4.8.3",
+ "socket.io-client": "^4.8.3",
"uuid": "^11.0.3",
"zod": "^3.24.1"
},
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 2a2e47d181..0917c4b77f 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -93,13 +93,13 @@ router.post('/tasks/reorder', asyncHandler(async (req, res) => {
// POST /api/cos/tasks - Add a new task
router.post('/tasks', asyncHandler(async (req, res) => {
- const { description, priority, context, model, provider, app, type = 'user', approvalRequired } = req.body;
+ const { description, priority, context, model, provider, app, type = 'user', approvalRequired, screenshots } = req.body;
if (!description) {
throw new ServerError('Description is required', { status: 400, code: 'VALIDATION_ERROR' });
}
- const taskData = { description, priority, context, model, provider, app, approvalRequired };
+ const taskData = { description, priority, context, model, provider, app, approvalRequired, screenshots };
const result = await cos.addTask(taskData, type);
res.json(result);
}));
@@ -166,8 +166,10 @@ router.post('/health/check', asyncHandler(async (req, res) => {
res.json(result);
}));
-// GET /api/cos/agents - Get all agents
+// GET /api/cos/agents - Get all agents (auto-cleans zombies)
router.get('/agents', asyncHandler(async (req, res) => {
+ // Cleanup zombie agents before returning list
+ await cos.cleanupZombieAgents();
const agents = await cos.getAgents();
res.json(agents);
}));
@@ -181,12 +183,28 @@ router.get('/agents/:id', asyncHandler(async (req, res) => {
res.json(agent);
}));
-// POST /api/cos/agents/:id/terminate - Terminate agent
+// POST /api/cos/agents/:id/terminate - Terminate agent (graceful SIGTERM, then SIGKILL)
router.post('/agents/:id/terminate', asyncHandler(async (req, res) => {
const result = await cos.terminateAgent(req.params.id);
res.json(result);
}));
+// POST /api/cos/agents/:id/kill - Force kill agent (immediate SIGKILL)
+router.post('/agents/:id/kill', asyncHandler(async (req, res) => {
+ const result = await cos.killAgent(req.params.id);
+ if (result?.error) {
+ throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(result);
+}));
+
+// GET /api/cos/agents/:id/stats - Get process stats for agent (CPU, memory)
+router.get('/agents/:id/stats', asyncHandler(async (req, res) => {
+ const stats = await cos.getAgentProcessStats(req.params.id);
+ // Return success with active:false instead of 404 - this is expected when process isn't running
+ res.json(stats || { active: false, pid: null });
+}));
+
// DELETE /api/cos/agents/:id - Delete a single agent
router.delete('/agents/:id', asyncHandler(async (req, res) => {
const result = await cos.deleteAgent(req.params.id);
diff --git a/server/routes/runs.js b/server/routes/runs.js
index 5f8f126802..e209570afc 100644
--- a/server/routes/runs.js
+++ b/server/routes/runs.js
@@ -99,9 +99,10 @@ router.get('/:id', asyncHandler(async (req, res, next) => {
});
}
+ const isActive = await runner.isRunActive(req.params.id);
res.json({
...metadata,
- isActive: runner.isRunActive(req.params.id)
+ isActive
});
}));
@@ -150,7 +151,8 @@ router.post('/:id/stop', asyncHandler(async (req, res, next) => {
// DELETE /api/runs/:id - Delete run and artifacts
router.delete('/:id', asyncHandler(async (req, res, next) => {
// Don't allow deleting active runs
- if (runner.isRunActive(req.params.id)) {
+ const isActive = await runner.isRunActive(req.params.id);
+ if (isActive) {
throw new ServerError('Cannot delete active run', {
status: 409,
code: 'RUN_ACTIVE'
@@ -169,4 +171,10 @@ router.delete('/:id', asyncHandler(async (req, res, next) => {
res.status(204).send();
}));
+// DELETE /api/runs/failed - Delete all failed runs
+router.delete('/', asyncHandler(async (req, res, next) => {
+ const deletedCount = await runner.deleteFailedRuns();
+ res.json({ deleted: deletedCount });
+}));
+
export default router;
diff --git a/server/services/autoFixer.js b/server/services/autoFixer.js
index 9bd0db0c46..b456ef23e1 100644
--- a/server/services/autoFixer.js
+++ b/server/services/autoFixer.js
@@ -12,11 +12,44 @@ import { errorEvents } from '../lib/errorHandler.js';
const recentErrors = new Map();
const ERROR_DEDUPE_WINDOW = 60000; // 1 minute
+// Store pending tasks when CoS is not running (for later pickup)
+const pendingAutoFixTasks = [];
+
+/**
+ * Check if an error is a duplicate within the dedupe window
+ * Also cleans up expired entries
+ * @returns {boolean} true if this is a duplicate error
+ */
+function isDuplicateError(errorKey) {
+ const now = Date.now();
+ const lastSeen = recentErrors.get(errorKey);
+
+ // Clean up expired entries
+ for (const [key, timestamp] of recentErrors.entries()) {
+ if (now - timestamp > ERROR_DEDUPE_WINDOW) {
+ recentErrors.delete(key);
+ }
+ }
+
+ if (lastSeen && (now - lastSeen) < ERROR_DEDUPE_WINDOW) {
+ return true;
+ }
+
+ recentErrors.set(errorKey, now);
+ return false;
+}
+
/**
* Initialize auto-fixer event listeners
*/
export function initAutoFixer() {
errorEvents.on('error', async (error) => {
+ // Always handle AI provider errors (even if CoS not running)
+ if (error.code === 'AI_PROVIDER_EXECUTION_FAILED') {
+ await handleAIProviderError(error);
+ return;
+ }
+
if (shouldAutoFix(error)) {
await createAutoFixTask(error);
}
@@ -25,6 +58,68 @@ export function initAutoFixer() {
console.log('🔧 Auto-fixer initialized');
}
+/**
+ * Get pending autofix tasks (for CoS to pick up when it starts)
+ */
+export function getPendingAutoFixTasks() {
+ return [...pendingAutoFixTasks];
+}
+
+/**
+ * Clear pending autofix tasks after they've been processed
+ */
+export function clearPendingAutoFixTasks() {
+ pendingAutoFixTasks.length = 0;
+}
+
+/**
+ * Handle AI provider execution failures specifically
+ * These are always tracked and can create tasks even if CoS is not running
+ */
+async function handleAIProviderError(error) {
+ const ctx = error.context || {};
+ const errorKey = `${error.code}-${ctx.runId}`;
+
+ if (isDuplicateError(errorKey)) {
+ console.log(`⏭️ Skipping duplicate AI provider error: ${ctx.runId}`);
+ return;
+ }
+
+ console.log(`🤖 AI provider error detected: ${ctx.provider} - run ${ctx.runId}`);
+
+ // Build specialized context for AI provider errors
+ const context = buildAIProviderErrorContext(error);
+
+ const taskData = {
+ description: `Investigate AI provider failure: ${ctx.provider} (${ctx.model})`,
+ priority: 'MEDIUM',
+ context,
+ app: 'portos', // Associate with PortOS app
+ approvalRequired: true // Require user approval before investigating
+ };
+
+ // If CoS is running, create the task immediately
+ if (isRunning()) {
+ const task = await addTask(taskData, 'internal');
+ console.log(`✅ AI provider investigation task created: ${task.id}`);
+ return task;
+ }
+
+ // Otherwise, store for later pickup
+ console.log(`📋 CoS not running - queuing AI provider investigation task`);
+ pendingAutoFixTasks.push({
+ ...taskData,
+ createdAt: Date.now(),
+ error: {
+ code: error.code,
+ message: error.message,
+ context: ctx
+ }
+ });
+
+ return null;
+}
+
/**
* Determine if an error should trigger auto-fix
*/
@@ -39,26 +134,82 @@ function shouldAutoFix(error) {
return false;
}
- // Check for duplicate errors within dedupe window
const errorKey = `${error.code}-${error.message}`;
- const lastSeen = recentErrors.get(errorKey);
- const now = Date.now();
- if (lastSeen && (now - lastSeen) < ERROR_DEDUPE_WINDOW) {
+ if (isDuplicateError(errorKey)) {
console.log(`⏭️ Skipping duplicate error: ${error.code}`);
return false;
}
- recentErrors.set(errorKey, now);
+ return true;
+}
- // Clean up old entries
- for (const [key, timestamp] of recentErrors.entries()) {
- if (now - timestamp > ERROR_DEDUPE_WINDOW) {
- recentErrors.delete(key);
+/**
+ * Build detailed context for AI provider execution errors
+ */
+function buildAIProviderErrorContext(error) {
+ const ctx = error.context || {};
+ const lines = [
+ '# AI Provider Execution Failure',
+ '',
+ '## Run Details',
+ `- **Run ID:** ${ctx.runId || 'N/A'}`,
+ `- **Provider:** ${ctx.provider || 'Unknown'}`,
+ `- **Provider ID:** ${ctx.providerId || 'N/A'}`,
+ `- **Model:** ${ctx.model || 'N/A'}`,
+ `- **Exit Code:** ${ctx.exitCode ?? 'N/A'}`,
+ `- **Duration:** ${ctx.duration ? `${(ctx.duration / 1000).toFixed(1)}s` : 'N/A'}`,
+ `- **Workspace:** ${ctx.workspaceName || ctx.workspacePath || 'N/A'}`,
+ ''
+ ];
+
+ // Add error category if available
+ if (ctx.errorCategory) {
+ lines.push(`## Error Category: ${ctx.errorCategory}`);
+ if (ctx.suggestedFix) {
+ lines.push(`**Suggested Fix:** ${ctx.suggestedFix}`);
}
+ lines.push('');
}
- return true;
+ // Add error details
+ lines.push('## Error Details');
+ if (ctx.errorDetails) {
+ lines.push('```');
+ lines.push(ctx.errorDetails);
+ lines.push('```');
+ } else {
+ lines.push(error.message || 'No error details available');
+ }
+ lines.push('');
+
+ // Add prompt preview if available
+ if (ctx.promptPreview) {
+ lines.push('## Prompt Preview');
+ lines.push('```');
+ lines.push(ctx.promptPreview);
+ lines.push('```');
+ lines.push('');
+ }
+
+ // Add output tail if available (last part of output for debugging)
+ if (ctx.outputTail) {
+ lines.push('## Output Tail (last 2KB)');
+ lines.push('```');
+ lines.push(ctx.outputTail);
+ lines.push('```');
+ lines.push('');
+ }
+
+ lines.push('## Investigation Steps');
+ lines.push('1. Check if the AI provider is configured correctly in /devtools/providers');
+ lines.push('2. Verify API keys and endpoints are valid');
+ lines.push('3. Check server logs for additional context (pm2 logs portos-server)');
+ lines.push('4. If this is a CLI provider, verify the command is installed and accessible');
+ lines.push('5. Check for rate limiting or quota issues with the provider');
+ lines.push('6. Review the output tail for specific error messages');
+
+ return lines.join('\n');
}
/**
diff --git a/server/services/cos.js b/server/services/cos.js
index 3ffa1e27cc..d60e94bd8f 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -771,7 +771,16 @@ export async function updateAgent(agentId, updates) {
return null;
}
- state.agents[agentId] = { ...state.agents[agentId], ...updates };
+ // Merge metadata if present in updates
+ if (updates.metadata) {
+ state.agents[agentId] = {
+ ...state.agents[agentId],
+ ...updates,
+ metadata: { ...state.agents[agentId].metadata, ...updates.metadata }
+ };
+ } else {
+ state.agents[agentId] = { ...state.agents[agentId], ...updates };
+ }
await saveState(state);
cosEvents.emit('agent:updated', state.agents[agentId]);
@@ -803,6 +812,7 @@ export async function completeAgent(agentId, result = {}) {
await saveState(state);
cosEvents.emit('agent:completed', state.agents[agentId]);
+ cosEvents.emit('agent:updated', state.agents[agentId]);
// Save agent data to file for history
const agentDir = join(AGENTS_DIR, agentId);
@@ -887,10 +897,92 @@ export async function getAgent(agentId) {
* Terminate an agent (will be handled by spawner)
*/
export async function terminateAgent(agentId) {
+ // Emit event to kill the process FIRST
cosEvents.emit('agent:terminate', agentId);
+ // The spawner will handle marking the agent as completed after termination
return { success: true, agentId };
}
+/**
+ * Force kill an agent with SIGKILL (immediate, no graceful shutdown)
+ */
+export async function killAgent(agentId) {
+ const { killAgent: killAgentFromSpawner } = await import('./subAgentSpawner.js');
+ return killAgentFromSpawner(agentId);
+}
+
+/**
+ * Get process stats for an agent (CPU, memory)
+ */
+export async function getAgentProcessStats(agentId) {
+ const { getAgentProcessStats: getStatsFromSpawner } = await import('./subAgentSpawner.js');
+ return getStatsFromSpawner(agentId);
+}
+
+/**
+ * Check if a PID is still running
+ */
+async function isPidAlive(pid) {
+ if (!pid) return false;
+ const { exec } = await import('child_process');
+ const { promisify } = await import('util');
+ const execAsync = promisify(exec);
+ const result = await execAsync(`ps -p ${pid} -o pid= 2>/dev/null`).catch(() => ({ stdout: '' }));
+ return result.stdout.trim() !== '';
+}
+
+/**
+ * Cleanup zombie agents - agents marked as running but whose process is dead
+ */
+export async function cleanupZombieAgents() {
+ // Also check against activeAgents map from spawner
+ const { getActiveAgentIds } = await import('./subAgentSpawner.js');
+ const activeIds = getActiveAgentIds();
+
+ return withStateLock(async () => {
+ const state = await loadState();
+ const runningAgents = Object.values(state.agents).filter(a => a.status === 'running');
+ const cleaned = [];
+
+ for (const agent of runningAgents) {
+ let isZombie = false;
+
+ // If agent has a PID, check if it's still alive
+ if (agent.pid) {
+ const alive = await isPidAlive(agent.pid);
+ if (!alive) {
+ isZombie = true;
+ }
+ } else {
+ // No PID stored - check if it's in activeAgents map
+ // If not in map, it's a zombie from before PID tracking
+ if (!activeIds.includes(agent.id)) {
+ isZombie = true;
+ }
+ }
+
+ if (isZombie) {
+ console.log(`🧟 Zombie agent detected: ${agent.id} (PID ${agent.pid || 'unknown'} is dead)`);
+ state.agents[agent.id] = {
+ ...agent,
+ status: 'completed',
+ completedAt: new Date().toISOString(),
+ result: { success: false, error: 'Agent process was orphaned (server restart)' }
+ };
+ cleaned.push(agent.id);
+ }
+ }
+
+ if (cleaned.length > 0) {
+ await saveState(state);
+ console.log(`🧹 Cleaned up ${cleaned.length} zombie agents: ${cleaned.join(', ')}`);
+ cosEvents.emit('agents:changed', { action: 'zombie-cleanup', cleaned });
+ }
+
+ return { cleaned, count: cleaned.length };
+ });
+}
+
/**
* Delete a single agent from state
*/
@@ -1036,6 +1128,7 @@ export async function addTask(taskData, taskType = 'user') {
if (taskData.model) metadata.model = taskData.model;
if (taskData.provider) metadata.provider = taskData.provider;
if (taskData.app) metadata.app = taskData.app;
+ if (taskData.screenshots?.length > 0) metadata.screenshots = taskData.screenshots;
// Create the new task
const newTask = {
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
new file mode 100644
index 0000000000..18056da025
--- /dev/null
+++ b/server/services/cosRunnerClient.js
@@ -0,0 +1,300 @@
+/**
+ * CoS Runner Client
+ *
+ * Communicates with the standalone portos-cos PM2 process
+ * that manages agent spawning to prevent orphaned processes.
+ */
+
+import { io } from 'socket.io-client';
+
+const COS_RUNNER_URL = process.env.COS_RUNNER_URL || 'http://localhost:5558';
+
+// Socket.IO client for real-time events
+let socket = null;
+let eventHandlers = new Map();
+
+/**
+ * Initialize connection to CoS Runner
+ */
+export function initCosRunnerConnection() {
+ if (socket) return;
+
+ socket = io(COS_RUNNER_URL, {
+ reconnection: true,
+ reconnectionAttempts: Infinity,
+ reconnectionDelay: 1000
+ });
+
+ socket.on('connect', () => {
+ console.log('🔌 Connected to CoS Runner');
+ // Emit reconnect event so services can sync their state
+ const handler = eventHandlers.get('connection:ready');
+ if (handler) handler();
+ });
+
+ socket.on('disconnect', () => {
+ console.log('🔌 Disconnected from CoS Runner');
+ const handler = eventHandlers.get('connection:lost');
+ if (handler) handler();
+ });
+
+ // Forward events to registered handlers
+ socket.on('agent:output', (data) => {
+ const handler = eventHandlers.get('agent:output');
+ if (handler) handler(data);
+ });
+
+ socket.on('agent:completed', (data) => {
+ const handler = eventHandlers.get('agent:completed');
+ if (handler) handler(data);
+ });
+
+ socket.on('agent:error', (data) => {
+ const handler = eventHandlers.get('agent:error');
+ if (handler) handler(data);
+ });
+
+ // Forward devtools run events to registered handlers
+ socket.on('run:data', (data) => {
+ const handler = eventHandlers.get('run:data');
+ if (handler) handler(data);
+ });
+
+ socket.on('run:complete', (data) => {
+ const handler = eventHandlers.get('run:complete');
+ if (handler) handler(data);
+ });
+
+ socket.on('run:error', (data) => {
+ const handler = eventHandlers.get('run:error');
+ if (handler) handler(data);
+ });
+}
+
+/**
+ * Register event handler
+ */
+export function onCosRunnerEvent(event, handler) {
+ eventHandlers.set(event, handler);
+}
+
+/**
+ * Check if CoS Runner is available
+ */
+export async function isRunnerAvailable() {
+ const response = await fetch(`${COS_RUNNER_URL}/health`).catch(() => null);
+ if (!response || !response.ok) return false;
+ return true;
+}
+
+/**
+ * Get runner health status
+ */
+export async function getRunnerHealth() {
+ const response = await fetch(`${COS_RUNNER_URL}/health`).catch(() => null);
+ if (!response || !response.ok) {
+ return { available: false, error: 'Runner not available' };
+ }
+ const data = await response.json();
+ return { available: true, ...data };
+}
+
+/**
+ * Spawn an agent via the CoS Runner
+ */
+export async function spawnAgentViaRunner(options) {
+ const {
+ agentId,
+ taskId,
+ prompt,
+ workspacePath,
+ model,
+ envVars,
+ claudePath
+ } = options;
+
+ const response = await fetch(`${COS_RUNNER_URL}/spawn`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ agentId,
+ taskId,
+ prompt,
+ workspacePath,
+ model,
+ envVars,
+ claudePath
+ })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to spawn agent');
+ }
+
+ return response.json();
+}
+
+/**
+ * Get list of active agents from runner
+ */
+export async function getActiveAgentsFromRunner() {
+ const response = await fetch(`${COS_RUNNER_URL}/agents`);
+ if (!response.ok) {
+ throw new Error('Failed to get agents');
+ }
+ return response.json();
+}
+
+/**
+ * Terminate an agent via the runner (graceful SIGTERM with SIGKILL fallback)
+ */
+export async function terminateAgentViaRunner(agentId) {
+ const response = await fetch(`${COS_RUNNER_URL}/terminate/${agentId}`, {
+ method: 'POST'
+ });
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to terminate agent');
+ }
+ return response.json();
+}
+
+/**
+ * Force kill an agent via the runner (immediate SIGKILL)
+ */
+export async function killAgentViaRunner(agentId) {
+ const response = await fetch(`${COS_RUNNER_URL}/kill/${agentId}`, {
+ method: 'POST'
+ });
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to kill agent');
+ }
+ return response.json();
+}
+
+/**
+ * Get process stats for an agent
+ */
+export async function getAgentStatsFromRunner(agentId) {
+ const response = await fetch(`${COS_RUNNER_URL}/agents/${agentId}/stats`);
+ if (!response.ok) {
+ return null;
+ }
+ return response.json();
+}
+
+/**
+ * Terminate all agents via the runner
+ */
+export async function terminateAllAgentsViaRunner() {
+ const response = await fetch(`${COS_RUNNER_URL}/terminate-all`, {
+ method: 'POST'
+ });
+ if (!response.ok) {
+ throw new Error('Failed to terminate agents');
+ }
+ return response.json();
+}
+
+/**
+ * Get agent output from runner
+ */
+export async function getAgentOutputFromRunner(agentId) {
+ const response = await fetch(`${COS_RUNNER_URL}/agents/${agentId}/output`);
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to get agent output');
+ }
+ return response.json();
+}
+
+// ============================================
+// DEVTOOLS RUNS - CLI execution via runner
+// ============================================
+
+/**
+ * Execute a CLI run via the CoS Runner
+ */
+export async function executeCliRunViaRunner(options) {
+ const {
+ runId,
+ command,
+ args,
+ prompt,
+ workspacePath,
+ envVars,
+ timeout
+ } = options;
+
+ const response = await fetch(`${COS_RUNNER_URL}/run`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ runId,
+ command,
+ args,
+ prompt,
+ workspacePath,
+ envVars,
+ timeout
+ })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to execute run');
+ }
+
+ return response.json();
+}
+
+/**
+ * Get list of active runs from runner
+ */
+export async function getActiveRunsFromRunner() {
+ const response = await fetch(`${COS_RUNNER_URL}/runs`);
+ if (!response.ok) {
+ throw new Error('Failed to get runs');
+ }
+ return response.json();
+}
+
+/**
+ * Check if a run is active in the runner
+ */
+export async function isRunActiveInRunner(runId) {
+ const response = await fetch(`${COS_RUNNER_URL}/runs/${runId}/active`);
+ if (!response.ok) {
+ return false;
+ }
+ const data = await response.json();
+ return data.active;
+}
+
+/**
+ * Get run output from runner
+ */
+export async function getRunOutputFromRunner(runId) {
+ const response = await fetch(`${COS_RUNNER_URL}/runs/${runId}/output`);
+ if (!response.ok) {
+ return null;
+ }
+ const data = await response.json();
+ return data.output;
+}
+
+/**
+ * Stop a run via the runner
+ */
+export async function stopRunViaRunner(runId) {
+ const response = await fetch(`${COS_RUNNER_URL}/runs/${runId}/stop`, {
+ method: 'POST'
+ });
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to stop run');
+ }
+ return response.json();
+}
diff --git a/server/services/runner.js b/server/services/runner.js
index 5c47f1b1ef..53b4bc1726 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -1,19 +1,271 @@
-import { spawn } from 'child_process';
import { mkdir, writeFile, readFile, readdir, rm } from 'fs/promises';
import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
import { getProviderById } from './providers.js';
+import { errorEvents } from '../lib/errorHandler.js';
+import {
+ isRunnerAvailable,
+ executeCliRunViaRunner,
+ isRunActiveInRunner,
+ stopRunViaRunner,
+ initCosRunnerConnection,
+ onCosRunnerEvent
+} from './cosRunnerClient.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const DATA_DIR = join(__dirname, '../../data');
const RUNS_DIR = join(DATA_DIR, 'runs');
-// Track active runs for cancellation
+// Track active runs for cancellation (only used for API runs, CLI runs are in cos-runner)
const activeRuns = new Map();
+// Track pending callbacks for runs delegated to cos-runner
+const pendingRunCallbacks = new Map();
+
+// Initialize cos-runner connection and event handlers
+let cosRunnerInitialized = false;
+
+function initRunnerEvents() {
+ if (cosRunnerInitialized) return;
+ cosRunnerInitialized = true;
+
+ initCosRunnerConnection();
+
+ // Handle reconnection - sync active runs to detect completions we may have missed
+ onCosRunnerEvent('connection:ready', async () => {
+ await syncActiveRuns();
+ });
+
+ // Handle run output from cos-runner
+ onCosRunnerEvent('run:data', ({ runId, text }) => {
+ const callbacks = pendingRunCallbacks.get(runId);
+ if (callbacks?.onData) {
+ callbacks.onData(text);
+ }
+ });
+
+ // Handle run completion from cos-runner
+ onCosRunnerEvent('run:complete', async ({ runId, exitCode, success, duration }) => {
+ const callbacks = pendingRunCallbacks.get(runId);
+ if (callbacks) {
+ // Read the final metadata and update it
+ const metadataPath = join(RUNS_DIR, runId, 'metadata.json');
+ const outputPath = join(RUNS_DIR, runId, 'output.txt');
+
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+ const output = await readFile(outputPath, 'utf-8').catch(() => '');
+
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = duration;
+ metadata.exitCode = exitCode;
+ metadata.success = success;
+ metadata.outputSize = Buffer.byteLength(output);
+
+ // Extract and store error details for failed runs
+ if (!success) {
+ const errorDetails = extractErrorDetails(output, exitCode);
+ const { category, suggestion } = categorizeError(output, exitCode);
+ metadata.error = errorDetails;
+ metadata.errorDetails = errorDetails;
+ metadata.errorCategory = category;
+ metadata.suggestedFix = suggestion;
+ console.log(`🔴 Run ${runId} failed with exit code ${exitCode}, category: ${category}`);
+ emitProviderError(metadata, errorDetails, output);
+ }
+
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+
+ if (callbacks.onComplete) {
+ callbacks.onComplete(metadata);
+ }
+
+ pendingRunCallbacks.delete(runId);
+ }
+ });
+
+ // Handle run errors from cos-runner
+ onCosRunnerEvent('run:error', async ({ runId, error }) => {
+ const callbacks = pendingRunCallbacks.get(runId);
+ if (callbacks) {
+ const metadataPath = join(RUNS_DIR, runId, 'metadata.json');
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+
+ metadata.endTime = new Date().toISOString();
+ metadata.success = false;
+ metadata.error = error;
+ metadata.errorDetails = error;
+ const { category, suggestion } = categorizeError(error, -1);
+ metadata.errorCategory = category;
+ metadata.suggestedFix = suggestion;
+
+ emitProviderError(metadata, error, '');
+
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+
+ if (callbacks.onComplete) {
+ callbacks.onComplete(metadata);
+ }
+
+ pendingRunCallbacks.delete(runId);
+ }
+ });
+}
+
+/**
+ * Categorize errors into actionable types
+ */
+function categorizeError(output, exitCode) {
+ const lowerOutput = output.toLowerCase();
+
+ // API/Model errors - check specific patterns first
+ if (lowerOutput.includes('not_found_error') && lowerOutput.includes('model:')) {
+ return { category: 'model_not_found', suggestion: 'The specified model does not exist - check AI provider settings and select a valid model' };
+ }
+ if (lowerOutput.includes('model:') && (lowerOutput.includes('not_found') || lowerOutput.includes('not found'))) {
+ return { category: 'model_not_found', suggestion: 'Check AI provider settings - the model may be invalid or deprecated' };
+ }
+ if (lowerOutput.includes('api error') || lowerOutput.includes('api_error')) {
+ return { category: 'api_error', suggestion: 'API request failed - check provider endpoint and API key' };
+ }
+
+ // Authentication errors
+ if (lowerOutput.includes('unauthorized') || lowerOutput.includes('401') || lowerOutput.includes('invalid_api_key') || lowerOutput.includes('authentication failed')) {
+ return { category: 'auth_error', suggestion: 'Authentication failed - verify API key is valid and has correct permissions' };
+ }
+
+ // Rate limiting
+ if (lowerOutput.includes('rate limit') || lowerOutput.includes('429') || lowerOutput.includes('too many requests') || lowerOutput.includes('rate_limit_error')) {
+ return { category: 'rate_limit', suggestion: 'Rate limited - wait before retrying or upgrade API plan' };
+ }
+
+ // Quota/billing
+ if (lowerOutput.includes('quota') || lowerOutput.includes('billing') || lowerOutput.includes('exceeded') || lowerOutput.includes('insufficient')) {
+ return { category: 'quota_exceeded', suggestion: 'Quota or billing issue - check your API account' };
+ }
+
+ // Network errors
+ if (lowerOutput.includes('connection refused') || lowerOutput.includes('econnrefused') || lowerOutput.includes('network error')) {
+ return { category: 'network_error', suggestion: 'Network error - check internet connection and endpoint URL' };
+ }
+ if (lowerOutput.includes('timeout') || lowerOutput.includes('etimedout')) {
+ return { category: 'timeout', suggestion: 'Request timed out - try again or increase timeout setting' };
+ }
+
+ // Command/CLI errors - be more specific to avoid false positives
+ if (lowerOutput.includes('command not found') || lowerOutput.includes('enoent')) {
+ return { category: 'command_not_found', suggestion: 'Command not found - verify CLI tool is installed' };
+ }
+ if (lowerOutput.includes('permission denied')) {
+ return { category: 'permission_denied', suggestion: 'Permission denied - check file/directory permissions' };
+ }
+
+ // Process signals
+ if (exitCode === 143) {
+ return { category: 'terminated', suggestion: 'Process was terminated (SIGTERM) - likely hit timeout or was manually stopped' };
+ }
+ if (exitCode === 137) {
+ return { category: 'killed', suggestion: 'Process was killed (SIGKILL) - likely out of memory or force stopped' };
+ }
+ if (exitCode === 130) {
+ return { category: 'interrupted', suggestion: 'Process was interrupted (SIGINT)' };
+ }
+
+ return { category: 'unknown', suggestion: 'Check the output above for specific error details' };
+}
+
+/**
+ * Extract meaningful error details from CLI output
+ * Looks for common error patterns and extracts actionable info
+ */
+function extractErrorDetails(output, exitCode) {
+ const lines = output.split('\n').filter(l => l.trim());
+ const lastLines = lines.slice(-20); // Last 20 lines often contain error info
+
+ // Try to extract error message from JSON-like structure
+ // This handles API responses like: {"type":"error","error":{"type":"not_found_error","message":"model: codex"}}
+ const messageMatch = output.match(/"message"\s*:\s*"([^"]+)"/);
+ if (messageMatch) {
+ // Also try to get the error type for more context
+ const typeMatch = output.match(/"type"\s*:\s*"([^"]+_error)"/);
+ if (typeMatch) {
+ return `${typeMatch[1]}: ${messageMatch[1]}`;
+ }
+ return messageMatch[1];
+ }
+
+ // Look for common error patterns
+ const errorPatterns = [
+ /API Error[:\s]+\d+\s*(.+)/i, // "API Error: 404 {...}"
+ /API Error[:\s]+(.+)/i,
+ /error[:\s]*\{(.+)\}/i,
+ /error[:\s]+(.+)/i,
+ /failed[:\s]+(.+)/i,
+ /exception[:\s]+(.+)/i,
+ /fatal[:\s]+(.+)/i,
+ /not found[:\s]+(.+)/i,
+ /permission denied[:\s]+(.+)/i,
+ /connection refused/i,
+ /timeout/i,
+ /rate limit/i,
+ /invalid.*key/i,
+ /unauthorized/i,
+ /authentication failed/i,
+ /"message"[:\s]*"([^"]+)"/i,
+ /"error"[:\s]*"([^"]+)"/i
+ ];
+
+ const matchedErrors = [];
+ for (const line of lastLines) {
+ for (const pattern of errorPatterns) {
+ if (pattern.test(line)) {
+ matchedErrors.push(line.trim());
+ break;
+ }
+ }
+ }
+
+ // If we found specific errors, return them; otherwise return last few lines
+ if (matchedErrors.length > 0) {
+ return matchedErrors.slice(0, 5).join('\n');
+ }
+
+ // Return last 5 non-empty lines as fallback
+ return lastLines.slice(-5).join('\n') || `Process exited with code ${exitCode}`;
+}
+
+/**
+ * Emit an AI provider execution error for autofix handling
+ */
+function emitProviderError(metadata, errorDetails, output) {
+ console.log(`🔴 AI provider execution failed: ${metadata.providerName} - ${metadata.error}`);
+
+ errorEvents.emit('error', {
+ code: 'AI_PROVIDER_EXECUTION_FAILED',
+ message: `AI provider ${metadata.providerName} execution failed: ${metadata.error}`,
+ severity: 'error',
+ canAutoFix: true,
+ timestamp: Date.now(),
+ context: {
+ runId: metadata.id,
+ provider: metadata.providerName,
+ providerId: metadata.providerId,
+ model: metadata.model,
+ exitCode: metadata.exitCode,
+ duration: metadata.duration,
+ workspacePath: metadata.workspacePath,
+ workspaceName: metadata.workspaceName,
+ errorDetails: errorDetails,
+ errorCategory: metadata.errorCategory,
+ suggestedFix: metadata.suggestedFix,
+ promptPreview: metadata.prompt,
+ outputTail: output ? output.slice(-2000) : null // Last 2KB of output for context
+ }
+ });
+}
+
async function ensureRunsDir() {
if (!existsSync(RUNS_DIR)) {
await mkdir(RUNS_DIR, { recursive: true });
@@ -70,88 +322,62 @@ export async function createRun(options) {
}
export async function executeCliRun(runId, provider, prompt, workspacePath, onData, onComplete) {
- const runDir = join(RUNS_DIR, runId);
- const outputPath = join(runDir, 'output.txt');
- const metadataPath = join(runDir, 'metadata.json');
+ // Initialize runner events if not already done
+ initRunnerEvents();
- // Build command args
- const args = [...(provider.args || [])];
+ // Check if cos-runner is available
+ const runnerAvailable = await isRunnerAvailable().catch(() => false);
- // For claude CLI, the prompt goes at the end
- if (provider.command === 'claude') {
- args.push(prompt);
- } else {
- // For other CLIs, try stdin or args
- args.push(prompt);
+ if (!runnerAvailable) {
+ // Fall back to error - cos-runner must be running
+ console.error(`❌ CoS runner not available for run ${runId}`);
+ const metadataPath = join(RUNS_DIR, runId, 'metadata.json');
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+ metadata.endTime = new Date().toISOString();
+ metadata.success = false;
+ metadata.error = 'CoS runner service not available';
+ metadata.errorDetails = 'The portos-cos process is not running. Start it with: pm2 start ecosystem.config.cjs';
+ metadata.errorCategory = 'service_unavailable';
+ metadata.suggestedFix = 'Start the portos-cos process using PM2';
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+ onComplete?.(metadata);
+ return runId;
}
- const startTime = Date.now();
- let output = '';
-
- console.log(`🔧 Spawning: ${provider.command} ${args.join(' ')} in ${workspacePath || process.cwd()}`);
-
- const child = spawn(provider.command, args, {
- cwd: workspacePath || process.cwd(),
- env: { ...process.env, ...provider.envVars },
- stdio: ['pipe', 'pipe', 'pipe']
- });
-
- console.log(`🔧 Child process spawned, pid: ${child.pid}`);
- activeRuns.set(runId, child);
-
- const appendOutput = async (data) => {
- const text = data.toString();
- console.log(`📥 Received ${text.length} chars from child process`);
- output += text;
- await writeFile(outputPath, output);
- onData?.(text);
- };
-
- child.stdout.on('data', appendOutput);
- child.stderr.on('data', appendOutput);
-
- child.on('spawn', () => {
- console.log(`✓ Child process spawned successfully`);
- });
-
- child.on('close', async (code) => {
- activeRuns.delete(runId);
-
- const endTime = Date.now();
- const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+ // Build command args (without prompt - cos-runner adds it)
+ const args = [...(provider.args || [])];
- metadata.endTime = new Date().toISOString();
- metadata.duration = endTime - startTime;
- metadata.exitCode = code;
- metadata.success = code === 0;
- metadata.outputSize = Buffer.byteLength(output);
+ console.log(`🔧 Delegating run ${runId} to cos-runner: ${provider.command} ${args.join(' ')}`);
- await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
- onComplete?.(metadata);
- });
+ // Store callbacks for when cos-runner reports completion
+ pendingRunCallbacks.set(runId, { onData, onComplete });
- child.on('error', async (err) => {
- activeRuns.delete(runId);
+ // Execute via cos-runner
+ await executeCliRunViaRunner({
+ runId,
+ command: provider.command,
+ args,
+ prompt,
+ workspacePath: workspacePath || process.cwd(),
+ envVars: provider.envVars || {},
+ timeout: provider.timeout
+ }).catch(async (err) => {
+ console.error(`❌ Failed to delegate run ${runId} to cos-runner: ${err.message}`);
+ pendingRunCallbacks.delete(runId);
- const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+ const metadataPath = join(RUNS_DIR, runId, 'metadata.json');
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
metadata.endTime = new Date().toISOString();
- metadata.duration = Date.now() - startTime;
metadata.success = false;
metadata.error = err.message;
-
+ metadata.errorDetails = err.message;
+ const { category, suggestion } = categorizeError(err.message, -1);
+ metadata.errorCategory = category;
+ metadata.suggestedFix = suggestion;
await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
onComplete?.(metadata);
});
- // Set timeout
- if (provider.timeout) {
- setTimeout(() => {
- if (activeRuns.has(runId)) {
- child.kill('SIGTERM');
- }
- }, provider.timeout);
- }
-
return runId;
}
@@ -190,7 +416,34 @@ export async function executeApiRun(runId, provider, model, prompt, workspacePat
metadata.endTime = new Date().toISOString();
metadata.duration = Date.now() - startTime;
metadata.success = false;
- metadata.error = response.error || `API error: ${response.status}`;
+
+ // Try to extract detailed error info from response
+ let errorDetails = response.error || `API error: ${response.status}`;
+ let responseBody = null;
+ if (response.text) {
+ responseBody = await response.text().catch(() => null);
+ if (responseBody) {
+ // Try to parse as JSON for structured error
+ const parsed = JSON.parse(responseBody).catch?.(() => null);
+ if (parsed?.error?.message) {
+ errorDetails = `${response.status}: ${parsed.error.message}`;
+ } else if (parsed?.message) {
+ errorDetails = `${response.status}: ${parsed.message}`;
+ } else if (responseBody.length < 500) {
+ errorDetails = `${response.status}: ${responseBody}`;
+ }
+ }
+ }
+
+ metadata.error = errorDetails;
+ metadata.errorDetails = errorDetails;
+ const { category, suggestion } = categorizeError(errorDetails, response.status || -1);
+ metadata.errorCategory = category;
+ metadata.suggestedFix = suggestion;
+
+ // Emit error event for autofix system
+ emitProviderError(metadata, errorDetails, responseBody);
+
await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
onComplete?.(metadata);
return runId;
@@ -241,6 +494,14 @@ export async function executeApiRun(runId, provider, model, prompt, workspacePat
metadata.duration = Date.now() - startTime;
metadata.success = false;
metadata.error = err.message;
+ metadata.errorDetails = err.message;
+ const { category, suggestion } = categorizeError(err.message, -1);
+ metadata.errorCategory = category;
+ metadata.suggestedFix = suggestion;
+
+ // Emit error event for autofix system
+ emitProviderError(metadata, err.message, output);
+
await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
onComplete?.(metadata);
});
@@ -249,21 +510,29 @@ export async function executeApiRun(runId, provider, model, prompt, workspacePat
}
export async function stopRun(runId) {
+ // Check if it's a local API run
const active = activeRuns.get(runId);
- if (!active) {
- return false;
+ if (active) {
+ if (active.kill) {
+ // It's a child process
+ active.kill('SIGTERM');
+ } else if (active.abort) {
+ // It's an AbortController
+ active.abort();
+ }
+ activeRuns.delete(runId);
+ return true;
}
- if (active.kill) {
- // It's a child process
- active.kill('SIGTERM');
- } else if (active.abort) {
- // It's an AbortController
- active.abort();
+ // Check if it's a CLI run in cos-runner
+ const inRunner = await isRunActiveInRunner(runId).catch(() => false);
+ if (inRunner) {
+ await stopRunViaRunner(runId).catch(() => {});
+ pendingRunCallbacks.delete(runId);
+ return true;
}
- activeRuns.delete(runId);
- return true;
+ return false;
}
export async function getRun(runId) {
@@ -339,6 +608,95 @@ export async function deleteRun(runId) {
return true;
}
-export function isRunActive(runId) {
- return activeRuns.has(runId);
+export async function deleteFailedRuns() {
+ await ensureRunsDir();
+
+ const entries = await readdir(RUNS_DIR, { withFileTypes: true });
+ const runIds = entries.filter(e => e.isDirectory()).map(e => e.name);
+
+ let deletedCount = 0;
+ for (const runId of runIds) {
+ const metadataPath = join(RUNS_DIR, runId, 'metadata.json');
+ if (existsSync(metadataPath)) {
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+ if (metadata.success === false) {
+ await rm(join(RUNS_DIR, runId), { recursive: true });
+ deletedCount++;
+ }
+ }
+ }
+
+ return deletedCount;
+}
+
+export async function isRunActive(runId) {
+ // Check local API runs first
+ if (activeRuns.has(runId)) {
+ return true;
+ }
+ // Check if it's a CLI run in cos-runner
+ if (pendingRunCallbacks.has(runId)) {
+ return true;
+ }
+ // Double-check with cos-runner (in case of reconnect)
+ return isRunActiveInRunner(runId).catch(() => false);
+}
+
+/**
+ * Sync active runs from cos-runner on reconnection
+ * This handles runs that may have completed while we were disconnected
+ */
+async function syncActiveRuns() {
+ // Check all pending runs to see if they're still active in the runner
+ const pendingRunIds = Array.from(pendingRunCallbacks.keys());
+ if (pendingRunIds.length === 0) {
+ return;
+ }
+
+ console.log(`🔄 Syncing ${pendingRunIds.length} pending runs with cos-runner...`);
+
+ // Get list of active runs from the runner
+ const activeInRunner = await getActiveRunsFromRunner().catch(() => []);
+ const activeRunIds = new Set(activeInRunner.map(r => r.id));
+
+ // Check for runs that have completed while we were disconnected
+ for (const runId of pendingRunIds) {
+ if (!activeRunIds.has(runId)) {
+ // This run is no longer active in the runner - it may have completed
+ // Check if we have output written to disk (cos-runner writes output.txt on completion)
+ const outputPath = join(RUNS_DIR, runId, 'output.txt');
+ const metadataPath = join(RUNS_DIR, runId, 'metadata.json');
+
+ if (existsSync(outputPath) && existsSync(metadataPath)) {
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+
+ // If endTime is set, the run completed - we missed the event
+ if (metadata.endTime) {
+ console.log(`📥 Recovered completed run ${runId} (completed while disconnected)`);
+ const callbacks = pendingRunCallbacks.get(runId);
+ if (callbacks?.onComplete) {
+ callbacks.onComplete(metadata);
+ }
+ pendingRunCallbacks.delete(runId);
+ } else {
+ // Run output exists but no endTime - run is likely stuck or orphaned
+ // Mark it as failed
+ console.log(`⚠️ Run ${runId} appears orphaned - marking as failed`);
+ const output = await readFile(outputPath, 'utf-8').catch(() => '');
+ metadata.endTime = new Date().toISOString();
+ metadata.success = false;
+ metadata.error = 'Run was orphaned (process ended without proper completion)';
+ metadata.errorCategory = 'orphaned';
+ metadata.suggestedFix = 'The run process ended unexpectedly. Try again.';
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+
+ const callbacks = pendingRunCallbacks.get(runId);
+ if (callbacks?.onComplete) {
+ callbacks.onComplete(metadata);
+ }
+ pendingRunCallbacks.delete(runId);
+ }
+ }
+ }
+ }
}
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index f56e054e30..17f0673840 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -14,6 +14,7 @@ import { existsSync } from 'fs';
import { v4 as uuidv4 } from 'uuid';
import { cosEvents, registerAgent, updateAgent, completeAgent, appendAgentOutput, getConfig, updateTask, addTask } from './cos.js';
import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';
+import { isRunnerAvailable, spawnAgentViaRunner, terminateAgentViaRunner, killAgentViaRunner, getAgentStatsFromRunner, initCosRunnerConnection, onCosRunnerEvent, getActiveAgentsFromRunner } from './cosRunnerClient.js';
/**
* Emit a log event for UI display (mirrors cos.js helper)
@@ -84,9 +85,13 @@ function selectModelForTask(task, provider) {
return { model: provider.heavyModel || provider.mediumModel || provider.defaultModel, tier: 'heavy', reason: 'long-context' };
}
- // Simple/quick tasks → haiku/light
- if (/fix typo|update text|simple|rename|comment|documentation|readme|format/.test(desc) || contextLen < 100) {
- return { model: provider.lightModel || provider.defaultModel, tier: 'light', reason: 'simple-task' };
+ // Detect coding/development tasks - these should NEVER use light model
+ const isCodingTask = /\b(fix|bug|implement|develop|code|refactor|test|feature|function|class|module|api|endpoint|component|service|route|schema|migration|script|build|deploy|debug|error|exception|crash|issue|patch)\b/.test(desc);
+
+ // Simple/quick tasks → haiku/light (ONLY for non-coding tasks)
+ // Light model is reserved for documentation, text updates, and formatting only
+ if (!isCodingTask && /fix typo|update text|update docs|edit readme|update readme|write docs|documentation only|format text/.test(desc)) {
+ return { model: provider.lightModel || provider.defaultModel, tier: 'light', reason: 'documentation-task' };
}
// Standard tasks → sonnet/medium (default)
@@ -136,7 +141,9 @@ async function createAgentRun(agentId, task, model, provider, workspacePath) {
/**
* Complete a run entry with final results
*/
-async function completeAgentRun(runId, output, exitCode, duration, error = null) {
+async function completeAgentRun(runId, output, exitCode, duration, errorAnalysis = null) {
+ if (!runId) return; // Skip if no runId (e.g., agent recovered after restart)
+
const runDir = join(RUNS_DIR, runId);
const metaPath = join(runDir, 'metadata.json');
@@ -147,16 +154,100 @@ async function completeAgentRun(runId, output, exitCode, duration, error = null)
metadata.duration = duration;
metadata.exitCode = exitCode;
metadata.success = exitCode === 0;
- metadata.error = error;
metadata.outputSize = Buffer.byteLength(output || '');
+ // Store error details - extract from output if no analysis provided
+ if (exitCode !== 0) {
+ const errorInfo = errorAnalysis || extractErrorFromOutput(output, exitCode);
+ metadata.error = errorInfo.message || `Process exited with code ${exitCode}`;
+ metadata.errorDetails = errorInfo.details || metadata.error;
+ metadata.errorCategory = errorInfo.category || 'unknown';
+ metadata.suggestedFix = errorInfo.suggestedFix || null;
+ }
+
await writeFile(metaPath, JSON.stringify(metadata, null, 2));
await writeFile(join(runDir, 'output.txt'), output || '');
}
+/**
+ * Extract error information from output when no pattern matches
+ */
+function extractErrorFromOutput(output, exitCode) {
+ if (!output || output.trim().length === 0) {
+ // Map common exit codes to readable messages
+ const exitCodeMessages = {
+ 1: 'General error',
+ 2: 'Misuse of shell command',
+ 126: 'Command invoked cannot execute (permission or not executable)',
+ 127: 'Command not found',
+ 128: 'Invalid exit argument',
+ 130: 'Script terminated by Ctrl+C',
+ 137: 'Process killed (SIGKILL)',
+ 143: 'Process terminated (SIGTERM - likely timeout)',
+ 255: 'Exit status out of range'
+ };
+ const codeMsg = exitCodeMessages[exitCode] || `Unknown error`;
+ return {
+ message: `${codeMsg} (exit code ${exitCode})`,
+ details: `Process exited with code ${exitCode}. No output was captured.`,
+ category: exitCode === 143 ? 'timeout' : 'unknown'
+ };
+ }
+
+ const lines = output.split('\n').filter(l => l.trim());
+ const lastLines = lines.slice(-20);
+
+ // Look for common error patterns
+ const errorPatterns = [
+ { pattern: /API Error:\s*(\d+)/i, category: 'api-error' },
+ { pattern: /error[:\s]+(.+)/i, category: 'error' },
+ { pattern: /failed[:\s]+(.+)/i, category: 'failure' },
+ { pattern: /exception[:\s]+(.+)/i, category: 'exception' },
+ { pattern: /fatal[:\s]+(.+)/i, category: 'fatal' },
+ { pattern: /not found/i, category: 'not-found' },
+ { pattern: /permission denied/i, category: 'permission' },
+ { pattern: /connection refused/i, category: 'connection' },
+ { pattern: /timeout/i, category: 'timeout' },
+ { pattern: /rate limit/i, category: 'rate-limit' },
+ { pattern: /invalid.*key/i, category: 'auth' },
+ { pattern: /unauthorized/i, category: 'auth' },
+ { pattern: /authentication failed/i, category: 'auth' }
+ ];
+
+ const matchedErrors = [];
+ let category = 'unknown';
+ for (const line of lastLines) {
+ for (const { pattern, category: cat } of errorPatterns) {
+ if (pattern.test(line)) {
+ matchedErrors.push(line.trim());
+ if (category === 'unknown') category = cat;
+ break;
+ }
+ }
+ }
+
+ // Use matched errors or fallback to last lines
+ const errorLines = matchedErrors.length > 0
+ ? matchedErrors.slice(0, 5)
+ : lastLines.slice(-5);
+
+ return {
+ message: errorLines[0] || `Process exited with code ${exitCode}`,
+ details: errorLines.join('\n') || `Process exited with code ${exitCode}`,
+ category
+ };
+}
+
// Active agent processes
const activeAgents = new Map();
+/**
+ * Get list of active agent IDs (for zombie detection)
+ */
+export function getActiveAgentIds() {
+ return Array.from(activeAgents.keys());
+}
+
/**
* Error patterns that warrant investigation tasks
*/
@@ -283,10 +374,67 @@ Review the error, fix the configuration or code issue, and retry the original ta
return investigationTask;
}
+// Track if using runner mode
+let useRunner = false;
+
/**
* Initialize the spawner - listen for task:ready events
*/
-export function initSpawner() {
+export async function initSpawner() {
+ // Check if CoS Runner is available
+ useRunner = await isRunnerAvailable();
+
+ if (useRunner) {
+ console.log('🤖 Sub-agent spawner initialized (using CoS Runner)');
+ initCosRunnerConnection();
+
+ // Sync any agents that were running before server restart
+ const synced = await syncRunnerAgents();
+ if (synced > 0) {
+ console.log(`🔄 Recovered ${synced} agents from CoS Runner`);
+ }
+
+ // Set up event handlers for runner events
+ onCosRunnerEvent('agent:output', async (data) => {
+ const { agentId, text } = data;
+ await appendAgentOutput(agentId, text);
+
+ // Update phase on first output
+ const agent = runnerAgents.get(agentId);
+ if (agent && !agent.hasStartedWorking) {
+ agent.hasStartedWorking = true;
+ clearTimeout(agent.initializationTimeout);
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });
+ }
+
+ });
+
+ onCosRunnerEvent('agent:completed', async (data) => {
+ const { agentId, taskId, exitCode, success, duration, outputLength } = data;
+ const agent = runnerAgents.get(agentId);
+ if (agent) {
+ clearTimeout(agent.initializationTimeout);
+ }
+ await handleAgentCompletion(agentId, exitCode, success, duration);
+ });
+
+ onCosRunnerEvent('agent:error', async (data) => {
+ const { agentId, error } = data;
+ console.error(`❌ Agent ${agentId} error from runner: ${error}`);
+ cosEvents.emit('agent:error', { agentId, error });
+ const agent = runnerAgents.get(agentId);
+ if (agent) {
+ clearTimeout(agent.initializationTimeout);
+ await completeAgent(agentId, { success: false, error });
+ await completeAgentRun(agent.runId, '', 1, 0, { message: error, category: 'runner-error' });
+ runnerAgents.delete(agentId);
+ }
+ });
+ } else {
+ console.log('🤖 Sub-agent spawner initialized (direct mode - CoS Runner not available)');
+ }
+
cosEvents.on('task:ready', async (task) => {
await spawnAgentForTask(task);
});
@@ -294,8 +442,62 @@ export function initSpawner() {
cosEvents.on('agent:terminate', async (agentId) => {
await terminateAgent(agentId);
});
+}
+
+// Track runner-spawned agents
+const runnerAgents = new Map();
+
+/**
+ * Sync running agents from the runner (recovery after server restart)
+ * This allows us to receive completion events for agents spawned before restart
+ */
+async function syncRunnerAgents() {
+ const agents = await getActiveAgentsFromRunner().catch(() => []);
+ if (agents.length === 0) return 0;
+
+ console.log(`🔄 Syncing ${agents.length} running agents from CoS Runner`);
+
+ // Get all tasks to find task data for each agent
+ const { getAllTasks } = await import('./cos.js');
+ const allTasksData = await getAllTasks().catch(() => ({ user: {}, cos: {} }));
+
+ // Build a task lookup map from all task sources
+ const taskMap = new Map();
+ const addTasks = (groupedTasks) => {
+ if (!groupedTasks) return;
+ for (const tasks of Object.values(groupedTasks)) {
+ if (Array.isArray(tasks)) {
+ for (const task of tasks) {
+ taskMap.set(task.id, task);
+ }
+ }
+ }
+ };
+
+ addTasks(allTasksData.user?.grouped);
+ addTasks(allTasksData.cos?.grouped);
- console.log('🤖 Sub-agent spawner initialized');
+ let syncedCount = 0;
+ for (const agent of agents) {
+ // Only sync if not already tracked
+ if (!runnerAgents.has(agent.id)) {
+ // Try to find the task in our lookup map
+ const task = taskMap.get(agent.taskId);
+
+ runnerAgents.set(agent.id, {
+ taskId: agent.taskId,
+ task: task || { id: agent.taskId, description: 'Recovered from runner' },
+ runId: null, // Run tracking may be lost on restart
+ model: null,
+ hasStartedWorking: true,
+ startedAt: agent.startedAt
+ });
+ console.log(`🔄 Recovered agent ${agent.id} (task: ${agent.taskId})`);
+ syncedCount++;
+ }
+ }
+
+ return syncedCount;
}
/**
@@ -344,9 +546,6 @@ export async function spawnAgentForTask(task) {
// Create run entry for usage tracking
const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath);
- // Build spawn arguments with model selection
- const spawnArgs = buildSpawnArgs(config, selectedModel);
-
// Register the agent with model info
await registerAgent(agentId, task.id, {
workspacePath,
@@ -357,7 +556,8 @@ export async function spawnAgentForTask(task) {
modelTier: modelSelection.tier,
modelReason: modelSelection.reason,
runId,
- phase: 'initializing'
+ phase: 'initializing',
+ useRunner
});
emitLog('info', `Agent ${agentId} initializing...`, { agentId, taskId: task.id });
@@ -368,37 +568,168 @@ export async function spawnAgentForTask(task) {
// Spawn the Claude CLI process using full path for PM2 compatibility
const claudePath = process.env.CLAUDE_PATH || '/Users/antic/.nvm/versions/node/v25.2.1/bin/claude';
- // Build full command string for display
+ emitLog('success', `Spawning agent for task ${task.id}`, { agentId, model: selectedModel, mode: useRunner ? 'runner' : 'direct' });
+
+ // Use CoS Runner if available, otherwise spawn directly
+ if (useRunner) {
+ return spawnViaRunner(agentId, task, prompt, workspacePath, selectedModel, provider, runId, claudePath);
+ }
+
+ // Direct spawn mode (fallback)
+ return spawnDirectly(agentId, task, prompt, workspacePath, selectedModel, provider, runId, claudePath, agentDir);
+}
+
+/**
+ * Spawn agent via CoS Runner (isolated PM2 process)
+ */
+async function spawnViaRunner(agentId, task, prompt, workspacePath, model, provider, runId, claudePath) {
+ // Store tracking info for runner-spawned agents
+ const agentInfo = {
+ taskId: task.id,
+ task,
+ runId,
+ model,
+ hasStartedWorking: false,
+ startedAt: Date.now(),
+ initializationTimeout: null
+ };
+ runnerAgents.set(agentId, agentInfo);
+
+ // If no output after 3 seconds, transition from initializing to working to show progress
+ agentInfo.initializationTimeout = setTimeout(async () => {
+ const agent = runnerAgents.get(agentId);
+ if (agent && !agent.hasStartedWorking) {
+ agent.hasStartedWorking = true;
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });
+ }
+ }, 3000);
+
+ const result = await spawnAgentViaRunner({
+ agentId,
+ taskId: task.id,
+ prompt,
+ workspacePath,
+ model,
+ envVars: provider.envVars,
+ claudePath
+ });
+
+ // Store PID in persisted state for zombie detection
+ await updateAgent(agentId, { pid: result.pid });
+
+ emitLog('info', `Agent ${agentId} spawned via runner (PID: ${result.pid})`, { agentId, pid: result.pid });
+ return agentId;
+}
+
+/**
+ * Handle agent completion (from runner events)
+ */
+async function handleAgentCompletion(agentId, exitCode, success, duration) {
+ const agent = runnerAgents.get(agentId);
+ if (!agent) {
+ console.log(`⚠️ Received completion for unknown agent: ${agentId}`);
+ return;
+ }
+
+ const { task, runId, model } = agent;
+
+ // Read output from agent directory
+ const agentDir = join(AGENTS_DIR, agentId);
+ const outputFile = join(agentDir, 'output.txt');
+ let outputBuffer = '';
+ if (existsSync(outputFile)) {
+ outputBuffer = await readFile(outputFile, 'utf-8').catch(() => '');
+ }
+
+ // Analyze failure if applicable
+ const errorAnalysis = success ? null : analyzeAgentFailure(outputBuffer, task, model);
+
+ await completeAgent(agentId, {
+ success,
+ exitCode,
+ duration,
+ outputLength: outputBuffer.length,
+ errorAnalysis
+ });
+
+ // Complete run tracking (skip if no runId - agent was recovered after restart)
+ if (runId) {
+ await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);
+ }
+
+ // Update task status
+ const newStatus = success ? 'completed' : 'pending';
+ await updateTask(task.id, { status: newStatus }, task.taskType || 'user');
+
+ // On failure, create investigation task if actionable
+ if (!success && errorAnalysis?.actionable) {
+ await createInvestigationTask(agentId, task, errorAnalysis).catch(err => {
+ emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId });
+ });
+ }
+
+ // Extract memories from successful output
+ if (success && outputBuffer.length > 100) {
+ extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {
+ console.log(`⚠️ Memory extraction failed: ${err.message}`);
+ });
+ }
+
+ // Handle app cooldown
+ const appId = task.metadata?.app;
+ if (appId) {
+ const config = await getConfig();
+ const cooldownMs = config.appReviewCooldownMs || 3600000;
+
+ const issuesFound = success ? 1 : 0;
+ const issuesFixed = success ? 1 : 0;
+ await markAppReviewCompleted(appId, issuesFound, issuesFixed).catch(err => {
+ emitLog('warn', `Failed to mark app review completed: ${err.message}`, { appId });
+ });
+
+ await startAppCooldown(appId, cooldownMs).catch(err => {
+ emitLog('warn', `Failed to start app cooldown: ${err.message}`, { appId });
+ });
+
+ emitLog('info', `App ${appId} cooldown started (${Math.round(cooldownMs / 60000)} min)`, { appId, cooldownMs });
+ }
+
+ runnerAgents.delete(agentId);
+}
+
+/**
+ * Spawn agent directly (fallback when runner not available)
+ */
+async function spawnDirectly(agentId, task, prompt, workspacePath, model, provider, runId, claudePath, agentDir) {
+ const spawnArgs = buildSpawnArgs(null, model);
const fullCommand = `${claudePath} ${spawnArgs.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;
- emitLog('success', `Spawning agent for task ${task.id}`, { agentId, model: selectedModel });
+ // Ensure workspacePath is valid
+ const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;
const claudeProcess = spawn(claudePath, spawnArgs, {
- cwd: workspacePath,
+ cwd,
shell: false,
- stdio: ['pipe', 'pipe', 'pipe'], // stdin, stdout, stderr
+ stdio: ['pipe', 'pipe', 'pipe'],
env: {
...process.env,
- // Pass through any provider-specific env vars
...provider.envVars
}
});
- // Register the spawned agent with its full command for process listing
registerSpawnedAgent(claudeProcess.pid, {
fullCommand,
agentId,
taskId: task.id,
- model: selectedModel,
+ model,
workspacePath,
prompt: (task.description || '').substring(0, 500)
});
- // Send prompt via stdin and close it
claudeProcess.stdin.write(prompt);
claudeProcess.stdin.end();
- // Store process reference
activeAgents.set(agentId, {
process: claudeProcess,
taskId: task.id,
@@ -407,59 +738,62 @@ export async function spawnAgentForTask(task) {
pid: claudeProcess.pid
});
- // Set up output handling
+ // Store PID in persisted state for zombie detection
+ await updateAgent(agentId, { pid: claudeProcess.pid });
+
let outputBuffer = '';
let hasStartedWorking = false;
const outputFile = join(agentDir, 'output.txt');
+ // If no output after 3 seconds, transition from initializing to working to show progress
+ const initializationTimeout = setTimeout(async () => {
+ if (!hasStartedWorking && activeAgents.has(agentId)) {
+ hasStartedWorking = true;
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });
+ }
+ }, 3000);
+
claudeProcess.stdout.on('data', async (data) => {
const text = data.toString();
outputBuffer += text;
- // Update phase to 'working' on first output
if (!hasStartedWorking) {
hasStartedWorking = true;
- await updateAgent(agentId, { phase: 'working' });
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });
}
- // Append to file
await writeFile(outputFile, outputBuffer).catch(() => {});
-
- // Emit output event
await appendAgentOutput(agentId, text);
});
claudeProcess.stderr.on('data', async (data) => {
const text = data.toString();
outputBuffer += `[stderr] ${text}`;
-
- // Append to file
await writeFile(outputFile, outputBuffer).catch(() => {});
-
await appendAgentOutput(agentId, `[stderr] ${text}`);
});
claudeProcess.on('error', async (err) => {
+ clearTimeout(initializationTimeout);
console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);
cosEvents.emit('agent:error', { agentId, error: err.message });
await completeAgent(agentId, { success: false, error: err.message });
- // Complete the run tracking with error
- await completeAgentRun(runId, outputBuffer, 1, 0, err.message);
+ await completeAgentRun(runId, outputBuffer, 1, 0, { message: err.message, category: 'spawn-error' });
unregisterSpawnedAgent(claudeProcess.pid);
activeAgents.delete(agentId);
});
claudeProcess.on('close', async (code) => {
+ clearTimeout(initializationTimeout);
const success = code === 0;
const agentData = activeAgents.get(agentId);
const duration = Date.now() - (agentData?.startedAt || Date.now());
- // Save final output
await writeFile(outputFile, outputBuffer).catch(() => {});
- // Analyze failure and extract error details
- const errorAnalysis = success ? null : analyzeAgentFailure(outputBuffer, task, selectedModel);
+ const errorAnalysis = success ? null : analyzeAgentFailure(outputBuffer, task, model);
await completeAgent(agentId, {
success,
@@ -469,41 +803,34 @@ export async function spawnAgentForTask(task) {
errorAnalysis
});
- // Complete the run tracking
- await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration, errorAnalysis?.message);
+ await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration, errorAnalysis);
- // Update task status based on result
- const newStatus = success ? 'completed' : 'pending'; // Reset to pending on failure for retry
+ const newStatus = success ? 'completed' : 'pending';
await updateTask(task.id, { status: newStatus }, task.taskType || 'user');
- // On failure, auto-queue an investigation task if error is actionable
if (!success && errorAnalysis?.actionable) {
await createInvestigationTask(agentId, task, errorAnalysis).catch(err => {
emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId });
});
}
- // Extract and store memories from successful agent output
if (success && outputBuffer.length > 100) {
extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {
console.log(`⚠️ Memory extraction failed: ${err.message}`);
});
}
- // Start cooldown for the app if task had an associated app
const appId = task.metadata?.app;
if (appId) {
const config = await getConfig();
- const cooldownMs = config.appReviewCooldownMs || 3600000; // 1 hour default
+ const cooldownMs = config.appReviewCooldownMs || 3600000;
- // Mark review completed with stats
- const issuesFound = success ? 1 : 0; // TODO: Parse from output for accurate count
+ const issuesFound = success ? 1 : 0;
const issuesFixed = success ? 1 : 0;
await markAppReviewCompleted(appId, issuesFound, issuesFixed).catch(err => {
emitLog('warn', `Failed to mark app review completed: ${err.message}`, { appId });
});
- // Start cooldown
await startAppCooldown(appId, cooldownMs).catch(err => {
emitLog('warn', `Failed to start app cooldown: ${err.message}`, { appId });
});
@@ -576,6 +903,7 @@ You are an autonomous agent working on behalf of the Chief of Staff.
- **Description**: ${task.description}
${task.metadata?.context ? `- **Context**: ${task.metadata.context}` : ''}
${task.metadata?.app ? `- **Target App**: ${task.metadata.app}` : ''}
+${task.metadata?.screenshots?.length > 0 ? `- **Screenshots**: ${task.metadata.screenshots.join(', ')}` : ''}
## Instructions
1. Analyze the task requirements carefully
@@ -626,12 +954,40 @@ async function getAppWorkspace(appName) {
* Terminate an agent
*/
export async function terminateAgent(agentId) {
+ // Check if agent is in runner mode
+ if (runnerAgents.has(agentId)) {
+ const agentInfo = runnerAgents.get(agentId);
+ if (agentInfo?.initializationTimeout) {
+ clearTimeout(agentInfo.initializationTimeout);
+ }
+ const result = await terminateAgentViaRunner(agentId).catch(err => ({
+ success: false,
+ error: err.message
+ }));
+ if (result.success) {
+ // Mark agent as completed with termination status
+ await completeAgent(agentId, { success: false, error: 'Agent terminated by user' });
+ // Update task status back to pending
+ const task = agentInfo?.task;
+ if (task) {
+ await updateTask(task.id, { status: 'pending' }, task.taskType || 'user');
+ }
+ runnerAgents.delete(agentId);
+ }
+ return result;
+ }
+
+ // Direct mode
const agent = activeAgents.get(agentId);
if (!agent) {
return { success: false, error: 'Agent not found or not running' };
}
+ // Mark agent as completed immediately with termination status
+ await completeAgent(agentId, { success: false, error: 'Agent terminated by user' });
+
+ // Kill the process
agent.process.kill('SIGTERM');
// Give it a moment, then force kill if needed
@@ -651,56 +1007,195 @@ export async function terminateAgent(agentId) {
*/
export function getActiveAgents() {
const agents = [];
+
+ // Direct mode agents
for (const [agentId, agent] of activeAgents) {
agents.push({
id: agentId,
taskId: agent.taskId,
startedAt: agent.startedAt,
- runningTime: Date.now() - agent.startedAt
+ runningTime: Date.now() - agent.startedAt,
+ mode: 'direct'
});
}
+
+ // Runner mode agents
+ for (const [agentId, agent] of runnerAgents) {
+ agents.push({
+ id: agentId,
+ taskId: agent.taskId,
+ startedAt: agent.startedAt,
+ runningTime: Date.now() - agent.startedAt,
+ mode: 'runner'
+ });
+ }
+
return agents;
}
+/**
+ * Force kill an agent immediately with SIGKILL (no graceful shutdown)
+ */
+export async function killAgent(agentId) {
+ // Check if agent is in runner mode
+ if (runnerAgents.has(agentId)) {
+ const agentInfo = runnerAgents.get(agentId);
+ if (agentInfo?.initializationTimeout) {
+ clearTimeout(agentInfo.initializationTimeout);
+ }
+ const result = await killAgentViaRunner(agentId).catch(err => ({
+ success: false,
+ error: err.message
+ }));
+ if (result.success) {
+ // Mark agent as completed with kill status
+ await completeAgent(agentId, { success: false, error: 'Agent force killed by user (SIGKILL)' });
+ // Update task status back to pending
+ const task = agentInfo?.task;
+ if (task) {
+ await updateTask(task.id, { status: 'pending' }, task.taskType || 'user');
+ }
+ runnerAgents.delete(agentId);
+ }
+ return result;
+ }
+
+ // Direct mode
+ const agent = activeAgents.get(agentId);
+
+ if (!agent) {
+ return { success: false, error: 'Agent not found or not running' };
+ }
+
+ // Mark agent as completed immediately with kill status
+ await completeAgent(agentId, { success: false, error: 'Agent force killed by user (SIGKILL)' });
+
+ // Kill the process immediately with SIGKILL
+ agent.process.kill('SIGKILL');
+
+ unregisterSpawnedAgent(agent.pid);
+ activeAgents.delete(agentId);
+
+ return { success: true, agentId, pid: agent.pid, signal: 'SIGKILL' };
+}
+
+/**
+ * Get process stats for an agent (CPU, memory usage)
+ */
+export async function getAgentProcessStats(agentId) {
+ // Check if agent is in runner mode - use runner endpoint
+ if (runnerAgents.has(agentId) || useRunner) {
+ const stats = await getAgentStatsFromRunner(agentId);
+ return stats;
+ }
+
+ // Direct mode - get stats locally
+ const agent = activeAgents.get(agentId);
+ if (!agent) {
+ return null;
+ }
+
+ // Get process stats using ps command
+ const { exec } = await import('child_process');
+ const { promisify } = await import('util');
+ const execAsync = promisify(exec);
+
+ const result = await execAsync(`ps -p ${agent.pid} -o pid=,pcpu=,rss=,state= 2>/dev/null`).catch(() => ({ stdout: '' }));
+ const line = result.stdout.trim();
+
+ if (!line) {
+ return { active: false, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'dead' };
+ }
+
+ const parts = line.split(/\s+/).filter(Boolean);
+ if (parts.length >= 3) {
+ return {
+ active: true,
+ agentId,
+ pid: parseInt(parts[0], 10),
+ cpu: parseFloat(parts[1]) || 0,
+ memoryKb: parseInt(parts[2], 10) || 0,
+ memoryMb: Math.round((parseInt(parts[2], 10) || 0) / 1024 * 10) / 10,
+ state: parts[3] || 'unknown'
+ };
+ }
+
+ return { active: true, agentId, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'unknown' };
+}
+
/**
* Kill all active agents
*/
export async function killAllAgents() {
- const agentIds = Array.from(activeAgents.keys());
+ const directIds = Array.from(activeAgents.keys());
+ const runnerIds = Array.from(runnerAgents.keys());
+
+ for (const agentId of directIds) {
+ await terminateAgent(agentId);
+ }
- for (const agentId of agentIds) {
+ for (const agentId of runnerIds) {
await terminateAgent(agentId);
}
- return { killed: agentIds.length };
+ return { killed: directIds.length + runnerIds.length };
}
/**
* Clean up orphaned agents on startup
- * Agents marked as "running" in state but not in activeAgents map are orphaned
+ * Agents marked as "running" in state but not tracked anywhere are orphaned
+ *
+ * Must check:
+ * 1. Local activeAgents map (direct-spawned)
+ * 2. Local runnerAgents map (recently spawned via runner)
+ * 3. CoS Runner service (may have agents from before server restart)
*/
export async function cleanupOrphanedAgents() {
const { getAgents, completeAgent: markComplete } = await import('./cos.js');
const agents = await getAgents();
let cleanedCount = 0;
+ // Get list of agents actively running in the CoS Runner
+ const runnerActiveIds = new Set();
+ const runnerAgentsList = await getActiveAgentsFromRunner().catch(() => []);
+ for (const agent of runnerAgentsList) {
+ runnerActiveIds.add(agent.id);
+ }
+
+ // Also sync runner agents to our local map for event handling
+ if (runnerAgentsList.length > 0) {
+ const synced = await syncRunnerAgents();
+ if (synced > 0) {
+ console.log(`🔄 Synced ${synced} agents from CoS Runner`);
+ }
+ }
+
for (const agent of agents) {
- if (agent.status === 'running' && !activeAgents.has(agent.id)) {
- console.log(`🧹 Cleaning up orphaned agent ${agent.id}`);
- await markComplete(agent.id, {
- success: false,
- error: 'Agent process was orphaned (server restart)',
- orphaned: true
- });
- cleanedCount++;
+ if (agent.status === 'running') {
+ // Check if agent is tracked locally or in the runner
+ const inLocalDirect = activeAgents.has(agent.id);
+ const inLocalRunner = runnerAgents.has(agent.id);
+ const inRemoteRunner = runnerActiveIds.has(agent.id);
+
+ if (!inLocalDirect && !inLocalRunner && !inRemoteRunner) {
+ console.log(`🧹 Cleaning up orphaned agent ${agent.id}`);
+ await markComplete(agent.id, {
+ success: false,
+ error: 'Agent process was orphaned (server restart)',
+ orphaned: true
+ });
+ cleanedCount++;
+ }
}
}
return cleanedCount;
}
-// Initialize spawner when module loads
-initSpawner();
+// Initialize spawner when module loads (async)
+initSpawner().catch(err => {
+ console.error(`❌ Failed to initialize spawner: ${err.message}`);
+});
// Clean up orphaned agents after a short delay (let other services init first)
setTimeout(cleanupOrphanedAgents, 2000);