Elffuss BraidHub

utopia-ia/elffuss-code public

Stop: "Stopping..." goes straight to "Send", and each queued message keeps its own wait mark

After a stop, pump() cleared "Stopping..." while the conversation was still
pumping and only then saved it. For as long as that save took, the button came
back as an enabled "Stop" before turning into "Send", and a click there would
issue another stop. "Stopping..." is now cleared together with "pumping" when
the queue is empty; if another message is waiting, it is cleared at once as
before, because that message is about to run.

The hourglass mark was decided per conversation, and the 'turn' event removed
it from the first queued bubble. With another conversation holding the model,
the first message of an idle conversation got no mark while the second did, and
when the first started the second lost its mark and the first answer was
painted below the second message. Each queue item now has an id, send(),
startGoal() and startHardWork() return it, the bubble carries it, and 'turn'
unmarks exactly that bubble. A message is marked whenever any conversation is
busy, and the thinking bubble appears when its own turn starts, under it.

tests/stopqueue.mjs records every accessible name the button takes after the
stop: Stop, Stopping..., Send, with no Stop in between. tests/enterqueue.mjs
adds the cross-conversation case: both messages wait with their mark, only the
first one loses it when it starts, and each answer lands under its message.
Changeset22eb75f6760ec6ba5658bb34d7d3ca068cf9aa055ec97c39f29d6d97d8391c8b
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-11 15:10 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 15:10 +02:00
Parentsd7be1ec7f98f

Browse the files at this changeset

4 files changed

