Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: always-on CoS architecture with UI improvements
Adam Eivyeda06c343f88
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 5418d7deac..1750f3a54e 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -2,7 +2,6 @@ import { Routes, Route, Navigate } from 'react-router-dom';import Layout from './components/Layout';import Dashboard from './pages/Dashboard';import Apps from './pages/Apps';-import Logs from './pages/Logs';import CreateApp from './pages/CreateApp';import Templates from './pages/Templates';import AIProviders from './pages/AIProviders';@@ -16,7 +15,6 @@ export default function App() {<Route path="/" element={<Layout />}><Route index element={<Dashboard />} /><Route path="apps" element={<Apps />} />- <Route path="logs" element={<Logs />} /><Route path="devtools" element={<Navigate to="/devtools/runs" replace />} /><Route path="devtools/history" element={<HistoryPage />} /><Route path="devtools/runs" element={<RunsHistoryPage />} />@@ -27,7 +25,8 @@ export default function App() {<Route path="devtools/agents" element={<AgentsPage />} /><Route path="ai" element={<AIProviders />} /><Route path="prompts" element={<PromptManager />} />- <Route path="cos" element={<ChiefOfStaff />} />+ <Route path="cos" element={<Navigate to="/cos/tasks" replace />} />+ <Route path="cos/:tab" element={<ChiefOfStaff />} /><Route path="apps/create" element={<CreateApp />} /><Route path="templates" element={<Templates />} /><Route path="*" element={<Navigate to="/" replace />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 098d359865..7f1d0d2b1a 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -50,8 +50,7 @@ const navItems = [{ to: '/devtools/processes', label: 'Processes', icon: Activity },{ to: '/devtools/usage', label: 'Usage', icon: BarChart3 }]- },- { to: '/logs', label: 'Logs', icon: FileText, single: true }+ }];const SIDEBAR_KEY = 'portos-sidebar-collapsed';@@ -320,10 +319,14 @@ export default function Layout() {</header>{/* Main content */}- <main className="flex-1 p-4 md:p-6 overflow-auto">- <div className="max-w-7xl mx-auto">+ <main className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') ? '' : 'p-4 md:p-6'}`}>+ {location.pathname.startsWith('/cos') ? (<Outlet />- </div>+ ) : (+ <div className="max-w-7xl mx-auto">+ <Outlet />+ </div>+ )}</main></div></div>diff --git a/client/src/components/LogViewer.jsx b/client/src/components/LogViewer.jsxdeleted file mode 100644index 5f09cad5a6..0000000000--- a/client/src/components/LogViewer.jsx+++ /dev/null@@ -1,60 +0,0 @@-import { useEffect, useRef } from 'react';--export default function LogViewer({ logs, autoScroll = true, maxHeight = '500px' }) {- const containerRef = useRef(null);- const shouldScrollRef = useRef(true);-- useEffect(() => {- if (autoScroll && shouldScrollRef.current && containerRef.current) {- containerRef.current.scrollTop = containerRef.current.scrollHeight;- }- }, [logs, autoScroll]);-- const handleScroll = () => {- if (!containerRef.current) return;- const { scrollTop, scrollHeight, clientHeight } = containerRef.current;- // Auto-scroll if user is near bottom (within 50px)- shouldScrollRef.current = scrollHeight - scrollTop - clientHeight < 50;- };-- const getLineClass = (type) => {- switch (type) {- case 'stderr':- return 'text-port-warning';- case 'connected':- return 'text-port-success';- case 'error':- return 'text-port-error';- default:- return 'text-gray-300';- }- };-- return (- <div- ref={containerRef}- onScroll={handleScroll}- className="bg-port-bg border border-port-border rounded-lg overflow-auto font-mono text-sm"- style={{ maxHeight }}- >- {logs.length === 0 ? (- <div className="p-4 text-gray-500 text-center">- No logs available. Select a process and click "Start Streaming" to begin.- </div>- ) : (- <div className="p-3 space-y-0.5">- {logs.map((log, index) => (- <div key={index} className={`${getLineClass(log.type)} break-all`}>- {log.timestamp && (- <span className="text-gray-600 mr-2">- {new Date(log.timestamp).toLocaleTimeString()}- </span>- )}- <span>{log.line || log.message || JSON.stringify(log)}</span>- </div>- ))}- </div>- )}- </div>- );-}diff --git a/client/src/components/cos/CoSCharacter.jsx b/client/src/components/cos/CoSCharacter.jsxnew file mode 100644index 0000000000..109af01cc7--- /dev/null+++ b/client/src/components/cos/CoSCharacter.jsx@@ -0,0 +1,163 @@+import { AGENT_STATES } from './constants';++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">+ <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%">+ <stop offset="0%" stopColor="#1e293b" />+ <stop offset="100%" stopColor="#0f172a" />+ </linearGradient>+ <linearGradient id="screenGrad" x1="0%" y1="0%" x2="0%" y2="100%">+ <stop offset="0%" stopColor={stateConfig.color} stopOpacity="0.3" />+ <stop offset="100%" stopColor={stateConfig.color} stopOpacity="0.1" />+ </linearGradient>+ <filter id="glow">+ <feGaussianBlur stdDeviation="3" result="coloredBlur"/>+ <feMerge>+ <feMergeNode in="coloredBlur"/>+ <feMergeNode in="SourceGraphic"/>+ </feMerge>+ </filter>+ <filter id="innerGlow">+ <feGaussianBlur stdDeviation="2" result="blur"/>+ <feComposite in="SourceGraphic" in2="blur" operator="over"/>+ </filter>+ </defs>++ {/* Particles */}+ <g className={`particles particles-${state}`}>+ {[+ { cx: 30, cy: 50 },+ { cx: 170, cy: 60 },+ { cx: 25, cy: 130 },+ { cx: 175, cy: 140 },+ { cx: 40, cy: 200 },+ { cx: 160, cy: 190 }+ ].map((pos, i) => (+ <circle+ key={i}+ cx={pos.cx}+ cy={pos.cy}+ r="2"+ fill={stateConfig.color}+ opacity="0.6"+ className={`cos-particle cos-particle-${i}`}+ />+ ))}+ </g>++ {/* Body */}+ <rect x="50" y="90" width="100" height="120" rx="20" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" />++ {/* Chest Screen */}+ <rect x="60" y="100" width="80" height="50" rx="8" fill="#0f172a" stroke={stateConfig.color} strokeWidth="1" opacity="0.8" />+ <rect x="65" y="105" width="70" height="40" rx="5" fill="url(#screenGrad)" />++ {/* Chest Display Content */}+ <g className="chest-display">+ {state === 'coding' && (+ <g className="code-lines">+ {[0, 1, 2, 3].map(i => (+ <rect key={i} x="70" y={110 + i * 8} width={30 + (i % 2) * 15} height="3" rx="1" fill={stateConfig.color} opacity="0.8" className={`code-line code-line-${i}`} />+ ))}+ </g>+ )}+ {state === 'thinking' && (+ <g className="thinking-dots">+ {[0, 1, 2].map(i => (+ <circle key={i} cx={85 + i * 15} cy="125" r="4" fill={stateConfig.color} className={`thinking-dot thinking-dot-${i}`} />+ ))}+ </g>+ )}+ {state === 'planning' && (+ <g className="plan-grid">+ {[0, 1, 2].map(row =>+ [0, 1, 2].map(col => (+ <rect key={`${row}-${col}`} x={72 + col * 20} y={108 + row * 12} width="15" height="8" rx="2" fill={stateConfig.color} opacity={0.4 + ((row + col) % 3) * 0.2} className="plan-cell" />+ ))+ )}+ </g>+ )}+ {state === 'investigating' && (+ <g className="scan-line-group">+ <line x1="70" y1="125" x2="130" y2="125" stroke={stateConfig.color} strokeWidth="2" className="scan-line" />+ </g>+ )}+ {state === 'reviewing' && (+ <g className="review-checks">+ {[0, 1, 2].map(i => (+ <path key={i} d={`M${75 + i * 20},125 l4,4 l8,-8`} stroke={stateConfig.color} strokeWidth="2" fill="none" className={`check check-${i}`} />+ ))}+ </g>+ )}+ {state === 'ideating' && (+ <g className="lightbulb">+ <ellipse cx="100" cy="120" rx="12" ry="15" fill={stateConfig.color} opacity="0.3" className="bulb-glow" />+ <ellipse cx="100" cy="120" rx="8" ry="10" fill={stateConfig.color} className="bulb" />+ </g>+ )}+ {state === 'sleeping' && (+ <g className="zzz">+ <text x="80" y="130" fill={stateConfig.color} fontSize="16" fontFamily="monospace" className="cos-z cos-z-1">Z</text>+ <text x="95" y="120" fill={stateConfig.color} fontSize="12" fontFamily="monospace" className="cos-z cos-z-2">z</text>+ <text x="105" y="112" fill={stateConfig.color} fontSize="8" fontFamily="monospace" className="cos-z cos-z-3">z</text>+ </g>+ )}+ </g>++ {/* Arms */}+ <rect x="30" y="100" width="18" height="60" rx="9" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`arm arm-left arm-${state}`} />+ <rect x="152" y="100" width="18" height="60" rx="9" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`arm arm-right arm-${state}`} />++ {/* Hands */}+ <circle cx="39" cy="165" r="10" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`hand hand-left hand-${state}`} />+ <circle cx="161" cy="165" r="10" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`hand hand-right hand-${state}`} />++ {/* Head */}+ <rect x="55" y="20" width="90" height="75" rx="15" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" />++ {/* Face Screen */}+ <rect x="62" y="28" width="76" height="55" rx="10" fill="#0f172a" stroke={stateConfig.color} strokeWidth="1.5" filter="url(#innerGlow)" />++ {/* Eyes */}+ <g className={`eyes eyes-${state}`}>+ {state === 'sleeping' ? (+ <>+ <line x1="75" y1="50" x2="90" y2="50" stroke={stateConfig.color} strokeWidth="3" strokeLinecap="round" />+ <line x1="110" y1="50" x2="125" y2="50" stroke={stateConfig.color} strokeWidth="3" strokeLinecap="round" />+ </>+ ) : (+ <>+ <ellipse cx="82" cy="48" rx="10" ry={state === 'investigating' ? 12 : 8} fill={stateConfig.color} filter="url(#glow)" className="eye eye-left" />+ <ellipse cx="118" cy="48" rx="10" ry={state === 'investigating' ? 12 : 8} fill={stateConfig.color} filter="url(#glow)" className="eye eye-right" />+ <circle cx="82" cy="48" r="3" fill="#0f172a" className="pupil pupil-left" />+ <circle cx="118" cy="48" r="3" fill="#0f172a" className="pupil pupil-right" />+ </>+ )}+ </g>++ {/* Mouth */}+ <g className={`mouth mouth-${state} ${speaking ? 'speaking' : ''}`}>+ {speaking ? (+ <ellipse cx="100" cy="70" rx="12" ry="6" fill={stateConfig.color} opacity="0.8" className="mouth-open" />+ ) : state === 'sleeping' ? (+ <ellipse cx="100" cy="68" rx="8" ry="3" fill={stateConfig.color} opacity="0.5" />+ ) : (+ <path d="M88,68 Q100,78 112,68" stroke={stateConfig.color} strokeWidth="2" fill="none" strokeLinecap="round" />+ )}+ </g>++ {/* Antenna */}+ <line x1="100" y1="20" x2="100" y2="5" stroke="#334155" strokeWidth="3" />+ <circle cx="100" cy="5" r="5" fill={stateConfig.color} filter="url(#glow)" className="antenna-light" />++ {/* Status Light */}+ <circle cx="148" cy="35" r="4" fill={stateConfig.color} filter="url(#glow)" className="status-light" />+ </svg>+ </div>+ );+}diff --git a/client/src/components/cos/EventLog.jsx b/client/src/components/cos/EventLog.jsxnew file mode 100644index 0000000000..d46bc00401--- /dev/null+++ b/client/src/components/cos/EventLog.jsx@@ -0,0 +1,35 @@+const levelColors = {+ info: 'text-blue-400',+ warn: 'text-yellow-400',+ error: 'text-red-400',+ success: 'text-green-400',+ debug: 'text-gray-500'+};++const levelIcons = {+ info: 'i',+ warn: '!',+ error: 'x',+ success: '+',+ debug: '?'+};++export default function EventLog({ logs }) {+ if (!logs || logs.length === 0) return null;++ return (+ <div className="mt-4 w-full max-w-[280px]">+ <div className="text-xs text-gray-500 mb-1 font-mono">Event Log</div>+ <div className="bg-slate-900/80 border border-slate-700/50 rounded-lg p-2 max-h-32 overflow-y-auto">+ {logs.slice(-5).reverse().map((log, i) => (+ <div key={i} className={`text-xs font-mono py-0.5 ${levelColors[log.level] || 'text-gray-400'}`}>+ <span className="mr-1">[{levelIcons[log.level] || '*'}]</span>+ <span className="text-gray-500">{new Date(log.timestamp).toLocaleTimeString()}</span>+ {' '}+ <span>{log.message}</span>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/client/src/components/cos/StatCard.jsx b/client/src/components/cos/StatCard.jsxnew file mode 100644index 0000000000..bed0fc81c5--- /dev/null+++ b/client/src/components/cos/StatCard.jsx@@ -0,0 +1,20 @@+export default function StatCard({ label, value, icon, active, activeLabel }) {+ return (+ <div className={`bg-port-card border rounded-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' : ''}>+ {icon}+ </div>+ </div>+ <div className="text-2xl font-bold text-white">{value}</div>+ {active && activeLabel && (+ <div className="text-xs text-port-accent mt-1 truncate animate-pulse">+ {activeLabel}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/StateLabel.jsx b/client/src/components/cos/StateLabel.jsxnew file mode 100644index 0000000000..1bda939a33--- /dev/null+++ b/client/src/components/cos/StateLabel.jsx@@ -0,0 +1,19 @@+import { AGENT_STATES } from './constants';++export default function StateLabel({ state }) {+ const stateConfig = AGENT_STATES[state] || AGENT_STATES.sleeping;++ return (+ <div+ className="flex items-center gap-2 px-4 py-2 rounded-full mt-4 font-mono text-xs"+ style={{+ background: 'rgba(15, 23, 42, 0.8)',+ border: `1px solid ${stateConfig.color}`,+ boxShadow: `0 0 20px rgba(99, 102, 241, 0.2)`+ }}+ >+ <span className="text-base">{stateConfig.icon}</span>+ <span className="text-gray-100">{stateConfig.label}</span>+ </div>+ );+}diff --git a/client/src/components/cos/StatusBubble.jsx b/client/src/components/cos/StatusBubble.jsxnew file mode 100644index 0000000000..d60541c1f5--- /dev/null+++ b/client/src/components/cos/StatusBubble.jsx@@ -0,0 +1,15 @@+export default function StatusBubble({ message, countdown }) {+ return (+ <div className="relative mt-4 px-4 py-3 rounded-2xl max-w-[280px] text-center text-sm leading-relaxed bg-indigo-500/10 border border-indigo-500/30">+ <div+ className="absolute -top-2 left-1/2 -translate-x-1/2 rotate-45 w-3.5 h-3.5 bg-indigo-500/10 border-l border-t border-indigo-500/30"+ />+ <div>{message}</div>+ {countdown && (+ <div className="mt-1 text-xs text-indigo-400/70 font-mono">+ Next check in {countdown.formatted}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/StatusIndicator.jsx b/client/src/components/cos/StatusIndicator.jsxnew file mode 100644index 0000000000..e2601422f8--- /dev/null+++ b/client/src/components/cos/StatusIndicator.jsx@@ -0,0 +1,12 @@+export default function StatusIndicator({ running }) {+ return (+ <div className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm ${+ running+ ? 'bg-port-success/20 text-port-success'+ : 'bg-gray-700 text-gray-400'+ }`}>+ <span className={`w-2 h-2 rounded-full ${running ? 'bg-port-success animate-pulse' : 'bg-gray-500'}`} />+ {running ? 'Running' : 'Stopped'}+ </div>+ );+}diff --git a/client/src/components/cos/TerminalCoSPanel.jsx b/client/src/components/cos/TerminalCoSPanel.jsxnew file mode 100644index 0000000000..ab868af816--- /dev/null+++ b/client/src/components/cos/TerminalCoSPanel.jsx@@ -0,0 +1,207 @@+import { Play, Square } from 'lucide-react';+import { AGENT_STATES } from './constants';++export default function TerminalCoSPanel({ state, speaking, statusMessage, eventLogs, running, onStart, onStop, stats, evalCountdown }) {+ const stateConfig = AGENT_STATES[state] || AGENT_STATES.sleeping;++ // Terminal-style ASCII art for the character - alien design+ const terminalAscii = {+ sleeping: [+ ' ◊ ◊ ',+ ' ▐▛███▜▌ ',+ ' ▝▜█z█▛▘ ',+ ' /| |\\ ',+ ' | | ',+ ' ◇ ◇ ',+ ],+ thinking: [+ ' ? ? ',+ ' ▐▛███▜▌ ',+ ' ▝▜█?█▛▘ ',+ ' /| |\\ ',+ ' | | ',+ ' ◇ ◇ ',+ ],+ coding: [+ ' ⟨ ⟩ ',+ ' ▐▛███▜▌ ',+ ' ▝▜█=█▛▘ ',+ ' /| |\\ ',+ ' | | ',+ ' ◈ ◈ ',+ ],+ investigating: [+ ' ◎ ◎ ',+ ' ▐▛███▜▌ ',+ ' ▝▜█◉█▛▘ ',+ ' /| |\\ ',+ ' | | ',+ ' ◇ ◇ ',+ ],+ reviewing: [+ ' ✓ ✓ ',+ ' ▐▛███▜▌ ',+ ' ▝▜█✓█▛▘ ',+ ' /| |\\ ',+ ' | | ',+ ' ◈ ◈ ',+ ],+ planning: [+ ' ▪ ▪ ',+ ' ▐▛███▜▌ ',+ ' ▝▜█▪█▛▘ ',+ ' /| |\\ ',+ ' | | ',+ ' ◇ ◇ ',+ ],+ ideating: [+ ' ✧ ✧ ',+ ' ▐▛███▜▌ ',+ ' ▝▜█•█▛▘ ',+ ' /| |\\ ',+ ' | | ',+ ' ◈ ◈ ',+ ]+ };++ const ascii = terminalAscii[state] || terminalAscii.sleeping;++ const levelColors = {+ info: 'text-cyan-400',+ warn: 'text-yellow-400',+ error: 'text-red-400',+ success: 'text-green-400',+ debug: 'text-gray-500'+ };++ const levelPrefixes = {+ info: '[INFO]',+ warn: '[WARN]',+ error: '[ERR!]',+ success: '[DONE]',+ debug: '[DBG.]'+ };++ 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">+ {/* Scanline effect */}+ <div+ className="absolute inset-0 pointer-events-none opacity-[0.02]"+ style={{+ background: 'repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(255,255,255,0.03) 2px, rgba(255,255,255,0.03) 4px)'+ }}+ />++ {/* Terminal header */}+ <div className="flex items-center gap-3 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>+ </div>+ <span className="text-gray-500 text-xs">cos-terminal</span>+ </div>++ {/* ASCII Art + Info */}+ <div className="flex items-start gap-4 mb-4">+ <div className="flex-shrink-0">+ {ascii.map((line, i) => (+ <div+ key={i}+ className={`whitespace-pre leading-tight ${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>+ </div>++ {/* Status line */}+ <div className="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'}+ </span>+ <span className="text-gray-600">│</span>+ <span className="text-gray-400">{stateConfig.icon}</span>+ </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>++ {/* Stats as terminal output */}+ {stats && (+ <div className="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>+ <div className="text-gray-400 pl-2">│ errors: <span className="text-red-400">{stats.errors || 0}</span></div>+ <div className="text-gray-500">└──────────────────────────┘</div>+ </div>+ )}++ {/* Event logs as terminal output */}+ <div className="flex-1 mb-4 flex 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) ? (+ <div className="text-gray-600 text-xs">waiting for events...</div>+ ) : (+ eventLogs.slice(-20).reverse().map((log, i) => (+ <div key={i} className={`text-xs ${levelColors[log.level] || 'text-gray-400'} leading-relaxed`}>+ <span className="text-gray-600">{new Date(log.timestamp).toLocaleTimeString('en-US', { hour12: false })}</span>+ {' '}+ <span className={levelColors[log.level]}>{levelPrefixes[log.level] || '[LOG]'}</span>+ {' '}+ <span className="text-gray-300">{log.message}</span>+ </div>+ ))+ )}+ </div>+ </div>++ {/* Control buttons as terminal commands */}+ <div className="mt-auto pt-3 border-t border-gray-700/50">+ <div className="flex gap-2">+ {running ? (+ <button+ onClick={onStop}+ className="flex items-center gap-2 px-3 py-1.5 bg-red-900/30 hover:bg-red-900/50 text-red-400 rounded border border-red-700/50 text-xs transition-colors"+ >+ <Square size={12} />+ ./stop+ </button>+ ) : (+ <button+ onClick={onStart}+ className="flex items-center gap-2 px-3 py-1.5 bg-green-900/30 hover:bg-green-900/50 text-green-400 rounded border border-green-700/50 text-xs transition-colors"+ >+ <Play size={12} />+ ./start+ </button>+ )}+ <div className={`flex items-center gap-2 px-3 py-1.5 rounded text-xs ${+ running ? 'text-green-400 bg-green-900/20' : 'text-gray-500 bg-gray-800/50'+ }`}>+ <span className={`w-1.5 h-1.5 rounded-full ${running ? 'bg-green-400' : 'bg-gray-600'}`}></span>+ {running ? 'running' : 'stopped'}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsnew file mode 100644index 0000000000..5e41461c22--- /dev/null+++ b/client/src/components/cos/constants.js@@ -0,0 +1,48 @@+import {+ FileText,+ Cpu,+ Terminal,+ Brain,+ Activity,+ Settings+} from 'lucide-react';++export const TABS = [+ { id: 'tasks', label: 'Tasks', icon: FileText },+ { id: 'agents', label: 'Agents', icon: Cpu },+ { id: 'scripts', label: 'Scripts', icon: Terminal },+ { id: 'memory', label: 'Memory', icon: Brain },+ { id: 'health', label: 'Health', icon: Activity },+ { id: 'config', label: 'Config', icon: Settings }+];++export const AGENT_STATES = {+ sleeping: { label: 'Sleeping', color: '#6366f1', icon: '💤' },+ thinking: { label: 'Thinking', color: '#f59e0b', icon: '🧠' },+ coding: { label: 'Coding', color: '#10b981', icon: '⚡' },+ investigating: { label: 'Investigating', color: '#ec4899', icon: '🔍' },+ reviewing: { label: 'Reviewing', color: '#8b5cf6', icon: '📋' },+ planning: { label: 'Planning', color: '#06b6d4', icon: '📐' },+ ideating: { label: 'Ideating', color: '#f97316', icon: '💡' },+};++export const STATE_MESSAGES = {+ sleeping: ["Resting... Wake me if you need anything!", "💤 Power saving mode..."],+ thinking: ["Processing your request...", "Analyzing the situation...", "Let me think about this..."],+ coding: ["Writing some code...", "Implementing the solution...", "Building something cool..."],+ investigating: ["Looking into this...", "Researching the topic...", "Gathering information..."],+ reviewing: ["Checking the details...", "Reviewing for quality...", "Making sure everything's right..."],+ planning: ["Organizing the approach...", "Mapping out the strategy...", "Creating a plan..."],+ ideating: ["Brainstorming ideas...", "Getting creative!", "Inspiration incoming..."],+};++export const MEMORY_TYPES = ['fact', 'learning', 'observation', 'decision', 'preference', 'context'];++export const MEMORY_TYPE_COLORS = {+ fact: 'bg-blue-500/20 text-blue-400 border-blue-500/30',+ learning: 'bg-green-500/20 text-green-400 border-green-500/30',+ observation: 'bg-purple-500/20 text-purple-400 border-purple-500/30',+ decision: 'bg-orange-500/20 text-orange-400 border-orange-500/30',+ preference: 'bg-pink-500/20 text-pink-400 border-pink-500/30',+ context: 'bg-gray-500/20 text-gray-400 border-gray-500/30'+};diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.jsnew file mode 100644index 0000000000..aa34338975--- /dev/null+++ b/client/src/components/cos/index.js@@ -0,0 +1,24 @@+// Constants+export { TABS, AGENT_STATES, STATE_MESSAGES, MEMORY_TYPES, MEMORY_TYPE_COLORS } from './constants';++// Hook+export { default as useNextEvalCountdown } from './useNextEvalCountdown';++// Avatar/Character Components+export { default as CoSCharacter } from './CoSCharacter';+export { default as StateLabel } from './StateLabel';+export { default as TerminalCoSPanel } from './TerminalCoSPanel';++// UI Components+export { default as StatusIndicator } from './StatusIndicator';+export { default as StatCard } from './StatCard';+export { default as StatusBubble } from './StatusBubble';+export { default as EventLog } from './EventLog';++// Tab Components+export { default as TasksTab } from './tabs/TasksTab';+export { default as AgentsTab } from './tabs/AgentsTab';+export { default as ScriptsTab } from './tabs/ScriptsTab';+export { default as MemoryTab } from './tabs/MemoryTab';+export { default as HealthTab } from './tabs/HealthTab';+export { default as ConfigTab } from './tabs/ConfigTab';diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxnew file mode 100644index 0000000000..9da4897c20--- /dev/null+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -0,0 +1,180 @@+import { useState, useEffect } from 'react';+import {+ Cpu,+ Square,+ Trash2,+ CheckCircle,+ AlertCircle,+ RotateCcw,+ Loader2+} from 'lucide-react';+import * as api from '../../../services/api';++export default function AgentCard({ agent, onTerminate, 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);++ // Determine if this is a system agent (health check, etc.)+ const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');++ // Update duration display for running agents+ useEffect(() => {+ if (completed) return;+ const interval = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(interval);+ }, [completed]);++ // Fetch full output when expanded for completed agents+ useEffect(() => {+ if (expanded && completed && !fullOutput && !loadingOutput) {+ setLoadingOutput(true);+ api.getCosAgent(agent.id)+ .then(data => {+ setFullOutput(data.output || []);+ })+ .catch(() => {+ // Fall back to agent's stored output+ setFullOutput(agent.output || []);+ })+ .finally(() => setLoadingOutput(false));+ }+ }, [expanded, completed, agent.id, fullOutput, loadingOutput, agent.output]);++ const duration = agent.completedAt+ ? new Date(agent.completedAt) - new Date(agent.startedAt)+ : now - new Date(agent.startedAt);++ const formatDuration = (ms) => {+ const seconds = Math.floor(ms / 1000);+ const minutes = Math.floor(seconds / 60);+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;+ return `${seconds}s`;+ };++ // For running agents, use live output; for completed, use fetched full output or stored+ const output = completed+ ? (fullOutput || agent.output || [])+ : (liveOutput || agent.output || []);+ const lastOutput = output.length > 0 ? output[output.length - 1]?.line : null;++ return (+ <div className={`bg-port-card border rounded-lg overflow-hidden ${+ completed+ ? isSystemAgent ? 'border-port-border opacity-50' : 'border-port-border opacity-75'+ : 'border-port-accent/50'+ }`}>+ <div className="p-4">+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2 flex-wrap">+ <Cpu size={16} className={completed ? 'text-gray-500' : 'text-port-accent animate-pulse'} />+ <span className="font-mono text-sm text-gray-400">{agent.id}</span>+ {isSystemAgent && (+ <span className="px-1.5 py-0.5 text-xs bg-gray-500/20 text-gray-400 rounded">SYS</span>+ )}+ {agent.metadata?.model && (+ <span className={`px-2 py-0.5 text-xs rounded ${+ agent.metadata.modelTier === 'heavy' ? 'bg-purple-500/20 text-purple-400' :+ agent.metadata.modelTier === 'light' ? 'bg-green-500/20 text-green-400' :+ 'bg-blue-500/20 text-blue-400'+ }`} title={agent.metadata.modelReason}>+ {agent.metadata.model.replace('claude-', '').replace(/-\d+$/, '')}+ </span>+ )}+ {!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'}+ </span>+ )}+ </div>+ <div className="flex items-center gap-2">+ <span className="text-sm text-gray-500">{formatDuration(duration)}</span>+ {(output.length > 0 || completed) && (+ <button+ onClick={() => setExpanded(!expanded)}+ className="text-gray-500 hover:text-white transition-colors text-xs"+ >+ {expanded ? 'Hide' : 'Show'} Output+ </button>+ )}+ {!completed && onTerminate && (+ <button+ onClick={() => onTerminate(agent.id)}+ className="text-gray-500 hover:text-port-error transition-colors"+ title="Terminate"+ >+ <Square size={14} />+ </button>+ )}+ {completed && !isSystemAgent && onResume && (+ <button+ onClick={() => onResume(agent)}+ className="flex items-center gap-1 text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors"+ title="Create new task from this agent's context"+ >+ <RotateCcw size={12} />+ Resume+ </button>+ )}+ {completed && onDelete && (+ <button+ onClick={() => onDelete(agent.id)}+ className="text-gray-500 hover:text-port-error transition-colors"+ title="Remove"+ >+ <Trash2 size={14} />+ </button>+ )}+ </div>+ </div>+ <p className="text-white text-sm mb-2">{agent.metadata?.taskDescription || agent.taskId}</p>++ {/* Status / Last output line */}+ {!completed && lastOutput && (+ <div className="text-xs text-gray-500 font-mono truncate bg-port-bg/50 px-2 py-1 rounded">+ {lastOutput.substring(0, 100)}...+ </div>+ )}++ {agent.result && (+ <div className={`text-sm flex items-center gap-2 ${agent.result.success ? 'text-port-success' : 'text-port-error'}`}>+ {agent.result.success ? (+ <><CheckCircle size={14} /> Completed successfully</>+ ) : (+ <><AlertCircle size={14} /> {agent.result.error || 'Failed'}</>+ )}+ </div>+ )}+ </div>++ {/* Expanded output view */}+ {expanded && (+ <div className="border-t border-port-border bg-port-bg/50 p-3">+ {loadingOutput ? (+ <div className="flex items-center gap-2 text-gray-500 text-sm">+ <Loader2 size={14} className="animate-spin" />+ Loading full output...+ </div>+ ) : output.length > 0 ? (+ <pre className="text-xs font-mono text-gray-400 whitespace-pre-wrap">+ {output.map((o, i) => (+ <div key={i} className="py-0.5">+ {o.line}+ </div>+ ))}+ </pre>+ ) : (+ <div className="text-gray-500 text-sm">No output captured</div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsxnew file mode 100644index 0000000000..666244b566--- /dev/null+++ b/client/src/components/cos/tabs/AgentsTab.jsx@@ -0,0 +1,128 @@+import { useState } from 'react';+import { Trash2 } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';+import AgentCard from './AgentCard';+import ResumeAgentModal from './ResumeAgentModal';++export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, apps }) {+ const [resumingAgent, setResumingAgent] = useState(null);++ const handleTerminate = async (agentId) => {+ await api.terminateCosAgent(agentId).catch(err => toast.error(err.message));+ toast.success('Terminate signal sent');+ onRefresh();+ };++ const handleDelete = async (agentId) => {+ await api.deleteCosAgent(agentId).catch(err => toast.error(err.message));+ toast.success('Agent removed');+ onRefresh();+ };++ const handleResumeClick = (agent) => {+ setResumingAgent(agent);+ };++ const handleResumeSubmit = async ({ description, context, model, provider, app }) => {+ await api.addCosTask({+ description,+ context,+ model: model || undefined,+ provider: provider || undefined,+ app: app || undefined+ }).catch(err => {+ toast.error(err.message);+ return;+ });+ toast.success('Created resume task');+ setResumingAgent(null);+ onRefresh();+ };++ const handleClearCompleted = async () => {+ await api.clearCompletedCosAgents().catch(err => toast.error(err.message));+ toast.success('Cleared completed agents');+ onRefresh();+ };++ const runningAgents = agents.filter(a => a.status === 'running');+ // Sort completed agents by completion time (most recent first)+ const completedAgents = agents+ .filter(a => a.status === 'completed')+ .sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));++ return (+ <div className="space-y-6">+ {/* Active Agents */}+ <div>+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold text-white">Active Agents</h3>+ {runningAgents.length > 0 && (+ <span className="text-sm text-port-accent animate-pulse">+ {runningAgents.length} running+ </span>+ )}+ </div>+ {runningAgents.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No active agents. Start CoS and add tasks to see agents working.+ </div>+ ) : (+ <div className="space-y-2">+ {runningAgents.map(agent => (+ <AgentCard+ key={agent.id}+ agent={agent}+ onTerminate={handleTerminate}+ liveOutput={liveOutputs[agent.id]}+ />+ ))}+ </div>+ )}+ </div>++ {/* Completed Agents */}+ {completedAgents.length > 0 && (+ <div>+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold text-white">+ Completed Agents+ <span className="text-sm text-gray-500 font-normal ml-2">+ ({completedAgents.length} total)+ </span>+ </h3>+ <button+ onClick={handleClearCompleted}+ className="flex items-center gap-1 text-sm text-gray-500 hover:text-port-error transition-colors"+ >+ <Trash2 size={14} />+ Clear+ </button>+ </div>+ <div className="space-y-2">+ {completedAgents.slice(0, 15).map(agent => (+ <AgentCard key={agent.id} agent={agent} completed onDelete={handleDelete} onResume={handleResumeClick} />+ ))}+ {completedAgents.length > 15 && (+ <div className="text-center text-sm text-gray-500 py-2">+ + {completedAgents.length - 15} more completed agents+ </div>+ )}+ </div>+ </div>+ )}++ {/* Resume Modal */}+ {resumingAgent && (+ <ResumeAgentModal+ agent={resumingAgent}+ providers={providers}+ apps={apps}+ onSubmit={handleResumeSubmit}+ onClose={() => setResumingAgent(null)}+ />+ )}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/ConfigRow.jsx b/client/src/components/cos/tabs/ConfigRow.jsxnew file mode 100644index 0000000000..edcb9a4541--- /dev/null+++ b/client/src/components/cos/tabs/ConfigRow.jsx@@ -0,0 +1,31 @@+export default function ConfigRow({ label, value, editing, type, inputValue, onChange, suffix, tooltip }) {+ return (+ <div className="flex items-center justify-between p-4" title={tooltip}>+ <span className="text-gray-400 cursor-help">{label}</span>+ {editing ? (+ <div className="flex items-center gap-2">+ {type === 'checkbox' ? (+ <input+ type="checkbox"+ checked={inputValue}+ onChange={e => onChange(e.target.checked)}+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ ) : (+ <>+ <input+ type="number"+ value={inputValue}+ onChange={e => onChange(parseInt(e.target.value) || 0)}+ className="w-24 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm text-right"+ />+ {suffix && <span className="text-gray-500 text-sm">{suffix}</span>}+ </>+ )}+ </div>+ ) : (+ <span className="text-white">{value}</span>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxnew file mode 100644index 0000000000..85b283384c--- /dev/null+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -0,0 +1,171 @@+import { useState } from 'react';+import { Settings, Activity, CheckCircle, FileText } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';+import ConfigRow from './ConfigRow';++export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, setAvatarStyle, evalCountdown }) {+ const [editing, setEditing] = useState(false);+ const [formData, setFormData] = useState({+ evaluationIntervalMs: config?.evaluationIntervalMs || 60000,+ healthCheckIntervalMs: config?.healthCheckIntervalMs || 900000,+ maxConcurrentAgents: config?.maxConcurrentAgents || 3,+ maxProcessMemoryMb: config?.maxProcessMemoryMb || 2048,+ autoStart: config?.autoStart || false+ });++ const handleSave = async () => {+ await api.updateCosConfig(formData).catch(err => toast.error(err.message));+ toast.success('Configuration updated');+ setEditing(false);+ onUpdate();+ };++ return (+ <div className="space-y-6">+ <div className="flex items-center justify-between">+ <h3 className="text-lg font-semibold text-white">Configuration</h3>+ <div className="flex gap-2">+ <button+ onClick={onEvaluate}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors"+ title="Immediately check for pending tasks and spawn agents to work on them (normally runs on the evaluation interval)"+ >+ <Activity size={14} />+ Force Evaluate+ </button>+ {!editing ? (+ <button+ onClick={() => setEditing(true)}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"+ >+ <Settings size={14} />+ Edit+ </button>+ ) : (+ <button+ onClick={handleSave}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-success/20 hover:bg-port-success/30 text-port-success rounded-lg transition-colors"+ >+ <CheckCircle size={14} />+ Save+ </button>+ )}+ </div>+ </div>++ <div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">+ <ConfigRow+ label="Evaluation Interval"+ value={`${formData.evaluationIntervalMs / 1000}s`}+ editing={editing}+ type="number"+ inputValue={formData.evaluationIntervalMs / 1000}+ onChange={v => setFormData(f => ({ ...f, evaluationIntervalMs: v * 1000 }))}+ suffix="seconds"+ tooltip="How often CoS checks for pending tasks and spawns agents to work on them"+ />+ {evalCountdown && (+ <div className="flex items-center justify-between p-4 bg-port-accent/5">+ <span className="text-gray-500 text-sm">Next evaluation in</span>+ <span className="font-mono text-port-accent">{evalCountdown.formatted}</span>+ </div>+ )}+ <ConfigRow+ label="Health Check Interval"+ value={`${formData.healthCheckIntervalMs / 60000}m`}+ editing={editing}+ type="number"+ inputValue={formData.healthCheckIntervalMs / 60000}+ onChange={v => setFormData(f => ({ ...f, healthCheckIntervalMs: v * 60000 }))}+ suffix="minutes"+ tooltip="How often CoS runs system health checks (PM2 processes, memory usage, etc.)"+ />+ <ConfigRow+ label="Max Concurrent Agents"+ value={formData.maxConcurrentAgents}+ editing={editing}+ type="number"+ inputValue={formData.maxConcurrentAgents}+ onChange={v => setFormData(f => ({ ...f, maxConcurrentAgents: v }))}+ tooltip="Maximum number of AI agents that can run simultaneously"+ />+ <ConfigRow+ label="Max Process Memory"+ value={`${formData.maxProcessMemoryMb} MB`}+ editing={editing}+ type="number"+ inputValue={formData.maxProcessMemoryMb}+ onChange={v => setFormData(f => ({ ...f, maxProcessMemoryMb: v }))}+ suffix="MB"+ tooltip="Memory threshold for health alerts - processes exceeding this will be flagged"+ />+ <ConfigRow+ label="Auto Start"+ value={formData.autoStart ? 'Enabled' : 'Disabled'}+ editing={editing}+ type="checkbox"+ inputValue={formData.autoStart}+ onChange={v => setFormData(f => ({ ...f, autoStart: v }))}+ tooltip="Automatically start the CoS daemon when the server starts"+ />+ </div>++ {/* Avatar Style */}+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">Appearance</h4>+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div+ className="flex items-center justify-between"+ title="Choose the visual style for the CoS avatar in the sidebar panel"+ >+ <span className="text-gray-400 cursor-help">CoS Avatar Style</span>+ <select+ value={avatarStyle}+ onChange={async (e) => {+ const style = e.target.value;+ await setAvatarStyle(style);+ toast.success(`Avatar style changed to ${style === 'svg' ? 'Digital' : 'Minimalist'}`);+ }}+ className="bg-port-bg border border-port-border rounded px-3 py-1.5 text-white text-sm"+ >+ <option value="svg">Digital (SVG)</option>+ <option value="ascii">Minimalist (ASCII)</option>+ </select>+ </div>+ </div>+ </div>++ {/* MCP Servers */}+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">MCP Servers</h4>+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ {config?.mcpServers?.map((mcp, idx) => (+ <div key={idx} className="flex items-center gap-2 text-sm">+ <span className="text-port-accent font-mono">{mcp.name}</span>+ <span className="text-gray-500">:</span>+ <span className="text-gray-400">{mcp.command} {mcp.args?.join(' ')}</span>+ </div>+ )) || <span className="text-gray-500">No MCP servers configured</span>}+ </div>+ </div>++ {/* Task Files */}+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">Task Files</h4>+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-2">+ <div className="flex items-center gap-2 text-sm">+ <FileText size={14} className="text-gray-500" />+ <span className="text-gray-400">User Tasks:</span>+ <span className="text-white font-mono">{config?.userTasksFile || 'TASKS.md'}</span>+ </div>+ <div className="flex items-center gap-2 text-sm">+ <FileText size={14} className="text-gray-500" />+ <span className="text-gray-400">System Tasks:</span>+ <span className="text-white font-mono">{config?.cosTasksFile || 'COS-TASKS.md'}</span>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/cos/tabs/HealthTab.jsx b/client/src/components/cos/tabs/HealthTab.jsxnew file mode 100644index 0000000000..3ee4f9d6e3--- /dev/null+++ b/client/src/components/cos/tabs/HealthTab.jsx@@ -0,0 +1,56 @@+import { RefreshCw, CheckCircle, AlertCircle } from 'lucide-react';++export default function HealthTab({ health, onCheck }) {+ return (+ <div className="space-y-6">+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-lg font-semibold text-white">System Health</h3>+ {health?.lastCheck && (+ <p className="text-sm text-gray-500">+ Last check: {new Date(health.lastCheck).toLocaleString()}+ </p>+ )}+ </div>+ <button+ onClick={onCheck}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"+ >+ <RefreshCw size={14} />+ Run Check+ </button>+ </div>++ {!health?.issues || health.issues.length === 0 ? (+ <div className="bg-port-success/10 border border-port-success/30 rounded-lg p-6 text-center">+ <CheckCircle className="w-12 h-12 text-port-success mx-auto mb-3" />+ <p className="text-port-success font-medium">All Systems Healthy</p>+ <p className="text-gray-500 text-sm mt-1">No issues detected</p>+ </div>+ ) : (+ <div className="space-y-2">+ {health.issues.map((issue, idx) => (+ <div+ key={idx}+ className={`border rounded-lg p-4 ${+ issue.type === 'error'+ ? 'bg-port-error/10 border-port-error/30'+ : 'bg-yellow-500/10 border-yellow-500/30'+ }`}+ >+ <div className="flex items-center gap-2 mb-1">+ <AlertCircle size={16} className={issue.type === 'error' ? 'text-port-error' : 'text-yellow-500'} />+ <span className={`text-sm font-medium uppercase ${+ issue.type === 'error' ? 'text-port-error' : 'text-yellow-500'+ }`}>+ {issue.category}+ </span>+ </div>+ <p className="text-white">{issue.message}</p>+ </div>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/MemoryGraph.jsx b/client/src/components/cos/tabs/MemoryGraph.jsxnew file mode 100644index 0000000000..f2b6e04dcf--- /dev/null+++ b/client/src/components/cos/tabs/MemoryGraph.jsx@@ -0,0 +1,38 @@+import { useState, useEffect } from 'react';+import { RefreshCw, Brain } from 'lucide-react';+import * as api from '../../../services/api';++export default function MemoryGraph() {+ const [graphData, setGraphData] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ api.getMemoryGraph().then(setGraphData).catch(() => setGraphData(null)).finally(() => setLoading(false));+ }, []);++ if (loading) {+ return (+ <div className="flex items-center justify-center py-12">+ <RefreshCw className="animate-spin text-port-accent" size={24} />+ </div>+ );+ }++ if (!graphData || !graphData.nodes?.length) {+ return (+ <div className="text-center py-12 text-gray-500">+ No memory graph data available. Add more memories to see relationships.+ </div>+ );+ }++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 min-h-[400px]">+ <div className="text-center text-gray-500">+ <Brain size={48} className="mx-auto mb-4 text-port-accent/50" />+ <p>Graph visualization coming soon</p>+ <p className="text-sm mt-2">{graphData.nodes.length} nodes * {graphData.edges.length} connections</p>+ </div>+ </div>+ );+}diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsxnew file mode 100644index 0000000000..8c4e392289--- /dev/null+++ b/client/src/components/cos/tabs/MemoryTab.jsx@@ -0,0 +1,199 @@+import { useState, useEffect, useCallback } from 'react';+import { RefreshCw, Trash2, X } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';+import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';+import MemoryTimeline from './MemoryTimeline';+import MemoryGraph from './MemoryGraph';++export default function MemoryTab() {+ const [memories, setMemories] = useState([]);+ const [stats, setStats] = useState(null);+ const [loading, setLoading] = useState(true);+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState(null);+ const [view, setView] = useState('list'); // list, timeline, graph+ const [filters, setFilters] = useState({ types: [], categories: [] });+ const [categories, setCategories] = useState([]);+ const [embeddingStatus, setEmbeddingStatus] = useState(null);++ const fetchData = useCallback(async () => {+ setLoading(true);+ const [memoriesRes, statsRes, catsRes, embRes] = await Promise.all([+ api.getMemories({ limit: 100, ...filters }).catch(() => ({ memories: [] })),+ api.getMemoryStats().catch(() => null),+ api.getMemoryCategories().catch(() => []),+ api.getEmbeddingStatus().catch(() => null)+ ]);+ setMemories(memoriesRes.memories || []);+ setStats(statsRes);+ setCategories(catsRes);+ setEmbeddingStatus(embRes);+ setLoading(false);+ }, [filters]);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const handleSearch = async () => {+ if (!searchQuery.trim()) {+ setSearchResults(null);+ return;+ }+ setLoading(true);+ const results = await api.searchMemories(searchQuery, { limit: 20 }).catch(() => ({ memories: [] }));+ setSearchResults(results.memories || []);+ setLoading(false);+ };++ const handleDelete = async (id) => {+ await api.deleteMemory(id);+ toast.success('Memory archived');+ fetchData();+ };++ const displayMemories = searchResults || memories;++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-lg font-semibold text-white">Memory System</h3>+ <p className="text-sm text-gray-500">+ {stats?.active || 0} active memories+ {embeddingStatus?.available ? ' * LM Studio connected' : ' * LM Studio offline'}+ </p>+ </div>+ <div className="flex gap-2">+ {['list', 'timeline', 'graph'].map(v => (+ <button+ key={v}+ onClick={() => setView(v)}+ className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${+ view === v ? 'bg-port-accent text-white' : 'bg-port-border text-gray-400 hover:text-white'+ }`}+ >+ {v.charAt(0).toUpperCase() + v.slice(1)}+ </button>+ ))}+ </div>+ </div>++ {/* Search */}+ <div className="flex gap-2">+ <input+ type="text"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && handleSearch()}+ placeholder="Search memories semantically..."+ className="flex-1 bg-port-card border border-port-border rounded-lg px-4 py-2 text-white placeholder-gray-500 focus:border-port-accent outline-none"+ />+ <button+ onClick={handleSearch}+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"+ >+ Search+ </button>+ {searchResults && (+ <button+ onClick={() => { setSearchResults(null); setSearchQuery(''); }}+ className="px-3 py-2 bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors"+ >+ <X size={16} />+ </button>+ )}+ </div>++ {/* Type Filters */}+ <div className="flex flex-wrap gap-2">+ {MEMORY_TYPES.map(type => (+ <button+ key={type}+ onClick={() => {+ const newTypes = filters.types.includes(type)+ ? filters.types.filter(t => t !== type)+ : [...filters.types, type];+ setFilters({ ...filters, types: newTypes });+ }}+ className={`px-3 py-1 text-xs rounded-full border transition-colors ${+ filters.types.includes(type) ? MEMORY_TYPE_COLORS[type] : 'border-port-border text-gray-500 hover:text-gray-300'+ }`}+ >+ {type}+ </button>+ ))}+ </div>++ {/* Stats Row */}+ {stats && (+ <div className="grid grid-cols-3 md:grid-cols-6 gap-2">+ {Object.entries(stats.byType || {}).map(([type, count]) => (+ <div key={type} className={`p-2 rounded-lg border text-center ${MEMORY_TYPE_COLORS[type] || 'border-port-border'}`}>+ <div className="text-lg font-bold">{count}</div>+ <div className="text-xs opacity-75">{type}</div>+ </div>+ ))}+ </div>+ )}++ {/* Content */}+ {loading ? (+ <div className="flex items-center justify-center py-12">+ <RefreshCw className="animate-spin text-port-accent" size={24} />+ </div>+ ) : view === 'list' ? (+ <div className="space-y-3">+ {displayMemories.length === 0 ? (+ <div className="text-center py-12 text-gray-500">+ {searchQuery ? 'No memories found for this search' : 'No memories yet. Memories are extracted from agent task completions.'}+ </div>+ ) : (+ displayMemories.map(memory => (+ <div key={memory.id} className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-start justify-between gap-4">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-2">+ <span className={`px-2 py-0.5 text-xs rounded-full border ${MEMORY_TYPE_COLORS[memory.type]}`}>+ {memory.type}+ </span>+ <span className="text-xs text-gray-500">{memory.category}</span>+ {memory.similarity && (+ <span className="text-xs text-port-accent">{(memory.similarity * 100).toFixed(0)}% match</span>+ )}+ </div>+ <p className="text-white text-sm">{memory.summary || memory.content?.substring(0, 200)}</p>+ {memory.tags?.length > 0 && (+ <div className="flex gap-1 mt-2">+ {memory.tags.map(tag => (+ <span key={tag} className="px-2 py-0.5 text-xs bg-port-border rounded text-gray-400">+ {tag}+ </span>+ ))}+ </div>+ )}+ <div className="text-xs text-gray-500 mt-2">+ {new Date(memory.createdAt).toLocaleDateString()} * importance: {((memory.importance || 0.5) * 100).toFixed(0)}%+ </div>+ </div>+ <button+ onClick={() => handleDelete(memory.id)}+ className="p-2 text-gray-500 hover:text-port-error transition-colors"+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>+ ))+ )}+ </div>+ ) : view === 'timeline' ? (+ <MemoryTimeline memories={memories} />+ ) : (+ <MemoryGraph />+ )}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/MemoryTimeline.jsx b/client/src/components/cos/tabs/MemoryTimeline.jsxnew file mode 100644index 0000000000..6ebeb16432--- /dev/null+++ b/client/src/components/cos/tabs/MemoryTimeline.jsx@@ -0,0 +1,31 @@+export default function MemoryTimeline({ memories }) {+ const grouped = memories.reduce((acc, m) => {+ const date = m.createdAt?.split('T')[0] || 'Unknown';+ if (!acc[date]) acc[date] = [];+ acc[date].push(m);+ return acc;+ }, {});++ const dates = Object.keys(grouped).sort().reverse();++ return (+ <div className="space-y-6">+ {dates.map(date => (+ <div key={date}>+ <div className="text-sm font-medium text-gray-400 mb-2 sticky top-0 bg-port-bg py-1">+ {new Date(date).toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}+ </div>+ <div className="border-l border-port-border pl-4 space-y-3">+ {grouped[date].map(m => (+ <div key={m.id} className="relative">+ <div className="absolute -left-[21px] w-2 h-2 rounded-full bg-port-accent" />+ <div className="text-sm text-white">{m.summary}</div>+ <div className="text-xs text-gray-500 mt-1">{m.type} * {m.category}</div>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/ResumeAgentModal.jsx b/client/src/components/cos/tabs/ResumeAgentModal.jsxnew file mode 100644index 0000000000..ef4e387b82--- /dev/null+++ b/client/src/components/cos/tabs/ResumeAgentModal.jsx@@ -0,0 +1,167 @@+import { useState } from 'react';+import { X, CheckCircle, AlertCircle, RotateCcw } from 'lucide-react';++export default function ResumeAgentModal({ agent, providers, apps, onSubmit, onClose }) {+ const taskDescription = agent.metadata?.taskDescription || agent.taskId || 'Resume previous task';+ const outputSummary = agent.output?.length > 0+ ? agent.output.slice(-20).map(o => o.line).join('\n')+ : '';+ const resultInfo = agent.result+ ? (agent.result.success ? 'Previous run: Completed successfully' : `Previous run: Failed - ${agent.result.error || 'Unknown error'}`)+ : '';++ const initialContext = [+ '## Previous Agent Context',+ `Agent ID: ${agent.id}`,+ `Original Task: ${taskDescription}`,+ resultInfo,+ outputSummary ? `\n## Last Output:\n\`\`\`\n${outputSummary}\n\`\`\`` : ''+ ].filter(Boolean).join('\n');++ const [formData, setFormData] = useState({+ refinedInstructions: '',+ provider: agent.metadata?.provider || '',+ model: agent.metadata?.model || '',+ app: agent.metadata?.app || ''+ });++ const selectedProvider = providers?.find(p => p.id === formData.provider);+ const availableModels = selectedProvider?.models || [];++ const handleSubmit = (e) => {+ e.preventDefault();+ const fullContext = formData.refinedInstructions.trim()+ ? `## Additional Instructions\n${formData.refinedInstructions}\n\n${initialContext}`+ : initialContext;++ onSubmit({+ description: `[Resume] ${taskDescription}`,+ context: fullContext,+ model: formData.model,+ provider: formData.provider,+ app: formData.app+ });+ };++ 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-2xl max-h-[90vh] overflow-auto">+ <div className="flex items-center justify-between mb-4">+ <h2 className="text-xl font-bold text-white">Resume Agent Task</h2>+ <button+ onClick={onClose}+ className="text-gray-500 hover:text-white transition-colors"+ >+ <X size={20} />+ </button>+ </div>++ {/* Previous Task Info */}+ <div className="mb-4 p-3 bg-port-bg border border-port-border rounded-lg">+ <div className="text-sm text-gray-400 mb-1">Original Task</div>+ <div className="text-white">{taskDescription}</div>+ {agent.result && (+ <div className={`text-sm mt-2 flex items-center gap-2 ${agent.result.success ? 'text-port-success' : 'text-port-error'}`}>+ {agent.result.success ? (+ <><CheckCircle size={14} /> Completed successfully</>+ ) : (+ <><AlertCircle size={14} /> {agent.result.error || 'Failed'}</>+ )}+ </div>+ )}+ </div>++ <form onSubmit={handleSubmit} className="space-y-4">+ {/* Refined Instructions */}+ <div>+ <label className="block text-sm text-gray-400 mb-1">+ Additional Instructions (optional)+ </label>+ <textarea+ value={formData.refinedInstructions}+ onChange={e => setFormData({ ...formData, refinedInstructions: e.target.value })}+ placeholder="Provide refined or additional instructions for the resumed task..."+ rows={4}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none resize-none"+ autoFocus+ />+ </div>++ {/* App Selection */}+ <div>+ <label className="block text-sm text-gray-400 mb-1">Target App</label>+ <select+ value={formData.app}+ onChange={e => setFormData({ ...formData, app: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"+ >+ <option value="">PortOS (default)</option>+ {apps?.map(app => (+ <option key={app.id} value={app.id}>{app.name}</option>+ ))}+ </select>+ </div>++ {/* Provider and Model */}+ <div className="flex gap-3">+ <div className="flex-1">+ <label className="block text-sm text-gray-400 mb-1">Provider</label>+ <select+ value={formData.provider}+ onChange={e => setFormData({ ...formData, provider: e.target.value, model: '' })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"+ >+ <option value="">Auto (default)</option>+ {providers?.filter(p => p.enabled).map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ </div>+ <div className="flex-1">+ <label className="block text-sm text-gray-400 mb-1">Model</label>+ <select+ value={formData.model}+ onChange={e => setFormData({ ...formData, model: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"+ disabled={!formData.provider}+ >+ <option value="">{formData.provider ? 'Select model...' : 'Select provider first'}</option>+ {availableModels.map(m => (+ <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ ))}+ </select>+ </div>+ </div>++ {/* Context Preview (collapsed) */}+ <details className="text-sm">+ <summary className="text-gray-400 cursor-pointer hover:text-white transition-colors">+ View context to be included+ </summary>+ <pre className="mt-2 p-3 bg-port-bg border border-port-border rounded-lg text-gray-400 text-xs overflow-auto max-h-48 whitespace-pre-wrap">+ {initialContext}+ </pre>+ </details>++ {/* Actions */}+ <div className="flex justify-end gap-2 pt-2">+ <button+ type="button"+ onClick={onClose}+ className="px-4 py-2 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ type="submit"+ className="flex items-center gap-2 px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"+ >+ <RotateCcw size={14} />+ Queue Resume Task+ </button>+ </div>+ </form>+ </div>+ </div>+ );+}diff --git a/client/src/components/cos/tabs/ScriptCard.jsx b/client/src/components/cos/tabs/ScriptCard.jsxnew file mode 100644index 0000000000..fc78013f21--- /dev/null+++ b/client/src/components/cos/tabs/ScriptCard.jsx@@ -0,0 +1,243 @@+import { useState } from 'react';+import {+ Terminal,+ Play,+ Edit3,+ CheckCircle,+ Ban,+ Trash2,+ Save,+ Zap+} from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';++const scheduleLabels = {+ 'on-demand': 'On Demand',+ 'every-5-min': 'Every 5 min',+ 'every-15-min': 'Every 15 min',+ 'every-30-min': 'Every 30 min',+ 'hourly': 'Hourly',+ 'every-6-hours': 'Every 6 hours',+ 'daily': 'Daily',+ 'weekly': 'Weekly'+};++export default function ScriptCard({ script, onRun, onToggle, onDelete, onUpdate }) {+ const [expanded, setExpanded] = useState(false);+ const [editing, setEditing] = useState(false);+ const [editData, setEditData] = useState({+ name: script.name,+ description: script.description || '',+ command: script.command,+ schedule: script.schedule || 'on-demand',+ triggerAction: script.triggerAction || 'log-only',+ triggerPrompt: script.triggerPrompt || '',+ triggerPriority: script.triggerPriority || 'MEDIUM'+ });++ const handleSave = async () => {+ if (!editData.name.trim() || !editData.command.trim()) {+ toast.error('Name and command are required');+ return;+ }+ await api.updateCosScript(script.id, editData).catch(err => toast.error(err.message));+ toast.success('Script updated');+ setEditing(false);+ onUpdate?.();+ };++ const formatTime = (timestamp) => {+ if (!timestamp) return 'Never';+ const date = new Date(timestamp);+ const now = new Date();+ const diff = now - date;+ if (diff < 60000) return 'Just now';+ if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;+ return date.toLocaleDateString();+ };++ return (+ <div className={`bg-port-card border rounded-lg overflow-hidden ${+ script.enabled ? 'border-port-border' : 'border-port-border opacity-60'+ }`}>+ <div className="p-4">+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <Terminal size={16} className={script.enabled ? 'text-port-accent' : 'text-gray-500'} />+ <span className="font-medium text-white">{script.name}</span>+ <span className={`px-2 py-0.5 text-xs rounded ${+ script.schedule === 'on-demand' ? 'bg-gray-500/20 text-gray-400' : 'bg-port-accent/20 text-port-accent'+ }`}>+ {scheduleLabels[script.schedule] || script.schedule}+ </span>+ {script.triggerAction === 'spawn-agent' && (+ <span className="px-2 py-0.5 text-xs bg-purple-500/20 text-purple-400 rounded">+ <Zap size={10} className="inline mr-1" />+ Triggers Agent+ </span>+ )}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => onRun(script.id)}+ className="p-1.5 text-gray-500 hover:text-port-success transition-colors"+ title="Run now"+ >+ <Play size={14} />+ </button>+ <button+ onClick={() => setEditing(true)}+ className="p-1.5 text-gray-500 hover:text-white transition-colors"+ title="Edit"+ >+ <Edit3 size={14} />+ </button>+ <button+ onClick={() => onToggle(script)}+ className={`p-1.5 transition-colors ${+ script.enabled ? 'text-port-success hover:text-gray-500' : 'text-gray-500 hover:text-port-success'+ }`}+ title={script.enabled ? 'Disable' : 'Enable'}+ >+ {script.enabled ? <CheckCircle size={14} /> : <Ban size={14} />}+ </button>+ <button+ onClick={() => onDelete(script.id)}+ className="p-1.5 text-gray-500 hover:text-port-error transition-colors"+ title="Delete"+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>++ {/* Edit Form */}+ {editing ? (+ <div className="space-y-3 mt-3">+ <div className="flex gap-3">+ <input+ type="text"+ placeholder="Script name *"+ value={editData.name}+ onChange={e => setEditData(d => ({ ...d, name: e.target.value }))}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <select+ value={editData.schedule}+ onChange={e => setEditData(d => ({ ...d, schedule: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="on-demand">On Demand</option>+ <option value="every-5-min">Every 5 min</option>+ <option value="every-15-min">Every 15 min</option>+ <option value="hourly">Hourly</option>+ <option value="daily">Daily</option>+ <option value="weekly">Weekly</option>+ </select>+ </div>+ <input+ type="text"+ placeholder="Description"+ value={editData.description}+ onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <textarea+ placeholder="Shell command *"+ value={editData.command}+ onChange={e => setEditData(d => ({ ...d, command: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-20"+ />+ <div className="flex gap-3">+ <select+ value={editData.triggerAction}+ onChange={e => setEditData(d => ({ ...d, triggerAction: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="log-only">Log Only</option>+ <option value="spawn-agent">Spawn Agent</option>+ </select>+ <select+ value={editData.triggerPriority}+ onChange={e => setEditData(d => ({ ...d, triggerPriority: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="LOW">LOW</option>+ <option value="MEDIUM">MEDIUM</option>+ <option value="HIGH">HIGH</option>+ <option value="CRITICAL">CRITICAL</option>+ </select>+ </div>+ {editData.triggerAction === 'spawn-agent' && (+ <textarea+ placeholder="Prompt for agent when triggered"+ value={editData.triggerPrompt}+ onChange={e => setEditData(d => ({ ...d, triggerPrompt: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm h-16"+ />+ )}+ <div className="flex justify-end gap-2">+ <button+ onClick={() => setEditing(false)}+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleSave}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-success/20 hover:bg-port-success/30 text-port-success rounded-lg text-sm transition-colors"+ >+ <Save size={14} />+ Save+ </button>+ </div>+ </div>+ ) : (+ <>+ {script.description && (+ <p className="text-sm text-gray-400 mb-2">{script.description}</p>+ )}++ <div className="flex items-center gap-4 text-xs text-gray-500">+ <span>Last run: {formatTime(script.lastRun)}</span>+ {script.lastExitCode !== null && (+ <span className={script.lastExitCode === 0 ? 'text-port-success' : 'text-port-error'}>+ Exit: {script.lastExitCode}+ </span>+ )}+ <span>Runs: {script.runCount || 0}</span>+ {script.lastOutput && (+ <button+ onClick={() => setExpanded(!expanded)}+ className="text-port-accent hover:text-port-accent/80"+ >+ {expanded ? 'Hide' : 'Show'} output+ </button>+ )}+ </div>+ </>+ )}+ </div>++ {/* Command preview */}+ {!editing && (+ <div className="px-4 pb-3">+ <code className="text-xs text-gray-500 font-mono bg-port-bg/50 px-2 py-1 rounded block truncate">+ {script.command}+ </code>+ </div>+ )}++ {/* Expanded output */}+ {expanded && script.lastOutput && (+ <div className="border-t border-port-border bg-port-bg/50 p-3 max-h-48 overflow-y-auto">+ <pre className="text-xs font-mono text-gray-400 whitespace-pre-wrap">+ {script.lastOutput}+ </pre>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/ScriptsTab.jsx b/client/src/components/cos/tabs/ScriptsTab.jsxnew file mode 100644index 0000000000..5996280242--- /dev/null+++ b/client/src/components/cos/tabs/ScriptsTab.jsx@@ -0,0 +1,201 @@+import { useState } from 'react';+import { Plus, RefreshCw } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';+import ScriptCard from './ScriptCard';++export default function ScriptsTab({ scripts, onRefresh }) {+ const [showCreate, setShowCreate] = useState(false);+ const [newScript, setNewScript] = useState({+ name: '',+ description: '',+ command: '',+ schedule: 'on-demand',+ cronExpression: '',+ triggerAction: 'log-only',+ triggerPrompt: '',+ triggerPriority: 'MEDIUM'+ });++ const handleCreate = async () => {+ if (!newScript.name.trim() || !newScript.command.trim()) {+ toast.error('Name and command are required');+ return;+ }++ await api.createCosScript(newScript).catch(err => {+ toast.error(err.message);+ return;+ });++ toast.success('Script created');+ setNewScript({+ name: '',+ description: '',+ command: '',+ schedule: 'on-demand',+ cronExpression: '',+ triggerAction: 'log-only',+ triggerPrompt: '',+ triggerPriority: 'MEDIUM'+ });+ setShowCreate(false);+ onRefresh();+ };++ const handleRun = async (id) => {+ toast.loading('Running script...', { id: 'script-run' });+ const result = await api.runCosScript(id).catch(err => {+ toast.error(err.message, { id: 'script-run' });+ return null;+ });+ if (result) {+ if (result.success) {+ toast.success('Script completed', { id: 'script-run' });+ } else {+ toast.error(`Script failed: ${result.error || 'Unknown error'}`, { id: 'script-run' });+ }+ onRefresh();+ }+ };++ const handleToggle = async (script) => {+ await api.updateCosScript(script.id, { enabled: !script.enabled }).catch(err => toast.error(err.message));+ toast.success(script.enabled ? 'Script disabled' : 'Script enabled');+ onRefresh();+ };++ const handleDelete = async (id) => {+ await api.deleteCosScript(id).catch(err => toast.error(err.message));+ toast.success('Script deleted');+ onRefresh();+ };++ return (+ <div className="space-y-6">+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold text-white">Scheduled Scripts</h3>+ <div className="flex items-center gap-2">+ <button+ onClick={() => setShowCreate(!showCreate)}+ className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"+ >+ <Plus size={16} />+ New Script+ </button>+ <button+ onClick={onRefresh}+ className="text-gray-500 hover:text-white transition-colors"+ >+ <RefreshCw size={16} />+ </button>+ </div>+ </div>++ {/* Create Script Form */}+ {showCreate && (+ <div className="bg-port-card border border-port-accent/50 rounded-lg p-4 mb-4">+ <div className="space-y-3">+ <div className="flex gap-3">+ <input+ type="text"+ placeholder="Script name *"+ value={newScript.name}+ onChange={e => setNewScript(s => ({ ...s, name: e.target.value }))}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <select+ value={newScript.schedule}+ onChange={e => setNewScript(s => ({ ...s, schedule: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="on-demand">On Demand</option>+ <option value="every-5-min">Every 5 min</option>+ <option value="every-15-min">Every 15 min</option>+ <option value="hourly">Hourly</option>+ <option value="daily">Daily</option>+ <option value="weekly">Weekly</option>+ </select>+ </div>+ <input+ type="text"+ placeholder="Description"+ value={newScript.description}+ onChange={e => setNewScript(s => ({ ...s, description: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <textarea+ placeholder="Shell command *"+ value={newScript.command}+ onChange={e => setNewScript(s => ({ ...s, command: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-20"+ />+ <div className="flex gap-3">+ <select+ value={newScript.triggerAction}+ onChange={e => setNewScript(s => ({ ...s, triggerAction: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="log-only">Log Only</option>+ <option value="spawn-agent">Spawn Agent</option>+ </select>+ <select+ value={newScript.triggerPriority}+ onChange={e => setNewScript(s => ({ ...s, triggerPriority: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="LOW">LOW</option>+ <option value="MEDIUM">MEDIUM</option>+ <option value="HIGH">HIGH</option>+ <option value="CRITICAL">CRITICAL</option>+ </select>+ </div>+ {newScript.triggerAction === 'spawn-agent' && (+ <textarea+ placeholder="Prompt for agent when triggered"+ value={newScript.triggerPrompt}+ onChange={e => setNewScript(s => ({ ...s, triggerPrompt: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm h-16"+ />+ )}+ <div className="flex justify-end gap-2">+ <button+ onClick={() => setShowCreate(false)}+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleCreate}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"+ >+ <Plus size={14} />+ Create+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Scripts List */}+ {scripts.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No scripts configured. Create a script to automate tasks.+ </div>+ ) : (+ <div className="space-y-2">+ {scripts.map(script => (+ <ScriptCard+ key={script.id}+ script={script}+ onRun={handleRun}+ onToggle={handleToggle}+ onDelete={handleDelete}+ onUpdate={onRefresh}+ />+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/SortableTaskItem.jsx b/client/src/components/cos/tabs/SortableTaskItem.jsxnew file mode 100644index 0000000000..5ab9d25954--- /dev/null+++ b/client/src/components/cos/tabs/SortableTaskItem.jsx@@ -0,0 +1,32 @@+import { useSortable } from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';+import TaskItem from './TaskItem';++export default function SortableTaskItem({ task, onRefresh, providers }) {+ const {+ attributes,+ listeners,+ setNodeRef,+ transform,+ transition,+ isDragging,+ } = useSortable({ id: task.id });++ const style = {+ transform: CSS.Transform.toString(transform),+ transition,+ opacity: isDragging ? 0.5 : 1,+ zIndex: isDragging ? 1000 : 'auto',+ };++ return (+ <div ref={setNodeRef} style={style}>+ <TaskItem+ task={task}+ onRefresh={onRefresh}+ providers={providers}+ dragHandleProps={{ ...attributes, ...listeners }}+ />+ </div>+ );+}diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxnew file mode 100644index 0000000000..3e04069a53--- /dev/null+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -0,0 +1,200 @@+import { useState } from 'react';+import {+ Clock,+ Activity,+ CheckCircle,+ Ban,+ Trash2,+ Edit3,+ Save,+ X,+ GripVertical+} from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';++const statusIcons = {+ pending: <Clock size={16} className="text-yellow-500" />,+ in_progress: <Activity size={16} className="text-port-accent animate-pulse" />,+ completed: <CheckCircle size={16} className="text-port-success" />,+ blocked: <Ban size={16} className="text-port-error" />+};++export default function TaskItem({ task, isSystem, awaitingApproval, onRefresh, providers, dragHandleProps }) {+ const [editing, setEditing] = useState(false);+ const [editData, setEditData] = useState({+ description: task.description,+ context: task.metadata?.context || '',+ model: task.metadata?.model || '',+ provider: task.metadata?.provider || ''+ });++ // Get models for selected provider in edit mode+ const editProvider = providers?.find(p => p.id === editData.provider);+ const editModels = editProvider?.models || [];++ const handleStatusChange = async (newStatus) => {+ await api.updateCosTask(task.id, { status: newStatus }).catch(err => toast.error(err.message));+ toast.success(`Task marked as ${newStatus}`);+ onRefresh();+ };++ const handleSave = async () => {+ await api.updateCosTask(task.id, editData).catch(err => toast.error(err.message));+ toast.success('Task updated');+ setEditing(false);+ onRefresh();+ };++ const handleDelete = async () => {+ await api.deleteCosTask(task.id).catch(err => toast.error(err.message));+ toast.success('Task deleted');+ onRefresh();+ };++ const handleApprove = async () => {+ await api.approveCosTask(task.id).catch(err => toast.error(err.message));+ toast.success('Task approved');+ onRefresh();+ };++ return (+ <div className={`bg-port-card border rounded-lg p-4 group ${+ awaitingApproval ? 'border-yellow-500/50' : 'border-port-border'+ }`}>+ <div className="flex items-start gap-3">+ {/* Drag handle - only show for user tasks (not system or awaiting approval) */}+ {dragHandleProps && !isSystem && !awaitingApproval && (+ <button+ {...dragHandleProps}+ className="mt-0.5 cursor-grab active:cursor-grabbing text-gray-500 hover:text-gray-300 transition-colors touch-none"+ title="Drag to reorder"+ >+ <GripVertical size={16} />+ </button>+ )}+ <button+ onClick={() => handleStatusChange(task.status === 'completed' ? 'pending' : 'completed')}+ className="mt-0.5 hover:scale-110 transition-transform"+ title={task.status === 'completed' ? 'Mark as pending' : 'Mark as completed'}+ >+ {statusIcons[task.status]}+ </button>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-1 flex-wrap">+ <span className="text-sm font-mono text-gray-500">{task.id}</span>+ {isSystem && task.autoApproved && (+ <span className="px-2 py-0.5 rounded text-xs bg-port-success/20 text-port-success">AUTO</span>+ )}+ {awaitingApproval && (+ <button+ onClick={handleApprove}+ className="px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors"+ >+ APPROVE+ </button>+ )}+ </div>++ {editing ? (+ <div className="space-y-2">+ <input+ type="text"+ value={editData.description}+ onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ <input+ type="text"+ placeholder="Context"+ value={editData.context}+ onChange={e => setEditData(d => ({ ...d, context: e.target.value }))}+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ <div className="flex gap-2">+ <select+ value={editData.provider}+ onChange={e => setEditData(d => ({ ...d, provider: e.target.value, model: '' }))}+ className="w-36 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ >+ <option value="">Auto</option>+ {providers?.filter(p => p.enabled).map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ <select+ value={editData.model}+ onChange={e => setEditData(d => ({ ...d, model: e.target.value }))}+ className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ disabled={!editData.provider}+ >+ <option value="">{editData.provider ? 'Auto' : 'Select provider'}</option>+ {editModels.map(m => (+ <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ ))}+ </select>+ </div>+ <div className="flex gap-2">+ <button+ onClick={handleSave}+ className="flex items-center gap-1 text-xs text-port-success hover:text-port-success/80"+ >+ <Save size={12} /> Save+ </button>+ <button+ onClick={() => setEditing(false)}+ className="flex items-center gap-1 text-xs text-gray-500 hover:text-white"+ >+ <X size={12} /> Cancel+ </button>+ </div>+ </div>+ ) : (+ <>+ <p className="text-white">{task.description}</p>+ {task.metadata?.context && (+ <p className="text-sm text-gray-500 mt-1">{task.metadata.context}</p>+ )}+ {(task.metadata?.model || task.metadata?.provider) && (+ <div className="flex items-center gap-2 mt-1">+ {task.metadata?.model && (+ <span className="px-1.5 py-0.5 text-xs bg-purple-500/20 text-purple-400 rounded font-mono">+ {task.metadata.model}+ </span>+ )}+ {task.metadata?.provider && (+ <span className="px-1.5 py-0.5 text-xs bg-cyan-500/20 text-cyan-400 rounded">+ {task.metadata.provider}+ </span>+ )}+ </div>+ )}+ </>+ )}+ </div>++ {/* Action buttons */}+ <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">+ {!editing && (+ <>+ <button+ onClick={() => setEditing(true)}+ className="p-1 text-gray-500 hover:text-white transition-colors"+ title="Edit"+ >+ <Edit3 size={14} />+ </button>+ <button+ onClick={handleDelete}+ className="p-1 text-gray-500 hover:text-port-error transition-colors"+ title="Delete"+ >+ <Trash2 size={14} />+ </button>+ </>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxnew file mode 100644index 0000000000..7b3970c102--- /dev/null+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -0,0 +1,253 @@+import { useState, useEffect } from 'react';+import { Plus, RefreshCw } from 'lucide-react';+import toast from 'react-hot-toast';+import {+ DndContext,+ closestCenter,+ KeyboardSensor,+ PointerSensor,+ useSensor,+ useSensors,+} from '@dnd-kit/core';+import {+ arrayMove,+ SortableContext,+ sortableKeyboardCoordinates,+ verticalListSortingStrategy,+} from '@dnd-kit/sortable';+import * as api from '../../../services/api';+import TaskItem from './TaskItem';+import SortableTaskItem from './SortableTaskItem';++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 userTasks = tasks.user?.tasks || [];+ const cosTasks = tasks.cos?.tasks || [];++ // Keep local state in sync with server state+ useEffect(() => {+ setUserTasksLocal(userTasks);+ }, [userTasks]);++ // Drag and drop sensors+ const sensors = useSensors(+ useSensor(PointerSensor, {+ activationConstraint: { distance: 8 },+ }),+ useSensor(KeyboardSensor, {+ coordinateGetter: sortableKeyboardCoordinates,+ })+ );++ const handleDragEnd = async (event) => {+ const { active, over } = event;+ if (!over || active.id === over.id) return;++ const oldIndex = userTasksLocal.findIndex(t => t.id === active.id);+ const newIndex = userTasksLocal.findIndex(t => t.id === over.id);++ // Optimistically update local state+ const newOrder = arrayMove(userTasksLocal, oldIndex, newIndex);+ setUserTasksLocal(newOrder);++ // Persist to server+ const taskIds = newOrder.map(t => t.id);+ const result = await api.reorderCosTasks(taskIds).catch(err => {+ toast.error(err.message);+ setUserTasksLocal(userTasks); // Revert on error+ return null;+ });+ if (result?.success) {+ toast.success('Tasks reordered');+ onRefresh();+ }+ };++ // Get models for selected provider+ const selectedProvider = providers?.find(p => p.id === newTask.provider);+ const availableModels = selectedProvider?.models || [];++ const handleAddTask = async () => {+ if (!newTask.description.trim()) {+ toast.error('Description is required');+ return;+ }++ const taskId = newTask.id.trim() || `task-${Date.now()}`;+ await api.addCosTask({+ id: taskId,+ description: newTask.description,+ context: newTask.context,+ model: newTask.model || undefined,+ provider: newTask.provider || undefined,+ app: newTask.app || undefined+ }).catch(err => {+ toast.error(err.message);+ return;+ });++ toast.success('Task added');+ setNewTask({ id: '', description: '', context: '', model: '', provider: '', app: '' });+ setShowAddTask(false);+ onRefresh();+ };++ return (+ <div className="space-y-6">+ {/* User Tasks */}+ <div>+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold text-white">User Tasks (TASKS.md)</h3>+ <div className="flex items-center gap-2">+ <button+ onClick={() => setShowAddTask(!showAddTask)}+ className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"+ >+ <Plus size={16} />+ Add Task+ </button>+ <button+ onClick={onRefresh}+ className="text-gray-500 hover:text-white transition-colors"+ >+ <RefreshCw size={16} />+ </button>+ </div>+ </div>++ {/* Add Task Form */}+ {showAddTask && (+ <div className="bg-port-card border border-port-accent/50 rounded-lg p-4 mb-4">+ <div className="space-y-3">+ <input+ type="text"+ placeholder="Task ID (auto-generated if empty)"+ value={newTask.id}+ onChange={e => setNewTask(t => ({ ...t, id: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <input+ type="text"+ placeholder="Task description *"+ value={newTask.description}+ onChange={e => setNewTask(t => ({ ...t, description: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <input+ type="text"+ placeholder="Context (optional)"+ value={newTask.context}+ onChange={e => setNewTask(t => ({ ...t, context: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <div className="flex gap-3">+ <select+ value={newTask.app}+ onChange={e => setNewTask(t => ({ ...t, app: e.target.value }))}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="">PortOS (default)</option>+ {apps?.map(app => (+ <option key={app.id} value={app.id}>{app.name}</option>+ ))}+ </select>+ </div>+ <div className="flex gap-3">+ <select+ value={newTask.provider}+ onChange={e => setNewTask(t => ({ ...t, provider: e.target.value, model: '' }))}+ className="w-40 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="">Auto (default)</option>+ {providers?.filter(p => p.enabled).map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ <select+ value={newTask.model}+ onChange={e => setNewTask(t => ({ ...t, model: e.target.value }))}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ disabled={!newTask.provider}+ >+ <option value="">{newTask.provider ? 'Select model...' : 'Select provider first'}</option>+ {availableModels.map(m => (+ <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ ))}+ </select>+ </div>+ <div className="flex justify-end gap-2">+ <button+ onClick={() => setShowAddTask(false)}+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleAddTask}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"+ >+ <Plus size={14} />+ Add+ </button>+ </div>+ </div>+ </div>+ )}++ {userTasksLocal.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No user tasks. Click "Add Task" or edit TASKS.md directly.+ </div>+ ) : (+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={userTasksLocal.map(t => t.id)}+ strategy={verticalListSortingStrategy}+ >+ <div className="space-y-2">+ {userTasksLocal.map(task => (+ <SortableTaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} />+ ))}+ </div>+ </SortableContext>+ </DndContext>+ )}+ </div>++ {/* System Tasks */}+ <div>+ <h3 className="text-lg font-semibold text-white mb-3">System Tasks (COS-TASKS.md)</h3>++ {cosTasks.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No system tasks.+ </div>+ ) : (+ <div className="space-y-2">+ {cosTasks.map(task => (+ <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} />+ ))}+ </div>+ )}+ </div>++ {/* Awaiting Approval */}+ {tasks.cos?.awaitingApproval?.length > 0 && (+ <div>+ <h3 className="text-lg font-semibold text-yellow-500 mb-3">Awaiting Approval</h3>+ <div className="space-y-2">+ {tasks.cos.awaitingApproval.map(task => (+ <TaskItem key={task.id} task={task} awaitingApproval onRefresh={onRefresh} providers={providers} />+ ))}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/useNextEvalCountdown.js b/client/src/components/cos/useNextEvalCountdown.jsnew file mode 100644index 0000000000..5d3829fdd3--- /dev/null+++ b/client/src/components/cos/useNextEvalCountdown.js@@ -0,0 +1,37 @@+import { useState, useEffect } from 'react';++export default function useNextEvalCountdown(lastEvaluation, intervalMs, running) {+ const [countdown, setCountdown] = useState(null);++ useEffect(() => {+ if (!running || !lastEvaluation || !intervalMs) {+ setCountdown(null);+ return;+ }++ const updateCountdown = () => {+ const lastEvalTime = new Date(lastEvaluation).getTime();+ const nextEvalTime = lastEvalTime + intervalMs;+ const now = Date.now();+ const remaining = Math.max(0, nextEvalTime - now);++ if (remaining <= 0) {+ setCountdown({ seconds: 0, formatted: 'any moment...' });+ } else {+ const totalSeconds = Math.ceil(remaining / 1000);+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ const formatted = minutes > 0+ ? `${minutes}m ${seconds}s`+ : `${seconds}s`;+ setCountdown({ seconds: totalSeconds, formatted });+ }+ };++ updateCountdown();+ const timer = setInterval(updateCountdown, 1000);+ return () => clearInterval(timer);+ }, [lastEvaluation, intervalMs, running]);++ return countdown;+}diff --git a/client/src/index.css b/client/src/index.cssindex 12577a22cd..1cc0a20d41 100644--- a/client/src/index.css+++ b/client/src/index.css@@ -27,6 +27,15 @@ body {background: #4a4a4a;}+/* Hide scrollbar utility */+.scrollbar-hide {+ -ms-overflow-style: none;+ scrollbar-width: none;+}+.scrollbar-hide::-webkit-scrollbar {+ display: none;+}+/* Custom animations */@keyframes pulse-soft {0%, 100% {diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex a0a98b3523..705136a035 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -225,7 +225,7 @@ export default function AIProviders() {</span>{provider.id === activeProviderId && (<span className="text-xs px-2 py-0.5 rounded bg-port-accent/20 text-port-accent">- ACTIVE+ DEFAULT</span>)}{!provider.enabled && (@@ -303,7 +303,7 @@ export default function AIProviders() {onClick={() => handleSetActive(provider.id)}className="px-3 py-1 text-sm bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded transition-colors">- Set Active+ Set Default</button>)}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex ace8fa05e8..0699391bd4 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -1,311 +1,43 @@import { useState, useEffect, useCallback } from 'react';+import { useParams, useNavigate } from 'react-router-dom';import { useSocket } from '../hooks/useSocket';import * as api from '../services/api';-import {- Play,- Square,- RefreshCw,- CheckCircle,- Clock,- AlertCircle,- Ban,- Activity,- FileText,- Settings,- Cpu,- Trash2,- Plus,- Edit3,- Save,- X,- Terminal,- Zap,- GripVertical,- Brain-} from 'lucide-react';+import { Play, Square, Clock, CheckCircle, AlertCircle, Cpu } from 'lucide-react';import toast from 'react-hot-toast';-import {- DndContext,- closestCenter,- KeyboardSensor,- PointerSensor,- useSensor,- useSensors,-} from '@dnd-kit/core';-import {- arrayMove,- SortableContext,- sortableKeyboardCoordinates,- useSortable,- verticalListSortingStrategy,-} from '@dnd-kit/sortable';-import { CSS } from '@dnd-kit/utilities';--const TABS = [- { id: 'tasks', label: 'Tasks', icon: FileText },- { id: 'agents', label: 'Agents', icon: Cpu },- { id: 'scripts', label: 'Scripts', icon: Terminal },- { id: 'memory', label: 'Memory', icon: Brain },- { id: 'health', label: 'Health', icon: Activity },- { id: 'config', label: 'Config', icon: Settings }-];--const AGENT_STATES = {- sleeping: { label: 'Sleeping', color: '#6366f1', icon: '💤' },- thinking: { label: 'Thinking', color: '#f59e0b', icon: '🧠' },- coding: { label: 'Coding', color: '#10b981', icon: '⚡' },- investigating: { label: 'Investigating', color: '#ec4899', icon: '🔍' },- reviewing: { label: 'Reviewing', color: '#8b5cf6', icon: '📋' },- planning: { label: 'Planning', color: '#06b6d4', icon: '📐' },- ideating: { label: 'Ideating', color: '#f97316', icon: '💡' },-};--const STATE_MESSAGES = {- sleeping: ["Resting... Wake me if you need anything!", "💤 Power saving mode..."],- thinking: ["Processing your request...", "Analyzing the situation...", "Let me think about this..."],- coding: ["Writing some code...", "Implementing the solution...", "Building something cool..."],- investigating: ["Looking into this...", "Researching the topic...", "Gathering information..."],- reviewing: ["Checking the details...", "Reviewing for quality...", "Making sure everything's right..."],- planning: ["Organizing the approach...", "Mapping out the strategy...", "Creating a plan..."],- ideating: ["Brainstorming ideas...", "Getting creative!", "Inspiration incoming..."],-};--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">- <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%">- <stop offset="0%" stopColor="#1e293b" />- <stop offset="100%" stopColor="#0f172a" />- </linearGradient>- <linearGradient id="screenGrad" x1="0%" y1="0%" x2="0%" y2="100%">- <stop offset="0%" stopColor={stateConfig.color} stopOpacity="0.3" />- <stop offset="100%" stopColor={stateConfig.color} stopOpacity="0.1" />- </linearGradient>- <filter id="glow">- <feGaussianBlur stdDeviation="3" result="coloredBlur"/>- <feMerge>- <feMergeNode in="coloredBlur"/>- <feMergeNode in="SourceGraphic"/>- </feMerge>- </filter>- <filter id="innerGlow">- <feGaussianBlur stdDeviation="2" result="blur"/>- <feComposite in="SourceGraphic" in2="blur" operator="over"/>- </filter>- </defs>-- {/* Particles */}- <g className={`particles particles-${state}`}>- {[- { cx: 30, cy: 50 },- { cx: 170, cy: 60 },- { cx: 25, cy: 130 },- { cx: 175, cy: 140 },- { cx: 40, cy: 200 },- { cx: 160, cy: 190 }- ].map((pos, i) => (- <circle- key={i}- cx={pos.cx}- cy={pos.cy}- r="2"- fill={stateConfig.color}- opacity="0.6"- className={`cos-particle cos-particle-${i}`}- />- ))}- </g>-- {/* Body */}- <rect x="50" y="90" width="100" height="120" rx="20" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" />-- {/* Chest Screen */}- <rect x="60" y="100" width="80" height="50" rx="8" fill="#0f172a" stroke={stateConfig.color} strokeWidth="1" opacity="0.8" />- <rect x="65" y="105" width="70" height="40" rx="5" fill="url(#screenGrad)" />-- {/* Chest Display Content */}- <g className="chest-display">- {state === 'coding' && (- <g className="code-lines">- {[0, 1, 2, 3].map(i => (- <rect key={i} x="70" y={110 + i * 8} width={30 + (i % 2) * 15} height="3" rx="1" fill={stateConfig.color} opacity="0.8" className={`code-line code-line-${i}`} />- ))}- </g>- )}- {state === 'thinking' && (- <g className="thinking-dots">- {[0, 1, 2].map(i => (- <circle key={i} cx={85 + i * 15} cy="125" r="4" fill={stateConfig.color} className={`thinking-dot thinking-dot-${i}`} />- ))}- </g>- )}- {state === 'planning' && (- <g className="plan-grid">- {[0, 1, 2].map(row =>- [0, 1, 2].map(col => (- <rect key={`${row}-${col}`} x={72 + col * 20} y={108 + row * 12} width="15" height="8" rx="2" fill={stateConfig.color} opacity={0.4 + ((row + col) % 3) * 0.2} className="plan-cell" />- ))- )}- </g>- )}- {state === 'investigating' && (- <g className="scan-line-group">- <line x1="70" y1="125" x2="130" y2="125" stroke={stateConfig.color} strokeWidth="2" className="scan-line" />- </g>- )}- {state === 'reviewing' && (- <g className="review-checks">- {[0, 1, 2].map(i => (- <path key={i} d={`M${75 + i * 20},125 l4,4 l8,-8`} stroke={stateConfig.color} strokeWidth="2" fill="none" className={`check check-${i}`} />- ))}- </g>- )}- {state === 'ideating' && (- <g className="lightbulb">- <ellipse cx="100" cy="120" rx="12" ry="15" fill={stateConfig.color} opacity="0.3" className="bulb-glow" />- <ellipse cx="100" cy="120" rx="8" ry="10" fill={stateConfig.color} className="bulb" />- </g>- )}- {state === 'sleeping' && (- <g className="zzz">- <text x="80" y="130" fill={stateConfig.color} fontSize="16" fontFamily="monospace" className="cos-z cos-z-1">Z</text>- <text x="95" y="120" fill={stateConfig.color} fontSize="12" fontFamily="monospace" className="cos-z cos-z-2">z</text>- <text x="105" y="112" fill={stateConfig.color} fontSize="8" fontFamily="monospace" className="cos-z cos-z-3">z</text>- </g>- )}- </g>-- {/* Arms */}- <rect x="30" y="100" width="18" height="60" rx="9" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`arm arm-left arm-${state}`} />- <rect x="152" y="100" width="18" height="60" rx="9" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`arm arm-right arm-${state}`} />-- {/* Hands */}- <circle cx="39" cy="165" r="10" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`hand hand-left hand-${state}`} />- <circle cx="161" cy="165" r="10" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`hand hand-right hand-${state}`} />-- {/* Head */}- <rect x="55" y="20" width="90" height="75" rx="15" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" />-- {/* Face Screen */}- <rect x="62" y="28" width="76" height="55" rx="10" fill="#0f172a" stroke={stateConfig.color} strokeWidth="1.5" filter="url(#innerGlow)" />-- {/* Eyes */}- <g className={`eyes eyes-${state}`}>- {state === 'sleeping' ? (- <>- <line x1="75" y1="50" x2="90" y2="50" stroke={stateConfig.color} strokeWidth="3" strokeLinecap="round" />- <line x1="110" y1="50" x2="125" y2="50" stroke={stateConfig.color} strokeWidth="3" strokeLinecap="round" />- </>- ) : (- <>- <ellipse cx="82" cy="48" rx="10" ry={state === 'investigating' ? 12 : 8} fill={stateConfig.color} filter="url(#glow)" className="eye eye-left" />- <ellipse cx="118" cy="48" rx="10" ry={state === 'investigating' ? 12 : 8} fill={stateConfig.color} filter="url(#glow)" className="eye eye-right" />- <circle cx="82" cy="48" r="3" fill="#0f172a" className="pupil pupil-left" />- <circle cx="118" cy="48" r="3" fill="#0f172a" className="pupil pupil-right" />- </>- )}- </g>-- {/* Mouth */}- <g className={`mouth mouth-${state} ${speaking ? 'speaking' : ''}`}>- {speaking ? (- <ellipse cx="100" cy="70" rx="12" ry="6" fill={stateConfig.color} opacity="0.8" className="mouth-open" />- ) : state === 'sleeping' ? (- <ellipse cx="100" cy="68" rx="8" ry="3" fill={stateConfig.color} opacity="0.5" />- ) : (- <path d="M88,68 Q100,78 112,68" stroke={stateConfig.color} strokeWidth="2" fill="none" strokeLinecap="round" />- )}- </g>-- {/* Antenna */}- <line x1="100" y1="20" x2="100" y2="5" stroke="#334155" strokeWidth="3" />- <circle cx="100" cy="5" r="5" fill={stateConfig.color} filter="url(#glow)" className="antenna-light" />-- {/* Status Light */}- <circle cx="148" cy="35" r="4" fill={stateConfig.color} filter="url(#glow)" className="status-light" />- </svg>- </div>- );-}--function StateLabel({ state }) {- const stateConfig = AGENT_STATES[state] || AGENT_STATES.sleeping;-- return (- <div- className="flex items-center gap-2 px-4 py-2 rounded-full mt-4 font-mono text-xs"- style={{- background: 'rgba(15, 23, 42, 0.8)',- border: `1px solid ${stateConfig.color}`,- boxShadow: `0 0 20px rgba(99, 102, 241, 0.2)`- }}- >- <span className="text-base">{stateConfig.icon}</span>- <span className="text-gray-100">{stateConfig.label}</span>- </div>- );-}-function StatusBubble({ message }) {- return (- <div className="relative mt-4 px-4 py-3 rounded-2xl max-w-[280px] text-center text-sm leading-relaxed bg-indigo-500/10 border border-indigo-500/30">- <div- className="absolute -top-2 left-1/2 -translate-x-1/2 rotate-45 w-3.5 h-3.5 bg-indigo-500/10 border-l border-t border-indigo-500/30"- />- {message}- </div>- );-}--function EventLog({ logs }) {- if (!logs || logs.length === 0) return null;-- const levelColors = {- info: 'text-blue-400',- warn: 'text-yellow-400',- error: 'text-red-400',- success: 'text-green-400',- debug: 'text-gray-500'- };-- const levelIcons = {- info: 'ℹ️',- warn: '⚠️',- error: '❌',- success: '✅',- debug: '🔍'- };-- return (- <div className="mt-4 w-full max-w-[280px]">- <div className="text-xs text-gray-500 mb-1 font-mono">Event Log</div>- <div className="bg-slate-900/80 border border-slate-700/50 rounded-lg p-2 max-h-32 overflow-y-auto">- {logs.slice(-5).reverse().map((log, i) => (- <div key={i} className={`text-xs font-mono py-0.5 ${levelColors[log.level] || 'text-gray-400'}`}>- <span className="mr-1">{levelIcons[log.level] || '•'}</span>- <span className="text-gray-500">{new Date(log.timestamp).toLocaleTimeString()}</span>- {' '}- <span>{log.message}</span>- </div>- ))}- </div>- </div>- );-}+// Import from modular components+import {+ TABS,+ STATE_MESSAGES,+ useNextEvalCountdown,+ CoSCharacter,+ StateLabel,+ TerminalCoSPanel,+ StatusIndicator,+ StatCard,+ StatusBubble,+ EventLog,+ TasksTab,+ AgentsTab,+ ScriptsTab,+ MemoryTab,+ HealthTab,+ ConfigTab+} from '../components/cos';export default function ChiefOfStaff() {+ const { tab } = useParams();+ const navigate = useNavigate();+ const activeTab = tab || 'tasks';+const [status, setStatus] = useState(null);const [tasks, setTasks] = useState({ user: null, cos: null });const [agents, setAgents] = useState([]);const [scripts, setScripts] = useState([]);const [health, setHealth] = useState(null);const [providers, setProviders] = useState([]);+ const [apps, setApps] = useState([]);const [loading, setLoading] = useState(true);- const [activeTab, setActiveTab] = useState('tasks');const [agentState, setAgentState] = useState('sleeping');const [speaking, setSpeaking] = useState(false);const [statusMessage, setStatusMessage] = useState("Ready to help organize your day!");@@ -313,6 +45,22 @@ export default function ChiefOfStaff() {const [eventLogs, setEventLogs] = useState([]);const socket = useSocket();+ // Derive avatar style from server config+ const avatarStyle = status?.config?.avatarStyle || 'svg';++ // Update avatar style via server config+ const setAvatarStyle = async (style) => {+ await api.updateCosConfig({ avatarStyle: style });+ fetchData();+ };++ // Countdown to next evaluation+ const evalCountdown = useNextEvalCountdown(+ status?.stats?.lastEvaluation,+ status?.config?.evaluationIntervalMs,+ status?.running+ );+// Derive agent state from system statusconst deriveAgentState = useCallback((statusData, agentsData, healthData) => {if (!statusData?.running) return 'sleeping';@@ -327,13 +75,14 @@ export default function ChiefOfStaff() {}, []);const fetchData = useCallback(async () => {- const [statusData, tasksData, agentsData, scriptsData, healthData, providersData] = await Promise.all([+ const [statusData, tasksData, agentsData, scriptsData, healthData, providersData, appsData] = await Promise.all([api.getCosStatus().catch(() => null),api.getCosTasks().catch(() => ({ user: null, cos: null })),api.getCosAgents().catch(() => []),api.getCosScripts().catch(() => ({ scripts: [] })),api.getCosHealth().catch(() => null),- api.getProviders().catch(() => ({ providers: [] }))+ api.getProviders().catch(() => ({ providers: [] })),+ api.getApps().catch(() => [])]);setStatus(statusData);setTasks(tasksData);@@ -341,6 +90,8 @@ export default function ChiefOfStaff() {setScripts(scriptsData.scripts || []);setHealth(healthData);setProviders(providersData.providers || []);+ // Filter out PortOS Autofixer (it's part of PortOS project)+ setApps(appsData.filter(a => a.id !== 'portos-autofixer'));setLoading(false);const newState = deriveAgentState(statusData, agentsData, healthData);@@ -522,67 +273,81 @@ export default function ChiefOfStaff() {const hasIssues = (health?.issues?.length || 0) > 0;return (- <div className="flex flex-col lg:grid lg:grid-cols-[320px_1fr] min-h-[calc(100vh-120px)] -m-6">+ <div className="flex flex-col lg:grid lg:grid-cols-[320px_1fr] h-screen">{/* Agent Panel */}- <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 overflow-hidden">- {/* Background Effects */}- <div- className="absolute inset-0 pointer-events-none"- style={{- background: `- radial-gradient(circle at 50% 20%, rgba(99, 102, 241, 0.1) 0%, transparent 50%),- repeating-linear-gradient(0deg, transparent, transparent 50px, rgba(99, 102, 241, 0.03) 50px, rgba(99, 102, 241, 0.03) 51px)- `- }}+ {avatarStyle === 'ascii' ? (+ <TerminalCoSPanel+ state={agentState}+ speaking={speaking}+ statusMessage={statusMessage}+ eventLogs={eventLogs}+ running={status?.running}+ onStart={handleStart}+ onStop={handleStop}+ stats={status?.stats}+ evalCountdown={evalCountdown}/>-- <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">- Digital Assistant- </div>- <h1- className="text-2xl lg:text-3xl font-bold mb-4 lg:mb-8"+ ) : (+ <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">+ {/* Background Effects */}+ <div+ className="absolute inset-0 pointer-events-none"style={{- background: 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)',- WebkitBackgroundClip: 'text',- WebkitTextFillColor: 'transparent',- backgroundClip: 'text'+ background: `+ radial-gradient(circle at 50% 20%, rgba(99, 102, 241, 0.1) 0%, transparent 50%),+ repeating-linear-gradient(0deg, transparent, transparent 50px, rgba(99, 102, 241, 0.03) 50px, rgba(99, 102, 241, 0.03) 51px)+ `}}- >- Chief of Staff- </h1>+ />++ <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">+ Digital Assistant+ </div>+ <h1+ className="text-2xl lg:text-3xl font-bold mb-4 lg:mb-8"+ style={{+ background: 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)',+ WebkitBackgroundClip: 'text',+ WebkitTextFillColor: 'transparent',+ backgroundClip: 'text'+ }}+ >+ Chief of Staff+ </h1>- <CoSCharacter state={agentState} speaking={speaking} />- <StateLabel state={agentState} />- <StatusBubble message={statusMessage} />- {status?.running && <EventLog logs={eventLogs} />}+ <CoSCharacter state={agentState} speaking={speaking} />+ <StateLabel state={agentState} />+ <StatusBubble message={statusMessage} countdown={evalCountdown} />+ {status?.running && <EventLog logs={eventLogs} />}- {/* Control Buttons */}- <div className="flex items-center gap-3 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"- >- <Square size={16} />- 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"- >- <Play size={16} />- Start- </button>- )}- <StatusIndicator running={status?.running} />+ {/* Control Buttons */}+ <div className="flex items-center gap-3 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"+ >+ <Square size={16} />+ 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"+ >+ <Play size={16} />+ Start+ </button>+ )}+ <StatusIndicator running={status?.running} />+ </div></div></div>- </div>+ )}{/* Content Panel */}- <div className="flex-1 p-6 lg:p-8 overflow-y-auto">+ <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"><StatCard@@ -610,21 +375,21 @@ export default function ChiefOfStaff() {</div>{/* Tabs */}- <div className="flex gap-1 mb-6 border-b border-port-border overflow-x-auto">- {TABS.map(tab => {- const Icon = tab.icon;+ <div className="flex gap-1 mb-6 border-b border-port-border overflow-x-auto scrollbar-hide">+ {TABS.map(tabItem => {+ const Icon = tabItem.icon;return (<button- key={tab.id}- onClick={() => setActiveTab(tab.id)}+ 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 ${- activeTab === tab.id+ activeTab === tabItem.id? 'text-port-accent border-port-accent': 'text-gray-500 border-transparent hover:text-white'}`}><Icon size={16} />- {tab.label}+ {tabItem.label}</button>);})}@@ -632,10 +397,10 @@ export default function ChiefOfStaff() {{/* Tab Content */}{activeTab === 'tasks' && (- <TasksTab tasks={tasks} onRefresh={fetchData} providers={providers} />+ <TasksTab tasks={tasks} onRefresh={fetchData} providers={providers} apps={apps} />)}{activeTab === 'agents' && (- <AgentsTab agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} />+ <AgentsTab agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} providers={providers} apps={apps} />)}{activeTab === 'scripts' && (<ScriptsTab scripts={scripts} onRefresh={fetchData} />@@ -647,1608 +412,9 @@ export default function ChiefOfStaff() {<HealthTab health={health} onCheck={handleHealthCheck} />)}{activeTab === 'config' && (- <ConfigTab config={status?.config} onUpdate={fetchData} onEvaluate={handleForceEvaluate} />- )}- </div>- </div>- );-}--function StatusIndicator({ running }) {- return (- <div className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm ${- running- ? 'bg-port-success/20 text-port-success'- : 'bg-gray-700 text-gray-400'- }`}>- <span className={`w-2 h-2 rounded-full ${running ? 'bg-port-success animate-pulse' : 'bg-gray-500'}`} />- {running ? 'Running' : 'Stopped'}- </div>- );-}--function StatCard({ label, value, icon, active, activeLabel }) {- return (- <div className={`bg-port-card border rounded-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' : ''}>- {icon}- </div>- </div>- <div className="text-2xl font-bold text-white">{value}</div>- {active && activeLabel && (- <div className="text-xs text-port-accent mt-1 truncate animate-pulse">- {activeLabel}- </div>- )}- </div>- );-}--function TasksTab({ tasks, onRefresh, providers }) {- const [showAddTask, setShowAddTask] = useState(false);- const [newTask, setNewTask] = useState({ id: '', description: '', context: '', model: '', provider: '' });- const [userTasksLocal, setUserTasksLocal] = useState([]);- const userTasks = tasks.user?.tasks || [];- const cosTasks = tasks.cos?.tasks || [];-- // Keep local state in sync with server state- useEffect(() => {- setUserTasksLocal(userTasks);- }, [userTasks]);-- // Drag and drop sensors- const sensors = useSensors(- useSensor(PointerSensor, {- activationConstraint: { distance: 8 },- }),- useSensor(KeyboardSensor, {- coordinateGetter: sortableKeyboardCoordinates,- })- );-- const handleDragEnd = async (event) => {- const { active, over } = event;- if (!over || active.id === over.id) return;-- const oldIndex = userTasksLocal.findIndex(t => t.id === active.id);- const newIndex = userTasksLocal.findIndex(t => t.id === over.id);-- // Optimistically update local state- const newOrder = arrayMove(userTasksLocal, oldIndex, newIndex);- setUserTasksLocal(newOrder);-- // Persist to server- const taskIds = newOrder.map(t => t.id);- const result = await api.reorderCosTasks(taskIds).catch(err => {- toast.error(err.message);- setUserTasksLocal(userTasks); // Revert on error- return null;- });- if (result?.success) {- toast.success('Tasks reordered');- onRefresh();- }- };-- // Get models for selected provider- const selectedProvider = providers?.find(p => p.id === newTask.provider);- const availableModels = selectedProvider?.models || [];-- const handleAddTask = async () => {- if (!newTask.description.trim()) {- toast.error('Description is required');- return;- }-- const taskId = newTask.id.trim() || `task-${Date.now()}`;- await api.addCosTask({- id: taskId,- description: newTask.description,- context: newTask.context,- model: newTask.model || undefined,- provider: newTask.provider || undefined- }).catch(err => {- toast.error(err.message);- return;- });-- toast.success('Task added');- setNewTask({ id: '', description: '', context: '', model: '', provider: '' });- setShowAddTask(false);- onRefresh();- };-- return (- <div className="space-y-6">- {/* User Tasks */}- <div>- <div className="flex items-center justify-between mb-3">- <h3 className="text-lg font-semibold text-white">User Tasks (TASKS.md)</h3>- <div className="flex items-center gap-2">- <button- onClick={() => setShowAddTask(!showAddTask)}- className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"- >- <Plus size={16} />- Add Task- </button>- <button- onClick={onRefresh}- className="text-gray-500 hover:text-white transition-colors"- >- <RefreshCw size={16} />- </button>- </div>- </div>-- {/* Add Task Form */}- {showAddTask && (- <div className="bg-port-card border border-port-accent/50 rounded-lg p-4 mb-4">- <div className="space-y-3">- <input- type="text"- placeholder="Task ID (auto-generated if empty)"- value={newTask.id}- onChange={e => setNewTask(t => ({ ...t, id: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- />- <input- type="text"- placeholder="Task description *"- value={newTask.description}- onChange={e => setNewTask(t => ({ ...t, description: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- />- <input- type="text"- placeholder="Context (optional)"- value={newTask.context}- onChange={e => setNewTask(t => ({ ...t, context: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- />- <div className="flex gap-3">- <select- value={newTask.provider}- onChange={e => setNewTask(t => ({ ...t, provider: e.target.value, model: '' }))}- className="w-40 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- <option value="">Auto (default)</option>- {providers?.filter(p => p.enabled).map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>- <select- value={newTask.model}- onChange={e => setNewTask(t => ({ ...t, model: e.target.value }))}- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- disabled={!newTask.provider}- >- <option value="">{newTask.provider ? 'Select model...' : 'Select provider first'}</option>- {availableModels.map(m => (- <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>- ))}- </select>- </div>- <div className="flex justify-end gap-2">- <button- onClick={() => setShowAddTask(false)}- className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"- >- Cancel- </button>- <button- onClick={handleAddTask}- className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"- >- <Plus size={14} />- Add- </button>- </div>- </div>- </div>- )}-- {userTasksLocal.length === 0 ? (- <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">- No user tasks. Click "Add Task" or edit TASKS.md directly.- </div>- ) : (- <DndContext- sensors={sensors}- collisionDetection={closestCenter}- onDragEnd={handleDragEnd}- >- <SortableContext- items={userTasksLocal.map(t => t.id)}- strategy={verticalListSortingStrategy}- >- <div className="space-y-2">- {userTasksLocal.map(task => (- <SortableTaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} />- ))}- </div>- </SortableContext>- </DndContext>- )}- </div>-- {/* System Tasks */}- <div>- <h3 className="text-lg font-semibold text-white mb-3">System Tasks (COS-TASKS.md)</h3>-- {cosTasks.length === 0 ? (- <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">- No system tasks.- </div>- ) : (- <div className="space-y-2">- {cosTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} />- ))}- </div>- )}- </div>-- {/* Awaiting Approval */}- {tasks.cos?.awaitingApproval?.length > 0 && (- <div>- <h3 className="text-lg font-semibold text-yellow-500 mb-3">Awaiting Approval</h3>- <div className="space-y-2">- {tasks.cos.awaitingApproval.map(task => (- <TaskItem key={task.id} task={task} awaitingApproval onRefresh={onRefresh} providers={providers} />- ))}- </div>- </div>- )}- </div>- );-}--function SortableTaskItem({ task, onRefresh, providers }) {- const {- attributes,- listeners,- setNodeRef,- transform,- transition,- isDragging,- } = useSortable({ id: task.id });-- const style = {- transform: CSS.Transform.toString(transform),- transition,- opacity: isDragging ? 0.5 : 1,- zIndex: isDragging ? 1000 : 'auto',- };-- return (- <div ref={setNodeRef} style={style}>- <TaskItem- task={task}- onRefresh={onRefresh}- providers={providers}- dragHandleProps={{ ...attributes, ...listeners }}- />- </div>- );-}--function TaskItem({ task, isSystem, awaitingApproval, onRefresh, providers, dragHandleProps }) {- const [editing, setEditing] = useState(false);- const [editData, setEditData] = useState({- description: task.description,- context: task.metadata?.context || '',- model: task.metadata?.model || '',- provider: task.metadata?.provider || ''- });-- // Get models for selected provider in edit mode- const editProvider = providers?.find(p => p.id === editData.provider);- const editModels = editProvider?.models || [];-- const statusIcons = {- pending: <Clock size={16} className="text-yellow-500" />,- in_progress: <Activity size={16} className="text-port-accent animate-pulse" />,- completed: <CheckCircle size={16} className="text-port-success" />,- blocked: <Ban size={16} className="text-port-error" />- };-- const handleStatusChange = async (newStatus) => {- await api.updateCosTask(task.id, { status: newStatus }).catch(err => toast.error(err.message));- toast.success(`Task marked as ${newStatus}`);- onRefresh();- };-- const handleSave = async () => {- await api.updateCosTask(task.id, editData).catch(err => toast.error(err.message));- toast.success('Task updated');- setEditing(false);- onRefresh();- };-- const handleDelete = async () => {- await api.deleteCosTask(task.id).catch(err => toast.error(err.message));- toast.success('Task deleted');- onRefresh();- };-- const handleApprove = async () => {- await api.approveCosTask(task.id).catch(err => toast.error(err.message));- toast.success('Task approved');- onRefresh();- };-- return (- <div className={`bg-port-card border rounded-lg p-4 group ${- awaitingApproval ? 'border-yellow-500/50' : 'border-port-border'- }`}>- <div className="flex items-start gap-3">- {/* Drag handle - only show for user tasks (not system or awaiting approval) */}- {dragHandleProps && !isSystem && !awaitingApproval && (- <button- {...dragHandleProps}- className="mt-0.5 cursor-grab active:cursor-grabbing text-gray-500 hover:text-gray-300 transition-colors touch-none"- title="Drag to reorder"- >- <GripVertical size={16} />- </button>- )}- <button- onClick={() => handleStatusChange(task.status === 'completed' ? 'pending' : 'completed')}- className="mt-0.5 hover:scale-110 transition-transform"- title={task.status === 'completed' ? 'Mark as pending' : 'Mark as completed'}- >- {statusIcons[task.status]}- </button>- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 mb-1 flex-wrap">- <span className="text-sm font-mono text-gray-500">{task.id}</span>- {isSystem && task.autoApproved && (- <span className="px-2 py-0.5 rounded text-xs bg-port-success/20 text-port-success">AUTO</span>- )}- {awaitingApproval && (- <button- onClick={handleApprove}- className="px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors"- >- APPROVE- </button>- )}- </div>-- {editing ? (- <div className="space-y-2">- <input- type="text"- value={editData.description}- onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}- className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"- />- <input- type="text"- placeholder="Context"- value={editData.context}- onChange={e => setEditData(d => ({ ...d, context: e.target.value }))}- className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"- />- <div className="flex gap-2">- <select- value={editData.provider}- onChange={e => setEditData(d => ({ ...d, provider: e.target.value, model: '' }))}- className="w-36 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"- >- <option value="">Auto</option>- {providers?.filter(p => p.enabled).map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>- <select- value={editData.model}- onChange={e => setEditData(d => ({ ...d, model: e.target.value }))}- className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"- disabled={!editData.provider}- >- <option value="">{editData.provider ? 'Auto' : 'Select provider'}</option>- {editModels.map(m => (- <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>- ))}- </select>- </div>- <div className="flex gap-2">- <button- onClick={handleSave}- className="flex items-center gap-1 text-xs text-port-success hover:text-port-success/80"- >- <Save size={12} /> Save- </button>- <button- onClick={() => setEditing(false)}- className="flex items-center gap-1 text-xs text-gray-500 hover:text-white"- >- <X size={12} /> Cancel- </button>- </div>- </div>- ) : (- <>- <p className="text-white">{task.description}</p>- {task.metadata?.context && (- <p className="text-sm text-gray-500 mt-1">{task.metadata.context}</p>- )}- {(task.metadata?.model || task.metadata?.provider) && (- <div className="flex items-center gap-2 mt-1">- {task.metadata?.model && (- <span className="px-1.5 py-0.5 text-xs bg-purple-500/20 text-purple-400 rounded font-mono">- {task.metadata.model}- </span>- )}- {task.metadata?.provider && (- <span className="px-1.5 py-0.5 text-xs bg-cyan-500/20 text-cyan-400 rounded">- {task.metadata.provider}- </span>- )}- </div>- )}- </>- )}- </div>-- {/* Action buttons */}- <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">- {!editing && (- <>- <button- onClick={() => setEditing(true)}- className="p-1 text-gray-500 hover:text-white transition-colors"- title="Edit"- >- <Edit3 size={14} />- </button>- <button- onClick={handleDelete}- className="p-1 text-gray-500 hover:text-port-error transition-colors"- title="Delete"- >- <Trash2 size={14} />- </button>- </>- )}- </div>- </div>- </div>- );-}--function AgentsTab({ agents, onRefresh, liveOutputs }) {- const handleTerminate = async (agentId) => {- await api.terminateCosAgent(agentId).catch(err => toast.error(err.message));- toast.success('Terminate signal sent');- onRefresh();- };-- const handleDelete = async (agentId) => {- await api.deleteCosAgent(agentId).catch(err => toast.error(err.message));- toast.success('Agent removed');- onRefresh();- };-- const handleClearCompleted = async () => {- await api.clearCompletedCosAgents().catch(err => toast.error(err.message));- toast.success('Cleared completed agents');- onRefresh();- };-- const runningAgents = agents.filter(a => a.status === 'running');- // Sort completed agents by completion time (most recent first)- const completedAgents = agents- .filter(a => a.status === 'completed')- .sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));-- return (- <div className="space-y-6">- {/* Active Agents */}- <div>- <div className="flex items-center justify-between mb-3">- <h3 className="text-lg font-semibold text-white">Active Agents</h3>- {runningAgents.length > 0 && (- <span className="text-sm text-port-accent animate-pulse">- {runningAgents.length} running- </span>- )}- </div>- {runningAgents.length === 0 ? (- <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">- No active agents. Start CoS and add tasks to see agents working.- </div>- ) : (- <div className="space-y-2">- {runningAgents.map(agent => (- <AgentCard- key={agent.id}- agent={agent}- onTerminate={handleTerminate}- liveOutput={liveOutputs[agent.id]}- />- ))}- </div>- )}- </div>-- {/* Completed Agents */}- {completedAgents.length > 0 && (- <div>- <div className="flex items-center justify-between mb-3">- <h3 className="text-lg font-semibold text-white">- Completed Agents- <span className="text-sm text-gray-500 font-normal ml-2">- ({completedAgents.length} total)- </span>- </h3>- <button- onClick={handleClearCompleted}- className="flex items-center gap-1 text-sm text-gray-500 hover:text-port-error transition-colors"- >- <Trash2 size={14} />- Clear- </button>- </div>- <div className="space-y-2">- {completedAgents.slice(0, 15).map(agent => (- <AgentCard key={agent.id} agent={agent} completed onDelete={handleDelete} />- ))}- {completedAgents.length > 15 && (- <div className="text-center text-sm text-gray-500 py-2">- + {completedAgents.length - 15} more completed agents- </div>- )}- </div>- </div>- )}- </div>- );-}--function AgentCard({ agent, onTerminate, onDelete, completed, liveOutput }) {- const [expanded, setExpanded] = useState(false);- const [now, setNow] = useState(Date.now());-- // Determine if this is a system agent (health check, etc.)- const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');-- // Update duration display for running agents- useEffect(() => {- if (completed) return;- const interval = setInterval(() => setNow(Date.now()), 1000);- return () => clearInterval(interval);- }, [completed]);-- const duration = agent.completedAt- ? new Date(agent.completedAt) - new Date(agent.startedAt)- : now - new Date(agent.startedAt);-- const formatDuration = (ms) => {- const seconds = Math.floor(ms / 1000);- const minutes = Math.floor(seconds / 60);- if (minutes > 0) return `${minutes}m ${seconds % 60}s`;- return `${seconds}s`;- };-- // Combine stored output with live output- const output = liveOutput || agent.output || [];- const lastOutput = output.length > 0 ? output[output.length - 1]?.line : null;-- return (- <div className={`bg-port-card border rounded-lg overflow-hidden ${- completed- ? isSystemAgent ? 'border-port-border opacity-50' : 'border-port-border opacity-75'- : 'border-port-accent/50'- }`}>- <div className="p-4">- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2 flex-wrap">- <Cpu size={16} className={completed ? 'text-gray-500' : 'text-port-accent animate-pulse'} />- <span className="font-mono text-sm text-gray-400">{agent.id}</span>- {isSystemAgent && (- <span className="px-1.5 py-0.5 text-xs bg-gray-500/20 text-gray-400 rounded">SYS</span>- )}- {agent.metadata?.model && (- <span className={`px-2 py-0.5 text-xs rounded ${- agent.metadata.modelTier === 'heavy' ? 'bg-purple-500/20 text-purple-400' :- agent.metadata.modelTier === 'light' ? 'bg-green-500/20 text-green-400' :- 'bg-blue-500/20 text-blue-400'- }`} title={agent.metadata.modelReason}>- {agent.metadata.model.replace('claude-', '').replace(/-\d+$/, '')}- </span>- )}- {!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'}- </span>- )}- </div>- <div className="flex items-center gap-2">- <span className="text-sm text-gray-500">{formatDuration(duration)}</span>- {output.length > 0 && (- <button- onClick={() => setExpanded(!expanded)}- className="text-gray-500 hover:text-white transition-colors text-xs"- >- {expanded ? 'Hide' : 'Show'} Output- </button>- )}- {!completed && onTerminate && (- <button- onClick={() => onTerminate(agent.id)}- className="text-gray-500 hover:text-port-error transition-colors"- title="Terminate"- >- <Square size={14} />- </button>- )}- {completed && onDelete && (- <button- onClick={() => onDelete(agent.id)}- className="text-gray-500 hover:text-port-error transition-colors"- title="Remove"- >- <Trash2 size={14} />- </button>- )}- </div>- </div>- <p className="text-white text-sm mb-2">{agent.metadata?.taskDescription || agent.taskId}</p>-- {/* Status / Last output line */}- {!completed && lastOutput && (- <div className="text-xs text-gray-500 font-mono truncate bg-port-bg/50 px-2 py-1 rounded">- {lastOutput.substring(0, 100)}...- </div>- )}-- {agent.result && (- <div className={`text-sm flex items-center gap-2 ${agent.result.success ? 'text-port-success' : 'text-port-error'}`}>- {agent.result.success ? (- <><CheckCircle size={14} /> Completed successfully</>- ) : (- <><AlertCircle size={14} /> {agent.result.error || 'Failed'}</>- )}- </div>- )}- </div>-- {/* Expanded output view */}- {expanded && output.length > 0 && (- <div className="border-t border-port-border bg-port-bg/50 p-3 max-h-64 overflow-y-auto">- <pre className="text-xs font-mono text-gray-400 whitespace-pre-wrap">- {output.map((o, i) => (- <div key={i} className="py-0.5">- {o.line}- </div>- ))}- </pre>- </div>- )}- </div>- );-}--function ScriptsTab({ scripts, onRefresh }) {- const [showCreate, setShowCreate] = useState(false);- const [newScript, setNewScript] = useState({- name: '',- description: '',- command: '',- schedule: 'on-demand',- cronExpression: '',- triggerAction: 'log-only',- triggerPrompt: '',- triggerPriority: 'MEDIUM'- });-- const handleCreate = async () => {- if (!newScript.name.trim() || !newScript.command.trim()) {- toast.error('Name and command are required');- return;- }-- await api.createCosScript(newScript).catch(err => {- toast.error(err.message);- return;- });-- toast.success('Script created');- setNewScript({- name: '',- description: '',- command: '',- schedule: 'on-demand',- cronExpression: '',- triggerAction: 'log-only',- triggerPrompt: '',- triggerPriority: 'MEDIUM'- });- setShowCreate(false);- onRefresh();- };-- const handleRun = async (id) => {- toast.loading('Running script...', { id: 'script-run' });- const result = await api.runCosScript(id).catch(err => {- toast.error(err.message, { id: 'script-run' });- return null;- });- if (result) {- if (result.success) {- toast.success('Script completed', { id: 'script-run' });- } else {- toast.error(`Script failed: ${result.error || 'Unknown error'}`, { id: 'script-run' });- }- onRefresh();- }- };-- const handleToggle = async (script) => {- await api.updateCosScript(script.id, { enabled: !script.enabled }).catch(err => toast.error(err.message));- toast.success(script.enabled ? 'Script disabled' : 'Script enabled');- onRefresh();- };-- const handleDelete = async (id) => {- await api.deleteCosScript(id).catch(err => toast.error(err.message));- toast.success('Script deleted');- onRefresh();- };-- return (- <div className="space-y-6">- <div className="flex items-center justify-between mb-3">- <h3 className="text-lg font-semibold text-white">Scheduled Scripts</h3>- <div className="flex items-center gap-2">- <button- onClick={() => setShowCreate(!showCreate)}- className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"- >- <Plus size={16} />- New Script- </button>- <button- onClick={onRefresh}- className="text-gray-500 hover:text-white transition-colors"- >- <RefreshCw size={16} />- </button>- </div>- </div>-- {/* Create Script Form */}- {showCreate && (- <div className="bg-port-card border border-port-accent/50 rounded-lg p-4 mb-4">- <div className="space-y-3">- <div className="flex gap-3">- <input- type="text"- placeholder="Script name *"- value={newScript.name}- onChange={e => setNewScript(s => ({ ...s, name: e.target.value }))}- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- />- <select- value={newScript.schedule}- onChange={e => setNewScript(s => ({ ...s, schedule: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- <option value="on-demand">On Demand</option>- <option value="every-5-min">Every 5 min</option>- <option value="every-15-min">Every 15 min</option>- <option value="hourly">Hourly</option>- <option value="daily">Daily</option>- <option value="weekly">Weekly</option>- </select>- </div>- <input- type="text"- placeholder="Description"- value={newScript.description}- onChange={e => setNewScript(s => ({ ...s, description: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- />- <textarea- placeholder="Shell command *"- value={newScript.command}- onChange={e => setNewScript(s => ({ ...s, command: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-20"- />- <div className="flex gap-3">- <select- value={newScript.triggerAction}- onChange={e => setNewScript(s => ({ ...s, triggerAction: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- <option value="log-only">Log Only</option>- <option value="spawn-agent">Spawn Agent</option>- </select>- <select- value={newScript.triggerPriority}- onChange={e => setNewScript(s => ({ ...s, triggerPriority: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- <option value="LOW">LOW</option>- <option value="MEDIUM">MEDIUM</option>- <option value="HIGH">HIGH</option>- <option value="CRITICAL">CRITICAL</option>- </select>- </div>- {newScript.triggerAction === 'spawn-agent' && (- <textarea- placeholder="Prompt for agent when triggered"- value={newScript.triggerPrompt}- onChange={e => setNewScript(s => ({ ...s, triggerPrompt: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm h-16"- />- )}- <div className="flex justify-end gap-2">- <button- onClick={() => setShowCreate(false)}- className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"- >- Cancel- </button>- <button- onClick={handleCreate}- className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"- >- <Plus size={14} />- Create- </button>- </div>- </div>- </div>- )}-- {/* Scripts List */}- {scripts.length === 0 ? (- <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">- No scripts configured. Create a script to automate tasks.- </div>- ) : (- <div className="space-y-2">- {scripts.map(script => (- <ScriptCard- key={script.id}- script={script}- onRun={handleRun}- onToggle={handleToggle}- onDelete={handleDelete}- onUpdate={onRefresh}- />- ))}- </div>- )}- </div>- );-}--function ScriptCard({ script, onRun, onToggle, onDelete, onUpdate }) {- const [expanded, setExpanded] = useState(false);- const [editing, setEditing] = useState(false);- const [editData, setEditData] = useState({- name: script.name,- description: script.description || '',- command: script.command,- schedule: script.schedule || 'on-demand',- triggerAction: script.triggerAction || 'log-only',- triggerPrompt: script.triggerPrompt || '',- triggerPriority: script.triggerPriority || 'MEDIUM'- });-- const handleSave = async () => {- if (!editData.name.trim() || !editData.command.trim()) {- toast.error('Name and command are required');- return;- }- await api.updateCosScript(script.id, editData).catch(err => toast.error(err.message));- toast.success('Script updated');- setEditing(false);- onUpdate?.();- };-- const formatTime = (timestamp) => {- if (!timestamp) return 'Never';- const date = new Date(timestamp);- const now = new Date();- const diff = now - date;- if (diff < 60000) return 'Just now';- if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;- if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;- return date.toLocaleDateString();- };-- const scheduleLabels = {- 'on-demand': 'On Demand',- 'every-5-min': 'Every 5 min',- 'every-15-min': 'Every 15 min',- 'every-30-min': 'Every 30 min',- 'hourly': 'Hourly',- 'every-6-hours': 'Every 6 hours',- 'daily': 'Daily',- 'weekly': 'Weekly'- };-- return (- <div className={`bg-port-card border rounded-lg overflow-hidden ${- script.enabled ? 'border-port-border' : 'border-port-border opacity-60'- }`}>- <div className="p-4">- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Terminal size={16} className={script.enabled ? 'text-port-accent' : 'text-gray-500'} />- <span className="font-medium text-white">{script.name}</span>- <span className={`px-2 py-0.5 text-xs rounded ${- script.schedule === 'on-demand' ? 'bg-gray-500/20 text-gray-400' : 'bg-port-accent/20 text-port-accent'- }`}>- {scheduleLabels[script.schedule] || script.schedule}- </span>- {script.triggerAction === 'spawn-agent' && (- <span className="px-2 py-0.5 text-xs bg-purple-500/20 text-purple-400 rounded">- <Zap size={10} className="inline mr-1" />- Triggers Agent- </span>- )}- </div>- <div className="flex items-center gap-2">- <button- onClick={() => onRun(script.id)}- className="p-1.5 text-gray-500 hover:text-port-success transition-colors"- title="Run now"- >- <Play size={14} />- </button>- <button- onClick={() => setEditing(true)}- className="p-1.5 text-gray-500 hover:text-white transition-colors"- title="Edit"- >- <Edit3 size={14} />- </button>- <button- onClick={() => onToggle(script)}- className={`p-1.5 transition-colors ${- script.enabled ? 'text-port-success hover:text-gray-500' : 'text-gray-500 hover:text-port-success'- }`}- title={script.enabled ? 'Disable' : 'Enable'}- >- {script.enabled ? <CheckCircle size={14} /> : <Ban size={14} />}- </button>- <button- onClick={() => onDelete(script.id)}- className="p-1.5 text-gray-500 hover:text-port-error transition-colors"- title="Delete"- >- <Trash2 size={14} />- </button>- </div>- </div>-- {/* Edit Form */}- {editing ? (- <div className="space-y-3 mt-3">- <div className="flex gap-3">- <input- type="text"- placeholder="Script name *"- value={editData.name}- onChange={e => setEditData(d => ({ ...d, name: e.target.value }))}- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- />- <select- value={editData.schedule}- onChange={e => setEditData(d => ({ ...d, schedule: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- <option value="on-demand">On Demand</option>- <option value="every-5-min">Every 5 min</option>- <option value="every-15-min">Every 15 min</option>- <option value="hourly">Hourly</option>- <option value="daily">Daily</option>- <option value="weekly">Weekly</option>- </select>- </div>- <input- type="text"- placeholder="Description"- value={editData.description}- onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- />- <textarea- placeholder="Shell command *"- value={editData.command}- onChange={e => setEditData(d => ({ ...d, command: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-20"- />- <div className="flex gap-3">- <select- value={editData.triggerAction}- onChange={e => setEditData(d => ({ ...d, triggerAction: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- <option value="log-only">Log Only</option>- <option value="spawn-agent">Spawn Agent</option>- </select>- <select- value={editData.triggerPriority}- onChange={e => setEditData(d => ({ ...d, triggerPriority: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- <option value="LOW">LOW</option>- <option value="MEDIUM">MEDIUM</option>- <option value="HIGH">HIGH</option>- <option value="CRITICAL">CRITICAL</option>- </select>- </div>- {editData.triggerAction === 'spawn-agent' && (- <textarea- placeholder="Prompt for agent when triggered"- value={editData.triggerPrompt}- onChange={e => setEditData(d => ({ ...d, triggerPrompt: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm h-16"- />- )}- <div className="flex justify-end gap-2">- <button- onClick={() => setEditing(false)}- className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"- >- Cancel- </button>- <button- onClick={handleSave}- className="flex items-center gap-1 px-3 py-1.5 bg-port-success/20 hover:bg-port-success/30 text-port-success rounded-lg text-sm transition-colors"- >- <Save size={14} />- Save- </button>- </div>- </div>- ) : (- <>- {script.description && (- <p className="text-sm text-gray-400 mb-2">{script.description}</p>- )}-- <div className="flex items-center gap-4 text-xs text-gray-500">- <span>Last run: {formatTime(script.lastRun)}</span>- {script.lastExitCode !== null && (- <span className={script.lastExitCode === 0 ? 'text-port-success' : 'text-port-error'}>- Exit: {script.lastExitCode}- </span>- )}- <span>Runs: {script.runCount || 0}</span>- {script.lastOutput && (- <button- onClick={() => setExpanded(!expanded)}- className="text-port-accent hover:text-port-accent/80"- >- {expanded ? 'Hide' : 'Show'} output- </button>- )}- </div>- </>- )}- </div>-- {/* Command preview */}- {!editing && (- <div className="px-4 pb-3">- <code className="text-xs text-gray-500 font-mono bg-port-bg/50 px-2 py-1 rounded block truncate">- {script.command}- </code>- </div>- )}-- {/* Expanded output */}- {expanded && script.lastOutput && (- <div className="border-t border-port-border bg-port-bg/50 p-3 max-h-48 overflow-y-auto">- <pre className="text-xs font-mono text-gray-400 whitespace-pre-wrap">- {script.lastOutput}- </pre>- </div>- )}- </div>- );-}--function MemoryTab() {- const [memories, setMemories] = useState([]);- const [stats, setStats] = useState(null);- const [loading, setLoading] = useState(true);- const [searchQuery, setSearchQuery] = useState('');- const [searchResults, setSearchResults] = useState(null);- const [view, setView] = useState('list'); // list, timeline, graph- const [filters, setFilters] = useState({ types: [], categories: [] });- const [categories, setCategories] = useState([]);- const [embeddingStatus, setEmbeddingStatus] = useState(null);-- const MEMORY_TYPES = ['fact', 'learning', 'observation', 'decision', 'preference', 'context'];- const TYPE_COLORS = {- fact: 'bg-blue-500/20 text-blue-400 border-blue-500/30',- learning: 'bg-green-500/20 text-green-400 border-green-500/30',- observation: 'bg-purple-500/20 text-purple-400 border-purple-500/30',- decision: 'bg-orange-500/20 text-orange-400 border-orange-500/30',- preference: 'bg-pink-500/20 text-pink-400 border-pink-500/30',- context: 'bg-gray-500/20 text-gray-400 border-gray-500/30'- };-- const fetchData = useCallback(async () => {- setLoading(true);- const [memoriesRes, statsRes, catsRes, embRes] = await Promise.all([- api.getMemories({ limit: 100, ...filters }).catch(() => ({ memories: [] })),- api.getMemoryStats().catch(() => null),- api.getMemoryCategories().catch(() => []),- api.getEmbeddingStatus().catch(() => null)- ]);- setMemories(memoriesRes.memories || []);- setStats(statsRes);- setCategories(catsRes);- setEmbeddingStatus(embRes);- setLoading(false);- }, [filters]);-- useEffect(() => {- fetchData();- }, [fetchData]);-- const handleSearch = async () => {- if (!searchQuery.trim()) {- setSearchResults(null);- return;- }- setLoading(true);- const results = await api.searchMemories(searchQuery, { limit: 20 }).catch(() => ({ memories: [] }));- setSearchResults(results.memories || []);- setLoading(false);- };-- const handleDelete = async (id) => {- await api.deleteMemory(id);- toast.success('Memory archived');- fetchData();- };-- const displayMemories = searchResults || memories;-- return (- <div className="space-y-6">- {/* Header */}- <div className="flex items-center justify-between">- <div>- <h3 className="text-lg font-semibold text-white">Memory System</h3>- <p className="text-sm text-gray-500">- {stats?.active || 0} active memories- {embeddingStatus?.available ? ' • LM Studio connected' : ' • LM Studio offline'}- </p>- </div>- <div className="flex gap-2">- {['list', 'timeline', 'graph'].map(v => (- <button- key={v}- onClick={() => setView(v)}- className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${- view === v ? 'bg-port-accent text-white' : 'bg-port-border text-gray-400 hover:text-white'- }`}- >- {v.charAt(0).toUpperCase() + v.slice(1)}- </button>- ))}- </div>- </div>-- {/* Search */}- <div className="flex gap-2">- <input- type="text"- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- onKeyDown={(e) => e.key === 'Enter' && handleSearch()}- placeholder="Search memories semantically..."- className="flex-1 bg-port-card border border-port-border rounded-lg px-4 py-2 text-white placeholder-gray-500 focus:border-port-accent outline-none"- />- <button- onClick={handleSearch}- className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"- >- Search- </button>- {searchResults && (- <button- onClick={() => { setSearchResults(null); setSearchQuery(''); }}- className="px-3 py-2 bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors"- >- <X size={16} />- </button>+ <ConfigTab config={status?.config} onUpdate={fetchData} onEvaluate={handleForceEvaluate} avatarStyle={avatarStyle} setAvatarStyle={setAvatarStyle} evalCountdown={evalCountdown} />)}</div>-- {/* Type Filters */}- <div className="flex flex-wrap gap-2">- {MEMORY_TYPES.map(type => (- <button- key={type}- onClick={() => {- const newTypes = filters.types.includes(type)- ? filters.types.filter(t => t !== type)- : [...filters.types, type];- setFilters({ ...filters, types: newTypes });- }}- className={`px-3 py-1 text-xs rounded-full border transition-colors ${- filters.types.includes(type) ? TYPE_COLORS[type] : 'border-port-border text-gray-500 hover:text-gray-300'- }`}- >- {type}- </button>- ))}- </div>-- {/* Stats Row */}- {stats && (- <div className="grid grid-cols-3 md:grid-cols-6 gap-2">- {Object.entries(stats.byType || {}).map(([type, count]) => (- <div key={type} className={`p-2 rounded-lg border text-center ${TYPE_COLORS[type] || 'border-port-border'}`}>- <div className="text-lg font-bold">{count}</div>- <div className="text-xs opacity-75">{type}</div>- </div>- ))}- </div>- )}-- {/* Content */}- {loading ? (- <div className="flex items-center justify-center py-12">- <RefreshCw className="animate-spin text-port-accent" size={24} />- </div>- ) : view === 'list' ? (- <div className="space-y-3">- {displayMemories.length === 0 ? (- <div className="text-center py-12 text-gray-500">- {searchQuery ? 'No memories found for this search' : 'No memories yet. Memories are extracted from agent task completions.'}- </div>- ) : (- displayMemories.map(memory => (- <div key={memory.id} className="bg-port-card border border-port-border rounded-lg p-4">- <div className="flex items-start justify-between gap-4">- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 mb-2">- <span className={`px-2 py-0.5 text-xs rounded-full border ${TYPE_COLORS[memory.type]}`}>- {memory.type}- </span>- <span className="text-xs text-gray-500">{memory.category}</span>- {memory.similarity && (- <span className="text-xs text-port-accent">{(memory.similarity * 100).toFixed(0)}% match</span>- )}- </div>- <p className="text-white text-sm">{memory.summary || memory.content?.substring(0, 200)}</p>- {memory.tags?.length > 0 && (- <div className="flex gap-1 mt-2">- {memory.tags.map(tag => (- <span key={tag} className="px-2 py-0.5 text-xs bg-port-border rounded text-gray-400">- {tag}- </span>- ))}- </div>- )}- <div className="text-xs text-gray-500 mt-2">- {new Date(memory.createdAt).toLocaleDateString()} • importance: {((memory.importance || 0.5) * 100).toFixed(0)}%- </div>- </div>- <button- onClick={() => handleDelete(memory.id)}- className="p-2 text-gray-500 hover:text-port-error transition-colors"- >- <Trash2 size={14} />- </button>- </div>- </div>- ))- )}- </div>- ) : view === 'timeline' ? (- <MemoryTimeline memories={memories} />- ) : (- <MemoryGraph />- )}- </div>- );-}--function MemoryTimeline({ memories }) {- const grouped = memories.reduce((acc, m) => {- const date = m.createdAt?.split('T')[0] || 'Unknown';- if (!acc[date]) acc[date] = [];- acc[date].push(m);- return acc;- }, {});-- const dates = Object.keys(grouped).sort().reverse();-- return (- <div className="space-y-6">- {dates.map(date => (- <div key={date}>- <div className="text-sm font-medium text-gray-400 mb-2 sticky top-0 bg-port-bg py-1">- {new Date(date).toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}- </div>- <div className="border-l border-port-border pl-4 space-y-3">- {grouped[date].map(m => (- <div key={m.id} className="relative">- <div className="absolute -left-[21px] w-2 h-2 rounded-full bg-port-accent" />- <div className="text-sm text-white">{m.summary}</div>- <div className="text-xs text-gray-500 mt-1">{m.type} • {m.category}</div>- </div>- ))}- </div>- </div>- ))}- </div>- );-}--function MemoryGraph() {- const [graphData, setGraphData] = useState(null);- const [loading, setLoading] = useState(true);-- useEffect(() => {- api.getMemoryGraph().then(setGraphData).catch(() => setGraphData(null)).finally(() => setLoading(false));- }, []);-- if (loading) {- return (- <div className="flex items-center justify-center py-12">- <RefreshCw className="animate-spin text-port-accent" size={24} />- </div>- );- }-- if (!graphData || !graphData.nodes?.length) {- return (- <div className="text-center py-12 text-gray-500">- No memory graph data available. Add more memories to see relationships.- </div>- );- }-- return (- <div className="bg-port-card border border-port-border rounded-lg p-4 min-h-[400px]">- <div className="text-center text-gray-500">- <Brain size={48} className="mx-auto mb-4 text-port-accent/50" />- <p>Graph visualization coming soon</p>- <p className="text-sm mt-2">{graphData.nodes.length} nodes • {graphData.edges.length} connections</p>- </div>- </div>- );-}--function HealthTab({ health, onCheck }) {- return (- <div className="space-y-6">- <div className="flex items-center justify-between">- <div>- <h3 className="text-lg font-semibold text-white">System Health</h3>- {health?.lastCheck && (- <p className="text-sm text-gray-500">- Last check: {new Date(health.lastCheck).toLocaleString()}- </p>- )}- </div>- <button- onClick={onCheck}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"- >- <RefreshCw size={14} />- Run Check- </button>- </div>-- {!health?.issues || health.issues.length === 0 ? (- <div className="bg-port-success/10 border border-port-success/30 rounded-lg p-6 text-center">- <CheckCircle className="w-12 h-12 text-port-success mx-auto mb-3" />- <p className="text-port-success font-medium">All Systems Healthy</p>- <p className="text-gray-500 text-sm mt-1">No issues detected</p>- </div>- ) : (- <div className="space-y-2">- {health.issues.map((issue, idx) => (- <div- key={idx}- className={`border rounded-lg p-4 ${- issue.type === 'error'- ? 'bg-port-error/10 border-port-error/30'- : 'bg-yellow-500/10 border-yellow-500/30'- }`}- >- <div className="flex items-center gap-2 mb-1">- <AlertCircle size={16} className={issue.type === 'error' ? 'text-port-error' : 'text-yellow-500'} />- <span className={`text-sm font-medium uppercase ${- issue.type === 'error' ? 'text-port-error' : 'text-yellow-500'- }`}>- {issue.category}- </span>- </div>- <p className="text-white">{issue.message}</p>- </div>- ))}- </div>- )}- </div>- );-}--function ConfigTab({ config, onUpdate, onEvaluate }) {- const [editing, setEditing] = useState(false);- const [formData, setFormData] = useState({- evaluationIntervalMs: config?.evaluationIntervalMs || 60000,- healthCheckIntervalMs: config?.healthCheckIntervalMs || 900000,- maxConcurrentAgents: config?.maxConcurrentAgents || 3,- maxProcessMemoryMb: config?.maxProcessMemoryMb || 2048,- autoStart: config?.autoStart || false- });-- const handleSave = async () => {- await api.updateCosConfig(formData).catch(err => toast.error(err.message));- toast.success('Configuration updated');- setEditing(false);- onUpdate();- };-- return (- <div className="space-y-6">- <div className="flex items-center justify-between">- <h3 className="text-lg font-semibold text-white">Configuration</h3>- <div className="flex gap-2">- <button- onClick={onEvaluate}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors"- >- <Activity size={14} />- Force Evaluate- </button>- {!editing ? (- <button- onClick={() => setEditing(true)}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"- >- <Settings size={14} />- Edit- </button>- ) : (- <button- onClick={handleSave}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-success/20 hover:bg-port-success/30 text-port-success rounded-lg transition-colors"- >- <CheckCircle size={14} />- Save- </button>- )}- </div>- </div>-- <div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">- <ConfigRow- label="Evaluation Interval"- value={`${formData.evaluationIntervalMs / 1000}s`}- editing={editing}- type="number"- inputValue={formData.evaluationIntervalMs / 1000}- onChange={v => setFormData(f => ({ ...f, evaluationIntervalMs: v * 1000 }))}- suffix="seconds"- />- <ConfigRow- label="Health Check Interval"- value={`${formData.healthCheckIntervalMs / 60000}m`}- editing={editing}- type="number"- inputValue={formData.healthCheckIntervalMs / 60000}- onChange={v => setFormData(f => ({ ...f, healthCheckIntervalMs: v * 60000 }))}- suffix="minutes"- />- <ConfigRow- label="Max Concurrent Agents"- value={formData.maxConcurrentAgents}- editing={editing}- type="number"- inputValue={formData.maxConcurrentAgents}- onChange={v => setFormData(f => ({ ...f, maxConcurrentAgents: v }))}- />- <ConfigRow- label="Max Process Memory"- value={`${formData.maxProcessMemoryMb} MB`}- editing={editing}- type="number"- inputValue={formData.maxProcessMemoryMb}- onChange={v => setFormData(f => ({ ...f, maxProcessMemoryMb: v }))}- suffix="MB"- />- <ConfigRow- label="Auto Start"- value={formData.autoStart ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.autoStart}- onChange={v => setFormData(f => ({ ...f, autoStart: v }))}- />- </div>-- {/* MCP Servers */}- <div>- <h4 className="text-sm font-medium text-gray-400 mb-2">MCP Servers</h4>- <div className="bg-port-card border border-port-border rounded-lg p-4">- {config?.mcpServers?.map((mcp, idx) => (- <div key={idx} className="flex items-center gap-2 text-sm">- <span className="text-port-accent font-mono">{mcp.name}</span>- <span className="text-gray-500">:</span>- <span className="text-gray-400">{mcp.command} {mcp.args?.join(' ')}</span>- </div>- )) || <span className="text-gray-500">No MCP servers configured</span>}- </div>- </div>-- {/* Task Files */}- <div>- <h4 className="text-sm font-medium text-gray-400 mb-2">Task Files</h4>- <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-2">- <div className="flex items-center gap-2 text-sm">- <FileText size={14} className="text-gray-500" />- <span className="text-gray-400">User Tasks:</span>- <span className="text-white font-mono">{config?.userTasksFile || 'TASKS.md'}</span>- </div>- <div className="flex items-center gap-2 text-sm">- <FileText size={14} className="text-gray-500" />- <span className="text-gray-400">System Tasks:</span>- <span className="text-white font-mono">{config?.cosTasksFile || 'COS-TASKS.md'}</span>- </div>- </div>- </div>- </div>- );-}--function ConfigRow({ label, value, editing, type, inputValue, onChange, suffix }) {- return (- <div className="flex items-center justify-between p-4">- <span className="text-gray-400">{label}</span>- {editing ? (- <div className="flex items-center gap-2">- {type === 'checkbox' ? (- <input- type="checkbox"- checked={inputValue}- onChange={e => onChange(e.target.checked)}- className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"- />- ) : (- <>- <input- type="number"- value={inputValue}- onChange={e => onChange(parseInt(e.target.value) || 0)}- className="w-24 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm text-right"- />- {suffix && <span className="text-gray-500 text-sm">{suffix}</span>}- </>- )}- </div>- ) : (- <span className="text-white">{value}</span>- )}</div>);}diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsxindex a6a4d05369..6b66c10385 100644--- a/client/src/pages/DevTools.jsx+++ b/client/src/pages/DevTools.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useRef, Fragment } from 'react';import { useLocation, useNavigate } from 'react-router-dom';-import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info, Save } from 'lucide-react';+import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info, Save, Maximize2 } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../services/api';import socket from '../services/socket';@@ -1072,7 +1072,9 @@ export function ProcessesPage() {const [tailLines, setTailLines] = useState(500);const [subscribed, setSubscribed] = useState(false);const [saving, setSaving] = useState(false);+ const [fullscreen, setFullscreen] = useState(false);const logsRef = useRef(null);+ const fullscreenLogsRef = useRef(null);useEffect(() => {loadProcesses();@@ -1116,6 +1118,9 @@ export function ProcessesPage() {if (logsRef.current) {logsRef.current.scrollTop = logsRef.current.scrollHeight;}+ if (fullscreenLogsRef.current) {+ fullscreenLogsRef.current.scrollTop = fullscreenLogsRef.current.scrollHeight;+ }}, 10);}};@@ -1373,11 +1378,19 @@ export function ProcessesPage() {>Clear</button>+ <button+ onClick={() => setFullscreen(true)}+ className="text-xs text-gray-500 hover:text-white flex items-center gap-1"+ title="Fullscreen"+ >+ <Maximize2 size={12} />+ Fullscreen+ </button></div></div><divref={logsRef}- className="h-64 overflow-auto p-3 font-mono text-xs"+ className="h-[32rem] overflow-auto p-3 font-mono text-xs">{logs.length === 0 ? (<div className="text-gray-500">@@ -1413,6 +1426,75 @@ export function ProcessesPage() {</tbody></table></div>++ {/* Fullscreen Log Modal */}+ {fullscreen && expandedProcess && (+ <div className="fixed inset-0 bg-port-bg z-50 flex flex-col">+ <div className="flex items-center justify-between px-6 py-4 border-b border-port-border bg-port-card">+ <div className="flex items-center gap-4">+ <span className="text-lg font-medium text-white">Logs: {expandedProcess}</span>+ {subscribed && (+ <span className="text-sm text-port-success">● streaming</span>+ )}+ </div>+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-2">+ <label className="text-sm text-gray-500">Tail lines:</label>+ <select+ value={tailLines}+ onChange={(e) => {+ setTailLines(Number(e.target.value));+ setLogs([]);+ }}+ className="px-2 py-1 text-sm bg-port-bg border border-port-border rounded text-white"+ >+ <option value={100}>100</option>+ <option value={250}>250</option>+ <option value={500}>500</option>+ <option value={1000}>1000</option>+ <option value={2000}>2000</option>+ </select>+ </div>+ <span className="text-sm text-gray-600">{logs.length} lines</span>+ <button+ onClick={() => setLogs([])}+ className="text-sm text-gray-500 hover:text-white"+ >+ Clear+ </button>+ <button+ onClick={() => setFullscreen(false)}+ className="p-2 text-gray-400 hover:text-white"+ title="Exit fullscreen"+ >+ <X size={20} />+ </button>+ </div>+ </div>+ <div+ ref={fullscreenLogsRef}+ className="flex-1 overflow-auto p-4 font-mono text-sm"+ >+ {logs.length === 0 ? (+ <div className="text-gray-500">+ {subscribed ? 'No logs yet...' : 'Connecting to log stream...'}+ </div>+ ) : (+ logs.map((log, i) => (+ <div+ key={i}+ className={`py-0.5 ${log.type === 'stderr' ? 'text-port-error' : 'text-gray-300'}`}+ >+ <span className="text-gray-600 mr-3">+ {new Date(log.timestamp).toLocaleTimeString()}+ </span>+ {log.line}+ </div>+ ))+ )}+ </div>+ </div>+ )}</div>);}diff --git a/client/src/pages/Logs.jsx b/client/src/pages/Logs.jsxdeleted file mode 100644index 5d6d799855..0000000000--- a/client/src/pages/Logs.jsx+++ /dev/null@@ -1,281 +0,0 @@-import { useState, useEffect, useCallback } from 'react';-import LogViewer from '../components/LogViewer';-import StatusBadge from '../components/StatusBadge';-import * as api from '../services/api';-import socket, { subscribeToLogs } from '../services/socket';--const LINES_OPTIONS = [50, 100, 200, 500, 1000];--export default function Logs() {- const [processes, setProcesses] = useState([]);- const [selectedProcess, setSelectedProcess] = useState('');- const [logs, setLogs] = useState([]);- const [streaming, setStreaming] = useState(false);- const [lines, setLines] = useState(100);- const [loading, setLoading] = useState(true);- const [filter, setFilter] = useState('');- const [cleanupFn, setCleanupFn] = useState(null);- const [connected, setConnected] = useState(socket.connected);-- // Track socket connection status- useEffect(() => {- const onConnect = () => setConnected(true);- const onDisconnect = () => {- setConnected(false);- setStreaming(false);- };-- socket.on('connect', onConnect);- socket.on('disconnect', onDisconnect);-- return () => {- socket.off('connect', onConnect);- socket.off('disconnect', onDisconnect);- };- }, []);-- // Fetch PM2 processes- useEffect(() => {- const fetchProcesses = async () => {- const procs = await api.getProcesses().catch(() => []);- setProcesses(procs);- if (procs.length > 0 && !selectedProcess) {- setSelectedProcess(procs[0].name);- }- setLoading(false);- };- fetchProcesses();- const interval = setInterval(fetchProcesses, 10000);- return () => clearInterval(interval);- }, []);-- // Stop streaming on unmount- useEffect(() => {- return () => {- if (cleanupFn) cleanupFn();- };- }, [cleanupFn]);-- const fetchLogs = async () => {- if (!selectedProcess) return;- setLoading(true);- const result = await api.getProcessLogs(selectedProcess, lines).catch(() => ({ logs: '' }));- const logLines = (result.logs || '').split('\n').filter(Boolean).map(line => ({- line,- type: 'stdout',- timestamp: Date.now()- }));- setLogs(logLines);- setLoading(false);- };-- const startStreaming = useCallback(() => {- if (!selectedProcess || streaming || !connected) return;-- setLogs([]);- setStreaming(true);-- const cleanup = subscribeToLogs(selectedProcess, lines, {- onLine: (data) => {- setLogs(prev => [...prev, data]);- },- onSubscribed: (data) => {- setLogs(prev => [...prev, {- type: 'connected',- line: `Connected to ${data.processName}`,- timestamp: data.timestamp- }]);- },- onError: (data) => {- console.error('Stream error:', data);- setLogs(prev => [...prev, {- type: 'error',- line: `Error: ${data.error}`,- timestamp: Date.now()- }]);- },- onClose: (data) => {- setStreaming(false);- setLogs(prev => [...prev, {- type: 'connected',- line: `Stream closed (code: ${data.code})`,- timestamp: Date.now()- }]);- }- });-- setCleanupFn(() => cleanup);- }, [selectedProcess, lines, streaming, connected]);-- const stopStreaming = useCallback(() => {- if (cleanupFn) {- cleanupFn();- setCleanupFn(null);- }- setStreaming(false);- setLogs(prev => [...prev, { type: 'connected', line: 'Streaming stopped', timestamp: Date.now() }]);- }, [cleanupFn]);-- const clearLogs = () => setLogs([]);-- const filteredLogs = filter- ? logs.filter(log => (log.line || '').toLowerCase().includes(filter.toLowerCase()))- : logs;-- const getProcessStatus = (name) => {- const proc = processes.find(p => p.name === name);- return proc?.status || 'unknown';- };-- if (loading && processes.length === 0) {- return (- <div className="flex items-center justify-center h-64">- <div className="text-gray-500">Loading processes...</div>- </div>- );- }-- return (- <div className="space-y-4">- {/* Header */}- <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">- <div>- <h2 className="text-2xl font-bold text-white">Logs</h2>- <p className="text-gray-500">View and stream PM2 process logs</p>- </div>- <div className="flex items-center gap-2">- <span className={`w-2 h-2 rounded-full ${connected ? 'bg-port-success' : 'bg-port-error'}`} />- <span className="text-sm text-gray-400">- {connected ? 'Socket connected' : 'Socket disconnected'}- </span>- </div>- </div>-- {/* Controls */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <div className="flex flex-col lg:flex-row gap-4">- {/* Process selector */}- <div className="flex-1">- <label className="block text-sm text-gray-400 mb-1">Process</label>- <select- value={selectedProcess}- onChange={(e) => {- if (streaming) stopStreaming();- setSelectedProcess(e.target.value);- setLogs([]);- }}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"- disabled={streaming}- >- <option value="">Select a process...</option>- {processes.map(proc => (- <option key={proc.name} value={proc.name}>- {proc.name} ({proc.status})- </option>- ))}- </select>- </div>-- {/* Lines */}- <div className="w-full lg:w-32">- <label className="block text-sm text-gray-400 mb-1">Lines</label>- <select- value={lines}- onChange={(e) => setLines(parseInt(e.target.value))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"- disabled={streaming}- >- {LINES_OPTIONS.map(n => (- <option key={n} value={n}>{n}</option>- ))}- </select>- </div>-- {/* Filter */}- <div className="flex-1">- <label className="block text-sm text-gray-400 mb-1">Filter</label>- <input- type="text"- value={filter}- onChange={(e) => setFilter(e.target.value)}- placeholder="Search logs..."- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"- />- </div>- </div>-- {/* Action buttons */}- <div className="flex flex-wrap gap-2 mt-4">- <button- onClick={fetchLogs}- disabled={!selectedProcess || streaming}- className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors disabled:opacity-50"- >- Fetch Logs- </button>-- {!streaming ? (- <button- onClick={startStreaming}- disabled={!selectedProcess || !connected}- className="px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"- >- Start Streaming- </button>- ) : (- <button- onClick={stopStreaming}- className="px-4 py-2 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"- >- Stop Streaming- </button>- )}-- <button- onClick={clearLogs}- className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-gray-300 rounded-lg transition-colors"- >- Clear- </button>-- {streaming && (- <div className="flex items-center gap-2 ml-auto">- <span className="w-2 h-2 rounded-full bg-port-success animate-pulse" />- <span className="text-sm text-port-success">Streaming live</span>- </div>- )}- </div>- </div>-- {/* Selected process info */}- {selectedProcess && (- <div className="flex items-center gap-3 flex-wrap">- <span className="text-gray-400">Viewing:</span>- <span className="font-medium text-white">{selectedProcess}</span>- <StatusBadge status={getProcessStatus(selectedProcess)} size="sm" />- <span className="text-gray-500 text-sm">- {filteredLogs.length} lines {filter && '(filtered)'}- </span>- </div>- )}-- {/* Log viewer */}- <LogViewer- logs={filteredLogs}- autoScroll={streaming}- maxHeight="calc(100vh - 400px)"- />-- {/* Empty state */}- {processes.length === 0 && (- <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">- <div className="text-4xl mb-4">📋</div>- <h3 className="text-lg font-semibold text-white mb-2">No PM2 processes found</h3>- <p className="text-gray-500">- Start an app from the Dashboard to see its logs here.- </p>- </div>- )}- </div>- );-}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex a2e544af9f..e6ce2ebfc3 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -70,49 +70,6 @@ export const allocatePorts = (count = 1) => request('/ports/allocate', {body: JSON.stringify({ count })});-// Logs-export const getProcesses = () => request('/logs/processes');-export const getProcessLogs = (processName, lines = 100) =>- request(`/logs/${encodeURIComponent(processName)}?lines=${lines}`);--/**- * Create SSE connection for streaming logs- * @param {string} processName - PM2 process name- * @param {number} lines - Initial lines to fetch- * @param {function} onMessage - Callback for each log line- * @param {function} onError - Error callback- * @returns {function} Cleanup function to close connection- */-export const streamLogs = (processName, lines, onMessage, onError) => {- const url = `/api/logs/${encodeURIComponent(processName)}?follow=true&lines=${lines}`;- const eventSource = new EventSource(url);-- eventSource.addEventListener('stdout', (e) => {- const data = JSON.parse(e.data);- onMessage({ ...data, type: 'stdout' });- });-- eventSource.addEventListener('stderr', (e) => {- const data = JSON.parse(e.data);- onMessage({ ...data, type: 'stderr' });- });-- eventSource.addEventListener('connected', (e) => {- const data = JSON.parse(e.data);- onMessage({ type: 'connected', ...data });- });-- eventSource.addEventListener('error', (e) => {- onError?.(e);- });-- eventSource.addEventListener('close', () => {- eventSource.close();- });-- return () => eventSource.close();-};-// Detectexport const detectRepo = (path) => request('/detect/repo', {method: 'POST',@@ -256,6 +213,11 @@ export const killAgent = (pid) => request(`/agents/${pid}`, { method: 'DELETE' }export const getCosStatus = () => request('/cos');export const startCos = () => request('/cos/start', { method: 'POST' });export const stopCos = () => request('/cos/stop', { method: 'POST' });+export const pauseCos = (reason) => request('/cos/pause', {+ method: 'POST',+ body: JSON.stringify({ reason })+});+export const resumeCos = () => request('/cos/resume', { method: 'POST' });export const getCosConfig = () => request('/cos/config');export const updateCosConfig = (config) => request('/cos/config', {method: 'PUT',diff --git a/client/src/services/socket.js b/client/src/services/socket.jsindex 2a23b6c08e..8774a6357e 100644--- a/client/src/services/socket.js+++ b/client/src/services/socket.js@@ -25,58 +25,6 @@ socket.on('connect_error', (error) => {export default socket;-/**- * Subscribe to log streaming for a process- * @param {string} processName - PM2 process name- * @param {number} lines - Initial lines to fetch- * @param {function} onLine - Callback for each log line- * @param {function} onSubscribed - Callback when subscribed- * @param {function} onError - Error callback- * @returns {function} Cleanup function- */-export function subscribeToLogs(processName, lines, { onLine, onSubscribed, onError, onClose }) {- const handleLine = (data) => {- if (data.processName === processName) {- onLine?.(data);- }- };-- const handleSubscribed = (data) => {- if (data.processName === processName) {- onSubscribed?.(data);- }- };-- const handleError = (data) => {- if (data.processName === processName) {- onError?.(data);- }- };-- const handleClose = (data) => {- if (data.processName === processName) {- onClose?.(data);- }- };-- socket.on('logs:line', handleLine);- socket.on('logs:subscribed', handleSubscribed);- socket.on('logs:error', handleError);- socket.on('logs:close', handleClose);-- // Start subscription- socket.emit('logs:subscribe', { processName, lines });-- // Return cleanup function- return () => {- socket.off('logs:line', handleLine);- socket.off('logs:subscribed', handleSubscribed);- socket.off('logs:error', handleError);- socket.off('logs:close', handleClose);- socket.emit('logs:unsubscribe');- };-}-/*** Check if socket is connected*/diff --git a/data.sample/providers.json b/data.sample/providers.jsonindex c65b7e2b9e..6af1339333 100644--- a/data.sample/providers.json+++ b/data.sample/providers.json@@ -22,8 +22,11 @@"type": "cli","command": "codex","args": [],- "models": ["codex"],- "defaultModel": "codex",+ "models": ["gpt-5.1-codex-mini", "gpt-5.1-codex-max"],+ "defaultModel": "gpt-5.1-codex-max",+ "lightModel": "gpt-5.1-codex-mini",+ "mediumModel": "gpt-5.1-codex-max",+ "heavyModel": "gpt-5.1-codex-max","timeout": 300000,"enabled": true,"envVars": {}diff --git a/server/routes/cos.js b/server/routes/cos.jsindex fd369215d5..2a2e47d181 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -5,6 +5,7 @@import { Router } from 'express';import * as cos from '../services/cos.js';import * as taskWatcher from '../services/taskWatcher.js';+import * as appActivity from '../services/appActivity.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();@@ -29,6 +30,19 @@ router.post('/stop', asyncHandler(async (req, res) => {res.json(result);}));+// POST /api/cos/pause - Pause CoS daemon (stays running but skips evaluations)+router.post('/pause', asyncHandler(async (req, res) => {+ const { reason } = req.body;+ const result = await cos.pause(reason);+ res.json(result);+}));++// POST /api/cos/resume - Resume CoS daemon from pause+router.post('/resume', asyncHandler(async (req, res) => {+ const result = await cos.resume();+ res.json(result);+}));+// GET /api/cos/config - Get configurationrouter.get('/config', asyncHandler(async (req, res) => {const config = await cos.getConfig();@@ -79,13 +93,13 @@ router.post('/tasks/reorder', asyncHandler(async (req, res) => {// POST /api/cos/tasks - Add a new taskrouter.post('/tasks', asyncHandler(async (req, res) => {- const { description, priority, context, model, provider, type = 'user', approvalRequired } = req.body;+ const { description, priority, context, model, provider, app, type = 'user', approvalRequired } = req.body;if (!description) {throw new ServerError('Description is required', { status: 400, code: 'VALIDATION_ERROR' });}- const taskData = { description, priority, context, model, provider, approvalRequired };+ const taskData = { description, priority, context, model, provider, app, approvalRequired };const result = await cos.addTask(taskData, type);res.json(result);}));@@ -93,7 +107,7 @@ router.post('/tasks', asyncHandler(async (req, res) => {// PUT /api/cos/tasks/:id - Update a taskrouter.put('/tasks/:id', asyncHandler(async (req, res) => {const { id } = req.params;- const { description, priority, status, context, model, provider, type = 'user' } = req.body;+ const { description, priority, status, context, model, provider, app, type = 'user' } = req.body;const updates = {};if (description !== undefined) updates.description = description;@@ -102,6 +116,7 @@ router.put('/tasks/:id', asyncHandler(async (req, res) => {if (context !== undefined) updates.context = context;if (model !== undefined) updates.model = model;if (provider !== undefined) updates.provider = provider;+ if (app !== undefined) updates.app = app;const result = await cos.updateTask(id, updates, type);if (result?.error) {@@ -235,4 +250,26 @@ router.get('/watcher', (req, res) => {res.json(taskWatcher.getWatcherStatus());});+// GET /api/cos/app-activity - Get per-app activity data+router.get('/app-activity', asyncHandler(async (req, res) => {+ const activity = await appActivity.loadAppActivity();+ res.json(activity);+}));++// GET /api/cos/app-activity/:appId - Get activity for specific app+router.get('/app-activity/:appId', asyncHandler(async (req, res) => {+ const activity = await appActivity.getAppActivityById(req.params.appId);+ if (!activity) {+ res.json({ appId: req.params.appId, activity: null, message: 'No activity recorded for this app' });+ return;+ }+ res.json({ appId: req.params.appId, activity });+}));++// POST /api/cos/app-activity/:appId/clear-cooldown - Clear cooldown for an app+router.post('/app-activity/:appId/clear-cooldown', asyncHandler(async (req, res) => {+ const result = await appActivity.clearAppCooldown(req.params.appId);+ res.json({ success: true, appId: req.params.appId, activity: result });+}));+export default router;diff --git a/server/services/appActivity.js b/server/services/appActivity.jsnew file mode 100644index 0000000000..976eb075e2--- /dev/null+++ b/server/services/appActivity.js@@ -0,0 +1,278 @@+/**+ * App Activity Tracking Service+ *+ * Manages per-app cooldowns, review history, and active work tracking.+ * Prevents the CoS from working on the same app in a loop.+ */++import { readFile, writeFile, mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '../../data/cos');+const ACTIVITY_FILE = join(DATA_DIR, 'app-activity.json');++const DEFAULT_ACTIVITY = {+ apps: {},+ global: {+ lastIdleReviewAt: null,+ totalReviews: 0+ }+};++/**+ * Ensure the data directory exists+ */+async function ensureDir() {+ if (!existsSync(DATA_DIR)) {+ await mkdir(DATA_DIR, { recursive: true });+ }+}++/**+ * Load app activity data+ */+export async function loadAppActivity() {+ await ensureDir();++ if (!existsSync(ACTIVITY_FILE)) {+ return { ...DEFAULT_ACTIVITY };+ }++ const content = await readFile(ACTIVITY_FILE, 'utf-8');+ return { ...DEFAULT_ACTIVITY, ...JSON.parse(content) };+}++/**+ * Save app activity data+ */+export async function saveAppActivity(activity) {+ await ensureDir();+ await writeFile(ACTIVITY_FILE, JSON.stringify(activity, null, 2));+}++/**+ * Get activity for a specific app+ */+export async function getAppActivityById(appId) {+ const activity = await loadAppActivity();+ return activity.apps[appId] || null;+}++/**+ * Update activity for a specific app+ */+export async function updateAppActivity(appId, updates) {+ const activity = await loadAppActivity();++ if (!activity.apps[appId]) {+ activity.apps[appId] = {+ lastReviewedAt: null,+ lastTaskCompletedAt: null,+ activeAgentId: null,+ cooldownUntil: null,+ stats: {+ reviewCount: 0,+ issuesFound: 0,+ issuesFixed: 0+ }+ };+ }++ // Merge updates, handling nested stats object+ if (updates.stats) {+ activity.apps[appId].stats = { ...activity.apps[appId].stats, ...updates.stats };+ delete updates.stats;+ }++ activity.apps[appId] = { ...activity.apps[appId], ...updates };+ await saveAppActivity(activity);++ return activity.apps[appId];+}++/**+ * Start cooldown for an app (called when agent completes work on it)+ */+export async function startAppCooldown(appId, cooldownMs) {+ const cooldownUntil = new Date(Date.now() + cooldownMs).toISOString();+ return updateAppActivity(appId, {+ cooldownUntil,+ activeAgentId: null,+ lastTaskCompletedAt: new Date().toISOString()+ });+}++/**+ * Mark an app review as started+ */+export async function markAppReviewStarted(appId, agentId) {+ return updateAppActivity(appId, {+ activeAgentId: agentId,+ lastReviewedAt: new Date().toISOString()+ });+}++/**+ * Mark an app review as completed+ */+export async function markAppReviewCompleted(appId, issuesFound = 0, issuesFixed = 0) {+ const activity = await getAppActivityById(appId) || { stats: {} };+ return updateAppActivity(appId, {+ activeAgentId: null,+ stats: {+ reviewCount: (activity.stats?.reviewCount || 0) + 1,+ issuesFound: (activity.stats?.issuesFound || 0) + issuesFound,+ issuesFixed: (activity.stats?.issuesFixed || 0) + issuesFixed+ }+ });+}++/**+ * Clear cooldown for an app (manual override)+ */+export async function clearAppCooldown(appId) {+ return updateAppActivity(appId, { cooldownUntil: null });+}++/**+ * Check if an app is on cooldown+ */+export async function isAppOnCooldown(appId, cooldownMs) {+ const activity = await loadAppActivity();+ const appActivity = activity.apps[appId];++ if (!appActivity) return false;++ const now = Date.now();++ // Check explicit cooldown+ if (appActivity.cooldownUntil) {+ const cooldownTime = new Date(appActivity.cooldownUntil).getTime();+ if (cooldownTime > now) {+ return true;+ }+ }++ // Check last activity time against cooldown period+ const lastActivity = Math.max(+ appActivity.lastReviewedAt ? new Date(appActivity.lastReviewedAt).getTime() : 0,+ appActivity.lastTaskCompletedAt ? new Date(appActivity.lastTaskCompletedAt).getTime() : 0+ );++ if (lastActivity && (now - lastActivity) < cooldownMs) {+ return true;+ }++ // Check if already has an active agent+ if (appActivity.activeAgentId) {+ return true;+ }++ return false;+}++/**+ * Get the next app eligible for review (not on cooldown, oldest review first)+ */+export async function getNextAppForReview(apps, cooldownMs) {+ const activity = await loadAppActivity();+ const now = Date.now();++ // Build list of eligible apps with their last review time+ const eligible = [];++ for (const app of apps) {+ const appActivity = activity.apps[app.id];++ // Skip if on cooldown+ if (appActivity) {+ // Check explicit cooldown+ if (appActivity.cooldownUntil && new Date(appActivity.cooldownUntil).getTime() > now) {+ continue;+ }++ // Check last activity cooldown+ const lastActivity = Math.max(+ appActivity.lastReviewedAt ? new Date(appActivity.lastReviewedAt).getTime() : 0,+ appActivity.lastTaskCompletedAt ? new Date(appActivity.lastTaskCompletedAt).getTime() : 0+ );++ if (lastActivity && (now - lastActivity) < cooldownMs) {+ continue;+ }++ // Check active agent+ if (appActivity.activeAgentId) {+ continue;+ }+ }++ // App is eligible+ const lastReview = appActivity?.lastReviewedAt+ ? new Date(appActivity.lastReviewedAt).getTime()+ : 0;++ eligible.push({+ app,+ lastReview,+ timeSinceReview: now - lastReview+ });+ }++ // Sort by longest time since review (oldest first)+ eligible.sort((a, b) => b.timeSinceReview - a.timeSinceReview);++ return eligible[0]?.app || null;+}++/**+ * Update global idle review timestamp+ */+export async function markIdleReviewStarted() {+ const activity = await loadAppActivity();+ activity.global.lastIdleReviewAt = new Date().toISOString();+ activity.global.totalReviews = (activity.global.totalReviews || 0) + 1;+ await saveAppActivity(activity);+ return activity.global;+}++/**+ * Get time until next eligible app is off cooldown+ */+export async function getNextCooldownExpiry(apps, cooldownMs) {+ const activity = await loadAppActivity();+ const now = Date.now();+ let nextExpiry = null;++ for (const app of apps) {+ const appActivity = activity.apps[app.id];+ if (!appActivity) continue;++ // Check explicit cooldown+ if (appActivity.cooldownUntil) {+ const expiryTime = new Date(appActivity.cooldownUntil).getTime();+ if (expiryTime > now && (!nextExpiry || expiryTime < nextExpiry)) {+ nextExpiry = expiryTime;+ }+ }++ // Check activity-based cooldown+ const lastActivity = Math.max(+ appActivity.lastReviewedAt ? new Date(appActivity.lastReviewedAt).getTime() : 0,+ appActivity.lastTaskCompletedAt ? new Date(appActivity.lastTaskCompletedAt).getTime() : 0+ );++ if (lastActivity) {+ const expiryTime = lastActivity + cooldownMs;+ if (expiryTime > now && (!nextExpiry || expiryTime < nextExpiry)) {+ nextExpiry = expiryTime;+ }+ }+ }++ return nextExpiry ? nextExpiry - now : null;+}diff --git a/server/services/cos.js b/server/services/cos.jsindex 703024fea1..ad01ba1e48 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -15,6 +15,9 @@ import { promisify } from 'util';import { v4 as uuidv4 } from 'uuid';import { getActiveProvider } from './providers.js';import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasks, getAwaitingApprovalTasks, updateTaskStatus, generateTasksMarkdown } from '../lib/taskParser.js';+import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted } from './appActivity.js';+import { classifyTask, isIdleReviewTask } from './taskClassifier.js';+import { getAllApps } from './apps.js';const execAsync = promisify(exec);@@ -70,7 +73,7 @@ async function withStateLock(fn) {const DEFAULT_CONFIG = {userTasksFile: 'data/TASKS.md', // User-defined taskscosTasksFile: 'data/COS-TASKS.md', // CoS internal/system tasks- evaluationIntervalMs: 60000, // 1 minute+ evaluationIntervalMs: 60000, // 1 minute (also used for idle check frequency)healthCheckIntervalMs: 900000, // 15 minutesmaxConcurrentAgents: 3,maxProcessMemoryMb: 2048, // Alert if any process exceeds this@@ -79,8 +82,25 @@ const DEFAULT_CONFIG = {{ name: 'filesystem', command: 'npx', args: ['-y', '@anthropic/mcp-server-filesystem'] },{ name: 'puppeteer', command: 'npx', args: ['-y', '@anthropic/mcp-puppeteer', '--isolated'] }],- autoStart: false,- selfImprovementEnabled: true // Allow CoS to suggest improvements to its own prompts+ autoStart: false, // Legacy: use alwaysOn instead+ selfImprovementEnabled: true, // Allow CoS to suggest improvements to its own prompts+ avatarStyle: 'svg', // UI preference: 'svg' or 'ascii'+ // Always-on mode settings+ alwaysOn: true, // CoS starts automatically and stays active+ appReviewCooldownMs: 3600000, // 1 hour between working on same app+ idleReviewEnabled: true, // Review apps for improvements when no user tasks+ idleReviewPriority: 'LOW', // Priority for auto-generated review tasks+ immediateExecution: true, // Execute new tasks immediately, don't wait for interval+ autoFixThresholds: {+ maxLinesChanged: 50, // Auto-approve if <= this many lines changed+ allowedCategories: [ // Categories that can auto-execute+ 'formatting',+ 'dry-violations',+ 'dead-code',+ 'typo-fix',+ 'import-cleanup'+ ]+ }};/**@@ -88,12 +108,16 @@ const DEFAULT_CONFIG = {*/const DEFAULT_STATE = {running: false,+ paused: false, // Pause state for always-on mode+ pausedAt: null, // Timestamp when paused+ pauseReason: null, // Optional reason for pauseconfig: DEFAULT_CONFIG,stats: {tasksCompleted: 0,totalRuntime: 0,agentsSpawned: 0,- lastEvaluation: null+ lastEvaluation: null,+ lastIdleReview: null // Track last idle review time},agents: {}};@@ -152,6 +176,9 @@ export async function getStatus() {return {running: daemonRunning,+ paused: state.paused || false,+ pausedAt: state.pausedAt,+ pauseReason: state.pauseReason,config: state.config,stats: state.stats,activeAgents,@@ -255,6 +282,61 @@ export async function stop() {return { success: true };}+/**+ * Pause the CoS daemon (for always-on mode)+ * Daemon stays running but skips evaluations+ */+export async function pause(reason = null) {+ const state = await loadState();++ if (state.paused) {+ return { success: false, error: 'Already paused' };+ }++ state.paused = true;+ state.pausedAt = new Date().toISOString();+ state.pauseReason = reason;+ await saveState(state);++ emitLog('info', `CoS paused${reason ? `: ${reason}` : ''}`);+ cosEvents.emit('status:paused', { paused: true, pausedAt: state.pausedAt, reason });+ return { success: true, pausedAt: state.pausedAt };+}++/**+ * Resume the CoS daemon from pause+ */+export async function resume() {+ const state = await loadState();++ if (!state.paused) {+ return { success: false, error: 'Not paused' };+ }++ state.paused = false;+ state.pausedAt = null;+ state.pauseReason = null;+ await saveState(state);++ emitLog('info', 'CoS resumed');+ cosEvents.emit('status:resumed', { paused: false });++ // Trigger immediate evaluation on resume+ if (daemonRunning) {+ setTimeout(() => evaluateTasks(), 500);+ }++ return { success: true };+}++/**+ * Check if CoS is paused+ */+export async function isPaused() {+ const state = await loadState();+ return state.paused || false;+}+/*** Get user tasks from TASKS.md*/@@ -338,10 +420,22 @@ async function resetOrphanedTasks() {/*** Evaluate tasks and decide what to spawn+ *+ * Priority order:+ * 1. User tasks (not on cooldown)+ * 2. Auto-approved system tasks (not on cooldown)+ * 3. Generate idle review task if no other work*/export async function evaluateTasks() {if (!daemonRunning) return;+ // Check if paused - skip evaluation if so+ const paused = await isPaused();+ if (paused) {+ emitLog('debug', 'CoS is paused - skipping evaluation');+ return;+ }+// Update evaluation timestamp with lock to prevent race conditionsconst state = await withStateLock(async () => {const s = await loadState();@@ -353,17 +447,7 @@ export async function evaluateTasks() {// Get both user and CoS tasksconst { user: userTaskData, cos: cosTaskData } = await getAllTasks();- const pendingUserTasks = userTaskData.grouped?.pending?.length || 0;- const inProgressUserTasks = userTaskData.grouped?.in_progress?.length || 0;- const pendingCosTasks = cosTaskData.grouped?.pending?.length || 0;-- emitLog('info', `Evaluating tasks: ${pendingUserTasks} pending, ${inProgressUserTasks} in_progress, ${pendingCosTasks} system`, {- pendingUser: pendingUserTasks,- inProgressUser: inProgressUserTasks,- pendingSystem: pendingCosTasks- });-- // Count running agents+ // Count running agents and available slotsconst runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;const availableSlots = state.config.maxConcurrentAgents - runningAgents;@@ -373,40 +457,78 @@ export async function evaluateTasks() {return;}- // Priority 1: Check for auto-approved CoS tasks (system maintenance)- if (cosTaskData.exists && cosTaskData.autoApproved?.length > 0) {- const nextAutoTask = cosTaskData.autoApproved[0];- emitLog('info', `Found auto-approved system task: ${nextAutoTask.id}`, { taskId: nextAutoTask.id });- cosEvents.emit('evaluation', {- message: 'Found auto-approved system task',- task: nextAutoTask,- type: 'internal'- });- cosEvents.emit('task:ready', { ...nextAutoTask, taskType: 'internal' });- return;+ const tasksToSpawn = [];++ // Priority 1: User tasks (not on cooldown)+ const pendingUserTasks = userTaskData.grouped?.pending || [];+ for (const task of pendingUserTasks) {+ if (tasksToSpawn.length >= availableSlots) break;++ // Check if task's app is on cooldown+ const appId = task.metadata?.app;+ if (appId) {+ const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);+ if (onCooldown) {+ emitLog('debug', `Skipping task ${task.id} - app ${appId} on cooldown`);+ continue;+ }+ }++ tasksToSpawn.push({ ...task, taskType: 'user' });+ }++ // Priority 2: Auto-approved system tasks (if slots available)+ if (tasksToSpawn.length < availableSlots && cosTaskData.exists) {+ const autoApproved = cosTaskData.autoApproved || [];+ for (const task of autoApproved) {+ if (tasksToSpawn.length >= availableSlots) break;++ // Check if task's app is on cooldown+ const appId = task.metadata?.app;+ if (appId) {+ const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);+ if (onCooldown) {+ emitLog('debug', `Skipping system task ${task.id} - app ${appId} on cooldown`);+ continue;+ }+ }++ tasksToSpawn.push({ ...task, taskType: 'internal' });+ }}- // Priority 2: Check for user tasks- if (userTaskData.exists) {- const nextUserTask = getNextTask(userTaskData.tasks);- if (nextUserTask) {- emitLog('success', `Found user task: ${nextUserTask.id} (${nextUserTask.priority})`, {- taskId: nextUserTask.id,- priority: nextUserTask.priority,- description: nextUserTask.description?.substring(0, 80)- });- cosEvents.emit('evaluation', {- message: 'Found user task to process',- task: nextUserTask,- pendingCount: userTaskData.grouped.pending.length,- type: 'user'- });- cosEvents.emit('task:ready', { ...nextUserTask, taskType: 'user' });- return;+ // Priority 3: Generate idle review task if no other work and idle review enabled+ if (tasksToSpawn.length === 0 && state.config.idleReviewEnabled) {+ const idleTask = await generateIdleReviewTask(state);+ if (idleTask) {+ tasksToSpawn.push(idleTask);}}- // Emit tasks awaiting approval if any+ // Emit evaluation status+ const pendingUserCount = userTaskData.grouped?.pending?.length || 0;+ const inProgressCount = userTaskData.grouped?.in_progress?.length || 0;+ const pendingSystemCount = cosTaskData.grouped?.pending?.length || 0;++ emitLog('info', `Evaluation: ${pendingUserCount} user pending, ${inProgressCount} in_progress, ${pendingSystemCount} system, spawning ${tasksToSpawn.length}`, {+ pendingUser: pendingUserCount,+ inProgress: inProgressCount,+ pendingSystem: pendingSystemCount,+ toSpawn: tasksToSpawn.length,+ availableSlots+ });++ // Spawn all ready tasks (up to available slots)+ for (const task of tasksToSpawn) {+ emitLog('success', `Spawning task: ${task.id} (${task.priority || 'MEDIUM'})`, {+ taskId: task.id,+ taskType: task.taskType,+ app: task.metadata?.app+ });+ cosEvents.emit('task:ready', task);+ }++ // Emit awaiting approval count if anyif (cosTaskData.exists && cosTaskData.awaitingApproval?.length > 0) {emitLog('info', `${cosTaskData.awaitingApproval.length} tasks awaiting approval`);cosEvents.emit('evaluation', {@@ -415,8 +537,67 @@ export async function evaluateTasks() {});}- emitLog('info', 'No pending tasks to process - idle');- cosEvents.emit('evaluation', { message: 'No pending tasks to process' });+ if (tasksToSpawn.length === 0) {+ emitLog('info', 'No tasks to process - idle');+ cosEvents.emit('evaluation', { message: 'No pending tasks to process' });+ }+}++/**+ * Generate an idle review task when no user/system tasks are pending+ *+ * @param {Object} state - Current CoS state+ * @returns {Object|null} Generated task or null if no apps eligible+ */+async function generateIdleReviewTask(state) {+ // Get all managed apps+ const apps = await getAllApps().catch(() => []);++ if (apps.length === 0) {+ emitLog('debug', 'No managed apps found for idle review');+ return null;+ }++ // Find next app eligible for review (not on cooldown, oldest review first)+ const nextApp = await getNextAppForReview(apps, state.config.appReviewCooldownMs);++ if (!nextApp) {+ emitLog('debug', 'All apps on cooldown - no idle review possible');+ return null;+ }++ // Mark that we're starting an idle review+ await markIdleReviewStarted();+ await markAppReviewStarted(nextApp.id, `idle-review-${Date.now()}`);++ // Update lastIdleReview timestamp+ await withStateLock(async () => {+ const s = await loadState();+ s.stats.lastIdleReview = new Date().toISOString();+ await saveState(s);+ });++ emitLog('info', `Generating idle review task for ${nextApp.name}`, { appId: nextApp.id });++ // Create an idle review task+ const reviewTask = {+ id: `idle-review-${nextApp.id}-${Date.now().toString(36)}`,+ status: 'pending',+ priority: state.config.idleReviewPriority || 'LOW',+ priorityValue: PRIORITY_VALUES[state.config.idleReviewPriority] || 1,+ description: `[Idle Review] Review ${nextApp.name} codebase for improvements: formatting issues, dead code, DRY violations, typos, and other small fixes that can be auto-approved`,+ metadata: {+ app: nextApp.id,+ appName: nextApp.name,+ repoPath: nextApp.repoPath,+ reviewType: 'idle',+ autoGenerated: true+ },+ taskType: 'internal',+ autoApproved: true // Idle reviews are auto-approved to start, but individual fixes need classification+ };++ return reviewTask;}/**@@ -679,11 +860,28 @@ export async function getAgents() {}/**- * Get agent by ID+ * Get agent by ID with full output from file*/export async function getAgent(agentId) {const state = await loadState();- return state.agents[agentId] || null;+ const agent = state.agents[agentId];+ if (!agent) return null;++ // For completed agents, read full output from file+ if (agent.status === 'completed') {+ const outputFile = join(AGENTS_DIR, agentId, 'output.txt');+ if (existsSync(outputFile)) {+ const fullOutput = await readFile(outputFile, 'utf-8');+ // Convert string to output array format+ const lines = fullOutput.split('\n').filter(line => line.trim());+ return {+ ...agent,+ output: lines.map(line => ({ line, timestamp: agent.completedAt }))+ };+ }+ }++ return agent;}/**@@ -897,6 +1095,7 @@ export async function updateTask(taskId, updates, taskType = 'user') {if (updates.context !== undefined) updatedMetadata.context = updates.context || undefined;if (updates.model !== undefined) updatedMetadata.model = updates.model || undefined;if (updates.provider !== undefined) updatedMetadata.provider = updates.provider || undefined;+ if (updates.app !== undefined) updatedMetadata.app = updates.app || undefined;// Clean undefined values from metadataObject.keys(updatedMetadata).forEach(key => {@@ -1044,8 +1243,9 @@ async function init() {const state = await loadState();- // Auto-start if configured- if (state.config.autoStart) {+ // Auto-start if alwaysOn mode is enabled (or legacy autoStart)+ if (state.config.alwaysOn || state.config.autoStart) {+ console.log('🚀 CoS auto-starting (alwaysOn mode)');await start();}}diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex d5a6e625ce..f56e054e30 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -12,7 +12,8 @@ import { fileURLToPath } from 'url';import { writeFile, mkdir, readFile } from 'fs/promises';import { existsSync } from 'fs';import { v4 as uuidv4 } from 'uuid';-import { cosEvents, registerAgent, updateAgent, completeAgent, appendAgentOutput, getConfig, updateTask } from './cos.js';+import { cosEvents, registerAgent, updateAgent, completeAgent, appendAgentOutput, getConfig, updateTask, addTask } from './cos.js';+import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';/*** Emit a log event for UI display (mirrors cos.js helper)@@ -156,6 +157,132 @@ async function completeAgentRun(runId, output, exitCode, duration, error = null)// Active agent processesconst activeAgents = new Map();+/**+ * Error patterns that warrant investigation tasks+ */+const ERROR_PATTERNS = [+ {+ pattern: /API Error: 404.*model:\s*(\S+)/i,+ category: 'model-not-found',+ actionable: true,+ extract: (match, output, task, model) => ({+ message: `Model "${match[1]}" not found`,+ suggestedFix: `Update model configuration - "${match[1]}" doesn't exist. Check provider settings or task metadata.`,+ affectedModel: match[1],+ configuredModel: model+ })+ },+ {+ pattern: /API Error: 401|authentication|unauthorized/i,+ category: 'auth-error',+ actionable: true,+ extract: () => ({+ message: 'Authentication failed',+ suggestedFix: 'Check API keys and provider configuration'+ })+ },+ {+ pattern: /API Error: 429|rate.?limit|too many requests/i,+ category: 'rate-limit',+ actionable: false, // Transient, retry will handle+ extract: () => ({+ message: 'Rate limit exceeded',+ suggestedFix: 'Wait and retry - temporary rate limiting'+ })+ },+ {+ pattern: /API Error: 5\d{2}|server error|internal error/i,+ category: 'server-error',+ actionable: false, // Transient+ extract: () => ({+ message: 'API server error',+ suggestedFix: 'Retry later - temporary server issue'+ })+ },+ {+ pattern: /ECONNREFUSED|ETIMEDOUT|network error/i,+ category: 'network-error',+ actionable: false, // Transient+ extract: () => ({+ message: 'Network connection failed',+ suggestedFix: 'Check network connectivity'+ })+ },+ {+ pattern: /not_found_error.*model/i,+ category: 'model-not-found',+ actionable: true,+ extract: (match, output, task, model) => ({+ message: `Model not found in API response`,+ suggestedFix: `The model "${model}" specified for this task doesn't exist. Update provider or task configuration.`,+ configuredModel: model+ })+ }+];++/**+ * Analyze agent failure output and categorize the error+ */+function analyzeAgentFailure(output, task, model) {+ for (const errorDef of ERROR_PATTERNS) {+ const match = output.match(errorDef.pattern);+ if (match) {+ const extracted = errorDef.extract(match, output, task, model);+ return {+ category: errorDef.category,+ actionable: errorDef.actionable,+ ...extracted+ };+ }+ }++ // Generic failure - not actionable by default+ return {+ category: 'unknown',+ actionable: false,+ message: 'Agent failed with unknown error',+ suggestedFix: 'Review agent output logs for details'+ };+}++/**+ * Create an investigation task in COS-TASKS.md for failed agent+ */+async function createInvestigationTask(agentId, originalTask, errorAnalysis) {+ const description = `[Auto] Investigate agent failure: ${errorAnalysis.message}++**Failed Agent**: ${agentId}+**Original Task**: ${originalTask.id} - ${(originalTask.description || '').substring(0, 100)}+**Error Category**: ${errorAnalysis.category}+**Suggested Fix**: ${errorAnalysis.suggestedFix}+${errorAnalysis.configuredModel ? `**Configured Model**: ${errorAnalysis.configuredModel}` : ''}+${errorAnalysis.affectedModel ? `**Affected Model**: ${errorAnalysis.affectedModel}` : ''}++Review the error, fix the configuration or code issue, and retry the original task.`;++ const investigationTask = await addTask({+ description,+ priority: 'HIGH',+ context: `Auto-generated from agent ${agentId} failure`,+ approvalRequired: true // Require human approval before auto-fixing+ }, 'internal');++ emitLog('info', `Created investigation task ${investigationTask.id} for failed agent ${agentId}`, {+ agentId,+ taskId: investigationTask.id,+ errorCategory: errorAnalysis.category+ });++ cosEvents.emit('investigation:created', {+ investigationTaskId: investigationTask.id,+ failedAgentId: agentId,+ originalTaskId: originalTask.id,+ errorAnalysis+ });++ return investigationTask;+}+/*** Initialize the spawner - listen for task:ready events*/@@ -331,20 +458,31 @@ export async function spawnAgentForTask(task) {// Save final outputawait writeFile(outputFile, outputBuffer).catch(() => {});+ // Analyze failure and extract error details+ const errorAnalysis = success ? null : analyzeAgentFailure(outputBuffer, task, selectedModel);+await completeAgent(agentId, {success,exitCode: code,duration,- outputLength: outputBuffer.length+ outputLength: outputBuffer.length,+ errorAnalysis});// Complete the run tracking- await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration);+ await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration, errorAnalysis?.message);// Update task status based on resultconst newStatus = success ? 'completed' : 'pending'; // Reset to pending on failure for retryawait 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 outputif (success && outputBuffer.length > 100) {extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {@@ -352,6 +490,27 @@ export async function spawnAgentForTask(task) {});}+ // 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++ // Mark review completed with stats+ const issuesFound = success ? 1 : 0; // TODO: Parse from output for accurate count+ 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 });+ });++ emitLog('info', `App ${appId} cooldown started (${Math.round(cooldownMs / 60000)} min)`, { appId, cooldownMs });+ }+unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);activeAgents.delete(agentId);});diff --git a/server/services/taskClassifier.js b/server/services/taskClassifier.jsnew file mode 100644index 0000000000..fc0780ab9f--- /dev/null+++ b/server/services/taskClassifier.js@@ -0,0 +1,240 @@+/**+ * Task Classifier Service+ *+ * Analyzes tasks and their outputs to determine if they can be auto-approved+ * or require user confirmation.+ */++// Classification categories with auto-approve rules+const CLASSIFICATION_RULES = {+ // Auto-approvable categories (small, safe changes)+ autoApprove: {+ 'formatting': {+ patterns: [/format|lint|prettier|eslint|style/i],+ maxLines: 100,+ description: 'Code formatting and linting fixes'+ },+ 'dry-violations': {+ patterns: [/dry|duplicate|extract.*function|refactor.*common/i],+ maxLines: 50,+ description: 'Removing code duplication'+ },+ 'dead-code': {+ patterns: [/dead.*code|unused|remove.*unused/i],+ maxLines: 30,+ description: 'Removing unused code'+ },+ 'typo-fix': {+ patterns: [/typo|spelling|grammar|comment/i],+ maxLines: 20,+ description: 'Fixing typos and comments'+ },+ 'import-cleanup': {+ patterns: [/import|require|module.*cleanup/i],+ maxLines: 30,+ description: 'Cleaning up imports'+ },+ 'documentation': {+ patterns: [/doc|readme|jsdoc|add.*comment/i],+ maxLines: 100,+ description: 'Documentation updates'+ }+ },++ // Always require approval (risky changes)+ requireApproval: {+ 'security': {+ pattern: /security|auth|password|token|credential|secret|key|permission/i,+ reason: 'Security-related changes require manual review'+ },+ 'database': {+ pattern: /database|migration|schema|sql|query|prisma/i,+ reason: 'Database changes require manual review'+ },+ 'api-change': {+ pattern: /api.*change|endpoint.*change|route.*change|breaking.*change/i,+ reason: 'API changes may affect consumers'+ },+ 'dependency': {+ pattern: /package\.json|dependency|upgrade.*version|npm.*install/i,+ reason: 'Dependency changes require verification'+ },+ 'architecture': {+ pattern: /architect|restructure|rewrite|major.*refactor/i,+ reason: 'Architectural changes need approval'+ },+ 'config': {+ pattern: /config.*change|environment|\.env|ecosystem\.config/i,+ reason: 'Configuration changes require review'+ },+ 'deployment': {+ pattern: /deploy|production|release|publish/i,+ reason: 'Deployment changes need approval'+ }+ }+};++/**+ * Classify a task to determine if it can be auto-approved+ *+ * @param {Object} task - The task to classify+ * @param {Object} analysisResult - Optional analysis result with line counts+ * @param {Object} config - Config with autoFixThresholds+ * @returns {Object} Classification result+ */+export function classifyTask(task, analysisResult = null, config = null) {+ const description = (task.description || '').toLowerCase();+ const totalLines = analysisResult?.linesChanged || 0;+ const maxAllowedLines = config?.autoFixThresholds?.maxLinesChanged || 50;+ const allowedCategories = config?.autoFixThresholds?.allowedCategories || [];++ // Check for required approval patterns first (these always need approval)+ for (const [category, rule] of Object.entries(CLASSIFICATION_RULES.requireApproval)) {+ if (rule.pattern.test(description)) {+ return {+ autoApprove: false,+ category,+ reason: rule.reason,+ confidence: 'high'+ };+ }+ }++ // Check for auto-approvable patterns+ for (const [category, rule] of Object.entries(CLASSIFICATION_RULES.autoApprove)) {+ for (const pattern of rule.patterns) {+ if (pattern.test(description)) {+ // Check if category is in allowed list+ if (!allowedCategories.includes(category)) {+ return {+ autoApprove: false,+ category,+ reason: `Category '${category}' not in auto-approve list`,+ confidence: 'medium'+ };+ }++ // Check line count threshold+ const categoryMaxLines = Math.min(rule.maxLines, maxAllowedLines);+ if (totalLines > categoryMaxLines) {+ return {+ autoApprove: false,+ category,+ reason: `Changes exceed auto-approve limit (${totalLines} > ${categoryMaxLines} lines)`,+ confidence: 'medium'+ };+ }++ return {+ autoApprove: true,+ category,+ reason: rule.description,+ confidence: 'high',+ maxLines: categoryMaxLines+ };+ }+ }+ }++ // Default: require approval for unknown categories+ return {+ autoApprove: false,+ category: 'unknown',+ reason: 'Task does not match auto-approve patterns',+ confidence: 'low'+ };+}++/**+ * Classify findings from an idle code review+ *+ * @param {Array} findings - Array of findings from review+ * @param {Object} config - Config with autoFixThresholds+ * @returns {Array} Classified findings+ */+export function classifyReviewFindings(findings, config = null) {+ return findings.map(finding => {+ const classification = classifyTask(+ { description: finding.description || finding.title },+ { linesChanged: finding.estimatedLines || 0 },+ config+ );+ return {+ ...finding,+ ...classification+ };+ });+}++/**+ * Get classification rules for UI display+ */+export function getClassificationRules() {+ return {+ autoApprove: Object.entries(CLASSIFICATION_RULES.autoApprove).map(([key, value]) => ({+ category: key,+ patterns: value.patterns.map(p => p.toString()),+ maxLines: value.maxLines,+ description: value.description+ })),+ requireApproval: Object.entries(CLASSIFICATION_RULES.requireApproval).map(([key, value]) => ({+ category: key,+ pattern: value.pattern.toString(),+ reason: value.reason+ }))+ };+}++/**+ * Check if a task description suggests it's an idle review task+ */+export function isIdleReviewTask(task) {+ const description = (task.description || '').toLowerCase();+ return (+ description.includes('[idle review]') ||+ description.includes('autonomous code review') ||+ task.metadata?.reviewType === 'idle' ||+ task.metadata?.autoGenerated === true+ );+}++/**+ * Estimate complexity of a task based on description+ */+export function estimateTaskComplexity(task) {+ const description = (task.description || '').toLowerCase();++ // High complexity indicators+ const highComplexity = [+ /multiple.*file/i,+ /across.*codebase/i,+ /refactor.*entire/i,+ /restructure/i,+ /migration/i,+ /integration/i+ ];++ // Low complexity indicators+ const lowComplexity = [+ /single.*file/i,+ /one.*line/i,+ /simple/i,+ /typo/i,+ /comment/i,+ /rename/i+ ];++ for (const pattern of highComplexity) {+ if (pattern.test(description)) {+ return { level: 'high', reason: 'Task involves multiple files or significant changes' };+ }+ }++ for (const pattern of lowComplexity) {+ if (pattern.test(description)) {+ return { level: 'low', reason: 'Task is simple and localized' };+ }+ }++ return { level: 'medium', reason: 'Standard complexity task' };+}diff --git a/server/services/taskWatcher.js b/server/services/taskWatcher.jsindex 9bc369713d..9349e1dec7 100644--- a/server/services/taskWatcher.js+++ b/server/services/taskWatcher.js@@ -8,7 +8,7 @@import { watch } from 'chokidar';import { join, dirname } from 'path';import { fileURLToPath } from 'url';-import { cosEvents, getUserTasks, getCosTasks, getConfig } from './cos.js';+import { cosEvents, getUserTasks, getCosTasks, getConfig, evaluateTasks, isRunning, isPaused } from './cos.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -19,6 +19,47 @@ let isWatching = false;let lastUserTasks = null;let lastCosTasks = null;+// Debounce timer for immediate evaluation+let immediateEvalTimeout = null;+const IMMEDIATE_EVAL_DEBOUNCE_MS = 500;++/**+ * Trigger immediate task evaluation (debounced)+ * Called when new tasks are added and immediateExecution is enabled+ */+async function triggerImmediateEvaluation(reason = 'task-added') {+ // Clear any pending evaluation+ if (immediateEvalTimeout) {+ clearTimeout(immediateEvalTimeout);+ }++ // Debounce to avoid rapid-fire evaluations+ immediateEvalTimeout = setTimeout(async () => {+ const config = await getConfig();++ // Check if immediate execution is enabled+ if (!config.immediateExecution) {+ return;+ }++ // Check if CoS is running and not paused+ if (!isRunning()) {+ return;+ }++ const paused = await isPaused();+ if (paused) {+ return;+ }++ console.log(`⚡ Triggering immediate evaluation: ${reason}`);+ cosEvents.emit('evaluation:immediate', { reason });++ // Run evaluation+ await evaluateTasks();+ }, IMMEDIATE_EVAL_DEBOUNCE_MS);+}+/*** Start watching task files*/@@ -116,6 +157,8 @@ async function handleUserTasksChange() {if (changes.added.length > 0) {cosEvents.emit('tasks:user:added', { tasks: changes.added });+ // Trigger immediate evaluation for new user tasks+ triggerImmediateEvaluation('user-task-added');}if (changes.completed.length > 0) {@@ -124,6 +167,11 @@ async function handleUserTasksChange() {if (changes.modified.length > 0) {cosEvents.emit('tasks:user:modified', { tasks: changes.modified });+ // Check if any task was changed to pending (might need immediate eval)+ const pendingChanges = changes.modified.filter(c => c.new.status === 'pending' && c.old.status !== 'pending');+ if (pendingChanges.length > 0) {+ triggerImmediateEvaluation('task-status-changed-to-pending');+ }}if (changes.removed.length > 0) {@@ -150,6 +198,11 @@ async function handleCosTasksChange() {if (changes.added.length > 0) {cosEvents.emit('tasks:cos:added', { tasks: changes.added });+ // Trigger immediate evaluation for new auto-approved system tasks+ const autoApprovedTasks = changes.added.filter(t => t.autoApproved);+ if (autoApprovedTasks.length > 0) {+ triggerImmediateEvaluation('system-task-added');+ }}if (changes.completed.length > 0) {@@ -158,6 +211,13 @@ async function handleCosTasksChange() {if (changes.modified.length > 0) {cosEvents.emit('tasks:cos:modified', { tasks: changes.modified });+ // Check if any task was approved (changed from approvalRequired to autoApproved)+ const approvedTasks = changes.modified.filter(c =>+ c.new.autoApproved && !c.old.autoApproved+ );+ if (approvedTasks.length > 0) {+ triggerImmediateEvaluation('task-approved');+ }}if (changes.removed.length > 0) {