| 1 | import { useEffect, useState } from 'react'; |
| 2 | import { Settings2, Save, Server, Cpu, Globe, Activity, Lock, Users, Plus, Trash2, GitBranch, Database, UserPlus, ShieldCheck, Mail as MailIcon, AlertCircle, Copy } from 'lucide-react'; |
| 3 | import { api } from '../api.js'; |
| 4 | |
| 5 | export default function Settings() { |
| 6 | const [cfg, setCfg] = useState(null); |
| 7 | const [draft, setDraft] = useState({}); |
| 8 | const [saving, setSaving] = useState(false); |
| 9 | const [msg, setMsg] = useState(''); |
| 10 | const [users, setUsers] = useState([]); |
| 11 | const [newUser, setNewUser] = useState({ username: '', password: '', name: '', email: '' }); |
| 12 | const [mailStatus, setMailStatus] = useState(null); |
| 13 | const [mailboxes, setMailboxes] = useState([]); |
| 14 | const [newLocal, setNewLocal] = useState(''); |
| 15 | const [createdMb, setCreatedMb] = useState(null); |
| 16 | |
| 17 | async function reload() { |
| 18 | const c = await api('/api/settings'); |
| 19 | setCfg(c); setDraft(c); |
| 20 | try { setUsers(await api('/api/auth/users')); } catch {} |
| 21 | try { |
| 22 | const ms = await api('/api/mail/status'); |
| 23 | setMailStatus(ms); |
| 24 | if (ms.available) setMailboxes(await api('/api/mail/mailboxes')); |
| 25 | } catch {} |
| 26 | } |
| 27 | async function addMailbox() { |
| 28 | if (!newLocal.trim()) return; |
| 29 | try { |
| 30 | const r = await api('/api/mail/mailboxes', { |
| 31 | method: 'POST', body: JSON.stringify({ localPart: newLocal.trim() }), |
| 32 | }); |
| 33 | setCreatedMb(r); setNewLocal(''); reload(); |
| 34 | } catch (e) { alert(e.message); } |
| 35 | } |
| 36 | async function delMailbox(email) { |
| 37 | if (!confirm(`Eliminar el mailbox ${email}?`)) return; |
| 38 | await api(`/api/mail/mailboxes/${encodeURIComponent(email)}`, { method: 'DELETE' }); |
| 39 | reload(); |
| 40 | } |
| 41 | useEffect(() => { reload().catch(() => {}); }, []); |
| 42 | |
| 43 | function field(k, v) { setDraft(d => ({ ...d, [k]: v })); } |
| 44 | function authField(k, v) { setDraft(d => ({ ...d, auth: { ...d.auth, [k]: v } })); } |
| 45 | function oidcField(k, v) { setDraft(d => ({ ...d, auth: { ...d.auth, oidc: { ...(d.auth?.oidc || {}), [k]: v } } })); } |
| 46 | function intField(k, v) { setDraft(d => ({ ...d, integrations: { ...(d.integrations || {}), [k]: v } })); } |
| 47 | |
| 48 | async function save() { |
| 49 | setSaving(true); setMsg(''); |
| 50 | try { |
| 51 | const next = await api('/api/settings', { method: 'PATCH', body: JSON.stringify(draft) }); |
| 52 | setCfg(next); setDraft(next); |
| 53 | setMsg('Guardado.'); |
| 54 | } catch (e) { setMsg(e.message); } |
| 55 | finally { setSaving(false); } |
| 56 | } |
| 57 | |
| 58 | async function addUser() { |
| 59 | if (!newUser.username || !newUser.password) return; |
| 60 | try { |
| 61 | await api('/api/auth/users', { method: 'POST', body: JSON.stringify(newUser) }); |
| 62 | setNewUser({ username: '', password: '', name: '', email: '' }); |
| 63 | reload(); |
| 64 | } catch (e) { alert(e.message); } |
| 65 | } |
| 66 | async function delUser(username) { |
| 67 | if (!confirm(`Eliminar usuario "${username}"?`)) return; |
| 68 | await api(`/api/auth/users/${encodeURIComponent(username)}`, { method: 'DELETE' }); |
| 69 | reload(); |
| 70 | } |
| 71 | async function toggleAdmin(username, cur) { |
| 72 | await api(`/api/auth/users/${encodeURIComponent(username)}/admin`, { |
| 73 | method: 'PATCH', body: JSON.stringify({ isAdmin: !cur }), |
| 74 | }); |
| 75 | reload(); |
| 76 | } |
| 77 | |
| 78 | if (!cfg) return <div className="p-6 text-slate-500 text-sm">Cargando…</div>; |
| 79 | |
| 80 | const mode = draft.auth?.mode || 'none'; |
| 81 | |
| 82 | return ( |
| 83 | <div className="h-full overflow-y-auto p-6 max-w-3xl"> |
| 84 | <h1 className="text-lg font-semibold text-slate-100 mb-1 flex items-center gap-2"> |
| 85 | <Settings2 size={16} className="text-violet-300" /> Settings |
| 86 | </h1> |
| 87 | <p className="text-xs text-slate-500 mb-6">Configuración del runtime de ClonAgent.</p> |
| 88 | |
| 89 | <div className="space-y-4"> |
| 90 | {/* ── Auth ─────────────────────────────────────────────────────── */} |
| 91 | <Section icon={Lock} title="Autenticación" desc="Modo de login. Cambia y guarda; los usuarios actuales se desconectarán."> |
| 92 | <div className="grid grid-cols-3 gap-2"> |
| 93 | {['none','basic','oidc'].map(m => ( |
| 94 | <button key={m} |
| 95 | onClick={() => authField('mode', m)} |
| 96 | className={`px-3 py-2 rounded-lg border text-sm capitalize transition ${ |
| 97 | mode === m ? 'bg-violet/15 border-violet/40 text-violet-200' : 'border-border-subtle text-slate-400 hover:bg-surface-2' |
| 98 | }`}> |
| 99 | {m === 'none' ? 'Abierto' : m === 'basic' ? 'Básica' : 'SSO (OIDC)'} |
| 100 | </button> |
| 101 | ))} |
| 102 | </div> |
| 103 | |
| 104 | {mode === 'basic' && ( |
| 105 | <div className="space-y-3 pt-3 border-t border-border-subtle"> |
| 106 | <label className="flex items-center gap-2 cursor-pointer"> |
| 107 | <input type="checkbox" checked={!!draft.auth?.allowRegistration} |
| 108 | onChange={e => authField('allowRegistration', e.target.checked)} /> |
| 109 | <UserPlus size={12} className="text-violet-300" /> |
| 110 | <span className="text-sm text-slate-200">Permitir registro abierto</span> |
| 111 | <span className="text-[10px] text-slate-600">(cualquiera puede crear cuenta)</span> |
| 112 | </label> |
| 113 | |
| 114 | <div className="text-[11px] uppercase tracking-wider text-slate-500 flex items-center gap-1 mt-3"> |
| 115 | <Users size={11} /> Usuarios ({users.length}) |
| 116 | </div> |
| 117 | {users.length === 0 && ( |
| 118 | <div className="text-xs text-slate-600">Sin usuarios — añade el primero abajo o habilita registro abierto.</div> |
| 119 | )} |
| 120 | {users.map(u => ( |
| 121 | <div key={u.username} className="flex items-center justify-between bg-surface-2/50 rounded-lg px-3 py-2 text-sm"> |
| 122 | <div className="min-w-0 flex-1"> |
| 123 | <div className="flex items-center gap-2"> |
| 124 | <span className="font-mono text-slate-200">{u.username}</span> |
| 125 | {u.isAdmin && <span className="pill bg-amber-500/10 text-amber-300 border border-amber-500/30 text-[10px]">admin</span>} |
| 126 | </div> |
| 127 | <div className="text-[10px] text-slate-600"> |
| 128 | {u.email || '—'} · creado {new Date(u.createdAt).toLocaleDateString('es')} |
| 129 | {u.lastLoginAt && <> · last {new Date(u.lastLoginAt).toLocaleDateString('es')}</>} |
| 130 | </div> |
| 131 | </div> |
| 132 | <button onClick={() => toggleAdmin(u.username, u.isAdmin)} className="btn-ghost text-xs" |
| 133 | title={u.isAdmin ? 'Quitar admin' : 'Hacer admin'}> |
| 134 | <ShieldCheck size={11} /> |
| 135 | </button> |
| 136 | <button onClick={() => delUser(u.username)} className="btn-ghost text-rose-300"> |
| 137 | <Trash2 size={12} /> |
| 138 | </button> |
| 139 | </div> |
| 140 | ))} |
| 141 | <div className="grid grid-cols-2 gap-2 mt-3"> |
| 142 | <input className="input text-sm" placeholder="usuario" value={newUser.username} onChange={e => setNewUser(u => ({ ...u, username: e.target.value }))} /> |
| 143 | <input className="input text-sm" placeholder="contraseña" type="password" value={newUser.password} onChange={e => setNewUser(u => ({ ...u, password: e.target.value }))} /> |
| 144 | <input className="input text-sm" placeholder="nombre" value={newUser.name} onChange={e => setNewUser(u => ({ ...u, name: e.target.value }))} /> |
| 145 | <input className="input text-sm" placeholder="email" value={newUser.email} onChange={e => setNewUser(u => ({ ...u, email: e.target.value }))} /> |
| 146 | </div> |
| 147 | <button className="btn-ghost text-xs" onClick={addUser}> |
| 148 | <Plus size={11} /> Añadir usuario manualmente |
| 149 | </button> |
| 150 | </div> |
| 151 | )} |
| 152 | |
| 153 | {mode === 'oidc' && ( |
| 154 | <div className="space-y-2 pt-2"> |
| 155 | <Field label="Issuer URL" value={draft.auth?.oidc?.issuerUrl} onChange={v => oidcField('issuerUrl', v)} placeholder="https://keycloak.utopiaia.com/realms/kikocisbot" mono /> |
| 156 | <Field label="Client ID" value={draft.auth?.oidc?.clientId} onChange={v => oidcField('clientId', v)} mono /> |
| 157 | <Field label="Client Secret" value={draft.auth?.oidc?.clientSecret} onChange={v => oidcField('clientSecret', v)} mono secret /> |
| 158 | <Field label="Redirect URI" value={draft.auth?.oidc?.redirectUri} onChange={v => oidcField('redirectUri', v)} mono /> |
| 159 | <p className="text-[11px] text-slate-500"> |
| 160 | Crea un cliente en Keycloak con esta Redirect URI y pega aquí el secret. |
| 161 | </p> |
| 162 | </div> |
| 163 | )} |
| 164 | </Section> |
| 165 | |
| 166 | <Section icon={Server} title="Host Relay" desc="El relay lanza sesiones de Claude CLI con la auth de subscripción."> |
| 167 | <Field label="Relay URL" value={draft.relayUrl} onChange={v => field('relayUrl', v)} placeholder="http://localhost:3201" mono /> |
| 168 | <Field label="Internal API key" value={draft.relayKey} onChange={v => field('relayKey', v)} placeholder="relay-internal-2026" mono secret /> |
| 169 | </Section> |
| 170 | |
| 171 | <Section icon={Cpu} title="Model" desc="Modelo usado por el chat de configuración."> |
| 172 | <Field label="Model name" value={draft.model} onChange={v => field('model', v)} placeholder="claude-opus-4-7" mono /> |
| 173 | </Section> |
| 174 | |
| 175 | <Section icon={Globe} title="URL pública" desc="URL base para las URLs de tracking en los emails de los agentes."> |
| 176 | <Field label="Public URL" value={draft.publicUrl} onChange={v => field('publicUrl', v)} placeholder="https://clonagent.utopiaia.com" mono /> |
| 177 | </Section> |
| 178 | |
| 179 | <Section icon={Activity} title="Polling" desc="Frecuencia con la que se revisa el inbox de cada agente."> |
| 180 | <Field label="Cron pattern" value={draft.cron} onChange={v => field('cron', v)} placeholder="* * * * *" mono /> |
| 181 | <p className="text-[11px] text-slate-600 mt-1">Default <code>* * * * *</code> = cada minuto.</p> |
| 182 | </Section> |
| 183 | |
| 184 | <Section icon={GitBranch} title="Gitea (built-in)" desc="Se usa para crear repos automáticamente cuando el chat detecta proyecto nuevo."> |
| 185 | <Field label="URL" value={draft.integrations?.giteaUrl} onChange={v => intField('giteaUrl', v)} placeholder="http://localhost:3200" mono /> |
| 186 | <Field label="Admin user" value={draft.integrations?.giteaUser} onChange={v => intField('giteaUser', v)} placeholder="kikocis" mono /> |
| 187 | <Field label="Token" value={draft.integrations?.giteaToken} onChange={v => intField('giteaToken', v)} placeholder="…" mono secret /> |
| 188 | </Section> |
| 189 | |
| 190 | <Section icon={Database} title="PostgreSQL (built-in)" desc="Para provisionar bases de datos a proyectos nuevos."> |
| 191 | <Field label="Container" value={draft.integrations?.pgContainer} onChange={v => intField('pgContainer', v)} placeholder="postgres-keycloak" mono /> |
| 192 | <Field label="Super user" value={draft.integrations?.pgSuperUser} onChange={v => intField('pgSuperUser', v)} placeholder="keycloak" mono /> |
| 193 | <Field label="Super DB" value={draft.integrations?.pgSuperDb} onChange={v => intField('pgSuperDb', v)} placeholder="keycloak" mono /> |
| 194 | </Section> |
| 195 | |
| 196 | <Section icon={MailIcon} title={`Mail server (${mailStatus?.domain || 'bot.utopiaia.com'})`} desc="Mailboxes propios para que cada agente tenga su buzón. Cuando creas un agente IMAP el mailbox se aprovisiona automáticamente."> |
| 197 | {!mailStatus?.available ? ( |
| 198 | <div className="card border-amber-500/30 bg-amber-500/5 space-y-2"> |
| 199 | <div className="flex items-start gap-2 text-sm"> |
| 200 | <AlertCircle size={14} className="text-amber-400 flex-shrink-0 mt-0.5" /> |
| 201 | <div className="text-xs text-slate-400"> |
| 202 | Mail server no disponible. Corre el setup en el host (una vez): |
| 203 | <code className="block bg-surface-2 rounded p-2 font-mono text-[11px] mt-1.5 text-slate-300"> |
| 204 | ssh ubuntu@145.239.65.26 'cd /home/ubuntu/clonagent && ./scripts/setup-mailserver.sh' |
| 205 | </code> |
| 206 | </div> |
| 207 | </div> |
| 208 | </div> |
| 209 | ) : ( |
| 210 | <> |
| 211 | {createdMb && ( |
| 212 | <div className="rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-3 space-y-2"> |
| 213 | <div className="text-sm font-medium text-emerald-200">Mailbox creado — guarda la password ahora, no se mostrará otra vez</div> |
| 214 | <div className="grid grid-cols-2 gap-2 text-xs font-mono"> |
| 215 | <div className="bg-surface-2 rounded p-2 flex items-center justify-between gap-2"> |
| 216 | <span className="text-slate-500 mr-2">email:</span> |
| 217 | <span className="text-slate-100 truncate flex-1">{createdMb.email}</span> |
| 218 | <button onClick={() => navigator.clipboard.writeText(createdMb.email)} className="text-slate-400 hover:text-slate-200"><Copy size={11} /></button> |
| 219 | </div> |
| 220 | <div className="bg-surface-2 rounded p-2 flex items-center justify-between gap-2"> |
| 221 | <span className="text-slate-500 mr-2">pass:</span> |
| 222 | <span className="text-slate-100 truncate flex-1">{createdMb.password}</span> |
| 223 | <button onClick={() => navigator.clipboard.writeText(createdMb.password)} className="text-slate-400 hover:text-slate-200"><Copy size={11} /></button> |
| 224 | </div> |
| 225 | </div> |
| 226 | <button className="btn-ghost text-xs" onClick={() => setCreatedMb(null)}>Cerrar</button> |
| 227 | </div> |
| 228 | )} |
| 229 | <div className="flex gap-2"> |
| 230 | <input className="input flex-1 font-mono text-sm" placeholder="local-part (mia, soporte, …)" |
| 231 | value={newLocal} onChange={e => setNewLocal(e.target.value)} /> |
| 232 | <span className="self-center text-sm text-slate-500 font-mono">@{mailStatus.domain}</span> |
| 233 | <button type="button" className="btn-primary text-sm" onClick={addMailbox} disabled={!newLocal.trim()}> |
| 234 | <Plus size={13} /> Crear |
| 235 | </button> |
| 236 | </div> |
| 237 | {mailboxes.length === 0 ? ( |
| 238 | <div className="text-xs text-slate-600">Sin mailboxes (los agentes IMAP los crean automáticamente).</div> |
| 239 | ) : ( |
| 240 | <div className="space-y-1.5"> |
| 241 | {mailboxes.map(b => ( |
| 242 | <div key={b.email} className="flex items-center justify-between bg-surface-2/50 rounded-lg px-3 py-2 text-sm"> |
| 243 | <div className="flex items-center gap-2"> |
| 244 | <MailIcon size={11} className="text-violet-300" /> |
| 245 | <span className="font-mono text-slate-200">{b.email}</span> |
| 246 | </div> |
| 247 | <button onClick={() => delMailbox(b.email)} className="text-rose-300 hover:text-rose-200"> |
| 248 | <Trash2 size={11} /> |
| 249 | </button> |
| 250 | </div> |
| 251 | ))} |
| 252 | </div> |
| 253 | )} |
| 254 | </> |
| 255 | )} |
| 256 | </Section> |
| 257 | </div> |
| 258 | |
| 259 | <div className="flex items-center gap-3 mt-6"> |
| 260 | <button className="btn-primary" onClick={save} disabled={saving}> |
| 261 | <Save size={13} /> {saving ? 'Guardando…' : 'Guardar'} |
| 262 | </button> |
| 263 | {msg && <span className="text-xs text-slate-400">{msg}</span>} |
| 264 | </div> |
| 265 | </div> |
| 266 | ); |
| 267 | } |
| 268 | |
| 269 | function Section({ icon: Icon, title, desc, children }) { |
| 270 | return ( |
| 271 | <div className="card space-y-3"> |
| 272 | <div className="flex items-start gap-2"> |
| 273 | <div className="w-7 h-7 rounded-lg bg-violet/15 border border-violet/30 flex items-center justify-center"> |
| 274 | <Icon size={13} className="text-violet-300" /> |
| 275 | </div> |
| 276 | <div> |
| 277 | <div className="text-sm font-semibold text-slate-200">{title}</div> |
| 278 | <div className="text-[11px] text-slate-500">{desc}</div> |
| 279 | </div> |
| 280 | </div> |
| 281 | <div className="space-y-2">{children}</div> |
| 282 | </div> |
| 283 | ); |
| 284 | } |
| 285 | |
| 286 | function Field({ label, value, onChange, placeholder, mono, secret }) { |
| 287 | const [show, setShow] = useState(!secret); |
| 288 | return ( |
| 289 | <div> |
| 290 | <label className="text-[11px] uppercase tracking-wider text-slate-500">{label}</label> |
| 291 | <div className="flex gap-2 mt-1"> |
| 292 | <input |
| 293 | type={show ? 'text' : 'password'} |
| 294 | value={value || ''} |
| 295 | onChange={e => onChange(e.target.value)} |
| 296 | placeholder={placeholder} |
| 297 | className={`input ${mono ? 'font-mono' : ''}`} |
| 298 | /> |
| 299 | {secret && <button className="btn-ghost text-xs" onClick={() => setShow(s => !s)}>{show ? 'Hide' : 'Show'}</button>} |
| 300 | </div> |
| 301 | </div> |
| 302 | ); |
| 303 | } |