| 1 | import { useEffect, useState } from 'react'; |
| 2 | import { useNavigate } from 'react-router-dom'; |
| 3 | import { Bot, KeyRound, Mail, Power, Play, Trash2, GitBranch, Server, X, Plus, Copy, CheckCheck, ListTodo, DollarSign, AlertTriangle } from 'lucide-react'; |
| 4 | import { api } from '../api.js'; |
| 5 | import VersionsModal from '../components/VersionsModal.jsx'; |
| 6 | import McpModal from '../components/McpModal.jsx'; |
| 7 | |
| 8 | export default function Agents() { |
| 9 | const nav = useNavigate(); |
| 10 | const [agents, setAgents] = useState([]); |
| 11 | const [spending, setSpending] = useState({}); // agentId -> {today, this_month, all_time, runs_month} |
| 12 | const [versionsFor, setVersionsFor] = useState(null); |
| 13 | const [mcpFor, setMcpFor] = useState(null); |
| 14 | |
| 15 | async function reload() { |
| 16 | const list = await api('/api/agents'); |
| 17 | setAgents(list); |
| 18 | // Fetch spending for all agents in parallel |
| 19 | const results = await Promise.allSettled(list.map(a => |
| 20 | api(`/api/agents/${a.id}/spending`).then(s => [a.id, s]) |
| 21 | )); |
| 22 | const map = {}; |
| 23 | for (const r of results) { |
| 24 | if (r.status === 'fulfilled') map[r.value[0]] = r.value[1]; |
| 25 | } |
| 26 | setSpending(map); |
| 27 | } |
| 28 | useEffect(() => { reload().catch(() => {}); }, []); |
| 29 | |
| 30 | async function toggle(a) { |
| 31 | const updated = await api(`/api/agents/${a.id}`, { |
| 32 | method: 'PATCH', body: JSON.stringify({ enabled: !a.enabled }), |
| 33 | }); |
| 34 | setAgents(list => list.map(x => x.id === a.id ? updated : x)); |
| 35 | } |
| 36 | |
| 37 | async function runNow(a) { |
| 38 | try { await api(`/api/agents/${a.id}/run`, { method: 'POST' }); } |
| 39 | catch (e) { alert(e.message); } |
| 40 | } |
| 41 | |
| 42 | async function remove(a) { |
| 43 | const msg = `Eliminar "${a.name}" completamente?\n\n` + |
| 44 | `Esto borra:\n` + |
| 45 | ` • la skill en ~/.claude/skills/${a.id}\n` + |
| 46 | (a.botEmail?.endsWith('@bot.utopiaia.com') ? ` • el mailbox ${a.botEmail}\n` : '') + |
| 47 | ` • todo el historial de versiones`; |
| 48 | if (!confirm(msg)) return; |
| 49 | try { |
| 50 | await api(`/api/agents/${a.id}`, { method: 'DELETE' }); |
| 51 | reload(); |
| 52 | } catch (e) { alert(e.message); } |
| 53 | } |
| 54 | |
| 55 | function senderEmails(agent) { |
| 56 | return (agent.authorizedSenders || []).map(s => typeof s === 'string' ? s : s.email); |
| 57 | } |
| 58 | async function patchSenders(agent, next) { |
| 59 | const updated = await api(`/api/agents/${agent.id}`, { |
| 60 | method: 'PATCH', body: JSON.stringify({ authorizedSenders: next }), |
| 61 | }); |
| 62 | setAgents(list => list.map(x => x.id === agent.id ? updated : x)); |
| 63 | } |
| 64 | async function addSender(agent, email, role = 'reader') { |
| 65 | email = (email || '').trim().toLowerCase(); |
| 66 | if (!email || !/.+@.+\..+/.test(email)) return; |
| 67 | if (senderEmails(agent).includes(email)) return; |
| 68 | const cur = (agent.authorizedSenders || []).map(s => typeof s === 'string' ? { email: s, role: 'reader' } : s); |
| 69 | await patchSenders(agent, [...cur, { email, role }]); |
| 70 | } |
| 71 | async function removeSender(agent, email) { |
| 72 | const cur = (agent.authorizedSenders || []).map(s => typeof s === 'string' ? { email: s, role: 'reader' } : s); |
| 73 | await patchSenders(agent, cur.filter(s => s.email !== email)); |
| 74 | } |
| 75 | async function changeRole(agent, email, newRole) { |
| 76 | const cur = (agent.authorizedSenders || []).map(s => typeof s === 'string' ? { email: s, role: 'reader' } : s); |
| 77 | await patchSenders(agent, cur.map(s => s.email === email ? { ...s, role: newRole } : s)); |
| 78 | } |
| 79 | |
| 80 | async function setSpendingLimit(agent, limitUsd) { |
| 81 | const val = limitUsd === '' || limitUsd == null ? null : parseFloat(limitUsd); |
| 82 | const updated = await api(`/api/agents/${agent.id}`, { |
| 83 | method: 'PATCH', body: JSON.stringify({ spendingLimitMonthly: val }), |
| 84 | }); |
| 85 | setAgents(list => list.map(x => x.id === agent.id ? updated : x)); |
| 86 | } |
| 87 | |
| 88 | return ( |
| 89 | <div className="h-full overflow-y-auto p-6 max-w-4xl"> |
| 90 | <div className="flex items-end justify-between mb-4"> |
| 91 | <div> |
| 92 | <h1 className="text-lg font-semibold text-slate-100">Agents</h1> |
| 93 | <p className="text-xs text-slate-500 mt-0.5"> |
| 94 | {agents.length} agente{agents.length === 1 ? '' : 's'} · {agents.filter(a=>a.enabled).length} activo{agents.filter(a=>a.enabled).length === 1 ? '' : 's'} |
| 95 | </p> |
| 96 | </div> |
| 97 | </div> |
| 98 | |
| 99 | {agents.length === 0 ? ( |
| 100 | <div className="card text-center py-12 text-slate-500 text-sm"> |
| 101 | <Bot size={28} className="mx-auto mb-2 opacity-40" /> |
| 102 | Aún no tienes agentes — crea el primero desde Chat. |
| 103 | </div> |
| 104 | ) : ( |
| 105 | <div className="space-y-2"> |
| 106 | {agents.map(a => ( |
| 107 | <div key={a.id} className="card"> |
| 108 | <div className="flex items-center gap-3"> |
| 109 | <div className="w-9 h-9 rounded-lg bg-violet/15 border border-violet/30 flex items-center justify-center"> |
| 110 | <Bot size={16} className="text-violet-300" /> |
| 111 | </div> |
| 112 | <div className="flex-1 min-w-0"> |
| 113 | <div className="flex items-center gap-2"> |
| 114 | <span className="font-medium text-slate-100">{a.name}</span> |
| 115 | <span className={a.enabled ? 'pill-on' : 'pill-off'}>{a.enabled ? 'on' : 'off'}</span> |
| 116 | {a.version && <span className="pill bg-violet/10 border border-violet/30 text-violet-300 font-mono">v{a.version}</span>} |
| 117 | {a.mailProvider === 'imap' |
| 118 | ? (!a.hasImapCredentials && <span className="pill bg-amber-500/10 border border-amber-500/30 text-amber-300">sin imap-credentials.json</span>) |
| 119 | : ( |
| 120 | <> |
| 121 | {!a.hasCredentials && <span className="pill bg-amber-500/10 border border-amber-500/30 text-amber-300">sin credentials.json</span>} |
| 122 | {a.hasCredentials && !a.hasToken && <span className="pill bg-amber-500/10 border border-amber-500/30 text-amber-300">sin OAuth token</span>} |
| 123 | </> |
| 124 | )} |
| 125 | {a.enabled && !a.ready && <span className="pill bg-rose-500/10 border border-rose-500/30 text-rose-300">no listo</span>} |
| 126 | {a.ready && !a.enabled && <span className="pill bg-emerald-500/10 border border-emerald-500/30 text-emerald-300">listo</span>} |
| 127 | </div> |
| 128 | <div className="text-xs text-slate-500 font-mono truncate">{a.id}</div> |
| 129 | </div> |
| 130 | <div className="flex gap-1.5"> |
| 131 | <button className="btn-ghost" title="Cola de tareas" onClick={() => nav(`/queue/${a.id}`)}> |
| 132 | <ListTodo size={13} /> |
| 133 | </button> |
| 134 | <button className="btn-ghost" title="MCP / Tools" onClick={() => setMcpFor(a.id)}> |
| 135 | <Server size={13} /> |
| 136 | </button> |
| 137 | <button className="btn-ghost" title="Versiones" onClick={() => setVersionsFor(a.id)}> |
| 138 | <GitBranch size={13} /> |
| 139 | </button> |
| 140 | <button className="btn-ghost" title="Ejecutar ahora" onClick={() => runNow(a)}> |
| 141 | <Play size={13} /> |
| 142 | </button> |
| 143 | <button className="btn-ghost" title={a.enabled ? 'Desactivar' : 'Activar'} onClick={() => toggle(a)}> |
| 144 | <Power size={13} className={a.enabled ? 'text-emerald-300' : 'text-slate-500'} /> |
| 145 | </button> |
| 146 | <button className="btn-ghost" title="Eliminar" onClick={() => remove(a)}> |
| 147 | <Trash2 size={13} className="text-rose-300" /> |
| 148 | </button> |
| 149 | </div> |
| 150 | </div> |
| 151 | |
| 152 | <div className="mt-3 pt-3 border-t border-border-subtle grid grid-cols-2 gap-x-4 gap-y-2 text-xs"> |
| 153 | <InboxRow agent={a} /> |
| 154 | <Field icon={KeyRound} label="SSH key" value={a.sshKey || '—'} mono /> |
| 155 | <Field icon={KeyRound} label="Servidor" |
| 156 | value={a.deployHost ? `${a.deployUser}@${a.deployHost}` : '—'} mono /> |
| 157 | <div /> {/* empty cell to keep the next row full-width */} |
| 158 | </div> |
| 159 | |
| 160 | {/* Senders list — always visible */} |
| 161 | <SendersEditor agent={a} |
| 162 | onAdd={(email, role) => addSender(a, email, role)} |
| 163 | onRemove={(email) => removeSender(a, email)} |
| 164 | onChangeRole={(email, role) => changeRole(a, email, role)} /> |
| 165 | |
| 166 | {/* Spending control */} |
| 167 | <SpendingCard agent={a} |
| 168 | data={spending[a.id]} |
| 169 | onSetLimit={val => setSpendingLimit(a, val)} /> |
| 170 | </div> |
| 171 | ))} |
| 172 | </div> |
| 173 | )} |
| 174 | |
| 175 | {versionsFor && ( |
| 176 | <VersionsModal |
| 177 | agentId={versionsFor} |
| 178 | onClose={() => setVersionsFor(null)} |
| 179 | onRollback={() => reload()} |
| 180 | /> |
| 181 | )} |
| 182 | {mcpFor && <McpModal agentId={mcpFor} onClose={() => setMcpFor(null)} />} |
| 183 | </div> |
| 184 | ); |
| 185 | } |
| 186 | |
| 187 | function Field({ icon: Icon, label, value, mono }) { |
| 188 | return ( |
| 189 | <div className="flex items-start gap-2"> |
| 190 | <Icon size={11} className="text-slate-600 mt-0.5 flex-shrink-0" /> |
| 191 | <div className="min-w-0"> |
| 192 | <div className="text-[10px] uppercase tracking-wider text-slate-600">{label}</div> |
| 193 | <div className={`text-slate-300 truncate ${mono ? 'font-mono' : ''}`}>{value}</div> |
| 194 | </div> |
| 195 | </div> |
| 196 | ); |
| 197 | } |
| 198 | |
| 199 | function InboxRow({ agent }) { |
| 200 | const [copied, setCopied] = useState(false); |
| 201 | function copy() { |
| 202 | navigator.clipboard.writeText(agent.botEmail); |
| 203 | setCopied(true); setTimeout(() => setCopied(false), 1200); |
| 204 | } |
| 205 | return ( |
| 206 | <div className="flex items-start gap-2"> |
| 207 | <Mail size={11} className="text-slate-600 mt-0.5 flex-shrink-0" /> |
| 208 | <div className="min-w-0 flex-1"> |
| 209 | <div className="text-[10px] uppercase tracking-wider text-slate-600">Inbox del bot</div> |
| 210 | <div className="flex items-center gap-1.5"> |
| 211 | <span className="font-mono text-slate-300 truncate">{agent.botEmail}</span> |
| 212 | <button onClick={copy} className="text-slate-500 hover:text-slate-300" title="Copiar"> |
| 213 | {copied ? <CheckCheck size={11} className="text-emerald-400" /> : <Copy size={11} />} |
| 214 | </button> |
| 215 | </div> |
| 216 | </div> |
| 217 | </div> |
| 218 | ); |
| 219 | } |
| 220 | |
| 221 | const ROLE_PILL = { |
| 222 | owner: 'bg-amber-500/15 border-amber-500/40 text-amber-300', |
| 223 | cocreator: 'bg-violet/15 border-violet/40 text-violet-300', |
| 224 | reader: 'bg-slate-700/50 border-slate-600 text-slate-400', |
| 225 | }; |
| 226 | const ROLE_TIP = { |
| 227 | owner: 'creador — permiso total', |
| 228 | cocreator: 'puede modificar el comportamiento', |
| 229 | reader: 'solo puede usar el agente', |
| 230 | }; |
| 231 | |
| 232 | function SendersEditor({ agent, onAdd, onRemove, onChangeRole }) { |
| 233 | const [val, setVal] = useState(''); |
| 234 | const [role, setRole] = useState('reader'); |
| 235 | const list = (agent.authorizedSenders || []).map(s => |
| 236 | typeof s === 'string' ? { email: s, role: 'reader' } : s |
| 237 | ); |
| 238 | |
| 239 | function submit() { |
| 240 | const email = val.trim().toLowerCase(); |
| 241 | if (!email || !/.+@.+\..+/.test(email)) return; |
| 242 | onAdd(email, role); |
| 243 | setVal(''); |
| 244 | } |
| 245 | |
| 246 | return ( |
| 247 | <div className="mt-3 pt-3 border-t border-border-subtle"> |
| 248 | <div className="flex items-center justify-between mb-2"> |
| 249 | <div className="text-[10px] uppercase tracking-wider text-slate-500 flex items-center gap-1"> |
| 250 | <Mail size={10} /> Remitentes autorizados |
| 251 | </div> |
| 252 | <span className="text-[10px] text-slate-600">{list.length} permitido{list.length !== 1 ? 's' : ''}</span> |
| 253 | </div> |
| 254 | |
| 255 | {list.length === 0 ? ( |
| 256 | <p className="text-[11px] text-slate-600 italic mb-2"> |
| 257 | Ninguno aún — añade emails que pueden escribir a este agente. |
| 258 | </p> |
| 259 | ) : ( |
| 260 | <div className="space-y-1 mb-2"> |
| 261 | {list.map(s => ( |
| 262 | <div key={s.email} |
| 263 | className="flex items-center gap-2 bg-surface-2/50 rounded-lg px-2.5 py-1.5"> |
| 264 | <span className="font-mono text-[12px] text-slate-200 flex-1 min-w-0 truncate" |
| 265 | title={s.email}> |
| 266 | {s.email} |
| 267 | </span> |
| 268 | <select |
| 269 | value={s.role} |
| 270 | onChange={e => onChangeRole(s.email, e.target.value)} |
| 271 | title={ROLE_TIP[s.role]} |
| 272 | className={`text-[10px] font-mono rounded border px-1.5 py-0.5 outline-none cursor-pointer bg-surface-1 ${ROLE_PILL[s.role] || ROLE_PILL.reader}`}> |
| 273 | <option value="reader">reader</option> |
| 274 | <option value="cocreator">cocreator</option> |
| 275 | <option value="owner">owner</option> |
| 276 | </select> |
| 277 | <button onClick={() => onRemove(s.email)} |
| 278 | className="text-slate-600 hover:text-rose-300 transition flex-shrink-0" |
| 279 | title="Quitar"> |
| 280 | <X size={12} /> |
| 281 | </button> |
| 282 | </div> |
| 283 | ))} |
| 284 | </div> |
| 285 | )} |
| 286 | |
| 287 | {/* Add row */} |
| 288 | <div className="flex items-center gap-2 bg-surface-2/30 border border-dashed border-border-subtle rounded-lg px-2.5 py-1.5"> |
| 289 | <input |
| 290 | type="email" |
| 291 | placeholder="nuevo@email.com" |
| 292 | className="flex-1 bg-transparent text-[12px] font-mono text-slate-300 placeholder:text-slate-600 outline-none min-w-0" |
| 293 | value={val} |
| 294 | onChange={e => setVal(e.target.value)} |
| 295 | onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); submit(); } if (e.key === 'Escape') setVal(''); }} |
| 296 | /> |
| 297 | <select value={role} onChange={e => setRole(e.target.value)} |
| 298 | className={`text-[10px] font-mono rounded border px-1.5 py-0.5 outline-none cursor-pointer bg-surface-1 ${ROLE_PILL[role]}`}> |
| 299 | <option value="reader">reader</option> |
| 300 | <option value="cocreator">cocreator</option> |
| 301 | <option value="owner">owner</option> |
| 302 | </select> |
| 303 | <button onClick={submit} disabled={!val.trim()} |
| 304 | className="text-violet-400 hover:text-violet-200 disabled:opacity-30 flex-shrink-0 transition" |
| 305 | title="Añadir remitente"> |
| 306 | <Plus size={13} /> |
| 307 | </button> |
| 308 | </div> |
| 309 | </div> |
| 310 | ); |
| 311 | } |
| 312 | |
| 313 | function SpendingCard({ agent, data, onSetLimit }) { |
| 314 | const [editing, setEditing] = useState(false); |
| 315 | const [limitVal, setLimitVal] = useState(''); |
| 316 | |
| 317 | const limit = agent.spendingLimitMonthly; |
| 318 | const spent = data?.this_month ?? 0; |
| 319 | const pct = limit ? Math.min(spent / limit * 100, 100) : 0; |
| 320 | const over = limit && spent >= limit; |
| 321 | |
| 322 | function startEdit() { |
| 323 | setLimitVal(limit != null ? String(limit) : ''); |
| 324 | setEditing(true); |
| 325 | } |
| 326 | function saveEdit() { |
| 327 | onSetLimit(limitVal); |
| 328 | setEditing(false); |
| 329 | } |
| 330 | |
| 331 | return ( |
| 332 | <div className="mt-3 pt-3 border-t border-border-subtle"> |
| 333 | <div className="flex items-center justify-between mb-2"> |
| 334 | <div className="text-[10px] uppercase tracking-wider text-slate-500 flex items-center gap-1"> |
| 335 | <DollarSign size={10} /> Gasto |
| 336 | </div> |
| 337 | {!editing ? ( |
| 338 | <button onClick={startEdit} |
| 339 | className="text-[10px] text-slate-600 hover:text-violet-300 transition"> |
| 340 | {limit != null ? `límite $${limit}/mes` : 'sin límite · configurar'} |
| 341 | </button> |
| 342 | ) : ( |
| 343 | <div className="flex items-center gap-1"> |
| 344 | <span className="text-[10px] text-slate-500">$</span> |
| 345 | <input |
| 346 | type="number" min="0" step="1" placeholder="ej. 5" |
| 347 | value={limitVal} |
| 348 | onChange={e => setLimitVal(e.target.value)} |
| 349 | onKeyDown={e => { if (e.key === 'Enter') saveEdit(); if (e.key === 'Escape') setEditing(false); }} |
| 350 | className="w-16 bg-surface-2 border border-border-subtle rounded px-1.5 py-0.5 text-[11px] font-mono text-slate-200 outline-none" |
| 351 | autoFocus |
| 352 | /> |
| 353 | <span className="text-[10px] text-slate-500">/mes</span> |
| 354 | <button onClick={saveEdit} className="text-[10px] text-violet-300 hover:text-violet-200 ml-1">guardar</button> |
| 355 | <button onClick={() => setEditing(false)} className="text-[10px] text-slate-600 hover:text-slate-400 ml-0.5">✕</button> |
| 356 | </div> |
| 357 | )} |
| 358 | </div> |
| 359 | |
| 360 | <div className="flex items-center gap-3"> |
| 361 | {/* Stats */} |
| 362 | <div className="flex gap-3 text-[11px] flex-1"> |
| 363 | <div> |
| 364 | <div className="text-slate-500 text-[10px]">hoy</div> |
| 365 | <div className="font-mono text-slate-300">${(data?.today ?? 0).toFixed(3)}</div> |
| 366 | </div> |
| 367 | <div> |
| 368 | <div className="text-slate-500 text-[10px]">este mes</div> |
| 369 | <div className={`font-mono ${over ? 'text-rose-300' : 'text-slate-300'} flex items-center gap-1`}> |
| 370 | ${spent.toFixed(3)} |
| 371 | {over && <AlertTriangle size={10} className="text-rose-400" />} |
| 372 | </div> |
| 373 | </div> |
| 374 | <div> |
| 375 | <div className="text-slate-500 text-[10px]">total</div> |
| 376 | <div className="font-mono text-slate-400">${(data?.all_time ?? 0).toFixed(3)}</div> |
| 377 | </div> |
| 378 | {data?.runs_month != null && ( |
| 379 | <div> |
| 380 | <div className="text-slate-500 text-[10px]">runs/mes</div> |
| 381 | <div className="font-mono text-slate-400">{data.runs_month}</div> |
| 382 | </div> |
| 383 | )} |
| 384 | </div> |
| 385 | </div> |
| 386 | |
| 387 | {/* Progress bar — only when limit is set */} |
| 388 | {limit != null && ( |
| 389 | <div className="mt-2"> |
| 390 | <div className="h-1 bg-surface-2 rounded-full overflow-hidden"> |
| 391 | <div |
| 392 | className={`h-full rounded-full transition-all ${over ? 'bg-rose-500' : pct > 75 ? 'bg-amber-500' : 'bg-violet-500'}`} |
| 393 | style={{ width: `${pct}%` }} |
| 394 | /> |
| 395 | </div> |
| 396 | <div className="text-[10px] text-slate-600 mt-0.5 text-right"> |
| 397 | {over |
| 398 | ? <span className="text-rose-400">límite superado — nuevas ejecuciones bloqueadas</span> |
| 399 | : `${pct.toFixed(0)}% del límite mensual ($${limit})`} |
| 400 | </div> |
| 401 | </div> |
| 402 | )} |
| 403 | </div> |
| 404 | ); |
| 405 | } |