Elffuss BraidHub

utopia-ia/elffuss-code public

main · 5.0 KiBRawPermalink
1// Notificaciones del navegador: SOLO saltan cuando el ciclo es sustancioso
2// (≥2 propuestas sólidas), NUNCA piden permiso fuera de un gesto del usuario,
3// y el panel ⚙ muestra el estado real del permiso.
4import { chromium } from 'playwright';
5const BASE = process.env.BASE || 'http://localhost:8799';
6let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
7
8const b = await chromium.launch();
9const ctx = await b.newContext({ locale: 'es-ES' });
10await ctx.addInitScript(() => {
11 try { localStorage.setItem('elffusscode.model', 'rules'); } catch {}
12 window.__notifs = []; window.__askedPermission = 0;
13 // Chromium headless no sincroniza Notification.permission con
14 // grantPermissions de forma fiable → se fija directamente. Las notificaciones
15 // reales pasan por el service worker (registration.showNotification, para
16 // poder llevar el botón «Ejecutar»), así que se espía ahí, no en `new Notification()`.
17 try { Object.defineProperty(Notification, 'permission', { value: 'granted', configurable: true }); } catch {}
18 const origRP = Notification.requestPermission?.bind(Notification);
19 Notification.requestPermission = (...a) => { window.__askedPermission++; return origRP ? origRP(...a) : Promise.resolve('granted'); };
20});
21const p = await ctx.newPage({ viewport: { width: 1300, height: 850 } });
22await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1500);
23await p.waitForFunction(() => navigator.serviceWorker && navigator.serviceWorker.controller, null, { timeout: 10000 }).catch(() => {});
24await p.evaluate(async () => {
25 const reg = await navigator.serviceWorker.ready;
26 const orig = reg.showNotification.bind(reg);
27 reg.showNotification = (title, opts) => { window.__notifs.push({ title, body: opts && opts.body }); return orig(title, { ...opts, silent: true }).catch(() => {}); };
28});
29
30// ── ciclo FLOJO: 1 sola propuesta sólida → NO debe notificar ──
31// notify() es async (espera a navigator.serviceWorker.ready) y reportImprovements
32// NO la espera (fire-and-forget) → hay que dar tiempo antes de leer el spy.
33await p.evaluate(async () => {
34 const m = await import('/js/main.js');
35 window.__notifs.length = 0;
36 m.reportImprovements({ proposals: [
37 { dept: 'Arquitectura', text: 'No encontré nada relevante que cambiar por ahora.' },
38 { dept: 'Calidad', text: 'Sin cambios.' },
39 { dept: 'Rendimiento', text: 'Convendría memoizar el cálculo pesado de renderList() para evitar recomputarlo en cada frame, ahorra bastante CPU.' },
40 { dept: 'Producto/DX', text: 'ok' },
41 ], path: '.elffuss/soul/x.md' });
42});
43await p.waitForTimeout(400);
44let r = await p.evaluate(() => ({ notifs: window.__notifs.length }));
45ok('ciclo flojo (1 propuesta sólida) → NO notifica', r.notifs === 0, `${r.notifs} notificaciones`);
46const chatAfterWeak = await p.locator('#chat-log').innerText();
47ok('pero SÍ se reporta en el chat (visual, siempre)', /Rendimiento/.test(chatAfterWeak));
48
49// ── ciclo BUENO: ≥2 propuestas sólidas → SÍ debe notificar ──
50await p.evaluate(async () => {
51 const m = await import('/js/main.js');
52 window.__notifs.length = 0;
53 m.reportImprovements({ proposals: [
54 { dept: 'Arquitectura', text: 'El módulo utils.js concentra demasiada lógica de negocio; propongo extraerlo en dos ficheros separados por responsabilidad, reduciendo el acoplamiento con la capa de vista.' },
55 { dept: 'Calidad', text: 'La función parseInput no valida entradas vacías ni nulas, lo que puede provocar un TypeError en producción; propongo añadir guardas explícitas y dos tests unitarios.' },
56 { dept: 'Rendimiento', text: 'ok' },
57 { dept: 'Producto/DX', text: 'nada' },
58 ], path: '.elffuss/soul/y.md' });
59});
60await p.waitForTimeout(400);
61r = await p.evaluate(() => ({ notifs: window.__notifs.length, title: window.__notifs[0]?.title }));
62ok('ciclo BUENO (2+ propuestas sólidas) → SÍ notifica', r.notifs === 1, JSON.stringify(r));
63ok('el título de la notificación es correcto', /mejora/.test(r.title || ''), r.title);
64
65// ── nunca pide permiso fuera de un gesto (notify() no debe llamar requestPermission) ──
66const asked = await p.evaluate(() => window.__askedPermission);
67ok('reportImprovements NUNCA pide permiso (solo lo hace un clic explícito)', asked === 0, `pedido ${asked} veces`);
68
69// ── panel ⚙: el estado de notificaciones se ve, sin botón "Activar" si ya está concedido ──
70await p.locator('#activity img').click(); await p.waitForTimeout(1000);
71await p.click('#mind-config'); await p.waitForTimeout(300);
72const notifTxt = await p.locator('.cfg-notif').innerText();
73ok('el panel muestra el permiso CONCEDIDO', /concedidas/.test(notifTxt), notifTxt);
74ok('sin botón «Activar» cuando ya está concedido', await p.locator('#cfg-notif-ask').count() === 0);
75
76console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ NOTIFICACIONES OK — filtro de calidad + sin pedir permiso sin gesto');
77await b.close();
78process.exit(fails ? 1 : 0);