Elffuss BraidHub

utopia-ia/elffuss-claw public

coordinated: Undo after 🧹 and a reload keep pending work, Hard Work included

- The queue was saved as plain texts, so a Hard Work message waiting
  behind a running turn went through as a normal chat turn after a
  reload. The queue is now saved as {text, hard} and restored with the
  choice; old saved queues (plain strings) still load. Main saves
  {text, intentos}: when rebasing, keep both fields.
- "Undo" after 🧹 restored the history only. The message waiting in the
  queue (and the turn that 🧹 stopped) was lost for good. The undo copy now
  carries the pending queue, read before stopping because stopping empties
  it, and Undo puts it back so it is processed after the reload.
- Undo silently replaced a conversation started after 🧹. If there is a
  newer conversation (or pending work), Undo now swaps them: the newer one
  becomes the undo copy and the notice after the reload offers to go back
  to it. Old undo copies (a bare history array) still work.

Tests: ux-borrar.mjs (queued message comes back and is processed, the
newer thread is kept and reachable) and ux-hardwork.mjs (a queued Hard
Work message keeps its mode across a reload). Both fail on the previous
tree.

Integration (onto stop-fix 7147228 / main 10073b7): the saved queue keeps
all four fields, { id, text, intentos, hard } (main's retry counter,
stop-fix 4f02675's id and this commit's Hard Work choice), and the undo copy
uses the same shape. restoreQueue still accepts plain strings and items
without an id, and keeps 4f02675's match by id (by text only for old saves).
🧹 keeps its busy button and notice from stop-fix d1384bc.
Changesetd71cf5fce503e847c56a833748f93a1c4b7ea52ccf145aebd4e7fc6f0b27de79
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 18:44 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 17:51 +02:00
Parentsd803b61064d1

Browse the files at this changeset

4 files changed

