Elffuss BraidHub

utopia-ia/elffuss-code public

Closing or deleting the active conversation switches the chat

closeTab() and remove() emitted 'tabs' instead of 'switch' when the closed
conversation was the active one. The tab bar repainted, but the chat log kept
showing the closed conversation and the next message went to another one that
was not on screen. Both now emit 'switch' with the new active id whenever the
active conversation changes.

remove() also stops a conversation that is still working before deleting it
and marks it so persistConv() skips it: the finishing turn used to write it
back to IndexedDB, so a deleted conversation came back in the History.

tests/convclose.mjs (?test-opfs, rules model): closing the active tab shows
the remaining conversation and the next message lands there; deleting the
active conversation from the History does the same; deleting one mid-turn
does not resurrect it. Against the previous conversations.js it fails 3 of
its checks.
Changeset7fc4ec96dbaa0002d9a11d3e7630b162155a036c52d54ae86ccfda1069b1a89b
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 15:37 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:11 +02:00
Parents956f3bd06054

Browse the files at this changeset

2 files changed

added tests/convclose.mjs +97 −0
@@ -0,0 +1,97 @@
1+// Cerrar o borrar la conversación ACTIVA: el chat tiene que pasar a la que
2+// queda activa, y lo siguiente que escribas tiene que ir a la que ves.
3+//
4+// Antes closeTab() y remove() avisaban con 'tabs' en vez de 'switch': la barra
5+// de pestañas cambiaba, pero el chat seguía enseñando la conversación cerrada y
6+// el siguiente mensaje iba a parar a otra que no estaba en pantalla. Y borrar
7+// una conversación que estaba trabajando la resucitaba en la Historial cuando
8+// su turno terminaba.
9+//
10+// BASE=http://127.0.0.1:8898 node tests/convclose.mjs
11+import { chromium } from 'playwright';
12+const BASE = process.env.BASE || 'http://localhost:8799';
13+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
14+
15+const b = await chromium.launch();
16+const ctx = await b.newContext({ locale: 'es-ES' });
17+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
18+const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } });
19+const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
20+await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
21+await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.(), null, { timeout: 15000 });
22+
23+const libre = () => p.waitForFunction(() => !window.elffussClaw.conv.isBusy(), null, { timeout: 10000 });
24+const escribe = async (txt) => { await p.fill('#prompt', txt); await p.press('#prompt', 'Enter'); await p.waitForTimeout(100); await libre(); };
25+const activa = () => p.evaluate(() => window.elffussClaw.conv.getActive().id);
26+const log = () => p.evaluate(() => document.getElementById('chat-log').innerText);
27+// la × de la pestaña activa (sea <b> o <button>)
28+const cierraActiva = () => p.locator('#conv-tabs .tab.active').locator('.tab-x, b').first().dispatchEvent('click');
29+
30+await escribe('mensaje de la uno');
31+const uno = await activa();
32+await p.locator('#conv-tabs .tab-add').dispatchEvent('click');
33+await p.waitForTimeout(150);
34+await escribe('mensaje de la dos');
35+const dos = await activa();
36+ok('dos conversaciones distintas', uno !== dos, `${uno} / ${dos}`);
37+
38+// 1 · cerrar la pestaña activa
39+await cierraActiva();
40+await p.waitForTimeout(200);
41+const tras1 = { activa: await activa(), log: await log() };
42+ok('1 · al cerrar la activa, pasa a ser activa la otra', tras1.activa === uno, tras1.activa);
43+ok('1 · el chat enseña la conversación que queda activa', tras1.log.includes('mensaje de la uno') && !tras1.log.includes('mensaje de la dos'), tras1.log.slice(0, 200));
44+await escribe('sigo en la uno');
45+const h1 = await p.evaluate((id) => window.elffussClaw.conv.getActive().id === id && window.elffussClaw.conv.getActive().agent.history.some(m => m.content === 'sigo en la uno'), uno);
46+ok('1 · lo siguiente que escribes va a la conversación que ves', h1);
47+
48+// 2 · borrar desde la Historial la conversación activa
49+await p.click('#btn-history');
50+await p.waitForSelector('#history-panel .hp-row');
51+// reabrir la dos desde la Historial (pasa a ser la activa)
52+await p.evaluate((id) => window.elffussClaw.conv.open(id), dos);
53+await p.waitForTimeout(150);
54+ok('2 · la dos vuelve a estar activa', (await activa()) === dos);
55+await p.evaluate(() => { window.confirm = () => true; });
56+await p.evaluate(async () => {
57+ const panel = document.getElementById('history-panel');
58+ if (panel.hidden) document.getElementById('btn-history').click();
59+});
60+await p.waitForSelector('#history-panel .hp-row');
61+await p.evaluate((id) => {
62+ const conv = window.elffussClaw.conv;
63+ const titulo = conv.titleFor(conv.getActive());
64+ const fila = [...document.querySelectorAll('#history-panel .hp-row')].find(r => r.querySelector('.hp-title')?.textContent === titulo);
65+ fila.querySelector('.hp-del').click();
66+}, dos);
67+await p.waitForTimeout(400);
68+const tras2 = { activa: await activa(), log: await log() };
69+ok('2 · tras borrar la activa, la activa es otra', tras2.activa !== dos, tras2.activa);
70+ok('2 · y el chat enseña esa otra, no la borrada', !tras2.log.includes('mensaje de la dos') && tras2.log.includes('mensaje de la uno'), tras2.log.slice(0, 200));
71+
72+// 3 · borrar una conversación MIENTRAS trabaja no la resucita al terminar su turno
73+const r3 = await p.evaluate(async () => {
74+ const conv = window.elffussClaw.conv;
75+ const db = await import('/js/db.js');
76+ const dormir = ms => new Promise(r => setTimeout(r, ms));
77+ const lento = { chat: async (h, s, cb, signal) => {
78+ for (let i = 0; i < 30; i++) { if (signal?.aborted) throw new DOMException('Parado', 'AbortError'); cb('·'); await dormir(30); }
79+ return 'terminé';
80+ } };
81+ conv.setProvider(lento);
82+ const c = conv.create();
83+ conv.send(c.id, 'trabajo que se borra');
84+ for (let i = 0; i < 40 && !c.pumping; i++) await dormir(20);
85+ await conv.remove(c.id);
86+ for (let i = 0; i < 100 && c.pumping; i++) await dormir(30);
87+ await dormir(300);
88+ const guardadas = await db.get('kv', 'conversations');
89+ return { resucita: guardadas.some(x => x.id === c.id), sigue: c.pumping };
90+});
91+ok('3 · borrada mientras trabajaba: no vuelve a aparecer en IndexedDB', !r3.resucita && !r3.sigue, JSON.stringify(r3));
92+
93+console.log('\n errores JS:', errs[0] || 'ninguno');
94+ok('sin errores de página', errs.length === 0, errs.join(' | '));
95+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CERRAR/BORRAR LA CONVERSACIÓN ACTIVA OK');
96+await b.close();
97+process.exit(fails ? 1 : 0);
modified web/js/conversations.js +27 −6
@@ -102,8 +102,9 @@
102102 function persistConv(conv) { return enOrden(() => persistConvYa(conv)); }
103103
104104 async function persistConvYa(conv) {
105- // Borrada desde la Historial mientras su guardado esperaba: no se resucita.
106- if (convs.get(conv.id) !== conv) return;
105+ // Borrada desde la Historial (también mientras su guardado esperaba): no se
106+ // vuelve a escribir, o resucitaría.
107+ if (conv.borrada || convs.get(conv.id) !== conv) return;
107108 // NO tragarse el error de lectura: un fallo transitorio devolvía [] y el
108109 // db.set de abajo reescribía el store entero con UNA sola conversación,
109110 // borrando el resto. Distinguir «no existe aún» (undefined → []) de «no se
@@ -196,18 +197,37 @@
196197 }
197198
198199 // quita la pestaña de la vista — la conversación sigue viva en la Historial
200+//
201+// Si la pestaña cerrada era la ACTIVA, se avisa con 'switch' y no con 'tabs':
202+// con 'tabs' la barra se repintaba pero el chat seguía enseñando la
203+// conversación cerrada, y lo siguiente que escribías iba a parar a otra que no
204+// estaba en pantalla.
199205 export function closeTab(id) {
206+ const eraActiva = activeId === id;
200207 openTabIds = openTabIds.filter(x => x !== id);
201- if (activeId === id) activeId = openTabIds[openTabIds.length - 1] || null;
208+ if (eraActiva) activeId = openTabIds[openTabIds.length - 1] || null;
202209 persistMeta();
203- if (!openTabIds.length) create(); else onChange('tabs');
210+ if (!openTabIds.length) create();
211+ else onChange(eraActiva ? 'switch' : 'tabs', activeId);
204212 }
205213
206214 // borra la conversación de verdad (desde la Historial)
215+//
216+// Si estaba trabajando se para antes de borrarla: su turno, al terminar,
217+// llamaba a persistConv y la volvía a escribir en IndexedDB, así que una
218+// conversación borrada resucitaba en la Historial.
207219 export async function remove(id) {
220+ const c = convs.get(id);
221+ if (c) {
222+ c.borrada = true;
223+ c.queue.length = 0;
224+ try { c.aborter?.abort(); } catch { /* */ }
225+ try { c.agent.stop(); } catch { /* */ }
226+ }
208227 convs.delete(id);
228+ const eraActiva = activeId === id;
209229 openTabIds = openTabIds.filter(x => x !== id);
210- if (activeId === id) activeId = openTabIds[openTabIds.length - 1] || null;
230+ if (eraActiva) activeId = openTabIds[openTabIds.length - 1] || null;
211231 // En la misma fila que los guardados: si no, un guardado en curso de esta
212232 // conversación la volvía a meter después de borrarla.
213233 await enOrden(async () => {
@@ -215,7 +235,8 @@
215235 await db.set('kv', 'conversations', all).catch(() => {});
216236 });
217237 persistMeta();
218- if (!openTabIds.length) create(); else onChange('tabs');
238+ if (!openTabIds.length) create();
239+ else onChange(eraActiva ? 'switch' : 'tabs', activeId);
219240 }
220241
221242 export async function listAll() {