Elffuss BraidHub

utopia-ia/elffuss-code public

7c24e7b60e19 · 13.9 KiBRawPermalink
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.
14import { Agent } from './agent.js';
15import { runGoal, TASK_PREFIX } from './goal.js';
16import * as db from './db.js';
17import * as telemetry from './telemetry.js';
18
19const NS = 'elffusscode';
20const TABS_KEY = NS + '.openTabs';
21const ACTIVE_KEY = NS + '.activeConv';
22const HIST_CAP = 80; // mensajes por conversación que se persisten
23
24let providerRef = null;
25const convs = new Map(); // id -> { id, title, agent, queue, pumping, createdAt, updatedAt }
26let openTabIds = [];
27let activeId = null;
28let onChange = () => {};
29
30const genId = () => 'c' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
31const cleanTitle = s => String(s).replace(/\s+/g, ' ').trim();
32
33const GOAL_PREFIX = TASK_PREFIX + 'Objetivo: ';
34export 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
47export function setProvider(mod) {
48 providerRef = mod;
49 for (const c of convs.values()) c.agent.setProvider(mod);
50}
51export function getProvider() { return providerRef; }
52
53export function isBusy() {
54 for (const c of convs.values()) if (c.pumping || c.queue.length) return true;
55 return false;
56}
57
58export 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.
64export 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
73export function getOpenTabs() { return openTabIds.map(id => convs.get(id)).filter(Boolean); }
74
75async 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}
93function persistMeta() {
94 try { localStorage.setItem(TABS_KEY, JSON.stringify(openTabIds)); } catch { /* lleno */ }
95 try { localStorage.setItem(ACTIVE_KEY, activeId || ''); } catch { /* lleno */ }
96}
97
98function 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
109export 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
120export 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
133export 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.
143export 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
152export 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)
160export 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
170export 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'.
180let inferenceLock = Promise.resolve();
181const normalizeItem = it => (typeof it === 'string' ? { kind: 'chat', text: it } : it);
182
183// Reanudar lo que quedó a medias, UNA VEZ HAY CEREBRO. Lo llama main.js después
184// de cargar el modelo.
185//
186// La guarda del contador no es paranoia: si un turno se llevó la pestaña por
187// delante —pasa con el modelo grande y poca memoria— reanudarlo al abrir la
188// vuelve a tumbar, y el usuario entra en un bucle del que no puede salir ni
189// abriendo la web. Se cuenta el intento ANTES de ejecutar y se persiste; si el
190// turno acaba, el item sale de la cola y el contador se va con él. Si la
191// pestaña muere, el contador sobrevive y al tercer intento ya no se reanuda
192// solo: se avisa y decide el usuario.
193const MAX_INTENTOS = 2;
194export function resumePending(onAviso = () => {}) {
195 for (const conv of convs.values()) {
196 if (!conv.queue.length) continue;
197 const it = normalizeItem(conv.queue[0]);
198 if ((it.intentos || 0) >= MAX_INTENTOS) {
199 onAviso(conv.id, it);
200 continue;
201 }
202 pump(conv);
203 }
204}
205
206// Descarta el turno atascado y sigue con el resto de la cola. Para el botón del
207// aviso: sin esto, una conversación con un turno que cuelga queda bloqueada
208// para siempre y no hay forma de usarla.
209export async function descartarPendiente(id) {
210 const conv = convs.get(id);
211 if (!conv || !conv.queue.length) return;
212 conv.queue.shift();
213 await persistConv(conv);
214 if (conv.queue.length) pump(conv);
215}
216
217export function send(id, text) {
218 const conv = convs.get(id);
219 if (!conv) return;
220 conv.queue.push({ kind: 'chat', text });
221 persistConv(conv);
222 pump(conv);
223}
224
225// 🎯 Modo Objetivo: en vez de un turno de chat normal, el mensaje se trata
226// como un objetivo — se planifica en tareas y se ejecutan una a una (ver
227// goal.js, mismo patrón planificador/ejecutor de clonagent).
228export function startGoal(id, text) {
229 const conv = convs.get(id);
230 if (!conv) return;
231 conv.queue.push({ kind: 'goal', text });
232 persistConv(conv);
233 pump(conv);
234}
235
236async function pump(conv) {
237 if (conv.pumping) return;
238 conv.pumping = true;
239 conv.stopped = false;
240 onChange('pumping', conv.id, true);
241 while (conv.queue.length) {
242 const item = normalizeItem(conv.queue[0]);
243 // El intento se cuenta y se GUARDA antes de ejecutar: si el turno se lleva
244 // la pestaña, esto es lo único que queda para saber que ya se intentó.
245 // Guardarlo después no serviría de nada — no habría «después».
246 item.intentos = (item.intentos || 0) + 1;
247 conv.queue[0] = item;
248 await persistConv(conv);
249 const myTurn = inferenceLock;
250 let release;
251 inferenceLock = new Promise(r => { release = r; });
252 await myTurn; // espera su turno de inferencia (un solo modelo cargado, no admite 2 generate() a la vez)
253 try {
254 // un fallo aquí (del modelo, de una tool, o del propio repintado en
255 // main.js) NUNCA debe dejar la conversación "pumping" para siempre —
256 // eso bloquearía sus futuros mensajes Y al cerebro CEO (isBusy()).
257 // Tasa de resolución y tiempo por tarea. Se mide aquí, que es donde una
258 // tarea empieza y acaba de verdad: el motor solo ve turnos y no sabe qué
259 // es una tarea. «Resuelta» = ni excepción ni evento de error, porque el
260 // fallo típico no es una excepción sino una respuesta que llega al
261 // usuario como error — contar solo excepciones daría un 100 % perpetuo.
262 const tTarea = (typeof performance !== 'undefined' ? performance.now() : Date.now());
263 let huboError = false;
264 const onEvent = ev => {
265 if (ev && ev.type === 'error') huboError = true;
266 try { onChange('event', conv.id, ev); } catch (e) { console.error('[elffuss] fallo pintando un evento de chat', e); }
267 };
268 try {
269 if (item.kind === 'goal') await runGoal(conv, item.text, onEvent);
270 else await conv.agent.handle(item.text, onEvent);
271 } finally {
272 try {
273 const vm = await import('./velocimetro.js');
274 const fin = (typeof performance !== 'undefined' ? performance.now() : Date.now());
275 vm.tarea({ ok: !huboError, ms: fin - tTarea });
276 } catch { /* sin velocímetro la app funciona igual */ }
277 }
278 } catch (e) {
279 console.error('[elffuss] fallo procesando el turno', e);
280 telemetry.reportError('pump: ' + (e?.message || e), { stack: e?.stack || '' });
281 try { onChange('event', conv.id, { type: 'error', text: 'Error interno: ' + (e?.message || e) }); } catch { /* ya está registrado arriba */ }
282 } finally { release(); }
283 conv.queue.shift();
284 conv.updatedAt = Date.now();
285 await persistConv(conv);
286 if (conv.stopped) break;
287 }
288 conv.pumping = false;
289 onChange('pumping', conv.id, false);
290}
291
292export async function init({ onEvent }) {
293 onChange = onEvent;
294
295 // migración única: el esquema viejo era UNA sola conversación (kv/history + kv/queue)
296 const already = await db.get('kv', 'conversations').catch(() => null);
297 if (!already) {
298 const oldHistory = await db.get('kv', 'history').catch(() => null);
299 if (oldHistory?.length) {
300 const oldQueue = await db.get('kv', 'queue').catch(() => null);
301 await db.set('kv', 'conversations', [{
302 id: genId(), title: null, history: oldHistory, queue: oldQueue || [],
303 createdAt: Date.now(), updatedAt: Date.now(),
304 }]).catch(() => {});
305 }
306 }
307
308 let tabIds = [], active = null;
309 try { tabIds = JSON.parse(localStorage.getItem(TABS_KEY) || '[]'); } catch { /* corrupto */ }
310 try { active = localStorage.getItem(ACTIVE_KEY) || null; } catch { /* */ }
311 const all = await db.get('kv', 'conversations').catch(() => null) || [];
312
313 for (const id of tabIds) {
314 const saved = all.find(c => c.id === id);
315 if (saved) { makeConv(id, saved); openTabIds.push(id); }
316 }
317 if (active && convs.has(active)) activeId = active;
318 else if (openTabIds.length) activeId = openTabIds[0];
319
320 if (!openTabIds.length) {
321 // nada abierto (primera vez, o se perdió el estado de pestañas): retoma
322 // la conversación más reciente si hay alguna, si no, una nueva vacía
323 const mostRecent = all.slice().sort((a, b) => b.updatedAt - a.updatedAt)[0];
324 if (mostRecent) { makeConv(mostRecent.id, mostRecent); openTabIds.push(mostRecent.id); activeId = mostRecent.id; }
325 else create();
326 }
327 // NO se reanuda aquí. Esta línea hacía `pump(conv)` directamente, y `init()`
328 // corre ANTES de que el modelo esté cargado: el proveedor en ese momento es
329 // `rules`, así que al refrescar a mitad de turno el mensaje en cola se
330 // reprocesaba con el cerebro BÁSICO y se gastaba — peor que no reanudar,
331 // porque además parecía que había contestado. Ahora lo dispara quien sabe
332 // que hay cerebro: main.js, tras cargar el modelo, llamando a
333 // `resumePending()`.
334 persistMeta();
335}