| 1 | // Conversaciones: varias a la vez, como pestañas — cada una con su propio |
| 2 | // historial (su propio Agent) y su propia cola de mensajes pendientes. |
| 3 | // Cerrar una pestaña NO borra la conversación (solo la Historial sí). Todo |
| 4 | // persiste en IndexedDB, sobrevive a recargar. |
| 5 | // |
| 6 | // Procesado: cada conversación acepta y encola mensajes de forma totalmente |
| 7 | // independiente (mandar en la pestaña B mientras la A está pensando no |
| 8 | // bloquea nada). La generación en sí (la llamada real al modelo) se |
| 9 | // serializa con un cerrojo global — solo hay UN modelo cargado en el |
| 10 | // navegador y una sesión de inferencia no admite dos generate() a la vez sin |
| 11 | // corromperse — así que las conversaciones se turnan para «hablar» con el |
| 12 | // modelo, pero cada una sigue funcionando y aceptando mensajes de forma |
| 13 | // independiente mientras espera su turno. |
| 14 | import { Agent } from './agent.js'; |
| 15 | import { runGoal, TASK_PREFIX } from './goal.js'; |
| 16 | import * as db from './db.js'; |
| 17 | import * as telemetry from './telemetry.js'; |
| 18 | |
| 19 | const NS = 'elffusscode'; |
| 20 | const TABS_KEY = NS + '.openTabs'; |
| 21 | const ACTIVE_KEY = NS + '.activeConv'; |
| 22 | const HIST_CAP = 80; // mensajes por conversación que se persisten |
| 23 | |
| 24 | let providerRef = null; |
| 25 | const convs = new Map(); // id -> { id, title, agent, queue, pumping, createdAt, updatedAt } |
| 26 | let openTabIds = []; |
| 27 | let activeId = null; |
| 28 | let onChange = () => {}; |
| 29 | |
| 30 | const genId = () => 'c' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7); |
| 31 | const cleanTitle = s => String(s).replace(/\s+/g, ' ').trim(); |
| 32 | |
| 33 | const GOAL_PREFIX = TASK_PREFIX + 'Objetivo: '; |
| 34 | export function titleFor(conv) { |
| 35 | if (conv.title) return conv.title; |
| 36 | const firstUser = conv.agent.history.find(m => |
| 37 | m.role === 'user' && !m.content.startsWith('[resultado') && |
| 38 | (!m.content.startsWith(TASK_PREFIX) || m.content.startsWith(GOAL_PREFIX))); |
| 39 | if (!firstUser) return 'Nueva conversación'; |
| 40 | // el objetivo lleva un prefijo interno ([tarea-objetivo] Objetivo: …) que |
| 41 | // no debe filtrarse al título de la pestaña — se muestra el texto limpio. |
| 42 | const raw = firstUser.content.startsWith(GOAL_PREFIX) ? firstUser.content.slice(GOAL_PREFIX.length) : firstUser.content; |
| 43 | const t = cleanTitle(raw); |
| 44 | return t.length > 40 ? t.slice(0, 40) + '…' : t || 'Nueva conversación'; |
| 45 | } |
| 46 | |
| 47 | export function setProvider(mod) { |
| 48 | providerRef = mod; |
| 49 | for (const c of convs.values()) c.agent.setProvider(mod); |
| 50 | } |
| 51 | export function getProvider() { return providerRef; } |
| 52 | |
| 53 | export function isBusy() { |
| 54 | for (const c of convs.values()) if (c.pumping || c.queue.length) return true; |
| 55 | return false; |
| 56 | } |
| 57 | |
| 58 | export function getActive() { return activeId ? convs.get(activeId) : null; } |
| 59 | |
| 60 | // Parar la conversación activa mientras trabaja: aborta la generación/bucle del |
| 61 | // agente (agent.stop() propaga la señal a los proveedores) y vacía la cola para |
| 62 | // que no arranque el siguiente turno. runGoal comprueba conv.stopped para no |
| 63 | // seguir con las tareas pendientes del plan. |
| 64 | export function stopActive() { |
| 65 | const c = getActive(); |
| 66 | if (!c) return false; |
| 67 | c.stopped = true; |
| 68 | try { c.agent.stop(); } catch { /* */ } |
| 69 | c.queue.length = 0; |
| 70 | return true; |
| 71 | } |
| 72 | |
| 73 | export function getOpenTabs() { return openTabIds.map(id => convs.get(id)).filter(Boolean); } |
| 74 | |
| 75 | async function persistConv(conv) { |
| 76 | // NO tragarse el error de lectura: un fallo transitorio devolvía [] y el |
| 77 | // db.set de abajo reescribía el store entero con UNA sola conversación, |
| 78 | // borrando el resto. Distinguir «no existe aún» (undefined → []) de «no se |
| 79 | // pudo leer» (excepción → no escribir nada este turno). |
| 80 | let stored; |
| 81 | try { stored = await db.get('kv', 'conversations'); } |
| 82 | catch (e) { console.warn('[elffuss] no se pudo leer conversations; no sobrescribo', e); return; } |
| 83 | const all = stored == null ? [] : stored; |
| 84 | if (!Array.isArray(all)) { console.warn('[elffuss] conversations corrupto; no sobrescribo'); return; } |
| 85 | const i = all.findIndex(c => c.id === conv.id); |
| 86 | const rec = { |
| 87 | id: conv.id, title: titleFor(conv), history: conv.agent.history.slice(-HIST_CAP), |
| 88 | queue: conv.queue, plan: conv.plan || null, createdAt: conv.createdAt, updatedAt: conv.updatedAt, |
| 89 | }; |
| 90 | if (i >= 0) all[i] = rec; else all.push(rec); |
| 91 | await db.set('kv', 'conversations', all).catch(() => {}); |
| 92 | } |
| 93 | function persistMeta() { |
| 94 | try { localStorage.setItem(TABS_KEY, JSON.stringify(openTabIds)); } catch { /* lleno */ } |
| 95 | try { localStorage.setItem(ACTIVE_KEY, activeId || ''); } catch { /* lleno */ } |
| 96 | } |
| 97 | |
| 98 | function makeConv(id, saved) { |
| 99 | const conv = { |
| 100 | id, title: saved?.title || null, agent: new Agent(providerRef), |
| 101 | queue: saved?.queue ? [...saved.queue] : [], pumping: false, plan: saved?.plan || null, |
| 102 | createdAt: saved?.createdAt || Date.now(), updatedAt: saved?.updatedAt || Date.now(), |
| 103 | }; |
| 104 | if (saved?.history) conv.agent.history = saved.history; |
| 105 | convs.set(id, conv); |
| 106 | return conv; |
| 107 | } |
| 108 | |
| 109 | export function create() { |
| 110 | const conv = makeConv(genId()); |
| 111 | openTabIds.push(conv.id); |
| 112 | activeId = conv.id; |
| 113 | persistMeta(); |
| 114 | onChange('switch', conv.id); |
| 115 | return conv; |
| 116 | } |
| 117 | |
| 118 | // reabre una conversación guardada (de la Historial) como pestaña, o activa |
| 119 | // la pestaña si ya estaba abierta |
| 120 | export async function open(id) { |
| 121 | if (!convs.has(id)) { |
| 122 | const saved = (await db.get('kv', 'conversations').catch(() => null) || []).find(c => c.id === id); |
| 123 | if (!saved) return null; |
| 124 | makeConv(id, saved); |
| 125 | } |
| 126 | if (!openTabIds.includes(id)) openTabIds.push(id); |
| 127 | activeId = id; |
| 128 | persistMeta(); |
| 129 | onChange('switch', id); |
| 130 | return convs.get(id); |
| 131 | } |
| 132 | |
| 133 | export function switchTo(id) { |
| 134 | if (!convs.has(id) || activeId === id) return; |
| 135 | activeId = id; |
| 136 | persistMeta(); |
| 137 | onChange('switch', id); |
| 138 | } |
| 139 | |
| 140 | // añade un mensaje fuera del ciclo normal de envío (p.ej. el informe |
| 141 | // autónomo del cerebro CEO) al historial REAL de una conversación — si no, |
| 142 | // solo viviría en el DOM y desaparecería al cambiar de pestaña o recargar. |
| 143 | export async function appendMessage(id, role, content) { |
| 144 | const c = convs.get(id); |
| 145 | if (!c) return; |
| 146 | c.agent.history.push({ role, content, ts: Date.now() }); |
| 147 | c.updatedAt = Date.now(); |
| 148 | await persistConv(c); |
| 149 | } |
| 150 | |
| 151 | // quita la pestaña de la vista — la conversación sigue viva en la Historial |
| 152 | export function closeTab(id) { |
| 153 | openTabIds = openTabIds.filter(x => x !== id); |
| 154 | if (activeId === id) activeId = openTabIds[openTabIds.length - 1] || null; |
| 155 | persistMeta(); |
| 156 | if (!openTabIds.length) create(); else onChange('tabs'); |
| 157 | } |
| 158 | |
| 159 | // borra la conversación de verdad (desde la Historial) |
| 160 | export async function remove(id) { |
| 161 | convs.delete(id); |
| 162 | openTabIds = openTabIds.filter(x => x !== id); |
| 163 | if (activeId === id) activeId = openTabIds[openTabIds.length - 1] || null; |
| 164 | const all = (await db.get('kv', 'conversations').catch(() => null) || []).filter(c => c.id !== id); |
| 165 | await db.set('kv', 'conversations', all).catch(() => {}); |
| 166 | persistMeta(); |
| 167 | if (!openTabIds.length) create(); else onChange('tabs'); |
| 168 | } |
| 169 | |
| 170 | export async function listAll() { |
| 171 | const all = await db.get('kv', 'conversations').catch(() => null) || []; |
| 172 | return all.slice().sort((a, b) => b.updatedAt - a.updatedAt); |
| 173 | } |
| 174 | |
| 175 | // ---- envío / procesado ---- |
| 176 | // items de la cola: {kind:'chat'|'goal', text} — 'chat' es un turno normal |
| 177 | // (agent.handle), 'goal' dispara el planificador/ejecutor de goal.js. Las |
| 178 | // colas persistidas ANTES de que existiera el modo Objetivo guardaban texto |
| 179 | // suelto (strings) — normalizeItem() los sigue aceptando como 'chat'. |
| 180 | let inferenceLock = Promise.resolve(); |
| 181 | const normalizeItem = it => (typeof it === 'string' ? { kind: 'chat', text: it } : it); |
| 182 | |
| 183 | export function send(id, text) { |
| 184 | const conv = convs.get(id); |
| 185 | if (!conv) return; |
| 186 | conv.queue.push({ kind: 'chat', text }); |
| 187 | persistConv(conv); |
| 188 | pump(conv); |
| 189 | } |
| 190 | |
| 191 | // 🎯 Modo Objetivo: en vez de un turno de chat normal, el mensaje se trata |
| 192 | // como un objetivo — se planifica en tareas y se ejecutan una a una (ver |
| 193 | // goal.js, mismo patrón planificador/ejecutor de clonagent). |
| 194 | export function startGoal(id, text) { |
| 195 | const conv = convs.get(id); |
| 196 | if (!conv) return; |
| 197 | conv.queue.push({ kind: 'goal', text }); |
| 198 | persistConv(conv); |
| 199 | pump(conv); |
| 200 | } |
| 201 | |
| 202 | async function pump(conv) { |
| 203 | if (conv.pumping) return; |
| 204 | conv.pumping = true; |
| 205 | conv.stopped = false; |
| 206 | onChange('pumping', conv.id, true); |
| 207 | while (conv.queue.length) { |
| 208 | const item = normalizeItem(conv.queue[0]); |
| 209 | const myTurn = inferenceLock; |
| 210 | let release; |
| 211 | inferenceLock = new Promise(r => { release = r; }); |
| 212 | await myTurn; // espera su turno de inferencia (un solo modelo cargado, no admite 2 generate() a la vez) |
| 213 | try { |
| 214 | // un fallo aquí (del modelo, de una tool, o del propio repintado en |
| 215 | // main.js) NUNCA debe dejar la conversación "pumping" para siempre — |
| 216 | // eso bloquearía sus futuros mensajes Y al cerebro CEO (isBusy()). |
| 217 | const onEvent = ev => { |
| 218 | try { onChange('event', conv.id, ev); } catch (e) { console.error('[elffuss] fallo pintando un evento de chat', e); } |
| 219 | }; |
| 220 | if (item.kind === 'goal') await runGoal(conv, item.text, onEvent); |
| 221 | else await conv.agent.handle(item.text, onEvent); |
| 222 | } catch (e) { |
| 223 | console.error('[elffuss] fallo procesando el turno', e); |
| 224 | telemetry.reportError('pump: ' + (e?.message || e), { stack: e?.stack || '' }); |
| 225 | try { onChange('event', conv.id, { type: 'error', text: 'Error interno: ' + (e?.message || e) }); } catch { /* ya está registrado arriba */ } |
| 226 | } finally { release(); } |
| 227 | conv.queue.shift(); |
| 228 | conv.updatedAt = Date.now(); |
| 229 | await persistConv(conv); |
| 230 | if (conv.stopped) break; |
| 231 | } |
| 232 | conv.pumping = false; |
| 233 | onChange('pumping', conv.id, false); |
| 234 | } |
| 235 | |
| 236 | export async function init({ onEvent }) { |
| 237 | onChange = onEvent; |
| 238 | |
| 239 | // migración única: el esquema viejo era UNA sola conversación (kv/history + kv/queue) |
| 240 | const already = await db.get('kv', 'conversations').catch(() => null); |
| 241 | if (!already) { |
| 242 | const oldHistory = await db.get('kv', 'history').catch(() => null); |
| 243 | if (oldHistory?.length) { |
| 244 | const oldQueue = await db.get('kv', 'queue').catch(() => null); |
| 245 | await db.set('kv', 'conversations', [{ |
| 246 | id: genId(), title: null, history: oldHistory, queue: oldQueue || [], |
| 247 | createdAt: Date.now(), updatedAt: Date.now(), |
| 248 | }]).catch(() => {}); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | let tabIds = [], active = null; |
| 253 | try { tabIds = JSON.parse(localStorage.getItem(TABS_KEY) || '[]'); } catch { /* corrupto */ } |
| 254 | try { active = localStorage.getItem(ACTIVE_KEY) || null; } catch { /* */ } |
| 255 | const all = await db.get('kv', 'conversations').catch(() => null) || []; |
| 256 | |
| 257 | for (const id of tabIds) { |
| 258 | const saved = all.find(c => c.id === id); |
| 259 | if (saved) { makeConv(id, saved); openTabIds.push(id); } |
| 260 | } |
| 261 | if (active && convs.has(active)) activeId = active; |
| 262 | else if (openTabIds.length) activeId = openTabIds[0]; |
| 263 | |
| 264 | if (!openTabIds.length) { |
| 265 | // nada abierto (primera vez, o se perdió el estado de pestañas): retoma |
| 266 | // la conversación más reciente si hay alguna, si no, una nueva vacía |
| 267 | const mostRecent = all.slice().sort((a, b) => b.updatedAt - a.updatedAt)[0]; |
| 268 | if (mostRecent) { makeConv(mostRecent.id, mostRecent); openTabIds.push(mostRecent.id); activeId = mostRecent.id; } |
| 269 | else create(); |
| 270 | } |
| 271 | for (const conv of convs.values()) if (conv.queue.length) pump(conv); |
| 272 | persistMeta(); |
| 273 | } |