Elffuss BraidHub

utopia-ia/elffuss-code public

Feedback, Clear cache, the 💾 chip and the model pill keep keyboard focus

The pattern the Stop button already left behind was still in four places,
and each dropped keyboard focus to <body> for good:

- Feedback "Send" and Settings' "Clear cache" set `disabled` on the focused
  button while they work, and the browser blurs a disabled button. They are
  now marked busy with aria-disabled and aria-busy (ocupa()), stay focused,
  look busy in code.css, and ignore a second press while busy, so a second
  Enter does not send the feedback twice.
- The 💾 chip hides itself once nothing is left to count. Before hiding with
  focus inside, it now passes focus to the next control in the header (the
  previous one, or the prompt, if there is none). What was freed is still
  said in the status bar, a live region.
- The model pill's Retry removed its own buttons and ✕ hid the pill, both
  with focus inside. Both now return focus to where it was before it entered
  the pill, or to the model dot (the landing's open button, or the prompt,
  when that is not on screen). The retry's progress and result are still
  announced by the pill itself.

tests/storage-honest.mjs drives the chip, "Clear cache" and "Send" with the
keyboard and records every focus loss: focus moves from the chip to the
history button, stays on "Clear cache" and on "Send", and a second Enter while
sending sends nothing. tests/messages-ux.mjs reaches Retry from the model
card: focus returns to the card after the retry and after it fails again, and
✕ returns it there too. Against the previous main.js 5 of these checks fail.
Changeseta6879f75021ca285f6a98f97eb5ea5177f27d6caefbc1c587f2923a5bf9fbcec
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-11 17:34 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 17:34 +02:00
Parents9e18172235f0

Browse the files at this changeset

4 files changed

