| 1 | // Bridge local: arranca el binario REAL compilado, conecta desde la UI (token |
| 2 | // pegado a mano, como haría el usuario), verifica los fuegos artificiales, y |
| 3 | // ejecuta un comando REAL (node/python) que solo un runtime de verdad puede |
| 4 | // producir — no algo que el shell emulado en JS pudiera fingir. |
| 5 | // |
| 6 | // Y PARAR: un comando largo se corta con la señal (resuelve en el acto con 130 |
| 7 | // y el proceso desaparece), cerrar el socket suelta los trabajos pendientes en |
| 8 | // vez de dejarlos colgados para siempre, Ctrl+C en el terminal corta el |
| 9 | // comando en curso, y parar a la elfa a mitad de un terminal.run mata el |
| 10 | // comando. |
| 11 | // |
| 12 | // Necesita el puerto 8765 (el del bridge, fijo en bridge.js) y servir la web en |
| 13 | // http://localhost:8799 (el único origen local que el bridge acepta). |
| 14 | import { chromium } from 'playwright'; |
| 15 | import { spawn, execFileSync } from 'node:child_process'; |
| 16 | import { mkdtempSync, realpathSync } from 'node:fs'; |
| 17 | import { tmpdir } from 'node:os'; |
| 18 | import { join } from 'node:path'; |
| 19 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 20 | const BRIDGE_BIN = process.env.BRIDGE_BIN |
| 21 | || new URL('../web/bridge-dl/elffuss-bridge-mac-arm64', import.meta.url).pathname; |
| 22 | const PORT = 8765; // puerto real que usa bridge.js (fijo) |
| 23 | const TOKEN = 'test-token-e2e-' + Math.random().toString(36).slice(2); |
| 24 | // La ejecución está acotada a una carpeta raíz (-root). La carpeta de trabajo que |
| 25 | // se pone en la UI tiene que estar DENTRO; antes se arrancaba sin -root (raíz = |
| 26 | // la carpeta desde la que se lanzaba el test) y se ponía /tmp, que el bridge |
| 27 | // rechaza con razón. |
| 28 | const ROOT = realpathSync(process.env.BRIDGE_ROOT || mkdtempSync(join(tmpdir(), 'elffuss-bridge-'))); |
| 29 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 30 | |
| 31 | // Grupo de procesos propio: al terminar se mata el bridge Y lo que haya lanzado. |
| 32 | const bp = spawn(BRIDGE_BIN, ['-port', String(PORT), '-token', TOKEN, '-root', ROOT], { stdio: 'pipe', detached: true }); |
| 33 | let bridgeLog = ''; |
| 34 | bp.stdout.on('data', d => bridgeLog += d.toString()); |
| 35 | bp.stderr.on('data', d => bridgeLog += d.toString()); |
| 36 | await new Promise(r => setTimeout(r, 800)); // que el bridge levante el puerto |
| 37 | const hijosDelBridge = () => { try { return execFileSync('pgrep', ['-P', String(bp.pid)]).toString().trim().split('\n').filter(Boolean); } catch { return []; } }; |
| 38 | const vivos = marca => { try { return execFileSync('pgrep', ['-f', marca]).toString().trim().split('\n').filter(Boolean).length; } catch { return 0; } }; |
| 39 | const esperar = ms => new Promise(r => setTimeout(r, ms)); |
| 40 | |
| 41 | const b = await chromium.launch(); |
| 42 | const ctx = await b.newContext({ locale: 'es-ES' }); |
| 43 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); |
| 44 | const p = await ctx.newPage({ viewport: { width: 1300, height: 900 } }); |
| 45 | p.on('console', m => { if (m.type() === 'error' && !/allow-same-origin/.test(m.text())) console.log(' err:', m.text().slice(0, 160)); }); |
| 46 | try { |
| 47 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1500); |
| 48 | |
| 49 | ok('el bridge real arrancó y escucha', /Escuchando SOLO en 127\.0\.0\.1/.test(bridgeLog), bridgeLog.slice(0, 80)); |
| 50 | const probed = await p.evaluate(async () => (await import('/js/bridge.js')).probe()); |
| 51 | ok('la web detecta el bridge escuchando (/ping)', probed); |
| 52 | |
| 53 | // abrir Ajustes, pegar el token real, conectar — flujo real de usuario |
| 54 | await p.click('#btn-settings'); await p.waitForTimeout(400); |
| 55 | await p.fill('#br-token', TOKEN); |
| 56 | await p.fill('#br-folder', ROOT); |
| 57 | await p.click('#br-connect'); |
| 58 | await p.waitForTimeout(1200); |
| 59 | ok('el punto de estado pasa a "conectado" (verde)', await p.evaluate(() => document.getElementById('br-dot')?.classList.contains('on'))); |
| 60 | ok('el texto de estado confirma la conexión', /conectado/.test(await p.locator('#br-status').innerText())); |
| 61 | ok('fuegos artificiales al conectar (canvas de celebración)', await p.locator('#fireworks-fx').count() > 0); |
| 62 | |
| 63 | // capabilities() ya refleja el bridge conectado |
| 64 | const caps = await p.evaluate(async () => (await import('/js/shell.js')).capabilities()); |
| 65 | ok('shell.capabilities() confirma bridge:true', caps.bridge === true, JSON.stringify(caps)); |
| 66 | |
| 67 | // EJECUCIÓN REAL: node -e con una marca única que solo un node real produce. |
| 68 | // (Aserción ESTRICTA: sin "syntax error" ni el eco del comando roto — antes |
| 69 | // un bug de comillas hacía que el propio mensaje de error "aprobara" el test |
| 70 | // por casualidad, al repetir la marca dentro de la línea rota.) |
| 71 | const MARK = 'REAL-NODE-' + Math.floor(Math.random() * 1e6); |
| 72 | const nodeOut = await p.evaluate(async (mark) => { |
| 73 | const s = await import('/js/shell.js'); |
| 74 | return s.stripAnsi(await s.exec(`node -e "console.log('${mark}')"`)); |
| 75 | }, MARK); |
| 76 | ok('node ejecuta de VERDAD en la máquina real (vía el bridge)', nodeOut.trim() === MARK, nodeOut); |
| 77 | |
| 78 | // python3 también, otra marca distinta |
| 79 | const MARK2 = 'REAL-PY-' + Math.floor(Math.random() * 1e6); |
| 80 | const pyOut = await p.evaluate(async (mark) => { |
| 81 | const s = await import('/js/shell.js'); |
| 82 | return s.stripAnsi(await s.exec(`python3 -c "print('${mark}')"`)); |
| 83 | }, MARK2); |
| 84 | ok('python3 ejecuta de VERDAD en la máquina real (vía el bridge)', pyOut.trim() === MARK2, pyOut); |
| 85 | |
| 86 | // el tool terminal.run del AGENTE también lo usa (mismo camino real) |
| 87 | const agentOut = await p.evaluate(async (mark) => { |
| 88 | const t = await import('/js/tools/index.js'); |
| 89 | return t.runTool('terminal.run', { command: `node -e "console.log('${mark}')"` }); |
| 90 | }, MARK + '-agent'); |
| 91 | ok('la elfa (terminal.run) también ejecuta de verdad vía el bridge', agentOut.trim() === MARK + '-agent', agentOut.slice(0, 60)); |
| 92 | |
| 93 | // ── PARAR ──────────────────────────────────────────────────────────────── |
| 94 | // 1. `sleep 30` con la señal abortada a mitad: resuelve en el acto con 130 y |
| 95 | // el bridge mata el proceso (deja de ser hijo suyo). |
| 96 | const r1 = await p.evaluate(async () => { |
| 97 | const br = await import('/js/bridge.js'); |
| 98 | const ac = new AbortController(); |
| 99 | const prom = br.exec('sleep 30', { signal: ac.signal }); |
| 100 | await new Promise(r => setTimeout(r, 700)); |
| 101 | ac.abort(); |
| 102 | // 5 s de margen frente a los 30 del comando: si espera al proceso, no llega. |
| 103 | return Promise.race([prom, new Promise(r => setTimeout(() => r('SIGUE ESPERANDO'), 5000))]); |
| 104 | }); |
| 105 | ok('`sleep 30` parado con la señal: resuelve en el acto con código 130', r1 === 130, String(r1)); |
| 106 | await esperar(500); |
| 107 | ok(' …y el bridge mató el proceso (ya no es hijo suyo)', hijosDelBridge().length === 0, `${hijosDelBridge().length} hijos vivos`); |
| 108 | |
| 109 | // 2. Cerrar el socket con un comando en marcha: el trabajo se resuelve (-1) y |
| 110 | // se avisa, en vez de quedarse pendiente para siempre. |
| 111 | const r2 = await p.evaluate(async () => { |
| 112 | const br = await import('/js/bridge.js'); |
| 113 | let err = ''; |
| 114 | const prom = br.exec('sleep 30', { onErr: t => { err += t; } }); |
| 115 | await new Promise(r => setTimeout(r, 500)); |
| 116 | br.disconnect(); |
| 117 | const code = await Promise.race([prom, new Promise(r => setTimeout(() => r('SIGUE ESPERANDO'), 5000))]); |
| 118 | return { code, err }; |
| 119 | }); |
| 120 | ok('cerrar el socket suelta el trabajo pendiente (resuelve con -1)', r2.code === -1, String(r2.code)); |
| 121 | ok(' …y lo dice: «[bridge desconectado]»', /\[bridge desconectado\]/.test(r2.err), JSON.stringify(r2.err)); |
| 122 | // reconectar para lo que sigue |
| 123 | const reconecta = await p.evaluate(async (tok) => { const br = await import('/js/bridge.js'); try { await br.connect(tok); return br.isConnected(); } catch (e) { return e.message; } }, TOKEN); |
| 124 | ok('se vuelve a conectar tras el corte', reconecta === true, String(reconecta)); |
| 125 | |
| 126 | // 3. Ctrl+C en el terminal corta el comando en curso (antes se ignoraba). |
| 127 | const MARK3 = 'CTRLC-' + Math.floor(Math.random() * 1e6); |
| 128 | await p.click('#act-term'); |
| 129 | await p.waitForTimeout(1500); |
| 130 | await p.locator('#terminal-host').click(); |
| 131 | await p.locator('#terminal-host .xterm-helper-textarea').focus().catch(() => {}); |
| 132 | // 'FI'+'N-…': la marca de final no aparece tal cual en la línea tecleada, |
| 133 | // solo en la salida si el comando llegara a terminar. |
| 134 | await p.keyboard.type(`node -e "setTimeout(()=>console.log('FI'+'N-${MARK3}'),30000)" ${MARK3}`); |
| 135 | await p.keyboard.press('Enter'); |
| 136 | await p.waitForTimeout(1200); |
| 137 | const corriendo = vivos(MARK3); |
| 138 | await p.keyboard.press('Control+C'); |
| 139 | await p.waitForTimeout(1200); |
| 140 | const rows = await p.locator('#terminal-host .xterm-rows').innerText().catch(() => ''); |
| 141 | ok('el comando largo estaba corriendo de verdad antes del Ctrl+C', corriendo >= 1, `${corriendo} procesos con la marca`); |
| 142 | ok('Ctrl+C mata el proceso', vivos(MARK3) === 0, `${vivos(MARK3)} procesos con la marca`); |
| 143 | ok(' …el terminal lo enseña (^C y código 130) y no llega al final', /\^C/.test(rows) && /130/.test(rows) && !rows.includes('FIN-' + MARK3), |
| 144 | rows.replace(/\n+/g, ' | ').slice(-200)); |
| 145 | await p.keyboard.type('echo de-vuelta'); |
| 146 | await p.keyboard.press('Enter'); |
| 147 | await p.waitForTimeout(600); |
| 148 | const rows2 = await p.locator('#terminal-host .xterm-rows').innerText().catch(() => ''); |
| 149 | ok(' …y el terminal vuelve a aceptar órdenes', /de-vuelta[\s\S]*de-vuelta/.test(rows2), rows2.replace(/\n+/g, ' | ').slice(-120)); |
| 150 | |
| 151 | // 4. La elfa parada a mitad de un terminal.run largo: la señal del turno llega |
| 152 | // por runTool → shell → bridge y mata el proceso. Antes runTool no pasaba |
| 153 | // nada a la herramienta y el turno esperaba al comando entero. |
| 154 | const MARK4 = 'AGENTE-' + Math.floor(Math.random() * 1e6); |
| 155 | const r4 = await p.evaluate(async (mark) => { |
| 156 | const { Agent } = await import('/js/agent.js'); |
| 157 | let llamadas = 0; |
| 158 | const llamada = { tool: 'terminal.run', args: { command: `node -e "setTimeout(()=>{},30000)" ${mark}` } }; |
| 159 | const ag = new Agent({ chat: async () => { llamadas++; return '```tool\n' + JSON.stringify(llamada) + '\n```'; } }); |
| 160 | const tipos = []; |
| 161 | const run = ag.handle('lanza algo largo', ev => tipos.push(ev.type)); |
| 162 | await new Promise(r => setTimeout(r, 1200)); |
| 163 | ag.stop(); |
| 164 | const fin = await Promise.race([run.then(() => 'terminó'), new Promise(r => setTimeout(() => r('SIGUE ESPERANDO'), 5000))]); |
| 165 | return { fin, tipos: [...new Set(tipos)], llamadas }; |
| 166 | }, MARK4); |
| 167 | ok('la elfa parada a mitad de terminal.run: el turno termina sin esperar al comando', r4.fin === 'terminó' && r4.tipos.includes('aborted') && r4.llamadas === 1, |
| 168 | `${r4.fin} · ${r4.tipos.join(',')} · ${r4.llamadas} llamadas`); |
| 169 | await esperar(300); |
| 170 | ok(' …y el comando muere en la máquina', vivos(MARK4) === 0, `${vivos(MARK4)} procesos con la marca`); |
| 171 | |
| 172 | // origen NO permitido: el bridge debe rechazar conexiones de otro origen |
| 173 | const originCheck = await fetch(`http://127.0.0.1:${PORT}/ping`, { headers: { Origin: 'https://evil.example' } }).then(r => r.status).catch(() => 'err'); |
| 174 | ok('el bridge RECHAZA orígenes no permitidos (seguridad)', originCheck === 403, `status ${originCheck}`); |
| 175 | } finally { |
| 176 | await b.close().catch(() => {}); |
| 177 | try { process.kill(-bp.pid, 'SIGTERM'); } catch { /* ya no estaba */ } |
| 178 | } |
| 179 | |
| 180 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ BRIDGE LOCAL OK — conexión real + ejecución real + parar + seguridad de origen'); |
| 181 | process.exit(fails ? 1 : 0); |