Elffuss BraidHub

utopia-ia/elffuss-code public

main · 13.7 KiBRawPermalink
1// Teclado, Escape, menús y búsqueda: lo que antes solo iba con ratón o no iba.
2//
3// 1. Escape cierra la capa de arriba (menú de la barra, Modos, Historial,
4// Ajustes, vista 3D) y el foco vuelve a quien la abrió.
5// 2. Barra de menús con teclado (↓ abre, →/← cambian de menú) y en el idioma
6// de la interfaz.
7// 3. Git: «Último» enseña el SHA corto y enlaza el commit en el remoto (sin
8// credenciales); la rama enlaza su árbol; `git log` del terminal da el SHA.
9// 4. Historial: filas que son botones, la activa marcada.
10// 5. Pestañas de conversación: ←/→ cambian, Supr cierra, el menú renombra.
11// 6. Modos: el botón dice qué está encendido, el menú no se cierra al tocar un
12// modo, y el texto del prompt avisa en modo Objetivo.
13// 7. Paleta «#»: Edit › Buscar en el código busca DENTRO de los ficheros y
14// abre el resultado en su línea; la lupa de la barra abre la paleta.
15// 8. Detalles: el medidor de contexto no promete un 🧹 que no existe, ↑ en
16// un borrador de varias líneas no lo pisa con el historial, «/new» en vez
17// de «/clear», y el terminal se redimensiona con ↑/↓.
18//
19// BASE=http://127.0.0.1:8898 node tests/keyboard-ux.mjs
20import { chromium } from 'playwright';
21const BASE = process.env.BASE || 'http://localhost:8799';
22let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
23
24const b = await chromium.launch();
25const ctx = await b.newContext({ locale: 'es-ES' });
26await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
27const p = await ctx.newPage({ viewport: { width: 1500, height: 900 } });
28const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
29
30const SHA = '3f9c2a17b04e5d6c8a9b0c1d2e3f405162738495';
31await p.goto(BASE + '/manifest.json');
32await p.evaluate(async (SHA) => {
33 const root = await navigator.storage.getDirectory();
34 const escribe = async (path, txt) => {
35 const parts = path.split('/'); const name = parts.pop(); let d = root;
36 for (const x of parts) d = await d.getDirectoryHandle(x, { create: true });
37 const w = await (await d.getFileHandle(name, { create: true })).createWritable(); await w.write(txt); await w.close();
38 };
39 await escribe('src/app.js', 'export const a = 1;\n// aquí está la palabraSecretaDePrueba\nexport const b = 2;\n');
40 await escribe('README.md', '# Demo\n');
41 await escribe('.git/HEAD', 'ref: refs/heads/main\n');
42 await escribe('.git/logs/HEAD', `0000000000000000000000000000000000000000 ${SHA} Ana Prueba <ana@example.com> 1760000000 +0200\tcommit: arregla el login\n`);
43 await escribe('.git/config', '[core]\n\tbare = false\n[remote "origin"]\n\turl = https://usuario:token123@github.com/demo-org/demo-repo.git\n');
44}, SHA);
45await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
46await p.waitForFunction(() => window.monaco && document.querySelector('#tree [data-path]') && window.elffussClaw?.conv?.getActive?.(), null, { timeout: 30000 });
47await p.evaluate(() => { window.__abiertas = []; window.open = (u) => { window.__abiertas.push(String(u)); return null; }; });
48const foco = () => p.evaluate(() => document.activeElement?.id || document.activeElement?.className || document.activeElement?.tagName);
49
50// 2 · barra de menús
51const nombres = await p.evaluate(() => [...document.querySelectorAll('#menubar button')].map(b => b.textContent));
52ok('2 · la barra de menús habla el idioma de la interfaz', JSON.stringify(nombres) === '["Archivo","Editar","Ver","Git"]', JSON.stringify(nombres));
53await p.locator('#menubar button[data-menu="file"]').focus();
54await p.keyboard.press('ArrowDown');
55await p.waitForTimeout(150);
56const enMenu = await p.evaluate(() => ({ abierto: !document.getElementById('topmenu').hidden, dentro: document.getElementById('topmenu').contains(document.activeElement), expanded: document.querySelector('#menubar button[data-menu="file"]').getAttribute('aria-expanded') }));
57ok('2 · ↓ en «Archivo» abre el menú con el foco en su primera opción', enMenu.abierto && enMenu.dentro && enMenu.expanded === 'true', JSON.stringify(enMenu));
58await p.keyboard.press('ArrowRight');
59await p.waitForTimeout(150);
60const editar = await p.evaluate(() => document.querySelector('#menubar button.open')?.dataset.menu);
61ok('2 · → pasa al menú «Editar»', editar === 'edit', editar);
62await p.keyboard.press('Escape');
63await p.waitForTimeout(100);
64const trasEsc = await p.evaluate(() => ({ cerrado: document.getElementById('topmenu').hidden, foco: document.activeElement?.dataset?.menu }));
65ok('1 · Escape cierra el menú y devuelve el foco a «Editar»', trasEsc.cerrado && trasEsc.foco === 'edit', JSON.stringify(trasEsc));
66
67// 3 · Git
68await p.click('#menubar button[data-menu="git"]');
69await p.waitForTimeout(250);
70const git = await p.evaluate(() => [...document.querySelectorAll('#topmenu .menu-item')].map(r => ({ txt: r.textContent, title: r.title, off: r.getAttribute('aria-disabled') })));
71const ultimo = git.find(g => /Último/.test(g.txt));
72ok('3 · «Último» enseña el SHA corto', /3f9c2a1 · commit: arregla el login/.test(ultimo?.txt || ''), JSON.stringify(git));
73ok('3 · …y enlaza el commit en el remoto, sin credenciales ni correo', ultimo?.title === `https://github.com/demo-org/demo-repo/commit/${SHA}` && !/token123|usuario|ana@/.test(JSON.stringify(git)), JSON.stringify(ultimo));
74await p.locator('#topmenu .menu-item', { hasText: 'Rama: main' }).click();
75ok('3 · la rama abre su árbol en el remoto', (await p.evaluate(() => window.__abiertas.at(-1))) === 'https://github.com/demo-org/demo-repo/tree/main');
76ok('3 · «Redactar el mensaje de commit» en vez de prometer un commit', git.some(g => /Redactar el mensaje de commit/.test(g.txt)) && !git.some(g => /commitee/.test(g.txt)));
77const logTxt = await p.evaluate(async () => { const sh = await import('/js/shell.js'); return sh.stripAnsi(await sh.exec('git log', { record: false })); });
78ok('3 · `git log` del terminal da el SHA, no la rama', logTxt.includes('commit ' + SHA) && !/correo|@example/.test(logTxt), logTxt.slice(0, 120));
79
80// 4 · Historial
81await p.fill('#prompt', 'hola');
82await p.press('#prompt', 'Enter');
83await p.waitForTimeout(400);
84await p.click('#btn-history');
85await p.waitForTimeout(300);
86const hist = await p.evaluate(() => ({ botones: document.querySelectorAll('#history-panel button.hp-open').length, actual: document.querySelectorAll('#history-panel .hp-open[aria-current="true"]').length, foco: document.activeElement?.className, dialog: document.getElementById('history-panel').getAttribute('role') }));
87ok('4 · el Historial es un diálogo con filas-botón y la conversación activa marcada', hist.botones >= 1 && hist.actual === 1 && hist.dialog === 'dialog' && /hp-open/.test(hist.foco || ''), JSON.stringify(hist));
88await p.keyboard.press('Escape');
89await p.waitForTimeout(100);
90ok('1 · Escape cierra el Historial y vuelve al botón', await p.evaluate(() => document.getElementById('history-panel').hidden && document.activeElement?.id === 'btn-history'));
91
92// 1 · Ajustes
93await p.click('#btn-settings');
94await p.waitForTimeout(300);
95ok('1 · Ajustes es un diálogo y el foco entra en él', await p.evaluate(() => document.getElementById('settings-panel').getAttribute('role') === 'dialog' && document.getElementById('settings-panel').contains(document.activeElement)));
96await p.keyboard.press('Escape');
97await p.waitForTimeout(100);
98ok('1 · Escape cierra Ajustes y el foco vuelve al engranaje', await p.evaluate(() => document.getElementById('settings-panel').hidden && document.activeElement?.id === 'btn-settings'));
99
100// 1 · vista 3D (arquitectura)
101await p.click('#act-arch');
102await p.waitForTimeout(800);
103await p.keyboard.press('Escape');
104await p.waitForTimeout(150);
105ok('1 · Escape cierra la vista de Arquitectura', await p.evaluate(() => document.getElementById('view-overlay').hidden));
106
107// 6 · Modos
108await p.click('#btn-modos');
109await p.waitForTimeout(100);
110await p.click('#btn-goal');
111await p.waitForTimeout(100);
112const modos = await p.evaluate(() => ({ abierto: !document.getElementById('modos-menu').hidden, boton: document.getElementById('btn-modos').textContent, aria: document.getElementById('btn-goal').getAttribute('aria-checked'), ph: document.getElementById('prompt').placeholder }));
113ok('6 · tocar un modo no cierra el menú y marca aria-checked', modos.abierto && modos.aria === 'true', JSON.stringify(modos));
114ok('6 · el botón «Modos» enseña 🎯 y el prompt avisa del modo Objetivo', /🎯/.test(modos.boton) && /objetivo/i.test(modos.ph), JSON.stringify(modos));
115await p.keyboard.press('Escape');
116await p.waitForTimeout(100);
117ok('1 · Escape cierra Modos', await p.evaluate(() => document.getElementById('modos-menu').hidden));
118await p.click('#btn-modos'); await p.click('#btn-goal'); await p.keyboard.press('Escape');
119
120// 5 · pestañas de conversación
121await p.locator('#conv-tabs .tab-add').dispatchEvent('click');
122await p.waitForTimeout(200);
123const antes = await p.evaluate(() => window.elffussClaw.conv.getActive().id);
124await p.locator('#conv-tabs .tab.active').focus();
125await p.keyboard.press('ArrowLeft');
126await p.waitForTimeout(150);
127const tras = await p.evaluate(() => ({ activa: window.elffussClaw.conv.getActive().id, role: document.querySelector('#conv-tabs .tab').getAttribute('role'), foco: document.activeElement?.getAttribute('role') }));
128ok('5 · ← cambia de conversación y las pestañas son role=tab', tras.activa !== antes && tras.role === 'tab' && tras.foco === 'tab', JSON.stringify(tras));
129await p.evaluate(() => { window.prompt = () => 'Mi conversación'; });
130await p.keyboard.press('Shift+F10');
131await p.waitForTimeout(100);
132await p.locator('#conv-menu .tm-item', { hasText: 'Renombrar' }).click();
133await p.waitForTimeout(250);
134ok('5 · el menú de la pestaña la renombra', await p.evaluate(() => document.querySelector('#conv-tabs .tab.active .tab-name')?.textContent === 'Mi conversación'));
135
136// 7 · paleta «#»
137await p.click('#menubar button[data-menu="edit"]');
138await p.locator('#topmenu .menu-item', { hasText: 'Buscar en el código' }).click();
139await p.waitForTimeout(150);
140const pal = await p.evaluate(() => ({ abierta: !document.getElementById('palette').hidden, valor: document.getElementById('pal-input').value, rol: document.getElementById('pal-input').getAttribute('role') }));
141ok('7 · Edit › Buscar en el código abre la paleta en modo «#» (y no se cierra sola)', pal.abierta && pal.valor === '#' && pal.rol === 'combobox', JSON.stringify(pal));
142await p.fill('#pal-input', '#palabraSecreta');
143await p.waitForSelector('#pal-list .pal-item', { timeout: 5000 }).catch(() => {});
144const hits = await p.evaluate(() => [...document.querySelectorAll('#pal-list .pal-item')].map(r => r.querySelector('.pi-hint').textContent));
145ok('7 · encuentra la palabra dentro de los ficheros, como fichero:línea', hits.includes('src/app.js:2'), JSON.stringify(hits));
146await p.press('#pal-input', 'Enter');
147await p.waitForTimeout(500);
148const abierto = await p.evaluate(() => ({ activa: document.querySelector('#tabs-bar .tab.active')?.dataset.path, linea: window.monaco?.editor?.getEditors?.()[0]?.getPosition()?.lineNumber }));
149ok('7 · Enter abre el fichero en esa línea', abierto.activa === 'src/app.js' && abierto.linea === 2, JSON.stringify(abierto));
150await p.click('#top-search');
151await p.waitForTimeout(200);
152ok('7 · la búsqueda fija de arriba abre la paleta (y se queda abierta)', await p.evaluate(() => !document.getElementById('palette').hidden));
153await p.keyboard.press('Escape');
154
155// 8 · detalles
156const ctxTitulo = await p.evaluate(async () => {
157 const m = await import('/js/main.js');
158 m.setCtxBudget(4100); // 100 tokens: casi lleno
159 window.elffussClaw.send('x'.repeat(600));
160 await new Promise(r => setTimeout(r, 400));
161 return document.getElementById('ctx-meter').title;
162});
163ok('8 · el medidor de contexto lleno manda a «+» y no a un 🧹 que no existe', !/🧹/.test(ctxTitulo) && /«\+»/.test(ctxTitulo), ctxTitulo);
164await p.click('#prompt');
165await p.fill('#prompt', '');
166await p.keyboard.type('linea uno');
167await p.keyboard.press('Shift+Enter');
168await p.keyboard.type('linea dos');
169await p.keyboard.press('ArrowUp');
170ok('8 · ↑ en un borrador de varias líneas no lo cambia por el historial', (await p.inputValue('#prompt')) === 'linea uno\nlinea dos');
171await p.fill('#prompt', '');
172await p.click('#btn-slash');
173await p.waitForTimeout(200);
174const slash = await p.evaluate(() => ({ items: [...document.querySelectorAll('#menu .menu-item b')].map(b => b.textContent), foco: document.activeElement?.classList.contains('menu-item') }));
175ok('8 · «/new» en vez de «/clear», y el foco entra en el menú', slash.items.includes('/new') && !slash.items.includes('/clear') && slash.foco, JSON.stringify(slash));
176await p.keyboard.press('ArrowDown');
177ok('8 · ↓ recorre el menú de comandos', await p.evaluate(() => document.activeElement?.textContent.startsWith('/search')));
178await p.keyboard.press('Escape');
179await p.waitForTimeout(100);
180ok('1 · Escape cierra el menú de comandos y vuelve a la caja de texto', await p.evaluate(() => document.getElementById('menu').hidden && document.activeElement?.id === 'prompt'));
181await p.click('#act-term');
182await p.waitForTimeout(400);
183const alto0 = await p.evaluate(() => document.getElementById('terminal-panel').offsetHeight);
184await p.locator('#term-resize').focus();
185await p.keyboard.press('ArrowUp');
186const alto1 = await p.evaluate(() => document.getElementById('terminal-panel').offsetHeight);
187ok('8 · el terminal se redimensiona con ↑ desde su separador', alto1 > alto0, `${alto0} → ${alto1}`);
188
189console.log('\n errores JS:', errs[0] || 'ninguno');
190ok('sin errores de página', errs.length === 0, errs.join(' | '));
191console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ TECLADO, ESCAPE, MENÚS Y BÚSQUEDA OK');
192await b.close();
193process.exit(fails ? 1 : 0);