| 1 | // Mente v3: estrellas por perfil (no consolas), historial completo, perfiles |
| 2 | // editables, ciudad de fondo + haces de actividad, y tool-calling REAL del CEO. |
| 3 | // |
| 4 | // Lo que depende del tiempo de la animación (estrellas, haces y vuelo viven |
| 5 | // unos segundos de reloj de fotogramas) se mide en el MISMO paso que lo |
| 6 | // provoca, no tras una espera fija: con el backend gráfico por defecto (sin |
| 7 | // ELFFUSS_CHROME_ARGS) un fotograma lento avanza ese reloj de golpe, y un haz de |
| 8 | // 1,4 s o un vuelo de 1,1 s ya habían terminado cuando se miraban. |
| 9 | import { chromium } from 'playwright'; |
| 10 | import { CHROME_ARGS } from './chrome-args.mjs'; |
| 11 | const OUT = (process.env.SCRATCH || '/tmp/elffuss-test'); |
| 12 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 13 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 14 | |
| 15 | const b = await chromium.launch({ args: ['--enable-unsafe-webgpu', ...CHROME_ARGS, '--autoplay-policy=no-user-gesture-required'] }); |
| 16 | const ctx = await b.newContext({ locale: 'es-ES' }); |
| 17 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.removeItem('elffusscode.ceoProfiles'); } catch {} }); |
| 18 | const p = await ctx.newPage({ viewport: { width: 1500, height: 900 } }); |
| 19 | p.on('console', m => { if (m.type() === 'error' && !/allow-same-origin|soundcloud|widget|encrypted-media|permissions policy/i.test(m.text())) console.log(' err:', m.text().slice(0, 160)); }); |
| 20 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 21 | const MARK = 'MARCA-UNICA-93af7c'; |
| 22 | await p.evaluate(async (mark) => { |
| 23 | const o = await navigator.storage.getDirectory(); |
| 24 | const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); }; |
| 25 | await w('README.md', '# demo\n' + mark + '\nProyecto de prueba.'); |
| 26 | const src = await o.getDirectoryHandle('src', { create: true }); |
| 27 | const wsrc = async (n, t) => { const f = await src.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); }; |
| 28 | await wsrc('app.js', 'export const app = 1;'); |
| 29 | }, MARK); |
| 30 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(2000); |
| 31 | |
| 32 | await p.locator('#activity img').click(); await p.waitForTimeout(1200); |
| 33 | ok('overlay + mundo montado', await p.locator('#mind-overlay').count() > 0); |
| 34 | |
| 35 | // leyenda con los 4 perfiles por defecto + CEO |
| 36 | const legendItems = await p.locator('#mind-legend .ml-item').allInnerTexts(); |
| 37 | ok('leyenda con 4 perfiles + CEO', legendItems.length === 5 && legendItems.some(t => /CEO/.test(t)) && legendItems.some(t => /Arquitectura/.test(t)), legendItems.join(' · ')); |
| 38 | |
| 39 | // ciudad de fondo construida (motor real) |
| 40 | await p.waitForTimeout(2500); |
| 41 | let dbg = await p.evaluate(async () => (await import('/js/mind.js'))._debug()); |
| 42 | ok('ciudad de fondo construida bajo la Mente', dbg.hasCity, JSON.stringify(dbg)); |
| 43 | |
| 44 | // estrellas: una línea normal vs una tool-call deben crear estrellas (tamaño/estilo distinto por kind, verificado por código) |
| 45 | const linea = await p.evaluate(async () => { |
| 46 | const m = await import('/js/mind.js'); |
| 47 | const antes = m._debug().starCount; |
| 48 | m.pushThought('arq', { type: 'open', name: 'Arquitectura' }); |
| 49 | m.pushThought('arq', { type: 'token', text: 'Esta es una línea de pensamiento normal que se vuelve estrella.\n' }); |
| 50 | return { antes, despues: m._debug().starCount }; |
| 51 | }); |
| 52 | ok('una línea de texto crea una estrella', linea.despues > linea.antes, `${linea.antes}→${linea.despues}`); |
| 53 | const tool = await p.evaluate(async () => { |
| 54 | const m = await import('/js/mind.js'); |
| 55 | const antes = m._debug().starCount; |
| 56 | m.pushThought('arq', { type: 'tool', text: 'leyendo README.md…', path: 'README.md' }); |
| 57 | return { antes, dbg: m._debug() }; |
| 58 | }); |
| 59 | ok('una tool-call crea otra estrella', tool.dbg.starCount > tool.antes, `${tool.antes}→${tool.dbg.starCount}`); |
| 60 | |
| 61 | // el historial completo muestra TODO (línea + tool) |
| 62 | const logText = await p.evaluate(() => document.getElementById('mind-log-body').innerText); |
| 63 | ok('el historial recoge la línea de texto', /línea de pensamiento normal/.test(logText)); |
| 64 | ok('el historial recoge la tool-call', /leyendo README\.md/.test(logText)); |
| 65 | |
| 66 | // haz de actividad sobre la ciudad (README.md existe en el modelo → beam real) |
| 67 | ok('la tool-call sobre un fichero real generó un haz + resaltado', tool.dbg.beamCount > 0 && tool.dbg.fileActivityCount > 0, JSON.stringify(tool.dbg)); |
| 68 | |
| 69 | // editor de perfiles: renombrar Arquitectura y cambiar color, guardar |
| 70 | await p.click('#mind-config'); await p.waitForTimeout(300); |
| 71 | const rows = p.locator('.cfg-prof'); |
| 72 | ok('panel de config muestra 4 filas de perfil', await rows.count() === 4); |
| 73 | await rows.nth(0).locator('.cp-name').fill('Seguridad'); |
| 74 | await rows.nth(0).locator('.cp-color').evaluate(el => { el.value = '#ff0055'; el.dispatchEvent(new Event('input')); }); |
| 75 | await p.click('#cfg-save'); await p.waitForTimeout(300); |
| 76 | const newLegend = await p.locator('#mind-legend .ml-item').allInnerTexts(); |
| 77 | ok('el perfil renombrado aparece en la leyenda', newLegend.some(t => /Seguridad/.test(t)), newLegend.join(' · ')); |
| 78 | |
| 79 | // tool-calling REAL del CEO: forceCycle con un proveedor falso que SÍ lee el fichero real |
| 80 | const cycleResult = await p.evaluate(async (mark) => { |
| 81 | const ceo = await import('/js/ceo.js'); |
| 82 | const mind = await import('/js/mind.js'); |
| 83 | ceo.init({ |
| 84 | provider: () => ({ |
| 85 | chat: async (history) => { |
| 86 | const res = history.find(m => m.role === 'user' && m.content.startsWith('[resultado code.read]')); |
| 87 | if (!res) return '```tool\n{"tool":"code.read","args":{"path":"README.md"}}\n```'; |
| 88 | const snippet = res.content.includes(mark) ? mark : 'NO-MARK'; |
| 89 | return 'Propuesta basada en el contenido real: ' + snippet; |
| 90 | }, |
| 91 | }), |
| 92 | isBusy: () => false, |
| 93 | onEvent: (ch, ev) => mind.pushThought(ch, ev), |
| 94 | }); |
| 95 | const t0 = Date.now(); |
| 96 | while (!ceo.isThisTabLeader() && Date.now() - t0 < 5000) await new Promise(r => setTimeout(r, 100)); |
| 97 | const ran = await ceo.forceCycle(); |
| 98 | return { ran, leader: ceo.isThisTabLeader() }; |
| 99 | }, MARK); |
| 100 | ok('forceCycle se ejecuta (semáforo líder + GPU libre)', cycleResult.ran, JSON.stringify(cycleResult)); |
| 101 | await p.waitForTimeout(500); |
| 102 | const logAfterCycle = await p.evaluate(() => document.getElementById('mind-log-body').innerText); |
| 103 | ok('la propuesta del CEO contiene el MARCADOR real leído del fichero (tool-calling REAL, no simulado)', logAfterCycle.includes(MARK), logAfterCycle.slice(-400)); |
| 104 | ok('se creó un nodo de propuesta forjada (clicable, con .md guardado)', await p.evaluate(() => document.querySelectorAll('.mind-node-label').length > 0)); |
| 105 | ok('el RESULTADO real de la tool (no solo el nombre) quedó linkado en el historial', /→ .*README/.test(logAfterCycle) || /→ /.test(logAfterCycle), '(línea "→ …" presente)'); |
| 106 | ok('el nombre del fichero guardado es DESCRIPTIVO (fecha+tema, no mejoras-NNN)', await p.evaluate(() => { |
| 107 | const rows = [...document.querySelectorAll('.mind-node-label')].map(l => l.textContent); |
| 108 | return rows.some(t => /^\d{4}-\d{2}-\d{2}-\d{4}-/.test(t)); |
| 109 | })); |
| 110 | |
| 111 | // clic en la leyenda → la cámara VUELA a centrarse (posición cambia de verdad) |
| 112 | const posBefore = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).cameraPos; |
| 113 | // el clic, y en el mismo paso, ¿hay vuelo en marcha? |
| 114 | const midFly = await p.evaluate(async () => { |
| 115 | const m = await import('/js/mind.js'); |
| 116 | document.querySelector('.ml-item[data-id="rend"]').click(); // perfil lejos de la posición inicial de cámara |
| 117 | return m._debug(); |
| 118 | }); |
| 119 | ok('el clic dispara el vuelo (flying=true a mitad de camino)', midFly.flying); |
| 120 | // que termine (dura 1,1 s de reloj de fotogramas): se pregunta desde aquí, sin |
| 121 | // waitForFunction, que no espera a un predicado asíncrono |
| 122 | const vuela = async () => (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).flying; |
| 123 | for (let i = 0; i < 150 && await vuela(); i++) await p.waitForTimeout(100); |
| 124 | const posAfter = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).cameraPos; |
| 125 | const moved = Math.hypot(posAfter[0] - posBefore[0], posAfter[1] - posBefore[1], posAfter[2] - posBefore[2]); |
| 126 | ok('la cámara realmente se movió al centrarse en el perfil', moved > 5, `desplazamiento ${moved.toFixed(1)}`); |
| 127 | const settledFly = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).flying; |
| 128 | ok('el vuelo termina solo (flying=false al acabar)', settledFly === false); |
| 129 | |
| 130 | // panel de propuesta: markdown FORMATEADO (no crudo) + botón «Ejecutar» |
| 131 | await p.evaluate(() => document.querySelectorAll('.mind-node-label')[0]?.click()); |
| 132 | await p.waitForTimeout(400); |
| 133 | const panelHtml = await p.evaluate(() => document.querySelector('#mind-panel .mp-body')?.innerHTML || ''); |
| 134 | ok('el .md se renderiza FORMATEADO (hay <h4> real, no texto crudo con ##)', /<h4/.test(panelHtml), panelHtml.slice(0, 80)); |
| 135 | ok('sin símbolos ## crudos en el panel (se renderizaron como encabezado)', !/##\s/.test(await p.evaluate(() => document.querySelector('#mind-panel .mp-body')?.innerText || ''))); |
| 136 | ok('botón «Ejecutar esta propuesta» presente', await p.locator('#mp-exec').count() > 0); |
| 137 | // clic en Ejecutar → cierra la Mente y la propuesta entra en la cola del chat real |
| 138 | await p.click('#mp-exec'); |
| 139 | await p.waitForTimeout(600); |
| 140 | ok('«Ejecutar» cierra la Mente y manda la propuesta a la cola del chat', await p.evaluate(() => document.getElementById('mind-overlay').style.display === 'none')); |
| 141 | const chatText = await p.locator('#chat-log').innerText(); |
| 142 | ok('la propuesta llegó como mensaje real al chat/cola', /Implementa esta propuesta/.test(chatText)); |
| 143 | |
| 144 | // anti-solape: crear MUCHOS nodos de golpe y comprobar que no quedan amontonados |
| 145 | await p.locator('#activity img').click(); await p.waitForTimeout(600); |
| 146 | await p.evaluate(async () => { |
| 147 | const m = await import('/js/mind.js'); |
| 148 | for (let i = 0; i < 20; i++) m.pushThought('ceo', { type: 'built', text: 'extra ' + i, path: `.elffuss/soul/extra-${i}.md`, md: '# extra ' + i, proposals: [] }); |
| 149 | }); |
| 150 | await p.waitForTimeout(1000); |
| 151 | const positions = await p.evaluate(() => [...document.querySelectorAll('.mind-node-label')].filter(l => l.style.display !== 'none').map(l => [parseFloat(l.style.left), parseFloat(l.style.top)])); |
| 152 | let overlaps = 0; |
| 153 | for (let i = 0; i < positions.length; i++) for (let j = i + 1; j < positions.length; j++) { |
| 154 | if (Math.abs(positions[i][0] - positions[j][0]) < 20 && Math.abs(positions[i][1] - positions[j][1]) < 8) overlaps++; |
| 155 | } |
| 156 | ok('con muchos nodos NO quedan etiquetas amontonadas en el mismo punto', overlaps === 0, `${overlaps} solapes entre ${positions.length} visibles`); |
| 157 | ok('el número de etiquetas visibles está acotado (no crece sin límite)', positions.length <= 14, `${positions.length} visibles`); |
| 158 | |
| 159 | await p.screenshot({ path: OUT + '/mind_stars.png' }); |
| 160 | console.log('captura → mind_stars.png'); |
| 161 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ MENTE v3 (estrellas + perfiles + ciudad + tool-calling real) OK'); |
| 162 | await b.close(); |
| 163 | process.exit(fails ? 1 : 0); |