modified tests/ux-borrar.mjs +64 −0
@@ -6,8 +6,11 @@
66 // siguiente mensaje (antes la conversación seguía en memoria y se volvía a
77 // guardar entera), y es TODO: claves de API, permisos, carpetas, sus
88 // automatizaciones, la bóveda (el aviso la nombra) y los ajustes.
9+// · 🧹 con un mensaje en cola: «Deshacer» lo devuelve; y si ya habías empezado
10+// otra conversación, no la tira: se intercambian.
911 //
1012 // BASE=http://localhost:8743 node tests/ux-borrar.mjs
13+import { createServer } from 'node:http';
1114 import { navegador, contexto, pagina, ok, hasta, espera, escribir, reposo, avisos, fin, kv } from './ux-comun.mjs';
1215
1316 const b = await navegador();
@@ -110,6 +113,67 @@
110113 await c3.close();
111114 }
112115
116+// ── 🧹 con trabajo pendiente, y «Deshacer» con una conversación nueva ya empezada ─
117+// Un cerebro de verdad (servidor de mentira local) para tener un turno en marcha
118+// y un mensaje esperando en la cola cuando se pulsa 🧹.
119+{
120+ const peticiones = [];
121+ const servidor = createServer((req, res) => {
122+ const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'content-type, authorization', 'Access-Control-Allow-Methods': 'POST, OPTIONS' };
123+ if (req.method === 'OPTIONS') { res.writeHead(204, cors); res.end(); return; }
124+ let cuerpo = '';
125+ req.on('data', d => { cuerpo += d; });
126+ req.on('end', () => {
127+ let msgs = [];
128+ try { msgs = JSON.parse(cuerpo).messages || []; } catch { /* */ }
129+ const ultimo = msgs.filter(m => m.role === 'user').at(-1)?.content || '';
130+ peticiones.push(ultimo);
131+ const responder = () => {
132+ res.writeHead(200, { ...cors, 'Content-Type': 'text/event-stream' });
133+ res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: 'respuesta a ' + ultimo.slice(0, 30) } }] })}\n\n`);
134+ res.write('data: [DONE]\n\n');
135+ res.end();
136+ };
137+ if (/LENTO/.test(ultimo)) setTimeout(responder, 4000); else responder();
138+ });
139+ });
140+ await new Promise(r => servidor.listen(0, '127.0.0.1', r));
141+ const puerto = servidor.address().port;
142+ const { ctx: c4 } = await contexto(b, {
143+ model: 'ext:ollama',
144+ extraInit: { 'elffuss.providers': JSON.stringify({ ollama: { enabled: true, baseURL: `http://127.0.0.1:${puerto}/v1`, model: 'falso', apiKey: 'ollama' } }) },
145+ });
146+ const { p: q } = await pagina(c4);
147+ const listoQ = () => q.waitForFunction(() => !!window.elffuss?.agent, null, { timeout: 15000 });
148+ const trasRecargar = async accion => { await Promise.all([q.waitForNavigation({ waitUntil: 'domcontentloaded' }), accion()]); await listoQ(); };
149+ const avisoQ = texto => q.locator('#toasts .toast', { hasText: texto });
150+ await hasta(() => q.evaluate(() => document.getElementById('model-select').value === 'ext:ollama'), { veces: 200 });
151+ await escribir(q, 'hola VIEJO-HILO');
152+ await reposo(q);
153+ await escribir(q, 'LENTO en marcha');
154+ await hasta(() => peticiones.some(t => /LENTO en marcha/.test(t)));
155+ await escribir(q, 'PENDIENTE-EN-COLA dos');
156+ ok('con un turno en marcha, el segundo mensaje espera en la cola', (await kv(q, 'queue'))?.some(x => /PENDIENTE-EN-COLA/.test(x.text || x)));
157+ await trasRecargar(() => q.click('#btn-clear'));
158+ await hasta(async () => await avisoQ('Conversación nueva').count() === 1);
159+ await escribir(q, 'NUEVO-HILO importante');
160+ await reposo(q);
161+ const n = peticiones.length;
162+ await trasRecargar(() => avisoQ('Conversación nueva').locator('.toast-accion').click());
163+ ok('«Deshacer» recupera la conversación anterior', await hasta(async () => (await q.locator('#log').innerText()).includes('VIEJO-HILO')));
164+ ok('…y el mensaje que esperaba en la cola vuelve y se procesa', await hasta(() =>
165+ peticiones.slice(n).some(t => /PENDIENTE-EN-COLA/.test(t)), { veces: 400 }), JSON.stringify(peticiones.slice(n)));
166+ ok('la conversación empezada después NO se pierde: el aviso ofrece volver a ella', await hasta(async () =>
167+ await avisoQ('La que empezaste después').locator('.toast-accion').count() === 1));
168+ const copia = await kv(q, 'historyBackup');
169+ ok('…y está guardada como copia', JSON.stringify(copia || '').includes('NUEVO-HILO'));
170+ await reposo(q);
171+ await trasRecargar(() => avisoQ('La que empezaste después').locator('.toast-accion').click());
172+ ok('«Deshacer» otra vez vuelve a la conversación nueva', await hasta(async () => (await q.locator('#log').innerText()).includes('NUEVO-HILO')));
173+ await c4.close();
174+ servidor.close();
175+}
176+
113177 // ── en inglés, el nombre de 🧹 y el aviso de «Borrar todo» ──────────────────
114178 {
115179 const { ctx: c2 } = await contexto(b, { locale: 'en-US' });
modified tests/ux-hardwork.mjs +28 −4
@@ -5,6 +5,7 @@
55 // · Cuenta lo que pasó: rondas de mejora reales, «solo el borrador» si la
66 // reescritura no salió, y el error si la app no se pudo guardar.
77 // · Con carpeta, no lee los ficheros que parecen secretos (.env).
8+// · Un mensaje de Hard Work que espera en la cola lo sigue siendo tras recargar.
89 //
910 // BASE=http://localhost:8743 node tests/ux-hardwork.mjs
1011 import { createServer } from 'node:http';
@@ -29,10 +30,14 @@
2930 else if (/mejorando tu propia app/.test(sistema)) out = reescrituraMala ? 'no sé hacerlo' : HTML('MEJORADA');
3031 else if (/creando una app web/.test(sistema)) out = HTML('BORRADOR');
3132 else if (/analista|sintetizador/.test(sistema)) out = 'resumen de la parte';
32- res.writeHead(200, { ...cors, 'Content-Type': 'text/event-stream' });
33- res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: out } }] })}\n\n`);
34- res.write('data: [DONE]\n\n');
35- res.end();
33+ const responder = () => {
34+ res.writeHead(200, { ...cors, 'Content-Type': 'text/event-stream' });
35+ res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: out } }] })}\n\n`);
36+ res.write('data: [DONE]\n\n');
37+ res.end();
38+ };
39+ // «LENTO»: un turno que tarda, para que lo siguiente espere en la cola.
40+ if (/LENTO/.test(usuario.split('\n').at(-1) || '')) setTimeout(responder, 3000); else responder();
3641 });
3742 });
3843 await new Promise(r => servidor.listen(0, '127.0.0.1', r));
@@ -91,6 +96,25 @@
9196 /no pude guardar la app/.test(await p.locator('#log .msg.assistant.err').last().innerText().catch(() => ''))));
9297 await reposo(p);
9398
99+// ── un mensaje de Hard Work que espera en la cola sigue siéndolo tras recargar ─
100+// (antes la cola guardaba solo el texto y, al recargar, iba como chat normal)
101+await espera(300);
102+if (await p.evaluate(() => document.getElementById('perm-dialog').open)) await p.click('#perm-deny');
103+await escribir(p, 'LENTO turno normal');
104+await hasta(() => peticiones.some(x => /LENTO turno normal/.test(x.usuario)));
105+if (await pulsado() !== 'true') await hw.click();
106+await escribir(p, 'hazme un juego de naves EN-COLA');
107+const cola = await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'queue'));
108+ok('el mensaje de Hard Work se guarda en la cola CON su elección', Array.isArray(cola)
109+ && cola.some(x => /EN-COLA/.test(x.text) && x.hard === true), JSON.stringify(cola));
110+desde = peticiones.length;
111+await p.reload({ waitUntil: 'domcontentloaded' });
112+ok('tras recargar, va por Hard Work (no como chat normal)', await hasta(() =>
113+ peticiones.slice(desde).some(x => /creando una app web/.test(x.sistema) && /EN-COLA/.test(x.usuario)), { veces: 400 }),
114+ JSON.stringify(peticiones.slice(desde).map(x => x.sistema.slice(0, 40) + ' | ' + x.usuario.slice(-30))));
115+ok('…y nunca como turno normal', !peticiones.slice(desde).some(x => /^Eres Elffuss: un sistema operativo/.test(x.sistema) && /EN-COLA/.test(x.usuario.split('\n').at(-1))));
116+await reposo(p);
117+
94118 // ── con carpeta: .env no se lee ─────────────────────────────────────────────
95119 await p.evaluate(async () => {
96120 const raiz = await (await navigator.storage.getDirectory()).getDirectoryHandle('proyecto', { create: true });
modified web/js/i18n.js +2 −0
@@ -153,6 +153,7 @@
153153 pickModel: 'Elegir modelo',
154154 newChat: 'Nueva conversación', chatRestored: 'Conversación restaurada',
155155 chatCleared: 'Conversación nueva: la anterior se ha borrado', undoGone: 'Ya no hay nada que deshacer',
156+ chatSwapped: 'Conversación anterior recuperada. La que empezaste después está guardada: «Deshacer» vuelve a ella.',
156157 diskChipT: 'Modelos descargados en este navegador: {size}. Pulsa para liberar ese espacio.',
157158 diskConfirm: 'Vas a borrar {size} de modelos descargados, también los del almacén compartido de Elffuss.\n\nNo se pierde nada tuyo: ni apps, ni conversación, ni bóveda; solo los pesos. La próxima vez habrá que bajarlos otra vez.\n\n¿Seguir?',
158159 diskFreed: 'Liberados {size}', diskSharedFail: '⚠ el almacén compartido no respondió: puede quedar algo guardado allí',
@@ -352,6 +353,7 @@
352353 pickModel: 'Pick a model',
353354 newChat: 'New conversation', chatRestored: 'Conversation restored',
354355 chatCleared: 'New conversation: the previous one was deleted', undoGone: 'There is nothing to undo any more',
356+ chatSwapped: 'Previous conversation restored. The one you started afterwards is kept: “Undo” goes back to it.',
355357 diskChipT: 'Models downloaded in this browser: {size}. Click to free that space.',
356358 diskConfirm: 'You are about to delete {size} of downloaded models, including the ones in the shared Elffuss store.\n\nNothing of yours is lost: no apps, no conversation, no vault; only the weights. Next time they will be downloaded again.\n\nContinue?',
357359 diskFreed: 'Freed {size}', diskSharedFail: '⚠ the shared store did not answer: something may still be stored there',
modified web/js/kernel.js +50 −15
@@ -308,15 +308,22 @@
308308 let bootReady;
309309 const bootPromise = new Promise(r => { bootReady = r; });
310310
311-// Se guarda {id, text, intentos} y no solo el texto. El contador es lo que
312-// impide el bucle de cuelgue: si un turno se lleva la pestaña por delante —pasa
313-// con el modelo grande y poca memoria— al reabrir se reanuda y la vuelve a
314-// tumbar, y no hay forma de salir ni cerrando, porque el mensaje sigue en la
311+// Se guarda {id, text, intentos, hard} y no solo el texto. El contador es lo
312+// que impide el bucle de cuelgue: si un turno se lleva la pestaña por delante
313+// —pasa con el modelo grande y poca memoria— al reabrir se reanuda y la vuelve
314+// a tumbar, y no hay forma de salir ni cerrando, porque el mensaje sigue en la
315315 // cola. El id es lo que distingue un mensaje de otro igual (ver restoreQueue).
316+// `hard` es la elección de Hard Work, que va CON el mensaje (ver send) también
317+// tras recargar: guardando solo el texto, un mensaje de Hard Work que esperaba
318+// detrás de otro turno se procesaba como chat normal al recargar.
316319 // Las colas guardadas por versiones anteriores son de strings sueltos o sin
317320 // id; restoreQueue las sigue aceptando.
318321 const persistQueue = () =>
319- db.set('kv', 'queue', queue.map(q => ({ id: q.id, text: q.text, intentos: q.intentos || 0 }))).catch(() => {});
322+ db.set('kv', 'queue', queue.map(paraGuardar)).catch(() => {});
323+const paraGuardar = q => ({ id: q.id, text: q.text, intentos: q.intentos || 0, hard: !!q.hard });
324+// Lo pendiente ahora mismo (el turno en marcha y lo que espera detrás), en el
325+// formato de la cola guardada.
326+const pendientesAhora = () => queue.map(paraGuardar);
320327 const MAX_INTENTOS = 2;
321328 const nuevoId = () => (globalThis.crypto?.randomUUID?.() || Date.now().toString(36) + Math.random().toString(36).slice(2));
322329
@@ -576,8 +583,8 @@
576583 async function restoreQueue() {
577584 let pending = await db.get('kv', 'queue').catch(() => null);
578585 if (!pending?.length) return;
579- // Compatibilidad: lo guardado por la versión anterior son strings sueltos.
580- pending = pending.map(x => (typeof x === 'string' ? { text: x, intentos: 0 } : x));
586+ // Compatibilidad: lo guardado por versiones anteriores son strings sueltos.
587+ pending = pending.map(x => (typeof x === 'string' ? { text: x, intentos: 0 } : x)).filter(x => typeof x?.text === 'string');
581588 const lastDone = await db.get('kv', 'lastDone').catch(() => null);
582589 // ¿El primero ya se procesó? Se reconoce por su id y no por el texto: antes,
583590 // reenviar lo mismo que acababas de parar —el reintento natural— y recargar a
@@ -592,7 +599,7 @@
592599 if (!pending.length) { db.set('kv', 'queue', []).catch(() => {}); return; }
593600 for (const it of pending) {
594601 const el = ui.addMsg('user queued', it.text);
595- queue.push({ id: it.id || nuevoId(), text: it.text, intentos: it.intentos || 0, el });
602+ queue.push({ id: it.id || nuevoId(), text: it.text, intentos: it.intentos || 0, el, hard: !!it.hard });
596603 }
597604 ui.toast(`${pending.length} mensaje(s) pendientes recuperados — los proceso en cuanto cargue el cerebro.`);
598605 pump();
@@ -673,13 +680,21 @@
673680 // 🧹 Nueva conversación. Sin confirmación, pero con «Deshacer»: la conversación
674681 // que se va se guarda aparte (kv/historyBackup) y, tras recargar, un aviso
675682 // ofrece recuperarla. Esa copia vive hasta la siguiente carga de la página.
683+//
684+// La copia lleva también lo PENDIENTE (el turno que se paró y lo que esperaba
685+// en la cola): antes «Deshacer» devolvía solo el histórico y un mensaje en cola
686+// se perdía para siempre. Se lee antes de parar, porque parar vacía la cola.
687+// Formato: { history, queue }; una copia antigua era solo el array del histórico.
688+const leerCopia = x => Array.isArray(x) ? { history: x, queue: [] }
689+ : x && Array.isArray(x.history) ? { history: x.history, queue: Array.isArray(x.queue) ? x.queue : [] } : null;
676690 async function nuevaConversacion() {
677691 const boton = document.getElementById('btn-clear');
678692 if (boton?.getAttribute('aria-busy') === 'true') return; // ya se está borrando
693+ const pendientes = pendientesAhora();
679694 await pararParaBorrar({ boton, aviso: t('clearing') });
680695 const actual = await db.get('kv', 'history').catch(() => null);
681- if (actual?.length) {
682- await db.set('kv', 'historyBackup', actual).catch(() => {});
696+ if (actual?.length || pendientes.length) {
697+ await db.set('kv', 'historyBackup', { history: actual || [], queue: pendientes }).catch(() => {});
683698 avisarTrasRecargar({ tipo: 'limpiado' });
684699 }
685700 await db.del('kv', 'history').catch(() => {});
@@ -687,13 +702,30 @@
687702 agent.history = [];
688703 recargar(boton);
689704 }
705+// «Deshacer» no tira lo que hayas empezado DESPUÉS de 🧹: antes lo sustituía
706+// en silencio. Si hay conversación nueva (o algo pendiente), las dos se
707+// intercambian —la nueva pasa a ser la copia— y el aviso tras recargar permite
708+// volver a ella.
690709 async function deshacerNuevaConversacion() {
691- const copia = await db.get('kv', 'historyBackup').catch(() => null);
692- if (!copia?.length) { ui.toast(t('undoGone')); return; }
710+ const copia = leerCopia(await db.get('kv', 'historyBackup').catch(() => null));
711+ if (!copia || (!copia.history.length && !copia.queue.length)) { ui.toast(t('undoGone')); return; }
712+ const pendientes = pendientesAhora();
693713 await pararParaBorrar();
694- await db.set('kv', 'history', copia).catch(() => {});
695- await db.del('kv', 'historyBackup').catch(() => {});
696- await db.del('kv', 'queue').catch(() => {});
714+ const nueva = await db.get('kv', 'history').catch(() => null);
715+ if (nueva?.length || pendientes.length) {
716+ await db.set('kv', 'historyBackup', { history: nueva || [], queue: pendientes }).catch(() => {});
717+ avisarTrasRecargar({ tipo: 'intercambiado' });
718+ } else {
719+ await db.del('kv', 'historyBackup').catch(() => {});
720+ }
721+ if (copia.history.length) await db.set('kv', 'history', copia.history).catch(() => {});
722+ else await db.del('kv', 'history').catch(() => {});
723+ if (copia.queue.length) {
724+ await db.set('kv', 'queue', copia.queue).catch(() => {});
725+ await db.del('kv', 'lastDone').catch(() => {}); // que restoreQueue no descarte el primero por error
726+ } else {
727+ await db.del('kv', 'queue').catch(() => {});
728+ }
697729 recargar();
698730 }
699731 document.getElementById('btn-clear').addEventListener('click', () => nuevaConversacion());
@@ -905,6 +937,9 @@
905937 restoreHistory().then(restoreQueue).then(() => {
906938 if (avisoAlCargar?.tipo === 'limpiado') {
907939 ui.toast(t('chatCleared'), { accion: { label: t('undo'), run: deshacerNuevaConversacion } });
940+ } else if (avisoAlCargar?.tipo === 'intercambiado') {
941+ // «Deshacer» con una conversación nueva ya empezada: esa queda guardada.
942+ ui.toast(t('chatSwapped'), { accion: { label: t('undo'), run: deshacerNuevaConversacion } });
908943 } else {
909944 // Sin el aviso, ya no hay nada que deshacer: la copia se va.
910945 db.del('kv', 'historyBackup').catch(() => {});