Elffuss BraidHub

utopia-ia/elffuss-code public

Enter while the agent works queues the message, only ■ stops

Pressing Enter while a turn was running stopped it, and the text stayed
unsent in the box, although each conversation accepts and queues messages.
The submit handler now stops only when the submitter is the ■ button (Enter
goes through requestSubmit() with no submitter). Enter with text sends it to
the conversation queue and shows it with the existing .msg.user.queued style
(⏳, with a title saying it goes out when the current work ends).

conversations.js emits 'turn' when an item really starts and keeps it in
conv.turno, so the UI drops the queued mark at that moment and moves the
thinking bubble under it. Output of the running turn is inserted above the
queued bubbles, so an answer never reads as a reply to a message that has not
started. renderActiveLog() repaints pending queue items, which used to vanish
when you switched tabs and came back. ■ empties the queue (that is what a
stop does), so the queued bubbles turn into "dropped" ones (struck through,
with a title) instead of waiting forever.

tests/enterqueue.mjs (?test-opfs, slow stand-in provider): Enter while busy
does not abort, empties the box and shows the message queued; the running
turn's answer lands above it; the model receives it when its turn comes; ■
stops and marks what was queued as dropped, below the "(Parado.)" line.
Against the previous main.js the first three checks fail.
Changeset405072fe561a6a885bcbccfc1833733a6ca6e95b7eff1039e155f82b20d12246
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 15:40 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:12 +02:00
Parents7fc4ec96dbaa

Browse the files at this changeset

5 files changed

