Elffuss BraidHub

utopia-ia/elffuss-code public

The ⚡ speed chip keeps opening and hides for brains that do not measure

velocimetro.montar() runs on every engine load and added another chip click
listener and another document click listener each time. After the engine
was loaded twice a click toggled the panel twice and it never opened.
The listeners are now wired once. montar(null), or a provider without
alMedir, cancels the previous subscription and hides the chip and the
panel; changeModel() calls it for every brain that is not the engine
(Basic, ONNX, LiteRT, external, and the fallback to Basic after a failed
load). Before, the chip kept showing the engine's figures after switching
to another model. The chip has aria-haspopup/aria-controls/aria-expanded,
the panel is a labelled dialog, and Escape closes it and returns focus to
the chip.

tests/speedchip.mjs (stand-in engine with alMedir/ultimaMedida): mounted
twice the chip still opens the panel, aria-expanded and Escape, and
switching to Basic hides it and drops the subscription. Against main it
fails 6 checks.
Changesetc09c8aa724edcbdddbf82b1660ed33f18a50935b1f61350bd1271c076bafdc1c
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 16:52 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:16 +02:00
Parents6fb41f3536ee

Browse the files at this changeset

3 files changed

added tests/speedchip.mjs +59 −0
@@ -0,0 +1,59 @@
1+// Chip ⚡ de velocidad (velocimetro.js).
2+//
3+// 1. Con el motor cargado DOS veces (montar() otra vez), el clic sigue
4+// abriendo el panel. Antes cada montar() añadía otro par de oyentes: el
5+// clic abría y cerraba a la vez y el panel no se abría nunca.
6+// 2. aria-expanded en el chip, y Escape cierra el panel devolviendo el foco.
7+// 3. Al pasar a un cerebro que no mide (Básico, ONNX, externo) el chip se
8+// oculta; antes seguía enseñando las cifras del motor.
9+// El «motor» es de mentira: un proveedor con alMedir/ultimaMedida.
10+//
11+// BASE=http://127.0.0.1:8898 node tests/speedchip.mjs
12+import { chromium } from 'playwright';
13+const BASE = process.env.BASE || 'http://localhost:8799';
14+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
15+
16+const b = await chromium.launch();
17+const ctx = await b.newContext({ locale: 'es-ES' });
18+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
19+const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } });
20+const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
21+await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
22+await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.(), null, { timeout: 20000 });
23+
24+await p.evaluate(async () => {
25+ const vm = await import('/js/velocimetro.js');
26+ const medida = { prefillTokS: 240, genTokS: 21, ttftMs: 320, genTokens: 12, procesados: 300, enCurso: false };
27+ window.__motor = { alMedir(cb) { window.__motor.cb = cb; return () => { window.__motor.cb = null; }; }, ultimaMedida: () => medida };
28+ vm.montar(window.__motor);
29+ vm.montar(window.__motor); // el motor cargado otra vez
30+});
31+const estado = () => p.evaluate(() => ({ chip: !document.getElementById('speed-chip').hidden, panel: !document.getElementById('speed-panel').hidden, exp: document.getElementById('speed-chip').getAttribute('aria-expanded') }));
32+ok('el chip se ve con el motor cargado', (await estado()).chip);
33+await p.click('#speed-chip');
34+await p.waitForTimeout(100);
35+let e = await estado();
36+ok('1 · montado dos veces, el clic abre el panel', e.panel, JSON.stringify(e));
37+ok('2 · aria-expanded refleja el panel abierto', e.exp === 'true', JSON.stringify(e));
38+await p.keyboard.press('Escape');
39+await p.waitForTimeout(100);
40+e = await estado();
41+ok('2 · Escape lo cierra y el foco vuelve al chip', !e.panel && e.exp === 'false' && await p.evaluate(() => document.activeElement?.id === 'speed-chip'), JSON.stringify(e));
42+await p.click('#speed-chip');
43+await p.waitForTimeout(100);
44+ok('1 · y se vuelve a abrir', (await estado()).panel);
45+
46+// 3 · cambiar a Básico desde Ajustes
47+await p.click('#btn-settings');
48+await p.waitForTimeout(300);
49+await p.locator('#settings-panel .model-card', { hasText: 'Básico' }).click();
50+await p.waitForTimeout(400);
51+e = await estado();
52+ok('3 · al pasar a Básico el chip y el panel se ocultan', !e.chip && !e.panel, JSON.stringify(e));
53+ok('3 · …y se deja de escuchar al motor', await p.evaluate(() => window.__motor.cb === null));
54+
55+console.log('\n errores JS:', errs[0] || 'ninguno');
56+ok('sin errores de página', errs.length === 0, errs.join(' | '));
57+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CHIP DE VELOCIDAD OK');
58+await b.close();
59+process.exit(fails ? 1 : 0);
modified web/js/main.js +7 −0
@@ -772,9 +772,14 @@
772772 let loadingId = null;
773773 // Lo pone renderSettings: repinta las tarjetas de modelo del panel abierto.
774774 let repintaTarjetasModelo = () => {};
775+// Solo el motor propio mide tok/s: con cualquier otro cerebro el chip ⚡ se
776+// oculta (montar(null)) en vez de seguir enseñando las cifras del motor.
777+const apagaVelocimetro = () => import('./velocimetro.js').then(v => v.montar(null)).catch(() => {});
778+
775779 async function changeModel(id) {
776780 if (id === 'rules') {
777781 conv.setProvider(rules);
782+ apagaVelocimetro();
778783 activeModel = 'rules';
779784 guardaPref('elffusscode.model', 'rules');
780785 pintaDot('off', 'rules');
@@ -794,6 +799,7 @@
794799 }
795800 });
796801 conv.setProvider(mod);
802+ if (!id.startsWith('engine:')) apagaVelocimetro();
797803 // AHORA sí se reanuda lo que quedó a medias. Al refrescar durante un turno,
798804 // el mensaje sigue en la cola —se guarda al enviarlo— pero reanudarlo antes
799805 // de este punto lo habría procesado con el cerebro básico. Aquí ya hay
@@ -834,6 +840,7 @@
834840 if (okc) return true;
835841 }
836842 conv.setProvider(rules);
843+ apagaVelocimetro();
837844 activeModel = 'rules';
838845 pintaDot('error', id);
839846 // En palabras de persona («sin conexión», «sin GPU», «sin espacio»…), con
modified web/js/velocimetro.js +46 −14
@@ -21,6 +21,10 @@
2121 let hist = []; // [{ p: prefillTokS, g: genTokS, t: ttftMs }]
2222 let tareas = []; // [{ ok: bool, ms: number }]
2323 let chip = null, panel = null, prov = null, cancelar = null;
24+// Los oyentes del chip y del documento se ponen UNA vez. montar() se llama en
25+// cada carga del motor, y antes cada llamada añadía otro par: con dos cargas
26+// un clic abría y cerraba el panel a la vez y ya no se abría nunca.
27+let cableado = false;
2428
2529 const leer = () => {
2630 try {
@@ -134,15 +138,54 @@
134138 if (panel && !panel.hidden) pintarPanel();
135139 }
136140
137-/** Engancha el velocímetro. `provider` es el módulo del motor, o null si no hay. */
141+function abrirPanel(abrir) {
142+ if (!panel || !chip) return;
143+ panel.hidden = !abrir;
144+ chip.setAttribute('aria-expanded', abrir ? 'true' : 'false');
145+ if (abrir) pintarPanel();
146+}
147+
148+function cablear() {
149+ if (cableado || !chip) return;
150+ cableado = true;
151+ chip.setAttribute('aria-haspopup', 'dialog');
152+ chip.setAttribute('aria-controls', panel?.id || '');
153+ chip.setAttribute('aria-expanded', 'false');
154+ if (panel) { panel.setAttribute('role', 'dialog'); panel.setAttribute('aria-label', 'Velocidad de esta máquina'); }
155+ chip.addEventListener('click', () => abrirPanel(!!panel && panel.hidden));
156+ // Cerrar al pulsar fuera, como el resto de los desplegables de la cabecera.
157+ document.addEventListener('click', e => {
158+ if (!panel || panel.hidden) return;
159+ if (e.target === chip || chip.contains(e.target) || panel.contains(e.target)) return;
160+ abrirPanel(false);
161+ });
162+ // …y con Escape, devolviendo el foco al chip.
163+ document.addEventListener('keydown', e => {
164+ if (e.key !== 'Escape' || !panel || panel.hidden || e.defaultPrevented) return;
165+ e.preventDefault();
166+ abrirPanel(false);
167+ chip.focus();
168+ });
169+}
170+
171+/** Engancha el velocímetro. `provider` es el módulo del motor, o null si no
172+ * hay: con null (o un proveedor que no mide) el chip y el panel se ocultan y
173+ * se deja de escuchar al anterior. Antes, al pasar del motor a ONNX o a un
174+ * proveedor externo, el chip seguía enseñando las cifras del motor. */
138175 export function montar(provider, chipId = 'speed-chip', panelId = 'speed-panel') {
139176 prov = provider || null;
140177 chip = document.getElementById(chipId);
141178 panel = document.getElementById(panelId);
142179 leer();
143- if (!chip || !prov?.alMedir) { if (chip) chip.hidden = true; return; }
144-
145180 cancelar?.();
181+ cancelar = null;
182+ if (!chip || !prov?.alMedir) {
183+ if (chip) { chip.hidden = true; chip.setAttribute('aria-expanded', 'false'); }
184+ if (panel) panel.hidden = true;
185+ return;
186+ }
187+ cablear();
188+
146189 cancelar = prov.alMedir(m => {
147190 pintarChip(m);
148191 // El historial se apunta UNA vez por turno, al cerrarse: apuntando en cada
@@ -155,17 +198,6 @@
155198 if (panel && !panel.hidden) pintarPanel();
156199 });
157200
158- chip.addEventListener('click', () => {
159- if (!panel) return;
160- panel.hidden = !panel.hidden;
161- if (!panel.hidden) pintarPanel();
162- });
163- // Cerrar al pulsar fuera, como el resto de los desplegables de la cabecera.
164- document.addEventListener('click', e => {
165- if (!panel || panel.hidden) return;
166- if (e.target === chip || panel.contains(e.target)) return;
167- panel.hidden = true;
168- });
169201 const m = prov.ultimaMedida?.();
170202 if (m) pintarChip(m); else chip.hidden = true;
171203 }