Elffuss BraidHub

utopia-ia/elffuss-code public

main · 10.8 KiBRawPermalink
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.
9import { chromium } from 'playwright';
10import { CHROME_ARGS } from './chrome-args.mjs';
11const OUT = (process.env.SCRATCH || '/tmp/elffuss-test');
12const BASE = process.env.BASE || 'http://localhost:8799';
13let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
14
15const b = await chromium.launch({ args: ['--enable-unsafe-webgpu', ...CHROME_ARGS, '--autoplay-policy=no-user-gesture-required'] });
16const ctx = await b.newContext({ locale: 'es-ES' });
17await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.removeItem('elffusscode.ceoProfiles'); } catch {} });
18const p = await ctx.newPage({ viewport: { width: 1500, height: 900 } });
19p.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)); });
20await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
21const MARK = 'MARCA-UNICA-93af7c';
22await 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);
30await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(2000);
31
32await p.locator('#activity img').click(); await p.waitForTimeout(1200);
33ok('overlay + mundo montado', await p.locator('#mind-overlay').count() > 0);
34
35// leyenda con los 4 perfiles por defecto + CEO
36const legendItems = await p.locator('#mind-legend .ml-item').allInnerTexts();
37ok('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)
40await p.waitForTimeout(2500);
41let dbg = await p.evaluate(async () => (await import('/js/mind.js'))._debug());
42ok('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)
45const 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});
52ok('una línea de texto crea una estrella', linea.despues > linea.antes, `${linea.antes}→${linea.despues}`);
53const 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});
59ok('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)
62const logText = await p.evaluate(() => document.getElementById('mind-log-body').innerText);
63ok('el historial recoge la línea de texto', /línea de pensamiento normal/.test(logText));
64ok('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)
67ok('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
70await p.click('#mind-config'); await p.waitForTimeout(300);
71const rows = p.locator('.cfg-prof');
72ok('panel de config muestra 4 filas de perfil', await rows.count() === 4);
73await rows.nth(0).locator('.cp-name').fill('Seguridad');
74await rows.nth(0).locator('.cp-color').evaluate(el => { el.value = '#ff0055'; el.dispatchEvent(new Event('input')); });
75await p.click('#cfg-save'); await p.waitForTimeout(300);
76const newLegend = await p.locator('#mind-legend .ml-item').allInnerTexts();
77ok('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
80const 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);
100ok('forceCycle se ejecuta (semáforo líder + GPU libre)', cycleResult.ran, JSON.stringify(cycleResult));
101await p.waitForTimeout(500);
102const logAfterCycle = await p.evaluate(() => document.getElementById('mind-log-body').innerText);
103ok('la propuesta del CEO contiene el MARCADOR real leído del fichero (tool-calling REAL, no simulado)', logAfterCycle.includes(MARK), logAfterCycle.slice(-400));
104ok('se creó un nodo de propuesta forjada (clicable, con .md guardado)', await p.evaluate(() => document.querySelectorAll('.mind-node-label').length > 0));
105ok('el RESULTADO real de la tool (no solo el nombre) quedó linkado en el historial', /→ .*README/.test(logAfterCycle) || /→ /.test(logAfterCycle), '(línea "→ …" presente)');
106ok('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)
112const posBefore = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).cameraPos;
113// el clic, y en el mismo paso, ¿hay vuelo en marcha?
114const 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});
119ok('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
122const vuela = async () => (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).flying;
123for (let i = 0; i < 150 && await vuela(); i++) await p.waitForTimeout(100);
124const posAfter = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).cameraPos;
125const moved = Math.hypot(posAfter[0] - posBefore[0], posAfter[1] - posBefore[1], posAfter[2] - posBefore[2]);
126ok('la cámara realmente se movió al centrarse en el perfil', moved > 5, `desplazamiento ${moved.toFixed(1)}`);
127const settledFly = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).flying;
128ok('el vuelo termina solo (flying=false al acabar)', settledFly === false);
129
130// panel de propuesta: markdown FORMATEADO (no crudo) + botón «Ejecutar»
131await p.evaluate(() => document.querySelectorAll('.mind-node-label')[0]?.click());
132await p.waitForTimeout(400);
133const panelHtml = await p.evaluate(() => document.querySelector('#mind-panel .mp-body')?.innerHTML || '');
134ok('el .md se renderiza FORMATEADO (hay <h4> real, no texto crudo con ##)', /<h4/.test(panelHtml), panelHtml.slice(0, 80));
135ok('sin símbolos ## crudos en el panel (se renderizaron como encabezado)', !/##\s/.test(await p.evaluate(() => document.querySelector('#mind-panel .mp-body')?.innerText || '')));
136ok('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
138await p.click('#mp-exec');
139await p.waitForTimeout(600);
140ok('«Ejecutar» cierra la Mente y manda la propuesta a la cola del chat', await p.evaluate(() => document.getElementById('mind-overlay').style.display === 'none'));
141const chatText = await p.locator('#chat-log').innerText();
142ok('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
145await p.locator('#activity img').click(); await p.waitForTimeout(600);
146await 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});
150await p.waitForTimeout(1000);
151const 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)]));
152let overlaps = 0;
153for (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}
156ok('con muchos nodos NO quedan etiquetas amontonadas en el mismo punto', overlaps === 0, `${overlaps} solapes entre ${positions.length} visibles`);
157ok('el número de etiquetas visibles está acotado (no crece sin límite)', positions.length <= 14, `${positions.length} visibles`);
158
159await p.screenshot({ path: OUT + '/mind_stars.png' });
160console.log('captura → mind_stars.png');
161console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ MENTE v3 (estrellas + perfiles + ciudad + tool-calling real) OK');
162await b.close();
163process.exit(fails ? 1 : 0);