added tests/enterqueue.mjs +87 −0
@@ -0,0 +1,87 @@
1+// Enter mientras la elfa trabaja ENCOLA el mensaje; solo el botón ■ para.
2+//
3+// Antes Enter con la elfa trabajando paraba el trabajo en curso y el texto se
4+// quedaba sin enviar en la caja, aunque conversations.js acepta y encola
5+// mensajes. Ahora:
6+// 1. Enter con texto mientras trabaja: no para, la caja se vacía y el mensaje
7+// aparece «en cola» (⏳) al final del chat.
8+// 2. La respuesta del turno en curso se pinta ANTES del mensaje encolado.
9+// 3. Cuando le toca, deja de estar en cola y el modelo lo recibe.
10+// 4. El botón ■ sí para, y lo que esperaba en cola se marca descartado.
11+//
12+// BASE=http://127.0.0.1:8898 node tests/enterqueue.mjs
13+import { chromium } from 'playwright';
14+const BASE = process.env.BASE || 'http://localhost:8799';
15+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
16+
17+const b = await chromium.launch();
18+const ctx = await b.newContext({ locale: 'es-ES' });
19+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
20+const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } });
21+const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
22+await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
23+await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.(), null, { timeout: 15000 });
24+
25+// proveedor lento que apunta qué recibe y cuántas veces lo paran
26+await p.evaluate(() => {
27+ const dormir = ms => new Promise(r => setTimeout(r, ms));
28+ window.__prov = { llamadas: [], abortadas: 0, async chat(h, s, cb, signal) {
29+ const q = [...h].reverse().find(m => m.role === 'user')?.content || '';
30+ this.llamadas.push(q);
31+ for (let i = 0; i < 40; i++) {
32+ if (signal?.aborted) { this.abortadas++; throw new DOMException('Parado', 'AbortError'); }
33+ cb('·'); await dormir(25);
34+ }
35+ return 'respuesta a ' + q;
36+ } };
37+ window.elffussClaw.conv.setProvider(window.__prov);
38+});
39+const estado = () => p.evaluate(() => ({
40+ busy: window.elffussClaw.conv.isBusy(),
41+ caja: document.getElementById('prompt').value,
42+ llamadas: window.__prov.llamadas.slice(), abortadas: window.__prov.abortadas,
43+ enCola: [...document.querySelectorAll('#chat-log > .msg.user.queued')].map(n => n.textContent),
44+ descartados: [...document.querySelectorAll('#chat-log > .msg.user.cancelled')].map(n => n.textContent),
45+ orden: [...document.querySelectorAll('#chat-log > .msg')].map(n => (n.classList.contains('user') ? 'U:' : n.classList.contains('assistant') ? 'A:' : '?:') + n.textContent.trim().slice(0, 30)),
46+}));
47+
48+await p.fill('#prompt', 'primero');
49+await p.press('#prompt', 'Enter');
50+await p.waitForFunction(() => window.__prov.llamadas.length === 1, null, { timeout: 5000 });
51+await p.fill('#prompt', 'segundo');
52+await p.press('#prompt', 'Enter');
53+await p.waitForTimeout(150);
54+const e1 = await estado();
55+ok('1 · Enter con la elfa trabajando NO para el turno en curso', e1.busy && e1.abortadas === 0, JSON.stringify(e1));
56+ok('1 · la caja se vacía (el mensaje salió)', e1.caja === '', JSON.stringify(e1.caja));
57+ok('1 · el mensaje aparece en cola (⏳)', e1.enCola.length === 1 && e1.enCola[0] === 'segundo', JSON.stringify(e1.enCola));
58+
59+await p.waitForFunction(() => window.__prov.llamadas.length === 2, null, { timeout: 8000 });
60+await p.waitForTimeout(100);
61+const e2 = await estado();
62+ok('3 · cuando le toca, el modelo recibe el mensaje encolado', e2.llamadas[1] === 'segundo', JSON.stringify(e2.llamadas));
63+ok('3 · …y deja de estar en cola', e2.enCola.length === 0, JSON.stringify(e2.enCola));
64+const iResp = e2.orden.findIndex(x => x.startsWith('A:respuesta a primero'));
65+const iSeg = e2.orden.findIndex(x => x === 'U:segundo');
66+ok('2 · la respuesta al primero va ANTES del segundo mensaje', iResp >= 0 && iSeg > iResp, JSON.stringify(e2.orden));
67+await p.waitForFunction(() => !window.elffussClaw.conv.isBusy(), null, { timeout: 8000 });
68+
69+// 4 · ■ para, y lo encolado queda descartado
70+await p.fill('#prompt', 'tercero');
71+await p.press('#prompt', 'Enter');
72+await p.waitForFunction(() => window.__prov.llamadas.length === 3, null, { timeout: 5000 });
73+await p.fill('#prompt', 'cuarto');
74+await p.press('#prompt', 'Enter');
75+await p.waitForTimeout(100);
76+await p.click('#btn-send');
77+await p.waitForFunction(() => !window.elffussClaw.conv.isBusy(), null, { timeout: 8000 });
78+const e4 = await estado();
79+ok('4 · el botón ■ sí para el turno', e4.abortadas === 1, JSON.stringify(e4));
80+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));
81+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));
82+
83+console.log('\n errores JS:', errs[0] || 'ninguno');
84+ok('sin errores de página', errs.length === 0, errs.join(' | '));
85+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ ENTER ENCOLA, ■ PARA');
86+await b.close();
87+process.exit(fails ? 1 : 0);
modified web/css/code.css +2 −0
@@ -303,6 +303,8 @@
303303 .msg.tool-result.err summary { color: #e5a53a; }
304304 .msg.user.queued { opacity: .55; }
305305 .msg.user.queued::after { content: ' ⏳'; }
306+/* encolado y descartado al pulsar ■ (parar vacía la cola) */
307+.msg.user.cancelled { opacity: .45; text-decoration: line-through; }
306308 .msg.thinking { background: var(--bg3); border: 1px dashed var(--line); color: var(--muted); font-size: .8rem; }
307309 .msg.thinking .gen { font-family: ui-monospace, monospace; font-size: .7rem; color: #5f6880; max-height: 168px; overflow-y: auto; white-space: pre-wrap; }
308310 .msg.thinking .gen.tool-preview { font-family: inherit; font-size: .78rem; color: var(--accent2); font-style: italic; }
modified web/js/conversations.js +4 −0
@@ -364,6 +364,9 @@
364364 try { onChange('event', conv.id, { type: 'aborted', text: '(Parado.)' }); } catch (e) { console.error('[elffuss] fallo pintando un evento de chat', e); }
365365 }
366366 if (tengoTurno && !signal.aborted && conv.queue[0] === item) {
367+ // Empieza DE VERDAD este mensaje: la UI deja de pintarlo «en cola».
368+ conv.turno = item;
369+ try { onChange('turn', conv.id, item); } catch (e) { console.error('[elffuss] fallo pintando el inicio de un turno', e); }
367370 // un fallo aquí (del modelo, de una tool, o del propio repintado en
368371 // main.js) NUNCA debe dejar la conversación "pumping" para siempre —
369372 // eso bloquearía sus futuros mensajes Y al cerebro CEO (isBusy()).
@@ -400,6 +403,7 @@
400403 telemetry.reportError('pump: ' + (e?.message || e), { stack: e?.stack || '' });
401404 try { onChange('event', conv.id, { type: 'error', text: 'Error interno: ' + (e?.message || e) }); } catch { /* ya está registrado arriba */ }
402405 } finally { if (tengoTurno) release(); }
406+ if (conv.turno === item) conv.turno = null;
403407 if (conv.aborter === aborter) conv.aborter = null;
404408 if (conv.queue[0] === item) conv.queue.shift();
405409 conv.updatedAt = Date.now();
modified web/js/i18n.js +6 −0
@@ -123,6 +123,9 @@
123123 setBridgeOtherOS: "otro sistema operativo",
124124 setBridgeOld: "¿Ya tenías un bridge y ahora no conecta? Descárgalo otra vez (versión 1.1.1): los anteriores no aceptan la dirección nueva de Elffuss Code.",
125125 setModelRulesName: "Básico (sin modelo)",
126+ // ronda UX 2026-10: cola, guardar, avisos honestos
127+ queuedTitle: "En cola: sale en cuanto termine lo de ahora",
128+ queuedCancelled: "Descartado: pulsaste ■ antes de que le tocara",
126129 },
127130 en: {
128131 ph: 'Type here… (@ attaches a file)',
@@ -241,6 +244,9 @@
241244 setBridgeOtherOS: "another operating system",
242245 setBridgeOld: "Already had a bridge and now it won't connect? Download it again (version 1.1.1): older ones don't accept Elffuss Code's new address.",
243246 setModelRulesName: "Basic (no model)",
247+ // UX round 2026-10: queue, save, honest notices
248+ queuedTitle: "Queued: it goes out as soon as the current work ends",
249+ queuedCancelled: "Dropped: you pressed ■ before its turn",
244250 },
245251 };
246252
modified web/js/main.js +57 −12
@@ -98,6 +98,18 @@
9898 });
9999 }
100100
101+// Todo lo que pinta el chat entra por aquí. Lo que se escribió mientras la elfa
102+// trabajaba espera AL FINAL, marcado «en cola» (⏳): lo que va llegando del turno
103+// en curso se coloca ANTES de esos mensajes, para que una respuesta no se lea
104+// como si contestara a un mensaje que todavía no ha empezado.
105+function appendLog(node) {
106+ const log = $('chat-log');
107+ // Los descartados al parar también hacen de tope mientras el turno parado se
108+ // suelta: su «(Parado.)» va encima de ellos, no debajo.
109+ const enCola = node.classList.contains('queued') ? null : log.querySelector(':scope > .msg.user.queued, :scope > .msg.user[data-parada]');
110+ if (enCola) log.insertBefore(node, enCola); else log.appendChild(node);
111+}
112+
101113 function addMsg(cls, text) {
102114 const div = document.createElement('div');
103115 div.className = 'msg ' + cls;
@@ -111,7 +123,7 @@
111123 } else {
112124 div.textContent = text;
113125 }
114- $('chat-log').appendChild(div);
126+ appendLog(div);
115127 $('chat-log').scrollTop = $('chat-log').scrollHeight;
116128 return div;
117129 }
@@ -131,7 +143,7 @@
131143 a.textContent = String(arg).slice(0, 60);
132144 div.appendChild(a);
133145 }
134- $('chat-log').appendChild(div);
146+ appendLog(div);
135147 $('chat-log').scrollTop = $('chat-log').scrollHeight;
136148 return div;
137149 }
@@ -145,7 +157,7 @@
145157 const pre = document.createElement('pre');
146158 pre.textContent = result.slice(0, 1500);
147159 det.append(sum, pre);
148- $('chat-log').appendChild(det);
160+ appendLog(det);
149161 $('chat-log').scrollTop = $('chat-log').scrollHeight;
150162 return det;
151163 }
@@ -165,7 +177,7 @@
165177 div = document.createElement('div');
166178 div.id = domId;
167179 div.className = 'msg plan-card';
168- $('chat-log').appendChild(div);
180+ appendLog(div);
169181 }
170182 div.innerHTML =
171183 `<span class="plan-status">${escapeHtml(PLAN_STATUS_LABEL[plan.status] || plan.status)}</span>` +
@@ -240,6 +252,9 @@
240252 }
241253 }
242254 if (active.pumping) activeThinking = thinkingBubble();
255+ // Lo que espera en la cola todavía no está en el historial: sin esto, al
256+ // volver a la pestaña los mensajes encolados desaparecían de la vista.
257+ for (const it of active.queue) if (it !== active.turno) addMsg('user queued', typeof it === 'string' ? it : it.text).title = t('queuedTitle');
243258 }
244259
245260 // evento del módulo de conversaciones: 'switch' (cambiaste de pestaña o se
@@ -248,6 +263,19 @@
248263 // Las conversaciones EN SEGUNDO PLANO nunca tocan el DOM visible — solo se
249264 // refleja su punto de «ocupada» en la barra de pestañas.
250265 function onConvEvent(kind, id, payload) {
266+ if (kind === 'turn') {
267+ // Un mensaje encolado empieza: deja de estar «en cola» y la burbuja de
268+ // «pensando» pasa debajo de él (era la del turno anterior, más arriba).
269+ const active = conv.getActive();
270+ if (!active || id !== active.id) return;
271+ const enCola = $('chat-log').querySelector(':scope > .msg.user.queued');
272+ if (enCola) {
273+ enCola.classList.remove('queued');
274+ enCola.removeAttribute('title');
275+ if (activeThinking) { activeThinking.remove(); activeThinking = thinkingBubble(); }
276+ }
277+ return;
278+ }
251279 if (kind !== 'event') renderTabsBar();
252280 // El botón es de la conversación ACTIVA: al cambiar de pestaña se repinta.
253281 // Antes se quedaba como lo dejó la anterior — un ■ sobre una conversación
@@ -263,7 +291,18 @@
263291 else { activeThinking?.remove(); activeThinking = null; }
264292 return;
265293 }
266- if (kind === 'stopping') { paintSendButton(); anunciarEnvio(payload ? t('stopping') : t('stopped')); return; }
294+ if (kind === 'stopping') {
295+ // Parar vacía la cola: lo que esperaba ya no se va a mandar, y se dice.
296+ if (payload) for (const m of $('chat-log').querySelectorAll(':scope > .msg.user.queued')) {
297+ m.classList.replace('queued', 'cancelled');
298+ m.title = t('queuedCancelled');
299+ m.dataset.parada = '1';
300+ }
301+ else for (const m of $('chat-log').querySelectorAll(':scope > .msg.user[data-parada]')) delete m.dataset.parada;
302+ paintSendButton();
303+ anunciarEnvio(payload ? t('stopping') : t('stopped'));
304+ return;
305+ }
267306 if (kind === 'event') {
268307 const ev = payload;
269308 if (ev.type === 'token') activeThinking?.tick(ev.text);
@@ -281,7 +320,9 @@
281320 function send(text) {
282321 const active = conv.getActive();
283322 if (!active) return;
284- addMsg('user', text);
323+ // Si la elfa ya está con algo, el mensaje espera su turno y se ve así (⏳).
324+ const burbuja = addMsg(active.pumping || active.queue.length ? 'user queued' : 'user', text);
325+ if (burbuja.classList.contains('queued')) burbuja.title = t('queuedTitle');
285326 if (goalMode) conv.startGoal(active.id, text);
286327 else conv.send(active.id, text);
287328 }
@@ -1180,13 +1221,17 @@
11801221 });
11811222 $('composer').addEventListener('submit', e => {
11821223 e.preventDefault();
1183- // Mientras el agente trabaja, el mismo botón PARA en vez de enviar. Si ya se
1184- // está parando, lo que se escriba con Enter va a la cola y sale en cuanto
1185- // termine; pulsar el propio botón, que dice «Parando…» y está aria-disabled,
1186- // no hace nada (requestSubmit() desde el cuadro de texto llega sin submitter).
1224+ // Mientras el agente trabaja, el BOTÓN para en vez de enviar. Enter no: con
1225+ // texto lo ENCOLA (cada conversación acepta y encola mensajes) y sale en
1226+ // cuanto termine lo de ahora. Antes Enter también paraba, y el texto se
1227+ // quedaba sin enviar en la caja. `submitter` es el botón solo en un clic (o
1228+ // Enter/Espacio con el foco en él); con Enter en el cuadro de texto
1229+ // (requestSubmit sin argumento) es null. Si ya se está parando, pulsar el
1230+ // propio botón, que dice «Parando…» y está aria-disabled, no hace nada.
11871231 const active = conv.getActive();
1188- if (active?.parando && e.submitter?.id === 'btn-send') return;
1189- if (active && active.pumping && !active.parando) { conv.stopActive(); return; }
1232+ const desdeBoton = e.submitter?.id === 'btn-send';
1233+ if (desdeBoton && active?.parando) return;
1234+ if (desdeBoton && active && active.pumping && !active.parando) { conv.stopActive(); return; }
11901235 const text = $('prompt').value.trim();
11911236 if (!text) return;
11921237 $('prompt').value = '';