| 1 | // Bug real reportado: ni el mensaje de mejoras en el chat ni la notificación |
| 2 | // del sistema tenían un botón para EJECUTAR la propuesta directamente. |
| 3 | // - Chat: reportImprovements ahora añade un botón real «▶ Ejecutar esta |
| 4 | // propuesta» que manda el .md a la cola/agente real. |
| 5 | // - Notificación: pasa por el service worker (registration.showNotification) |
| 6 | // con acciones («▶ Ejecutar» / «Ver en la Mente»); al pulsar, el SW avisa a |
| 7 | // la pestaña (postMessage) y esta ejecuta lo mismo que en el chat. |
| 8 | import { chromium } from 'playwright'; |
| 9 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 10 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 11 | |
| 12 | const b = await chromium.launch(); |
| 13 | const ctx = await b.newContext(); |
| 14 | await ctx.addInitScript(() => { |
| 15 | try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} |
| 16 | window.__shown = []; |
| 17 | // Chromium headless no sincroniza Notification.permission con |
| 18 | // grantPermissions de forma fiable (limitación conocida de Playwright) — |
| 19 | // igual que en notify.mjs, se fija directamente para poder probar el resto. |
| 20 | try { Object.defineProperty(Notification, 'permission', { value: 'granted', configurable: true }); } catch {} |
| 21 | }); |
| 22 | const p = await ctx.newPage({ viewport: { width: 1300, height: 850 } }); |
| 23 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1500); |
| 24 | // esperar a que el SW real controle la página (necesario para showNotification vía registration) |
| 25 | await p.waitForFunction(() => navigator.serviceWorker && navigator.serviceWorker.controller, null, { timeout: 10000 }).catch(() => {}); |
| 26 | // espiar showNotification en el registration real (sin disparar el permiso del SO en el test) |
| 27 | await p.evaluate(async () => { |
| 28 | const reg = await navigator.serviceWorker.ready; |
| 29 | const orig = reg.showNotification.bind(reg); |
| 30 | reg.showNotification = (title, opts) => { window.__shown.push({ title, opts }); return orig(title, { ...opts, silent: true }).catch(() => {}); }; |
| 31 | }); |
| 32 | |
| 33 | const MD = '# Propuestas de mejora — ciclo 7\n\n## Arquitectura\nExtraer un módulo de utilidades.\n'; |
| 34 | const dispatch = ev => p.evaluate(async (ev) => { const m = await import('/js/main.js'); m.reportImprovements(ev); }, ev); |
| 35 | |
| 36 | // ── botón real en el mensaje del chat ────────────────────────────────────── |
| 37 | await dispatch({ |
| 38 | proposals: [ |
| 39 | { dept: 'Arquitectura', text: 'Extraer un módulo de utilidades reduce el acoplamiento con la vista y facilita testear la lógica por separado.' }, |
| 40 | { dept: 'Calidad', text: 'Añadir guardas para entradas nulas evita un TypeError en producción cuando el usuario no rellena el campo.' }, |
| 41 | ], |
| 42 | path: '.elffuss/soul/2026-07-15-0748-tool.md', md: MD, |
| 43 | }); |
| 44 | await p.waitForTimeout(300); |
| 45 | const btn = p.locator('.proposal-exec-btn').last(); |
| 46 | ok('el mensaje del chat tiene un botón REAL de ejecutar', await btn.count() > 0); |
| 47 | await btn.click(); |
| 48 | await p.waitForTimeout(500); |
| 49 | const chatText = await p.locator('#chat-log').innerText(); |
| 50 | ok('al pulsar, la propuesta se manda a la cola/agente real (mismo .md)', chatText.includes('Extraer un módulo de utilidades')); |
| 51 | ok('el botón se deshabilita tras usarlo (no se puede disparar dos veces)', await btn.isDisabled()); |
| 52 | |
| 53 | // ── notificación del sistema con acción «Ejecutar» ───────────────────────── |
| 54 | await dispatch({ |
| 55 | proposals: [ |
| 56 | { dept: 'Rendimiento', text: 'Memoizar el cálculo evita recorrer el array entero en cada render, notable con listas grandes.' }, |
| 57 | { dept: 'Producto/DX', text: 'Renombrar variables crípticas y documentar la función principal ayuda a quien llegue nuevo al proyecto.' }, |
| 58 | ], |
| 59 | path: '.elffuss/soul/2026-07-15-0900-tool.md', md: MD, |
| 60 | }); |
| 61 | await p.waitForTimeout(400); |
| 62 | const shown = await p.evaluate(() => window.__shown); |
| 63 | ok('la notificación pasa por el SW (registration.showNotification), no la simple', shown.length > 0, JSON.stringify(shown.map(s => s.title))); |
| 64 | const last = shown.at(-1); |
| 65 | ok('trae la acción «execute»', last?.opts?.actions?.some(a => a.action === 'execute'), JSON.stringify(last?.opts?.actions)); |
| 66 | ok('trae la acción «open» (ver en la Mente)', last?.opts?.actions?.some(a => a.action === 'open')); |
| 67 | ok('lleva el .md real en data (para poder ejecutarlo al pulsar)', last?.opts?.data?.md === MD); |
| 68 | |
| 69 | // simular el clic en «▶ Ejecutar» de la notificación: el SW manda este mensaje |
| 70 | // a la pestaña (notificationclick → client.postMessage) — lo replicamos tal |
| 71 | // cual para probar el lado de la PÁGINA (el clic real en la notificación del |
| 72 | // SO no es automatizable, pero el contrato del mensaje sí). |
| 73 | await p.evaluate(() => { |
| 74 | const ev = new MessageEvent('message', { data: { type: 'notif-action', action: 'execute', md: '# Propuesta desde la notificación\nContenido real ejecutable.' } }); |
| 75 | navigator.serviceWorker.dispatchEvent(ev); |
| 76 | }); |
| 77 | await p.waitForTimeout(500); |
| 78 | const chatAfterNotif = await p.locator('#chat-log').innerText(); |
| 79 | ok('el clic en «▶ Ejecutar» de la notificación SÍ ejecuta la propuesta (mismo camino real)', chatAfterNotif.includes('Contenido real ejecutable')); |
| 80 | |
| 81 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ BOTÓN DE EJECUTAR (chat + notificación) OK'); |
| 82 | await b.close(); |
| 83 | process.exit(fails ? 1 : 0); |