| 1 | import { useState, useRef, useEffect } from 'react'; |
| 2 | import { Send, Bot, User, CheckCircle2, AlertCircle, Loader2, Plus, MessageSquare, Trash2, ChevronLeft, ChevronRight } from 'lucide-react'; |
| 3 | import { api } from '../api.js'; |
| 4 | |
| 5 | const SEED = { |
| 6 | role: 'assistant', |
| 7 | content: '¡Hola! Soy ClonAgent Builder. Te ayudo a crear o editar agentes que procesan correo electrónico.\n\nCada agente nuevo lleva por defecto su propio buzón en `bot.utopiaia.com` con IMAP/SMTP listo. Solo dime:\n• Para qué proyecto es\n• Qué emails están autorizados a escribirle\n\nY te lo monto.', |
| 8 | }; |
| 9 | |
| 10 | export default function Chat() { |
| 11 | const [sessionId, setSessionId] = useState(null); |
| 12 | const [list, setList] = useState([]); |
| 13 | const [messages, setMessages] = useState([SEED]); |
| 14 | const [input, setInput] = useState(''); |
| 15 | const [busy, setBusy] = useState(false); |
| 16 | const [showSidebar, setShowSidebar] = useState(true); |
| 17 | const scrollRef = useRef(null); |
| 18 | |
| 19 | // ── Initial load: get sessions, restore most recent ────────────────── |
| 20 | useEffect(() => { |
| 21 | (async () => { |
| 22 | try { |
| 23 | const ss = await api('/api/chat/sessions'); |
| 24 | setList(ss); |
| 25 | if (ss.length > 0) await loadSession(ss[0].id); |
| 26 | } catch {} |
| 27 | })(); |
| 28 | }, []); |
| 29 | |
| 30 | useEffect(() => { scrollRef.current?.scrollTo({ top: 9e9, behavior: 'smooth' }); }, [messages]); |
| 31 | |
| 32 | async function loadSession(id) { |
| 33 | try { |
| 34 | const s = await api(`/api/chat/sessions/${id}`); |
| 35 | setSessionId(id); |
| 36 | setMessages(s.messages || [SEED]); |
| 37 | } catch {} |
| 38 | } |
| 39 | |
| 40 | function newSession() { |
| 41 | setSessionId(null); |
| 42 | setMessages([SEED]); |
| 43 | setInput(''); |
| 44 | } |
| 45 | |
| 46 | async function deleteSession(id, e) { |
| 47 | e.stopPropagation(); |
| 48 | if (!confirm('Borrar esta conversación?')) return; |
| 49 | await api(`/api/chat/sessions/${id}`, { method: 'DELETE' }); |
| 50 | const ss = await api('/api/chat/sessions'); |
| 51 | setList(ss); |
| 52 | if (sessionId === id) newSession(); |
| 53 | } |
| 54 | |
| 55 | async function reloadList() { |
| 56 | const ss = await api('/api/chat/sessions'); |
| 57 | setList(ss); |
| 58 | } |
| 59 | |
| 60 | async function send() { |
| 61 | const text = input.trim(); |
| 62 | if (!text || busy) return; |
| 63 | const next = [...messages, { role: 'user', content: text }]; |
| 64 | setMessages(next); setInput(''); setBusy(true); |
| 65 | try { |
| 66 | const apiMsgs = next.filter(m => m !== SEED).map(({ role, content }) => ({ role, content })); |
| 67 | const res = await api('/api/chat', { |
| 68 | method: 'POST', |
| 69 | body: JSON.stringify({ messages: apiMsgs, sessionId }), |
| 70 | }); |
| 71 | if (res.sessionId && res.sessionId !== sessionId) setSessionId(res.sessionId); |
| 72 | setMessages(m => [ |
| 73 | ...m, |
| 74 | { role: 'assistant', content: res.reply, actions: res.actions || [] }, |
| 75 | ]); |
| 76 | reloadList(); |
| 77 | } catch (e) { |
| 78 | setMessages(m => [...m, { role: 'assistant', content: `❌ ${e.message}`, error: true }]); |
| 79 | } finally { setBusy(false); } |
| 80 | } |
| 81 | |
| 82 | return ( |
| 83 | <div className="h-full flex"> |
| 84 | {/* Sessions sidebar */} |
| 85 | {showSidebar ? ( |
| 86 | <aside className="w-64 border-r border-border-subtle bg-surface-1 flex flex-col"> |
| 87 | <div className="px-3 py-3 border-b border-border-subtle flex items-center justify-between"> |
| 88 | <div className="text-sm font-semibold text-slate-200 flex items-center gap-1.5"> |
| 89 | <MessageSquare size={13} className="text-violet-300" /> Conversaciones |
| 90 | </div> |
| 91 | <button onClick={() => setShowSidebar(false)} className="text-slate-500 hover:text-slate-200" title="Ocultar"> |
| 92 | <ChevronLeft size={14} /> |
| 93 | </button> |
| 94 | </div> |
| 95 | <button onClick={newSession} className="mx-2 mt-2 btn-ghost text-sm justify-center border border-border-subtle"> |
| 96 | <Plus size={12} /> Nueva conversación |
| 97 | </button> |
| 98 | <div className="flex-1 overflow-y-auto p-2 space-y-1"> |
| 99 | {list.length === 0 && <div className="text-xs text-slate-600 p-3 text-center">No hay sesiones aún.</div>} |
| 100 | {list.map(s => ( |
| 101 | <div key={s.id} |
| 102 | onClick={() => loadSession(s.id)} |
| 103 | className={`group cursor-pointer px-2.5 py-2 rounded-lg text-xs transition ${ |
| 104 | sessionId === s.id ? 'bg-violet/15 text-violet-200' : 'hover:bg-surface-2 text-slate-400' |
| 105 | }`}> |
| 106 | <div className="flex items-start gap-1.5"> |
| 107 | <div className="flex-1 min-w-0"> |
| 108 | <div className="truncate font-medium">{s.title}</div> |
| 109 | <div className="text-[10px] text-slate-600 mt-0.5">{new Date(s.updatedAt).toLocaleString('es', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })} · {s.messageCount} msg</div> |
| 110 | </div> |
| 111 | <button onClick={(e) => deleteSession(s.id, e)} |
| 112 | className="opacity-0 group-hover:opacity-100 text-rose-300 hover:text-rose-200 transition"> |
| 113 | <Trash2 size={11} /> |
| 114 | </button> |
| 115 | </div> |
| 116 | </div> |
| 117 | ))} |
| 118 | </div> |
| 119 | </aside> |
| 120 | ) : ( |
| 121 | <button onClick={() => setShowSidebar(true)} className="px-1.5 py-1.5 text-slate-500 hover:bg-surface-2 self-start mt-3" title="Mostrar conversaciones"> |
| 122 | <ChevronRight size={16} /> |
| 123 | </button> |
| 124 | )} |
| 125 | |
| 126 | {/* Main chat */} |
| 127 | <div className="flex-1 flex flex-col min-w-0"> |
| 128 | <div className="px-6 py-4 border-b border-border-subtle flex items-center justify-between"> |
| 129 | <div> |
| 130 | <h1 className="text-lg font-semibold text-slate-100">Chat — Crear / Editar agentes</h1> |
| 131 | <p className="text-xs text-slate-500 mt-0.5">Conversa para construir un email-triage agent o modificar uno existente.</p> |
| 132 | </div> |
| 133 | <button onClick={newSession} className="btn-ghost text-xs" title="Nueva conversación"> |
| 134 | <Plus size={11} /> Nueva |
| 135 | </button> |
| 136 | </div> |
| 137 | |
| 138 | <div ref={scrollRef} className="flex-1 overflow-y-auto px-6 py-6 space-y-4"> |
| 139 | {messages.map((m, i) => ( |
| 140 | <div key={i} className="flex gap-3"> |
| 141 | <div className={`flex-shrink-0 mt-0.5 w-7 h-7 rounded-lg flex items-center justify-center ${ |
| 142 | m.role === 'assistant' ? 'bg-violet/15 border border-violet/30' : 'bg-emerald-900/30 border border-emerald-700/30' |
| 143 | }`}> |
| 144 | {m.role === 'assistant' ? <Bot size={14} className="text-violet-300" /> : <User size={14} className="text-emerald-300" />} |
| 145 | </div> |
| 146 | <div className="flex-1 min-w-0"> |
| 147 | <div className={`text-sm leading-relaxed whitespace-pre-wrap ${m.error ? 'text-rose-300' : 'text-slate-200'}`}> |
| 148 | {m.content} |
| 149 | </div> |
| 150 | {(m.actions || []).map((a, j) => ( |
| 151 | <div key={j} className={`mt-2 inline-flex items-center gap-1.5 text-xs px-2 py-1 rounded-md border ${ |
| 152 | a.ok ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-300' |
| 153 | : 'bg-rose-500/10 border-rose-500/30 text-rose-300' |
| 154 | }`}> |
| 155 | {a.ok ? <CheckCircle2 size={12} /> : <AlertCircle size={12} />} |
| 156 | <span className="font-mono">{a.tool}</span> |
| 157 | {a.ok && a.agent && <span>· {a.agent.id}</span>} |
| 158 | {a.ok && a.mailbox && <span>· {a.mailbox.email}</span>} |
| 159 | {!a.ok && <span>· {a.error}</span>} |
| 160 | </div> |
| 161 | ))} |
| 162 | </div> |
| 163 | </div> |
| 164 | ))} |
| 165 | {busy && ( |
| 166 | <div className="flex gap-3"> |
| 167 | <div className="w-7 h-7 rounded-lg bg-violet/15 border border-violet/30 flex items-center justify-center"> |
| 168 | <Loader2 size={14} className="text-violet-300 animate-spin" /> |
| 169 | </div> |
| 170 | <div className="text-sm text-slate-500 mt-1">pensando…</div> |
| 171 | </div> |
| 172 | )} |
| 173 | </div> |
| 174 | |
| 175 | <div className="border-t border-border-subtle p-4"> |
| 176 | <div className="flex gap-2 max-w-4xl"> |
| 177 | <textarea |
| 178 | className="input min-h-[44px] max-h-40 resize-none" |
| 179 | placeholder="Cuenta qué agente quieres crear, o pídele un cambio…" |
| 180 | value={input} |
| 181 | onChange={e => setInput(e.target.value)} |
| 182 | onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }} |
| 183 | rows={1} |
| 184 | /> |
| 185 | <button className="btn-primary self-end" onClick={send} disabled={busy || !input.trim()}> |
| 186 | <Send size={14} /> Enviar |
| 187 | </button> |
| 188 | </div> |
| 189 | </div> |
| 190 | </div> |
| 191 | </div> |
| 192 | ); |
| 193 | } |