Elffuss BraidHub

utopia-ia/elffuss-copilot public

main · 33.8 KiBRawPermalink
1// Los arreglos de la auditoría de UX del Copiloto, uno por uno, en un navegador sin cabeza con micro
2// falso, modelos de mentira y webhooks locales (tests/browser). Uso: node copilot/tests/ux.mjs
3import { launch, newContext, startStatic, startWebhook, checker, sleep, until } from '../../tests/browser/harness.mjs';
4
5const { srv, base } = await startStatic();
6const browser = await launch();
7const C = checker('Copiloto · UX');
8const GiB = 1024 ** 3;
9const LAURA = [
10 { spk: 1, lang: 'es', text: 'Hola, me llamo Laura Pérez y trabajo en Construcciones Norte.' },
11 { spk: 0, lang: 'es', text: 'Encantado, ¿me da un teléfono?' },
12 { spk: 1, lang: 'es', text: 'Sí, el seis uno dos tres cuatro cinco seis siete ocho.' },
13];
14
15async function open({ query = '?ui=es&lang=es&skill=ficha', fake = { lines: LAURA }, gpu = 0, hfStatus = 200, gform = [], viewport, perms = [], extraInit } = {}) {
16 const ctx = await newContext(browser, { base, init: { fake, gpu }, hfStatus, gform, viewport });
17 if (perms.length) await ctx.grantPermissions(perms, { origin: base });
18 if (extraInit) await ctx.addInitScript(extraInit);
19 const page = await ctx.newPage();
20 const errors = []; page.on('pageerror', e => errors.push(e.message));
21 const dialogs = []; page.on('dialog', d => { dialogs.push({ type: d.type(), msg: d.message(), value: d.defaultValue() }); d.accept(); });
22 await page.goto(base + '/copilot/' + query);
23 return { ctx, page, errors, dialogs };
24}
25const sendRes = page => page.evaluate(() => { const r = document.getElementById('sendRes'); return { text: r.hidden ? '' : r.textContent, cls: r.className }; });
26const lines = page => page.evaluate(() => document.querySelectorAll('#log .tline').length);
27// Enviar «no disponible» mientras envía: aria-disabled (con disabled, el foco caía al <body>).
28const blocked = (page, id) => page.evaluate(id => document.getElementById(id).getAttribute('aria-disabled') === 'true' || document.getElementById(id).disabled, id);
29
30// ── Micro denegado: Empezar no se queda muerto ──
31{
32 const { ctx, page, errors, dialogs } = await open();
33 await page.evaluate(() => { window.__GUM_DENY = true; });
34 await page.click('#start');
35 await page.waitForSelector('#startErr:not([hidden])', { timeout: 8000 });
36 const r = await page.evaluate(() => ({ err: document.getElementById('startErr').textContent, help: document.querySelector('#startErr a')?.href, disabled: document.getElementById('start').disabled, setup: !document.getElementById('setup').hidden, focus: document.activeElement?.id }));
37 await page.evaluate(() => { window.__GUM_DENY = false; });
38 await page.click('#start');
39 const entered = await page.waitForSelector('#live:not([hidden])', { timeout: 10000 }).then(() => true, () => false);
40 const focus = await page.evaluate(() => document.activeElement?.id);
41 C.ok('sin micro: el motivo debajo de Empezar, con enlace de ayuda, sin alert', /Sin permiso para el micrófono/.test(r.err) && /support\.google\.com/.test(r.help || '') && !dialogs.length, { r, dialogs });
42 C.ok('Empezar vuelve a estar disponible (antes se quedaba desactivado hasta recargar)', !r.disabled && r.setup && r.focus === 'start', r);
43 C.ok('al permitirlo, Empezar entra en la llamada sin recargar', entered);
44 C.ok('al entrar, el foco va al título de la llamada', focus === 'skName', focus);
45 C.ok('sin errores en la página', !errors.length, errors);
46 await ctx.close();
47}
48
49// ── Enviar dice lo que pasó de verdad ──
50for (const [what, opts, expect] of [
51 ['500', { status: 500 }, r => /respondió 500/.test(r.text) && /err/.test(r.cls)],
52 ['200 con CORS', { status: 200 }, r => /^Enviado a 127\.0\.0\.1:\d+ ✓$/.test(r.text) && !/err|warn/.test(r.cls)],
53 ['sin CORS', { status: 200, cors: false }, r => /sin confirmación del servidor/.test(r.text) && /warn/.test(r.cls)],
54]) {
55 const hook = await startWebhook(opts);
56 const { ctx, page, errors } = await open();
57 await page.click('#dest summary');
58 await page.fill('#webhook', hook.url + '/secreto-del-cliente');
59 await page.click('#start');
60 await until(page, () => document.querySelectorAll('#log .tline').length >= 1, null, { timeout: 15000, what: 'una frase' });
61 await page.click('#send');
62 await until(page, () => { const r = document.getElementById('sendRes'); return !r.hidden && !/Enviando/.test(r.textContent); }, null, { what: 'resultado del envío' });
63 const r = await sendRes(page);
64 const n = await lines(page);
65 await until(page, k => document.querySelectorAll('#log .tline').length > k, n, { timeout: 12000, what: 'otra frase' });
66 const later = await sendRes(page);
67 C.ok(`webhook ${what}: el resultado es el de verdad`, expect(r), r);
68 C.ok(`webhook ${what}: solo enseña el host, nunca la URL`, !/secreto-del-cliente|\/hook/.test(r.text), r.text);
69 C.ok(`webhook ${what}: el resultado sigue ahí tras la siguiente frase`, later.text === r.text, later);
70 C.ok(`webhook ${what}: el servidor recibió la ficha`, hook.hits.some(h => h.method === 'POST' && /Laura/.test(h.body)), hook.hits.map(h => h.method));
71 C.ok('sin errores en la página', !errors.length, errors);
72 await ctx.close(); hook.srv.close();
73}
74
75// ── Un webhook que no contesta: tiempo límite, y «Nueva llamada» suelta el candado ──
76// El tiempo límite de la app (15 s) lo fija la prueba con window.__SEND_MS: corto para ver el aviso,
77// larguísimo para comprobar que «Nueva llamada» suelta el candado sin depender de él.
78{
79 const limit = () => { const orig = AbortSignal.timeout.bind(AbortSignal); AbortSignal.timeout = ms => orig(window.__SEND_MS ?? ms); };
80 const hang = await startWebhook({ hang: true }), good = await startWebhook({ status: 200 });
81 const { ctx, page, errors } = await open({ extraInit: limit });
82 await page.click('#dest summary');
83 await page.fill('#webhook', hang.url);
84 await page.click('#start');
85 await until(page, () => document.querySelectorAll('#log .tline').length >= 1, null, { timeout: 15000, what: 'una frase' });
86 await page.evaluate(() => { window.__SEND_MS = 3000; });
87 await page.click('#send');
88 const during = { res: await page.textContent('#sendRes'), send: await blocked(page, 'send') };
89 await page.evaluate(() => document.getElementById('send').click()); // un segundo clic mientras espera no manda otra vez
90 await page.waitForTimeout(500);
91 const hitsDuring = hang.hits.filter(h => h.method === 'POST').length;
92 await until(page, () => /no respondió/.test(document.getElementById('sendRes').textContent), null, { timeout: 15000, what: 'el aviso de que no respondió' });
93 const after = { ...await page.evaluate(() => ({ res: document.getElementById('sendRes').textContent, cls: document.getElementById('sendRes').className })), send: await blocked(page, 'send'), send2: await blocked(page, 'send2') };
94 // Otra vez al webhook mudo, que ahora espera de sobra, y con el envío pendiente:
95 // Parar → Nueva llamada → otro destino → Empezar.
96 await page.evaluate(() => { window.__SEND_MS = 600000; });
97 await page.click('#send');
98 await page.click('#stop'); await page.click('#newCall');
99 await page.fill('#webhook', good.url);
100 await page.click('#start');
101 await page.waitForSelector('#live:not([hidden])');
102 await until(page, () => !!document.getElementById('send2'), null, { what: 'la ficha nueva' });
103 const fresh = { send: await blocked(page, 'send'), send2: await blocked(page, 'send2') };
104 // El envío viejo acaba (el webhook mudo se cierra) con la llamada nueva en marcha: no debe pintar nada.
105 hang.srv.closeAllConnections?.(); hang.srv.close();
106 await page.waitForTimeout(1500);
107 const late = await sendRes(page);
108 await page.click('#send');
109 await until(page, () => /Enviado/.test(document.getElementById('sendRes').textContent), null, { what: 'enviado al webhook bueno' });
110 C.ok('mientras espera, dice «Enviando…» y no deja enviar dos veces', /Enviando/.test(during.res) && during.send && hitsDuring === 1, { during, hitsDuring });
111 C.ok('un webhook que no contesta: a su tiempo límite se dice, en rojo, y Enviar vuelve', /127\.0\.0\.1:\d+\) no respondió/.test(after.res) && /err/.test(after.cls) && !after.send && !after.send2, after);
112 C.ok('«Nueva llamada» suelta el candado aunque un envío siga esperando', !fresh.send && !fresh.send2, fresh);
113 C.ok('…el envío viejo, al acabar, no pinta nada en la llamada nueva', late.text === '', late);
114 C.ok('…y el envío siguiente llega', good.hits.some(h => h.method === 'POST'), good.hits.length);
115 C.ok('sin errores en la página', !errors.length, errors);
116 await ctx.close(); good.srv.close();
117}
118
119// ── Un Google Forms que no contesta: el mismo tiempo límite que el webhook ──
120// (antes solo lo tenía el webhook: Enviar se quedaba en «Enviando…» el resto de la llamada)
121{
122 const limit = () => { const orig = AbortSignal.timeout.bind(AbortSignal); AbortSignal.timeout = ms => orig(window.__SEND_MS ?? ms); };
123 const { ctx, page, errors } = await open({ extraInit: limit });
124 const held = [];
125 await ctx.route('https://docs.google.com/forms/**', route => { held.push(route.request().url()); }); // no contesta nunca
126 await page.click('#dest summary');
127 await page.fill('#gform', 'https://docs.google.com/forms/d/e/abc/viewform?usp=pp_url&entry.111=nombre');
128 await page.click('#start');
129 await until(page, () => /Laura/.test(document.getElementById('board').textContent), null, { timeout: 15000, what: 'nombre en la ficha' });
130 await page.evaluate(() => { window.__SEND_MS = 3000; });
131 await page.click('#send');
132 const during = { res: await page.textContent('#sendRes'), send: await blocked(page, 'send'), send2: await blocked(page, 'send2') };
133 const said = await until(page, () => /Google Forms no respondió/.test(document.getElementById('sendRes').textContent), null, { timeout: 15000, what: 'el aviso de que Forms no respondió' });
134 const after = { ...await sendRes(page), send: await blocked(page, 'send'), send2: await blocked(page, 'send2') };
135 C.ok('Forms que no contesta: mientras espera, «Enviando…»', /Enviando/.test(during.res) && during.send && during.send2, during);
136 C.ok('…a su tiempo límite se dice, en rojo, y los dos Enviar vuelven', held.length === 1 && said && /err/.test(after.cls) && !after.send && !after.send2, { held: held.length, after });
137 C.ok('sin errores en la página', !errors.length, errors);
138 await ctx.close();
139}
140
141// ── Google Forms con una skill de objetivos: la vista previa dice lo que de verdad se manda ──
142{
143 const gform = [];
144 // La primera voz que se oye es «Tú» y la segunda el cliente: los objetivos solo leen al cliente.
145 const VENTA = [{ spk: 0, lang: 'es', text: 'Buenos días, ¿con quién hablo?' }, { spk: 1, lang: 'es', text: 'Hola, me llamo Laura Pérez.' }];
146 const { ctx, page, errors } = await open({ query: '?ui=es&lang=es&skill=ventas', gform, fake: { lines: VENTA } });
147 await page.click('#dest summary');
148 await page.fill('#gform', 'https://docs.google.com/forms/d/e/abc/viewform?usp=pp_url&entry.111=nombre&entry.333=email&entry.555=empresa');
149 const map = await page.textContent('#gformMap');
150 await page.click('#start');
151 await until(page, () => document.querySelectorAll('#board .slot.done').length >= 1, null, { timeout: 20000, what: 'el nombre en los objetivos' });
152 await page.click('#send');
153 await until(page, () => /Google Forms/.test(document.getElementById('sendRes').textContent) && !/Enviando/.test(document.getElementById('sendRes').textContent), null, { what: 'enviado a Forms' });
154 const body = gform.map(g => decodeURIComponent(g.body)).join(' | ');
155 C.ok('la vista previa solo promete lo que esta skill rellena y dice lo que no', /Se rellenarán: entry\.111 → El cliente da su nombre\./.test(map) && /No se rellenan con esta skill: entry\.333 \(email\), entry\.555 \(empresa\)/.test(map) && !/entry\.333 →|entry\.555 →/.test(map), map);
156 C.ok('…y se manda justo eso', /entry\.111=sí/.test(body) && !/entry\.333|entry\.555/.test(body), body);
157 C.ok('sin errores en la página', !errors.length, errors);
158 await ctx.close();
159}
160
161// ── Micro que no está o que está ocupado: se dice eso, no que falta el permiso ──
162for (const [name, re] of [['NotFoundError', /No encuentro ningún micrófono/], ['NotReadableError', /lo esté usando otra aplicación/]]) {
163 const { ctx, page, errors } = await open();
164 await page.evaluate(n => { window.__GUM_ERR = n; }, name);
165 await page.click('#start');
166 await page.waitForSelector('#startErr:not([hidden])', { timeout: 8000 });
167 const r = await page.evaluate(() => ({ err: document.getElementById('startErr').textContent, start: !document.getElementById('start').disabled }));
168 C.ok(`micro con ${name}: el motivo de verdad, no el permiso`, re.test(r.err) && !/permiso/i.test(r.err) && r.start, r);
169 C.ok('sin errores en la página', !errors.length, errors);
170 await ctx.close();
171}
172
173// ── Enviar sin destino: el destino se edita ahí mismo, durante la llamada ──
174{
175 const hook = await startWebhook({ status: 200 });
176 const { ctx, page, errors } = await open();
177 await page.click('#start');
178 await until(page, () => document.querySelectorAll('#log .tline').length >= 1, null, { timeout: 15000, what: 'una frase' });
179 const label = await page.textContent('#send2');
180 await page.click('#send2');
181 const r = await page.evaluate(() => ({ res: document.getElementById('sendRes').textContent, open: !document.getElementById('destLive').hidden && document.getElementById('dest').open, inLive: !!document.querySelector('#destLive #dest'), focus: document.activeElement?.id }));
182 await page.fill('#webhook', hook.url);
183 const label2 = await page.textContent('#send2');
184 await page.click('#send');
185 await until(page, () => /Enviado/.test(document.getElementById('sendRes').textContent), null, { what: 'enviado' });
186 const sent = await sendRes(page);
187 C.ok('el botón de la ficha avisa de que falta el destino', /configura destino/.test(label), label);
188 C.ok('sin destino, se dice y se abre el destino bajo la barra, con el foco en el webhook', /Falta el destino/.test(r.res) && r.open && r.inLive && r.focus === 'webhook', r);
189 C.ok('al escribirlo, el aviso del botón desaparece', !/configura destino/.test(label2), label2);
190 C.ok('y Enviar ya llega', /Enviado a 127\.0\.0\.1/.test(sent.text) && hook.hits.length > 0, sent);
191 C.ok('sin errores en la página', !errors.length, errors);
192 await ctx.close(); hook.srv.close();
193}
194
195// ── Google Forms: vista previa del mapeo y nada de «✓» con el cuerpo vacío ──
196{
197 const gform = [];
198 const { ctx, page, errors } = await open({ gform });
199 await page.click('#dest summary');
200 await page.fill('#gform', 'https://docs.google.com/forms/d/e/abc/viewform?usp=pp_url');
201 const none = await page.evaluate(() => ({ text: document.getElementById('gformMap').textContent, cls: document.getElementById('gformMap').className }));
202 await page.fill('#gform', 'https://docs.google.com/forms/d/e/abc/viewform?usp=pp_url&entry.111=nombre&entry.222=telefono&entry.333=email&entry.444=empresa');
203 const map = await page.textContent('#gformMap');
204 await page.fill('#gform', 'https://docs.google.com/forms/d/e/abc/viewform?usp=pp_url');
205 await page.click('#start');
206 await until(page, () => document.querySelectorAll('#log .tline').length >= 1, null, { timeout: 15000, what: 'una frase' });
207 await page.click('#send');
208 await until(page, () => !/Enviando/.test(document.getElementById('sendRes').textContent) && !document.getElementById('sendRes').hidden, null, { what: 'resultado' });
209 const bad = await sendRes(page);
210 await page.evaluate(() => { document.getElementById('gform').value = 'https://docs.google.com/forms/d/e/abc/viewform?usp=pp_url&entry.111=nombre&entry.222=telefono&entry.444=empresa'; });
211 await until(page, () => /Laura/.test(document.getElementById('board').textContent), null, { what: 'nombre en la ficha' });
212 await page.click('#send');
213 await until(page, () => /Google Forms/.test(document.getElementById('sendRes').textContent) && !/Enviando/.test(document.getElementById('sendRes').textContent), null, { what: 'enviado a Forms' });
214 const ok = await sendRes(page);
215 C.ok('un enlace sin campos avisa al escribirlo', /no tiene campos/.test(none.text) && /warn/.test(none.cls), none);
216 C.ok('con campos, enseña qué campo recibe qué dato', /entry\.111 → Nombre/.test(map) && /entry\.222 → Teléfono/.test(map) && /entry\.444 → Empresa/.test(map), map);
217 C.ok('sin campos, Enviar no dice «✓»: dice que no se envió', /no se envió/.test(bad.text) && /err/.test(bad.cls) && !/✓/.test(bad.text), bad);
218 C.ok('con campos, se envía y se dice que no hay confirmación posible', /Google Forms, sin confirmación/.test(ok.text) && gform.some(g => /entry\.111=Laura/.test(g.body)), { ok, gform });
219 C.ok('sin errores en la página', !errors.length, errors);
220 await ctx.close();
221}
222
223// ── Parar → Nueva llamada, sin recargar ──
224{
225 const { ctx, page, errors, dialogs } = await open();
226 await page.click('#start');
227 await until(page, () => document.querySelectorAll('#log .tline').length >= 2, null, { timeout: 20000, what: 'dos frases' });
228 await page.click('#stop');
229 const stopped = await page.evaluate(() => ({ stop: !document.getElementById('stop').hidden, nc: !document.getElementById('newCall').hidden, focus: document.activeElement?.id, csv: !document.getElementById('exp').disabled, status: document.getElementById('status').textContent }));
230 await page.click('#newCall'); // la ficha (Laura, Construcciones Norte) no se envió ni se descargó: pregunta, y se acepta
231 const home = await page.evaluate(() => ({ setup: !document.getElementById('setup').hidden, ui: !document.getElementById('uiToggle').hidden, focus: document.activeElement?.id, log: document.querySelectorAll('#log .tline').length, board: document.getElementById('board').children.length }));
232 await page.click('#start');
233 const again = await until(page, () => document.querySelectorAll('#log .tline').length >= 1, null, { timeout: 15000, what: 'una frase en la segunda llamada' });
234 C.ok('tras Parar: «Nueva llamada» en su sitio y el foco en CSV (no en «Nueva llamada»), que sigue disponible', !stopped.stop && stopped.nc && stopped.focus === 'exp' && stopped.csv, stopped);
235 C.ok('el estado ya no pide recargar', !/Recarga/.test(stopped.status) && /Parado/.test(stopped.status), stopped.status);
236 C.ok('«Nueva llamada» con la ficha sin guardar pregunta antes de borrarla', dialogs.some(d => d.type === 'confirm' && /no se ha enviado ni descargado/.test(d.msg)), dialogs);
237 C.ok('«Nueva llamada» vuelve al inicio limpio, con el foco en Empezar', home.setup && home.ui && home.focus === 'start' && home.log === 0 && home.board === 0, home);
238 C.ok('y la segunda llamada funciona', again);
239 C.ok('sin errores en la página', !errors.length, errors);
240 await ctx.close();
241}
242
243// ── Cerrar o recargar pide confirmación durante la llamada y con una ficha sin guardar ──
244{
245 const { ctx, page, errors } = await open();
246 const unload = () => page.evaluate(() => { const e = new Event('beforeunload', { cancelable: true }); window.dispatchEvent(e); return e.defaultPrevented; });
247 const setup = await unload();
248 await page.click('#start');
249 await until(page, () => /Laura/.test(document.getElementById('board').textContent), null, { timeout: 15000, what: 'la ficha con datos' });
250 const live = await unload();
251 await page.click('#stop');
252 const stopped = await unload();
253 await page.click('#exp'); // descargar el CSV la deja guardada
254 const saved = await unload();
255 C.ok('en el inicio no pide nada', !setup);
256 C.ok('durante la llamada, cerrar o recargar pide confirmación', live);
257 C.ok('tras Parar, con la ficha sin enviar ni descargar, también', stopped);
258 C.ok('ya descargada en CSV, no', !saved);
259 C.ok('sin errores en la página', !errors.length, errors);
260 await ctx.close();
261}
262
263// ── Skills, URL y enlace para el equipo ──
264{
265 const { ctx, page, errors } = await open({ query: '?ui=es', perms: ['clipboard-read', 'clipboard-write'] });
266 await page.focus('[data-skill="ventas"]');
267 await page.keyboard.press('Enter');
268 const r = await page.evaluate(() => ({ focus: document.activeElement?.dataset?.skill, pressed: [...document.querySelectorAll('#skGrid button')].map(b => b.dataset.skill + ':' + b.getAttribute('aria-pressed')).join(' '), url: location.search }));
269 await page.selectOption('#lang', 'en');
270 const url2 = await page.evaluate(() => location.search);
271 await page.click('#dest summary');
272 await page.fill('#webhook', 'https://crm.example/hook/SECRETO');
273 await page.click('#teamLink');
274 await until(page, () => /Copiado/.test(document.getElementById('teamLinkRes').textContent), null, { what: 'copiado' });
275 const link = await page.evaluate(() => navigator.clipboard.readText());
276 const u = new URL(link);
277 C.ok('elegir con el teclado deja el foco en la tarjeta elegida', r.focus === 'ventas', r);
278 C.ok('aria-pressed dice cuál está elegida', r.pressed === 'ficha:false ventas:true facilitador:false', r.pressed);
279 C.ok('la URL dice la skill (y la interfaz)', /skill=ventas/.test(r.url) && /ui=es/.test(r.url), r.url);
280 C.ok('y el idioma de la conversación', /lang=en/.test(url2), url2);
281 C.ok('el enlace del equipo lleva skill, idioma y destino tras la «#», no en la consulta', !u.search && /skill=ventas/.test(u.hash) && /lang=en/.test(u.hash) && /webhook=https/.test(u.hash), link);
282 // Abrir ese enlace: llega configurado y el destino no se queda en la barra de direcciones.
283 const p2 = await ctx.newPage();
284 await p2.goto(link.replace(/^https?:\/\/[^/]+/, base));
285 const opened = await p2.evaluate(() => ({ webhook: document.getElementById('webhook').value, open: document.getElementById('dest').open, from: !document.getElementById('fromLink').hidden, skill: document.querySelector('#skGrid [aria-pressed="true"]')?.dataset.skill, lang: document.getElementById('lang').value, href: location.href }));
286 C.ok('al abrirlo: destino puesto y avisado («configurado desde un enlace»), misma skill e idioma', opened.webhook === 'https://crm.example/hook/SECRETO' && opened.open && opened.from && opened.skill === 'ventas' && opened.lang === 'en', opened);
287 C.ok('…y el webhook desaparece de la barra de direcciones', !/SECRETO|webhook/.test(opened.href), opened.href);
288 C.ok('sin errores en la página', !errors.length, errors);
289 await ctx.close();
290}
291
292// ── IA avanzada: opcional, con el motivo y Reintentar si falla ──
293{
294 const { ctx, page, errors } = await open({ gpu: 4 * GiB, hfStatus: 404 });
295 await until(page, () => !document.getElementById('iaOpt').disabled, null, { what: 'IA disponible' });
296 const opt = await page.evaluate(() => ({ checked: document.getElementById('iaOpt').checked, link: document.querySelector('#iaLbl a')?.href, label: document.getElementById('iaLbl').textContent }));
297 await page.check('#iaOpt');
298 await page.click('#start');
299 await until(page, () => !document.getElementById('iaRetry').hidden, null, { timeout: 15000, what: 'Reintentar' });
300 const fail = await page.evaluate(() => ({ chip: document.getElementById('iaChip').textContent, title: document.getElementById('iaChip').title }));
301 // El modelo vuelve a estar disponible: Reintentar lo carga sin parar la llamada.
302 await ctx.unroute('**/*').catch(() => {});
303 await ctx.route('**/*', route => {
304 const u = route.request().url();
305 if (u.startsWith('http://127.0.0.1')) return route.continue();
306 if (u.startsWith('https://huggingface.co/litert-community/')) return route.fulfill({ status: 200, headers: { 'Content-Type': 'application/octet-stream', 'Content-Length': '65536', 'Access-Control-Allow-Origin': '*' }, body: Buffer.alloc(65536, 7) });
307 return route.abort('blockedbyclient');
308 });
309 await page.click('#iaRetry');
310 const ready = await until(page, () => /^IA: Gemma/.test(document.getElementById('iaChip').textContent), null, { timeout: 15000, what: 'IA lista' });
311 C.ok('la IA avanzada viene desmarcada (2,8 GB se eligen, no se esquivan)', opt.checked === false, opt);
312 C.ok('el nombre del modelo enlaza a su ficha en Hugging Face', /huggingface\.co\/litert-community\/gemma-4-E4B-it-litert-lm$/.test(opt.link || ''), opt.link);
313 C.ok('si falla: el chip lo dice, el título da el motivo y aparece Reintentar', /no disponible/.test(fail.chip) && /404/.test(fail.title), fail);
314 C.ok('Reintentar la carga sin salir de la llamada', ready);
315 C.ok('sin errores en la página', !errors.length, errors);
316 await ctx.close();
317}
318
319// ── Descarga: una sola barra para los dos modelos, que no tapa nada, y un porcentaje que no retrocede ──
320{
321 const { ctx, page, errors } = await open({ fake: { lines: LAURA, dlStep: 120 } });
322 await page.evaluate(() => {
323 window.__ov = []; const p = document.getElementById('dlBar'), pr = document.getElementById('dlProgress');
324 const rec = () => window.__ov.push({ hidden: p.hidden, pct: +pr.getAttribute('aria-valuenow') });
325 new MutationObserver(rec).observe(p, { attributes: true, attributeFilter: ['hidden'] });
326 new MutationObserver(rec).observe(pr, { attributes: true, attributeFilter: ['aria-valuenow'] });
327 });
328 await page.click('#start');
329 await until(page, () => window.__ov.length > 2 && document.getElementById('dlBar').hidden, null, { timeout: 20000, what: 'fin de la descarga' });
330 const ov = await page.evaluate(() => window.__ov);
331 const shows = ov.filter((x, i) => i > 0 && !x.hidden && ov[i - 1].hidden).length + (ov[0] && !ov[0].hidden ? 1 : 0);
332 const pcts = ov.filter(x => !x.hidden).map(x => x.pct);
333 const a11y = await page.evaluate(() => { const pr = document.getElementById('dlProgress'), bar = document.getElementById('dlBar'); return { role: pr.getAttribute('role'), label: document.getElementById(pr.getAttribute('aria-labelledby'))?.textContent, live: !!bar.closest('[aria-live],[role=status],[role=alert]'), inTop: !!bar.closest('.livetop') }; });
334 C.ok('la barra de descarga se abre una vez y se cierra al acabar los dos', shows === 1 && ov.at(-1).hidden, ov.map(x => (x.hidden ? 'oculta' : x.pct)).join(' '));
335 C.ok('el porcentaje nunca retrocede', pcts.length > 2 && pcts.every((v, i) => i === 0 || v >= pcts[i - 1]), pcts);
336 C.ok('es una barra de progreso con nombre, en la barra de arriba y fuera de las regiones que se leen solas', a11y.role === 'progressbar' && /Descargando/.test(a11y.label || '') && !a11y.live && a11y.inTop, a11y);
337 C.ok('sin errores en la página', !errors.length, errors);
338 await ctx.close();
339}
340
341// ── Escritorio bajo: la tarjeta de inicio se ve entera desde arriba ──
342for (const vp of [{ width: 1280, height: 860 }, { width: 1366, height: 700 }]) {
343 const { ctx, page, errors } = await open({ viewport: vp });
344 const r = await page.evaluate(() => { const s = document.getElementById('setup'); s.scrollTop = 0; const c = document.querySelector('.setupcard').getBoundingClientRect(); return { cut: Math.round(s.getBoundingClientRect().top - c.top) }; });
345 C.ok(`${vp.width}×${vp.height}: no se corta el principio de la tarjeta`, r.cut <= 0, r);
346 C.ok('sin errores en la página', !errors.length, errors);
347 await ctx.close();
348}
349
350// ── Chip 💾, cabecera y pie ──
351{
352 const { ctx, page, errors, dialogs } = await open();
353 await page.evaluate(async () => { const c = await caches.open('transformers-cache'); await c.put('https://huggingface.co/x', new Response('x'.repeat(8e6))); });
354 await page.reload();
355 await until(page, () => { const c = document.getElementById('diskChip'); return c && !c.hidden; }, null, { what: 'chip de disco' });
356 const label = await page.getAttribute('#diskChip', 'aria-label');
357 await page.click('#diskChip');
358 await until(page, () => /Borrado/.test(document.getElementById('diskChip').textContent), null, { what: '✓ Borrado' });
359 await page.waitForFunction(() => document.getElementById('diskChip').hidden, null, { timeout: 6000 }).catch(() => {});
360 const gone = await page.evaluate(async () => ({ hidden: document.getElementById('diskChip').hidden, keys: (await caches.keys()).length }));
361 const links = await page.$$eval('a[href]', as => as.map(a => a.href));
362 const targets = await page.$$eval('a[href^="https://copilot.elffuss.com/blog/"], a[href^="https://translator.elffuss.com/"], a[href^="https://claw.elffuss.com/"]', as => as.map(a => a.target));
363 const need = ['https://copilot.elffuss.com/blog/', 'https://translator.elffuss.com/', 'https://claw.elffuss.com/', 'https://huggingface.co/onnx-community/whisper-base',
364 'https://huggingface.co/onnx-community/pyannote-segmentation-3.0', 'https://huggingface.co/onnx-community/wespeaker-voxceleb-resnet34-LM', 'https://creativecommons.org/licenses/by/4.0/'];
365 C.ok('el chip tiene nombre accesible con el tamaño', /^Modelos guardados: \d+ MB\. Pulsa para vaciar$/.test(label || ''), label);
366 C.ok('tras vaciar dice «✓ Borrado» y se esconde (no repite el tamaño viejo)', gone.hidden && gone.keys === 0 && dialogs.length === 1, { gone, dialogs });
367 C.ok('cabecera y pie enlazan el blog, el Traductor, Claw y los repositorios ONNX exactos', need.every(u => links.includes(u)), need.filter(u => !links.includes(u)));
368 C.ok('el blog, el Traductor y Claw abren en otra pestaña (un clic ya no corta la llamada)', targets.length >= 5 && targets.every(x => x === '_blank'), targets);
369 C.ok('sin errores en la página', !errors.length, errors);
370 await ctx.close();
371}
372
373// ── Lo que se dice durante la primera descarga se transcribe al terminar, también pasadas 30 frases ──
374// (antes la cola se quedaba con las 30 últimas y tiraba las primeras, las presentaciones, sin avisar)
375// Un micro falso con un tono más corto (una frase cada 1,45 s) para que caigan bastantes más de 30 en una
376// descarga de mentira de algo más de un minuto, y un espía que corta las frases con la misma regla que
377// la página.
378{
379 const spy = () => {
380 window.__segs = 0;
381 const orig = AudioContext.prototype.createScriptProcessor;
382 AudioContext.prototype.createScriptProcessor = function (...a) {
383 const p = orig.apply(this, a); let fn = null, voiced = false, sil = 0, len = 0; const SR = this.sampleRate;
384 p.addEventListener('audioprocess', e => {
385 if (!fn) return;
386 const d = e.inputBuffer.getChannelData(0); let s = 0; for (const x of d) s += x * x; const r = Math.sqrt(s / d.length);
387 if (r > 0.015) { voiced = true; sil = 0; len += d.length; } else if (voiced) { sil += d.length; if (sil > SR * 0.7) { if (len > SR * 0.4) window.__segs++; voiced = false; sil = 0; len = 0; } }
388 fn.call(p, e);
389 });
390 Object.defineProperty(p, 'onaudioprocess', { configurable: true, get: () => fn, set: v => { fn = v; } });
391 return p;
392 };
393 };
394 const fast = await launch({ tone: { on: 0.6, off: 0.85 } });
395 const call = async (fake, extraInit) => {
396 const ctx = await newContext(fast, { base, init: { fake } });
397 if (extraInit) await ctx.addInitScript(extraInit);
398 await ctx.addInitScript(spy);
399 const page = await ctx.newPage();
400 const errors = []; page.on('pageerror', e => errors.push(e.message));
401 page.on('dialog', d => d.accept());
402 await page.goto(base + '/copilot/?ui=es&lang=es&skill=ficha');
403 await page.click('#start');
404 await until(page, () => !document.getElementById('dlBar').hidden, null, { timeout: 10000, what: 'la barra de descarga' });
405 return { ctx, page, errors };
406 };
407 const FRASE = [{ spk: 1, lang: 'es', text: 'Frase {n}.' }];
408 // Lo cortado que aún no se ha transcrito: con todo transcrito es 0 (o 1 recién cortada).
409 const pending = page => page.evaluate(() => window.__segs - window.__fakeStats.asrCalls);
410 {
411 const { ctx, page, errors } = await call({ lines: FRASE, dlStep: 11000 });
412 const promise = await page.textContent('#status');
413 // Los modelos están cuando se transcribe la primera frase (la barra no sirve de señal: con más de
414 // 8 s entre aviso y aviso de progreso, su red de seguridad la esconde aunque siga bajando).
415 await until(page, () => window.__fakeStats.asrCalls > 0, null, { timeout: 120000, what: 'los modelos listos (primera transcripción)' });
416 const cut = await page.evaluate(() => window.__segs);
417 const caughtUp = await until(page, () => window.__segs - window.__fakeStats.asrCalls <= 1, null, { timeout: 30000, what: 'todo lo dicho, transcrito' });
418 const left = await pending(page);
419 C.ok('durante la primera descarga, el estado promete transcribir lo que se diga, con su límite', /lo que digas ahora \(hasta 5 minutos\) se transcribe al terminar/.test(promise), promise);
420 // Con el tope viejo (30 en cola y 1 en marcha) se perderían al menos 5: la prueba distingue de sobra.
421 C.ok(`bastantes más de 30 frases dichas durante la descarga (${cut})`, cut >= 36, cut);
422 C.ok('…y al terminar se transcriben todas: no se tira ninguna', caughtUp && left <= 1, { cut, left });
423 C.ok('sin errores en la página', !errors.length, errors);
424 await ctx.close();
425 }
426 {
427 // Si se llena (aquí con un tope de 4 s de voz, para no esperar 5 minutos), se dice cuántas no caben,
428 // y lo que dice es justo lo que falta al final.
429 const { ctx, page, errors } = await call({ lines: FRASE, dlStep: 3000 }, () => { window.__COPILOTO_COLA_CARGA_S = 4; });
430 const full = await until(page, () => /no cabe más/.test(document.getElementById('status').textContent), null, { timeout: 30000, what: 'el aviso de cola llena' });
431 await until(page, () => document.getElementById('dlBar').hidden, null, { timeout: 60000, what: 'el final de la descarga' });
432 const lost = await page.evaluate(() => Math.max(0, ...window.__status.map(s => +((/Frases que no se transcribirán: (\d+)/.exec(s.text) || [])[1] || 0))));
433 const settled = await until(page, k => { const d = window.__segs - window.__fakeStats.asrCalls; return d >= k && d <= k + 1; }, lost, { timeout: 30000, what: 'la cola guardada, transcrita' });
434 const left = await pending(page);
435 const st = (await page.evaluate(() => window.__status.map(s => s.text))).find(t => /no cabe más/.test(t)) || '';
436 C.ok('si no cabe más, el estado lo dice y cuántas frases no se transcribirán', full && lost >= 1 && /ya hay 5 minutos de voz esperando y no cabe más\. Frases que no se transcribirán: \d+\./.test(st), st);
437 C.ok('…y es verdad: al final faltan justo esas', settled && left >= lost && left <= lost + 1, { lost, left });
438 C.ok('sin errores en la página', !errors.length, errors);
439 await ctx.close();
440 }
441 await fast.close();
442}
443
444await browser.close(); srv.close();
445process.exit(C.done() ? 1 : 0);