modified tests/enterqueue.mjs +34 −1
@@ -8,6 +8,10 @@
88 // 2. La respuesta del turno en curso se pinta ANTES del mensaje encolado.
99 // 3. Cuando le toca, deja de estar en cola y el modelo lo recibe.
1010 // 4. El botón ■ sí para, y lo que esperaba en cola se marca descartado.
11+// 5. Con OTRA conversación generando, lo que mandas aquí espera (⏳) también
12+// el primero, y cada burbuja deja de estar en cola cuando empieza SU
13+// turno: antes la marca se decidía por conversación y se le quitaba a la
14+// primera en cola, y la respuesta al primero salía debajo del segundo.
1115 //
1216 // BASE=http://127.0.0.1:8898 node tests/enterqueue.mjs
1317 import { chromium } from 'playwright';
@@ -28,7 +32,8 @@
2832 window.__prov = { llamadas: [], abortadas: 0, async chat(h, s, cb, signal) {
2933 const q = [...h].reverse().find(m => m.role === 'user')?.content || '';
3034 this.llamadas.push(q);
31- for (let i = 0; i < 40; i++) {
35+ const n = this.pasosPara?.(q) ?? 40;
36+ for (let i = 0; i < n; i++) {
3237 if (signal?.aborted) { this.abortadas++; throw new DOMException('Parado', 'AbortError'); }
3338 cb('·'); await dormir(25);
3439 }
@@ -80,6 +85,34 @@
8085 ok('4 · lo que esperaba en cola no se manda y se marca descartado', !e4.llamadas.includes('cuarto') && e4.descartados.includes('cuarto') && e4.enCola.length === 0, JSON.stringify(e4));
8186 ok('4 · «(Parado.)» queda encima del descartado', e4.orden.indexOf('A:(Parado.)') >= 0 && e4.orden.indexOf('A:(Parado.)') < e4.orden.indexOf('U:cuarto'), JSON.stringify(e4.orden));
8287
88+// 5 · otra conversación tiene el modelo
89+await p.evaluate(async () => {
90+ const conv = window.elffussClaw.conv;
91+ window.__prov.pasosPara = q => q === 'B larga' ? 120 : 30; // B genera un buen rato
92+ const A = conv.create();
93+ const B = conv.create();
94+ conv.switchTo(A.id); // en pantalla, A
95+ conv.send(B.id, 'B larga');
96+});
97+await p.waitForFunction(() => window.__prov.llamadas.includes('B larga'), null, { timeout: 5000 });
98+await p.fill('#prompt', 'A-uno');
99+await p.press('#prompt', 'Enter');
100+await p.fill('#prompt', 'A-dos');
101+await p.press('#prompt', 'Enter');
102+await p.waitForTimeout(150);
103+const pensando = () => p.evaluate(() => document.querySelectorAll('#chat-log > .msg.thinking').length);
104+const e5a = { ...(await estado()), pensando: await pensando() };
105+ok('5 · con B generando, el PRIMER mensaje de A también espera (⏳), y el segundo', JSON.stringify(e5a.enCola) === '["A-uno","A-dos"]' && e5a.pensando === 0, JSON.stringify({ enCola: e5a.enCola, pensando: e5a.pensando }));
106+await p.waitForFunction(() => window.__prov.llamadas.includes('A-uno'), null, { timeout: 10000 });
107+await p.waitForTimeout(100);
108+const e5b = await estado();
109+const ordenA = o => o.filter(x => /^U:A-|^A:respuesta a A-|^\?:/.test(x)).map(x => x.startsWith('?:') ? 'pensando' : x);
110+ok('5 · al empezar A-uno solo él deja de estar en cola; A-dos sigue esperando', JSON.stringify(e5b.enCola) === '["A-dos"]', JSON.stringify(e5b.enCola));
111+ok('5 · …y «pensando» queda entre los dos', JSON.stringify(ordenA(e5b.orden)) === '["U:A-uno","pensando","U:A-dos"]', JSON.stringify(ordenA(e5b.orden)));
112+await p.waitForFunction(() => !window.elffussClaw.conv.isBusy(), null, { timeout: 15000 });
113+const e5c = await estado();
114+ok('5 · cada respuesta queda debajo de SU mensaje', JSON.stringify(ordenA(e5c.orden)) === '["U:A-uno","A:respuesta a A-uno","U:A-dos","A:respuesta a A-dos"]', JSON.stringify(ordenA(e5c.orden)));
115+
83116 console.log('\n errores JS:', errs[0] || 'ninguno');
84117 ok('sin errores de página', errs.length === 0, errs.join(' | '));
85118 console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ ENTER ENCOLA, ■ PARA');
modified tests/stopqueue.mjs +13 −1
@@ -9,7 +9,8 @@
99 // terminaba, y al recargar el mensaje parado se volvía a ejecutar.
1010 // 4. El botón ■ no se repintaba al cambiar de pestaña.
1111 // 5. Tras pulsar ■ no cambiaba nada hasta que el turno se soltaba: ahora sale
12-// «Parando…», deshabilitado y con aria-busy.
12+// «Parando…», deshabilitado y con aria-busy, y de ahí pasa a «Enviar» sin
13+// volver un momento a «Parar».
1314 // Y la tarjeta de un objetivo parado dice «parado», no «completado».
1415 //
1516 // Modelo de mentira inyectado por import('/js/conversations.js'): lento, cuenta
@@ -221,6 +222,13 @@
221222 await p.fill('#prompt', 'otro trabajo largo');
222223 await p.click('#btn-send');
223224 await p.waitForFunction(() => document.getElementById('btn-send').classList.contains('is-stop'), null, { timeout: 5000 }).catch(() => {});
225+// Cada nombre accesible que toma el botón desde aquí hasta «Enviar», en orden.
226+await p.evaluate(() => {
227+ const b = document.getElementById('btn-send');
228+ window.__etiquetas5 = [b.getAttribute('aria-label')];
229+ window.__obs5 = new MutationObserver(() => { const l = b.getAttribute('aria-label'); if (window.__etiquetas5.at(-1) !== l) window.__etiquetas5.push(l); });
230+ window.__obs5.observe(b, { attributes: true, attributeFilter: ['aria-label'] });
231+});
224232 await p.click('#btn-send');
225233 await p.waitForTimeout(150); // la región viva se escribe en otro tick
226234 const parando = await boton();
@@ -240,6 +248,7 @@
240248 await p.waitForFunction(() => !document.getElementById('btn-send').hasAttribute('aria-disabled') && !document.getElementById('btn-send').classList.contains('sending'), null, { timeout: 8000 }).catch(() => {});
241249 await p.waitForTimeout(150);
242250 const despues = await boton();
251+const etiquetas5 = await p.evaluate(() => { window.__obs5.disconnect(); return window.__etiquetas5; });
243252 ok('5 · justo tras el clic: «Parando…», aria-disabled y aria-busy, sin disabled', parando.texto === 'Parando…' && parando.ariaDisabled === 'true' && !parando.disabled && parando.aria === 'true', JSON.stringify(parando));
244253 ok('5 · …el foco sigue en el botón (antes caía a <body>)', parando.foco === 'btn-send', parando.foco);
245254 ok('5 · …y la región viva dice «Parando…»', parando.anuncio === 'Parando…', JSON.stringify(parando.anuncio));
@@ -247,6 +256,9 @@
247256 ok('5 · al soltarse el turno vuelve a «Enviar», sin aria-disabled ni aria-busy', !despues.disabled && despues.ariaDisabled === null && despues.title === 'Enviar' && despues.aria === null, JSON.stringify(despues));
248257 ok('5 · …con el foco todavía en el botón', despues.foco === 'btn-send', despues.foco);
249258 ok('5 · …y la región viva dice «Parado.»', despues.anuncio === 'Parado.', JSON.stringify(despues.anuncio));
259+// Antes, al soltarse el turno el botón volvía un momento a ■ «Parar» habilitado
260+// (mientras se guardaba la conversación) antes de quedar en «Enviar».
261+ok('5 · de «Parando…» pasa directo a «Enviar», sin volver a «Parar»', JSON.stringify(etiquetas5) === JSON.stringify(['Parar', 'Parando…', 'Enviar']), JSON.stringify(etiquetas5));
250262
251263 // 5b. Lo mismo con el teclado: Espacio sobre el botón para, y el foco se queda.
252264 await p.evaluate(async () => {
modified web/js/conversations.js +21 −19
@@ -299,24 +299,26 @@
299299 if (conv.queue.length) pump(conv);
300300 }
301301
302-export function send(id, text) {
302+// Cada mensaje de la cola lleva su id: la UI marca «en cola» (⏳) la burbuja de
303+// ESE mensaje y se la quita cuando empieza su turno ('turn' trae el item). Los
304+// tres envíos devuelven el id.
305+const genQid = () => 'q' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
306+function encola(id, kind, text) {
303307 const conv = convs.get(id);
304- if (!conv) return;
305- conv.queue.push({ kind: 'chat', text });
308+ if (!conv) return null;
309+ const item = { kind, text, id: genQid() };
310+ conv.queue.push(item);
306311 persistConv(conv);
307312 pump(conv);
313+ return item.id;
308314 }
309315
316+export function send(id, text) { return encola(id, 'chat', text); }
317+
310318 // 🎯 Modo Objetivo: en vez de un turno de chat normal, el mensaje se trata
311319 // como un objetivo — se planifica en tareas y se ejecutan una a una (ver
312320 // goal.js, mismo patrón planificador/ejecutor de clonagent).
313-export function startGoal(id, text) {
314- const conv = convs.get(id);
315- if (!conv) return;
316- conv.queue.push({ kind: 'goal', text });
317- persistConv(conv);
318- pump(conv);
319-}
321+export function startGoal(id, text) { return encola(id, 'goal', text); }
320322
321323 // ⛏ Hard Work: lee el proyecto entero por partes. Va por la MISMA cola que el
322324 // resto: así el ■ lo para, la conversación se ve ocupada (el cerebro CEO
@@ -325,13 +327,7 @@
325327 // Quien sabe leer el proyecto (main.js) registra cómo se ejecuta.
326328 let hardWorkRunner = null;
327329 export function setHardWorkRunner(fn) { hardWorkRunner = fn; }
328-export function startHardWork(id, text) {
329- const conv = convs.get(id);
330- if (!conv) return;
331- conv.queue.push({ kind: 'hard', text });
332- persistConv(conv);
333- pump(conv);
334-}
330+export function startHardWork(id, text) { return encola(id, 'hard', text); }
335331
336332 // true cuando le toca el turno; false si la parada llega antes.
337333 function turnoOParada(turno, signal) {
@@ -436,11 +432,17 @@
436432 if (conv.aborter === aborter) conv.aborter = null;
437433 if (conv.queue[0] === item) conv.queue.shift();
438434 conv.updatedAt = Date.now();
439- if (conv.parando) { conv.parando = false; onChange('stopping', conv.id, false); }
435+ // «Parando…» se quita aquí solo si hay otro turno detrás. Si la cola queda
436+ // vacía se quita DESPUÉS del bucle, junto con `pumping`: quitarlo aquí, con
437+ // la conversación aún «trabajando» mientras se guarda, devolvía el botón a
438+ // un ■ «Parar» habilitado durante ese rato antes de pasar a «Enviar».
439+ if (conv.parando && conv.queue.length) { conv.parando = false; onChange('stopping', conv.id, false); }
440440 await persistConv(conv);
441441 }
442- conv.parando = false; // una parada que llegó entre turnos ya no tiene nada que esperar
442+ const sueltaParada = conv.parando; // una parada que llegó entre turnos ya no tiene nada que esperar
443+ conv.parando = false;
443444 conv.pumping = false;
445+ if (sueltaParada) onChange('stopping', conv.id, false);
444446 onChange('pumping', conv.id, false);
445447 }
446448
modified web/js/main.js +35 −17
@@ -296,10 +296,21 @@
296296 }
297297 }
298298 }
299- if (active.pumping) activeThinking = thinkingBubble();
299+ // «Pensando» solo si hay un turno EN MARCHA: esperando el modelo (lo tiene
300+ // otra conversación) lo que se ve es el mensaje en cola, no una elfa pensando.
301+ if (active.pumping && active.turno) activeThinking = thinkingBubble();
300302 // Lo que espera en la cola todavía no está en el historial: sin esto, al
301303 // volver a la pestaña los mensajes encolados desaparecían de la vista.
302- for (const it of active.queue) if (it !== active.turno) addMsg('user queued', typeof it === 'string' ? it : it.text).title = t('queuedTitle');
304+ for (const it of active.queue) if (it !== active.turno) burbujaEnCola(typeof it === 'string' ? it : it.text, it?.id);
305+}
306+
307+// Un mensaje que espera su turno (⏳). Lleva el id de su item de la cola para
308+// quitarle la marca a ÉL cuando empiece, no a la primera burbuja en cola.
309+function burbujaEnCola(text, qid) {
310+ const d = addMsg('user queued', text);
311+ d.title = t('queuedTitle');
312+ if (qid) d.dataset.qid = qid;
313+ return d;
303314 }
304315
305316 // evento del módulo de conversaciones: 'switch' (cambiaste de pestaña o se
@@ -309,16 +320,20 @@
309320 // refleja su punto de «ocupada» en la barra de pestañas.
310321 function onConvEvent(kind, id, payload) {
311322 if (kind === 'turn') {
312- // Un mensaje encolado empieza: deja de estar «en cola» y la burbuja de
313- // «pensando» pasa debajo de él (era la del turno anterior, más arriba).
323+ // Empieza un mensaje: SU burbuja deja de estar «en cola» (se busca por el
324+ // id del item; antes se desmarcaba la primera en cola, que podía ser otra) y
325+ // la de «pensando» se pone debajo de él, encima de lo que siga esperando.
314326 const active = conv.getActive();
315327 if (!active || id !== active.id) return;
316- const enCola = $('chat-log').querySelector(':scope > .msg.user.queued');
317- if (enCola) {
318- enCola.classList.remove('queued');
319- enCola.removeAttribute('title');
320- if (activeThinking) { activeThinking.remove(); activeThinking = thinkingBubble(); }
328+ const log = $('chat-log');
329+ const qid = payload && typeof payload === 'object' ? payload.id : null;
330+ const burbuja = qid ? log.querySelector(`:scope > .msg.user[data-qid="${CSS.escape(qid)}"]`) : log.querySelector(':scope > .msg.user.queued');
331+ if (burbuja?.classList.contains('queued')) {
332+ burbuja.classList.remove('queued');
333+ burbuja.removeAttribute('title');
321334 }
335+ activeThinking?.remove();
336+ activeThinking = thinkingBubble();
322337 return;
323338 }
324339 if (kind !== 'event') renderTabsBar();
@@ -331,9 +346,10 @@
331346 if (kind === 'pumping') {
332347 // NO deshabilitar el botón mientras genera: se convierte en PARAR. Antes se
333348 // ponía disabled=payload, y por eso no había forma de cortar un run largo.
349+ // «Pensando» lo pone 'turn', cuando el mensaje empieza de verdad: mientras
350+ // espera el modelo (lo tiene otra conversación) no hay nada pensando.
334351 paintSendButton();
335- if (payload) { if (!activeThinking) activeThinking = thinkingBubble(); }
336- else { activeThinking?.remove(); activeThinking = null; }
352+ if (!payload) { activeThinking?.remove(); activeThinking = null; }
337353 return;
338354 }
339355 if (kind === 'stopping') {
@@ -366,12 +382,14 @@
366382 function send(text, modo) {
367383 const active = conv.getActive();
368384 if (!active) return;
369- // Si la elfa ya está con algo, el mensaje espera su turno y se ve así (⏳).
370- const burbuja = addMsg(active.pumping || active.queue.length ? 'user queued' : 'user', text);
371- if (burbuja.classList.contains('queued')) burbuja.title = t('queuedTitle');
372- if (modo === 'hard') conv.startHardWork(active.id, text);
373- else if (goalMode) conv.startGoal(active.id, text);
374- else conv.send(active.id, text);
385+ // Si el modelo ya está con algo (en ESTA conversación o en otra: hay un solo
386+ // modelo y se turnan), el mensaje espera su turno y se ve así (⏳) hasta que
387+ // empiece el suyo.
388+ const burbuja = conv.isBusy() ? burbujaEnCola(text) : addMsg('user', text);
389+ const qid = modo === 'hard' ? conv.startHardWork(active.id, text)
390+ : goalMode ? conv.startGoal(active.id, text)
391+ : conv.send(active.id, text);
392+ if (qid) burbuja.dataset.qid = qid;
375393 }
376394
377395 // Pestañas de conversación con semántica de pestañas: la activa entra con Tab,