modified tests/messages-ux.mjs +18 −2
@@ -2,6 +2,8 @@
22 //
33 // 1. Fallo al cargar el modelo: en palabras de persona («sin conexión…», no
44 // «Failed to fetch»), en una región viva, con «Reintentar» que reintenta.
5+// Con el teclado, Reintentar y ✕ devuelven el foco a donde estaba (antes
6+// quitaban sus propios botones con el foco dentro y caía a <body>).
57 // 2. Skills: sin conexión, «Explorar» lo dice dentro del panel con
68 // «Reintentar»; un repo que no vale se dice en línea, sin alert().
79 // 3. El modo Básico manda a ⚙️ Ajustes → Cerebro, no a un «selector 🧠» que
@@ -53,9 +55,23 @@
5355 const pildora = await p.evaluate(() => ({ txt: document.getElementById('model-progress-text').textContent, rol: document.getElementById('model-progress').getAttribute('role'), reintentar: !!document.querySelector('#model-progress .mp-acciones button') }));
5456 ok('1 · el fallo se dice en palabras de persona, no «Failed to fetch»', /no se pudo descargar/.test(pildora.txt) && !/Failed to fetch/.test(pildora.txt), JSON.stringify(pildora));
5557 ok('1 · la píldora es una región viva con «Reintentar»', pildora.rol === 'status' && pildora.reintentar, JSON.stringify(pildora));
56-await p.locator('#model-progress .mp-acciones button', { hasText: 'Reintentar' }).click();
57-await p.waitForTimeout(600);
58+// Con el teclado: desde la tarjeta del modelo se llega a «Reintentar» y se
59+// pulsa. Reintentar quita sus propios botones, y el foco caía en <body>; ahora
60+// vuelve a donde estaba.
61+await p.evaluate(() => { const c = [...document.querySelectorAll('#settings-panel .model-card')].find(x => /Qwen3.5-0.8B/.test(x.textContent)); if (c) c.id = 'tarjeta-qwen'; });
62+await p.focus('#tarjeta-qwen');
63+await p.locator('#model-progress .mp-acciones button', { hasText: 'Reintentar' }).focus();
64+await p.keyboard.press('Enter');
65+const trasReintentar = await p.evaluate(() => document.activeElement?.id || document.activeElement?.tagName);
66+await p.waitForFunction(() => window.__cargas === 2 && /No pude cargar/.test(document.getElementById('model-progress-text').textContent), null, { timeout: 8000 }).catch(() => {});
5867 ok('1 · «Reintentar» vuelve a intentar la carga', await p.evaluate(() => window.__cargas) === 2, String(await p.evaluate(() => window.__cargas)));
68+const trasFallar = await p.evaluate(() => document.activeElement?.id || document.activeElement?.tagName);
69+ok('1 · con el teclado, el foco vuelve a la tarjeta y no a <body>, también cuando vuelve a fallar',
70+ trasReintentar === 'tarjeta-qwen' && trasFallar === 'tarjeta-qwen', `${trasReintentar} → ${trasFallar}`);
71+await p.locator('#model-progress .mp-acciones button[aria-label]').focus();
72+await p.keyboard.press('Enter');
73+const trasCerrar = await p.evaluate(() => ({ oculta: document.getElementById('model-progress').hidden, foco: document.activeElement?.id || document.activeElement?.tagName }));
74+ok('1 · ✕ esconde la píldora y el foco vuelve a la tarjeta, no a <body>', trasCerrar.oculta && trasCerrar.foco === 'tarjeta-qwen', JSON.stringify(trasCerrar));
5975
6076 // 2 · skills sin conexión y repo que no vale
6177 await p.evaluate(() => document.getElementById('settings-panel').hidden || document.getElementById('btn-settings').click());
modified tests/storage-honest.mjs +37 −6
@@ -12,6 +12,10 @@
1212 // sin tocar lo demás, diciendo cuánto se liberó. Con un SDK de broker que
1313 // sabe del almacén compartido, se cuentan y vacían también el broker por
1414 // defecto y los hosts del motor, todos a la vez.
15+// 4. Con el teclado, el foco no se pierde: Enviar y «Vaciar caché» lo
16+// conservan mientras trabajan (antes se deshabilitaban con el foco dentro
17+// y caía a <body>), y el chip 💾, que desaparece al vaciar, lo pasa al
18+// control de al lado.
1519 // Ningún broker de verdad: sus páginas las contesta un doble local.
1620 //
1721 // BASE=http://127.0.0.1:8898 node tests/storage-honest.mjs
@@ -37,8 +41,18 @@
3741 const ctx = await b.newContext({ locale: 'es-ES' });
3842 await ctx.route(BROKERS, r => { brokersPedidos.push(r.request().url()); return r.fulfill({ status: 200, contentType: 'text/html', body: BROKER_FALSO }); });
3943 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} window.confirm = () => true; });
44+// Cada vez que el foco se pierde sin ir a ningún sitio (un botón que se
45+// deshabilita o se esconde con el foco dentro), queda apuntado aquí.
46+await ctx.addInitScript(() => {
47+ window.__focoPerdido = [];
48+ document.addEventListener('focusout', e => { if (!e.relatedTarget) window.__focoPerdido.push(e.target.id || e.target.tagName); }, true);
49+});
4050 const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } });
4151 const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
52+// Pulsa con el teclado (como quien no usa ratón) y dice dónde acabó el foco y
53+// si se perdió por el camino.
54+const conTeclado = async sel => { await p.focus(sel); await p.evaluate(() => { window.__focoPerdido = []; }); await p.keyboard.press('Enter'); };
55+const foco = () => p.evaluate(() => ({ en: document.activeElement?.id || document.activeElement?.tagName, perdido: window.__focoPerdido }));
4256
4357 const MB = 1048576;
4458 await p.goto(BASE + '/manifest.json');
@@ -56,8 +70,12 @@
5670 // 3 · el chip cuenta solo los modelos
5771 const chip = await p.evaluate(() => ({ txt: document.getElementById('disk-chip').textContent, title: document.getElementById('disk-chip').title }));
5872 ok('3 · el chip cuenta solo los modelos (3 MB), no los 3 MB de datos del proyecto', /💾 3 MB/.test(chip.txt), JSON.stringify(chip));
59-await p.click('#disk-chip');
73+await conTeclado('#disk-chip');
6074 await p.waitForFunction(() => /Liberados/.test(document.getElementById('statusbar').textContent), null, { timeout: 10000 }).catch(() => {});
75+await p.waitForFunction(() => document.getElementById('disk-chip').hidden, null, { timeout: 5000 }).catch(() => {});
76+const fChip = await foco();
77+ok('3 · con el teclado: al desaparecer el chip, el foco pasa al control de al lado, nunca a <body>',
78+ fChip.en === 'btn-history' && !fChip.perdido.length, JSON.stringify(fChip));
6179 const tras = await p.evaluate(async () => {
6280 const root = await navigator.storage.getDirectory();
6381 const hay = async (n) => { try { await root.getDirectoryHandle(n); return true; } catch { return false; } };
@@ -83,7 +101,8 @@
83101 await p.waitForTimeout(500);
84102 const tarjeta = await p.evaluate(() => [...document.querySelectorAll('#settings-panel .prov-card')].map(c => c.textContent).find(t => /modelos guardados|Ningún modelo/.test(t)) || '');
85103 ok('3 · la tarjeta de Ajustes habla de modelos guardados (1 MB)', /1 MB en modelos guardados/.test(tarjeta), tarjeta.slice(0, 120));
86-await p.locator('#settings-panel button', { hasText: 'Vaciar caché' }).click();
104+await p.evaluate(() => { const b = [...document.querySelectorAll('#settings-panel button')].find(x => x.textContent === 'Vaciar caché'); if (b) b.id = 'prueba-vaciar'; });
105+await conTeclado('#prueba-vaciar');
87106 await p.waitForTimeout(800);
88107 const ajustes = await p.evaluate(async () => {
89108 const root = await navigator.storage.getDirectory();
@@ -91,19 +110,31 @@
91110 return { hay, msg: [...document.querySelectorAll('#settings-panel [role="status"]')].map(n => n.textContent).join(' | ') };
92111 });
93112 ok('3 · «Vaciar caché» de Ajustes vacía los modelos y lo dice', !ajustes.hay && /Liberados 1 MB/.test(ajustes.msg), JSON.stringify(ajustes));
113+const fVaciar = await foco();
114+ok('3 · …y con el teclado el foco se queda en el botón todo el rato (antes se deshabilitaba y caía a <body>)',
115+ fVaciar.en === 'prueba-vaciar' && !fVaciar.perdido.length, JSON.stringify(fVaciar));
94116
95117 // 2 · Feedback: el 404 del servidor local NO es «enviado»
96118 await p.fill('#tel-feedback', 'un fallo que vi');
97-await p.click('#tel-send');
119+await conTeclado('#tel-send');
98120 await p.waitForTimeout(600);
99121 const f1 = await p.evaluate(() => ({ msg: document.getElementById('tel-msg').textContent, texto: document.getElementById('tel-feedback').value }));
100122 ok('2 · si el servidor no lo acepta, dice que falló', /No se pudo enviar/.test(f1.msg) && !/enviado, gracias/.test(f1.msg), JSON.stringify(f1));
101123 ok('2 · …y conserva el texto', f1.texto === 'un fallo que vi', JSON.stringify(f1));
102-await p.route('**/proxy/report', r => r.fulfill({ status: 200, contentType: 'application/json', body: '{"ok":true}' }));
103-await p.click('#tel-send');
104-await p.waitForTimeout(600);
124+const fEnviar = await foco();
125+ok('2 · con el teclado el foco sigue en «Enviar» mientras manda y después (antes caía a <body>)',
126+ fEnviar.en === 'tel-send' && !fEnviar.perdido.length, JSON.stringify(fEnviar));
127+// El servidor lo acepta (y tarda un poco en contestar): mientras manda, el botón
128+// está ocupado (aria-busy) y un segundo Enter no manda otro.
129+let envios = 0;
130+await p.route('**/proxy/report', async r => { envios++; await new Promise(res => setTimeout(res, 300)); return r.fulfill({ status: 200, contentType: 'application/json', body: '{"ok":true}' }); });
131+await conTeclado('#tel-send');
132+const ocupado = await p.evaluate(() => document.getElementById('tel-send').getAttribute('aria-busy'));
133+await p.keyboard.press('Enter');
134+await p.waitForFunction(() => /enviado, gracias/.test(document.getElementById('tel-msg').textContent), null, { timeout: 10000 }).catch(() => {});
105135 const f2 = await p.evaluate(() => ({ msg: document.getElementById('tel-msg').textContent, texto: document.getElementById('tel-feedback').value }));
106136 ok('2 · si el servidor lo acepta, lo da por enviado y vacía la caja', /enviado, gracias/.test(f2.msg) && f2.texto === '', JSON.stringify(f2));
137+ok('2 · mientras manda está ocupado (aria-busy) y un segundo Enter no manda otro', ocupado === 'true' && envios === 1, `aria-busy ${ocupado} · ${envios} envíos`);
107138 await p.unroute('**/proxy/report');
108139
109140 // 1 · «Guardar solo» guarda de verdad
modified web/css/code.css +3 −0
@@ -592,6 +592,9 @@
592592 .prov-head { display: flex; align-items: center; gap: 8px; }
593593 .prov-head b { flex: 1; font-size: .84rem; }
594594 .prov-use { background: linear-gradient(135deg, var(--accent), var(--accent2)); border: none; color: #fff; border-radius: 6px; padding: 4px 10px; font-size: .74rem; cursor: pointer; }
595+/* Ocupado (mandando, vaciando): con aria-disabled y no con disabled, para no
596+ sacarlo del foco (ver ocupa() en main.js); esto es lo que se ve. */
597+.prov-use[aria-busy="true"], .chip[aria-busy="true"] { opacity: .6; cursor: progress; }
595598 .prov-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
596599 .prov-fields.hide { display: none; }
597600 .prov-fields input { background: var(--bg); border: 1px solid var(--line); color: var(--fg); border-radius: 6px; padding: 6px 9px; font-size: .78rem; width: 100%; }
modified web/js/main.js +56 −11
@@ -779,9 +779,9 @@
779779 if (reintentar) {
780780 const acc = document.createElement('div'); acc.className = 'mp-acciones';
781781 const r = document.createElement('button'); r.type = 'button'; r.textContent = t('retry');
782- r.onclick = () => { acc.remove(); reintentar(); };
782+ r.onclick = () => { sueltaFocoPildora(); acc.remove(); reintentar(); };
783783 const x = document.createElement('button'); x.type = 'button'; x.textContent = '✕'; x.setAttribute('aria-label', t('close'));
784- x.onclick = () => showModelProgress(null);
784+ x.onclick = () => { sueltaFocoPildora(); showModelProgress(null); };
785785 acc.append(r, x);
786786 box.querySelector('.mp-body').appendChild(acc);
787787 }
@@ -794,6 +794,21 @@
794794 bar.style.width = pct + '%';
795795 }
796796 }
797+// Reintentar quita sus propios botones y ✕ esconde la píldora: con el foco en
798+// ellos, caía en <body> y no volvía. Se devuelve a donde estaba antes de entrar
799+// en la píldora y, si eso ya no se ve, al punto del modelo (que dice cómo va la
800+// carga). Lo que pasa después lo cuenta la píldora, que es una región viva.
801+let antesDePildora = null;
802+$('model-progress').addEventListener('focusin', e => {
803+ if (!$('model-progress').contains(e.relatedTarget)) antesDePildora = e.relatedTarget;
804+});
805+function sueltaFocoPildora() {
806+ const box = $('model-progress');
807+ if (!box.contains(document.activeElement)) return; // el foco no estaba aquí: no se toca
808+ const destino = [antesDePildora, $('model-dot'), $('open-project'), $('prompt')].find(x => seVe(x) && !box.contains(x));
809+ antesDePildora = null;
810+ destino?.focus();
811+}
797812
798813 // El punto de estado del modelo dice con palabras qué modelo es y cómo está
799814 // (antes era solo un color, con el título «modelo» siempre), y es un botón que
@@ -1357,12 +1372,13 @@
13571372 // creía haberlo mandado y lo había perdido.
13581373 telCard.querySelector('#tel-send').onclick = async () => {
13591374 const btn = telCard.querySelector('#tel-send');
1375+ if (ocupado(btn)) return; // ya se está mandando
13601376 const ta = telCard.querySelector('#tel-feedback');
13611377 const msg = telCard.querySelector('#tel-msg');
13621378 const text = ta.value.trim();
13631379 msg.style.color = '';
13641380 if (!text) { msg.textContent = t("setTelEmpty"); return; }
1365- btn.disabled = true; btn.setAttribute('aria-busy', 'true');
1381+ ocupa(btn, true);
13661382 msg.textContent = t('setTelSending');
13671383 const wasEnabled = telemetry.isEnabled();
13681384 if (!wasEnabled) telemetry.setEnabled(true); // el envío manual es explícito, se permite aunque el automático esté apagado
@@ -1370,7 +1386,7 @@
13701386 try { enviado = await telemetry.sendFeedback(text); }
13711387 finally {
13721388 if (!wasEnabled) telemetry.setEnabled(false); // no activa el automático de fondo si no lo pidió
1373- btn.disabled = false; btn.removeAttribute('aria-busy');
1389+ ocupa(btn, false);
13741390 }
13751391 if (!enviado) { msg.textContent = t('setTelFailed'); msg.style.color = '#ff6b8b'; return; }
13761392 ta.value = '';
@@ -3193,17 +3209,30 @@
31933209 // Tamaño legible: MB por debajo de 1 GB.
31943210 function tamano(n) { return n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : Math.round(n / 1048576) + ' MB'; }
31953211
3212+// Un botón ocupado (mandando, vaciando) se marca así y NO con `disabled`:
3213+// deshabilitar el botón que tiene el foco lo saca del foco, y quien va con
3214+// teclado se quedaba en <body> para siempre (lo mismo que se arregló en el botón
3215+// de parar, ver paintSendButton). aria-disabled se lo dice al lector, aria-busy
3216+// que está trabajando, y quien lo usa ignora los clics mientras tanto.
3217+function ocupa(b, si) {
3218+ if (si) { b.setAttribute('aria-disabled', 'true'); b.setAttribute('aria-busy', 'true'); }
3219+ else { b.removeAttribute('aria-disabled'); b.removeAttribute('aria-busy'); }
3220+}
3221+function ocupado(b) { return b.getAttribute('aria-busy') === 'true'; }
3222+
31963223 // Vaciar los modelos guardados: lo usan el chip 💾 y «Vaciar caché» de Ajustes.
31973224 // Devuelve el mensaje con lo que pasó (o null si el usuario canceló).
31983225 async function vaciarModelos(boton) {
3199- const m = await modelUsage();
3200- if (!confirm(t('clearModelsConfirm', { size: tamano(m.total) }) + (m.sharedOk ? '' : '\n\n' + t('clearModelsShared')))) return null;
3226+ if (ocupado(boton)) return null; // ya se está vaciando
32013227 const antes = boton.textContent;
3202- boton.disabled = true; boton.setAttribute('aria-busy', 'true');
3203- boton.textContent = t('setClearing');
3228+ ocupa(boton, true);
32043229 let r;
3205- try { r = await clearModels(); }
3206- finally { boton.disabled = false; boton.removeAttribute('aria-busy'); boton.textContent = antes; }
3230+ try {
3231+ const m = await modelUsage();
3232+ if (!confirm(t('clearModelsConfirm', { size: tamano(m.total) }) + (m.sharedOk ? '' : '\n\n' + t('clearModelsShared')))) return null;
3233+ boton.textContent = t('setClearing');
3234+ r = await clearModels();
3235+ } finally { ocupa(boton, false); boton.textContent = antes; }
32073236 let msg = t('clearModelsDone', { size: tamano(r.liberado) });
32083237 if (r.fallos.length) msg += ' ' + t('clearModelsFailed', { what: r.fallos.join(' · ') });
32093238 if (!r.sharedOk) msg += ' ' + t('clearModelsShared');
@@ -3211,6 +3240,15 @@
32113240 return msg;
32123241 }
32133242
3243+// El control a la vista más cercano a `el` en su grupo (el siguiente o, si no
3244+// hay, el anterior); si ninguno, el cuadro de texto del chat.
3245+function vecinoVisible(el) {
3246+ const vale = x => x.matches('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])') && !x.disabled && seVe(x);
3247+ for (let x = el.nextElementSibling; x; x = x.nextElementSibling) if (vale(x)) return x;
3248+ for (let x = el.previousElementSibling; x; x = x.previousElementSibling) if (vale(x)) return x;
3249+ return $('prompt');
3250+}
3251+
32143252 // Chip 💾: lo que ocupan los MODELOS (no el origen entero, que mezclaba
32153253 // conversaciones y el proyecto de prueba) y un clic para vaciarlos.
32163254 function mountDiskChip() {
@@ -3219,7 +3257,14 @@
32193257 async function paint() {
32203258 const { quota } = await cacheEstimate();
32213259 const m = await modelUsage();
3222- if (!m.total) { chip.hidden = true; return; }
3260+ if (!m.total) {
3261+ // Sin modelos el chip se esconde. Si tenía el foco (acabas de vaciar con
3262+ // él), el foco caía en <body> y no volvía: pasa antes al control de al lado
3263+ // en la cabecera. Lo que se liberó lo dice la barra de estado (región viva).
3264+ if (document.activeElement === chip) vecinoVisible(chip)?.focus();
3265+ chip.hidden = true;
3266+ return;
3267+ }
32233268 chip.hidden = false;
32243269 chip.textContent = '💾 ' + tamano(m.total);
32253270 chip.title = t('diskChipTitle', { size: tamano(m.total), quota: quota ? t('diskChipQuota', { quota: tamano(quota) }) : '' })