| 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. Lo que muere es el ÁRBOL: un `npm run dev`, un `a; b` o lo que siga |
| 11 | // corriendo al cerrar el socket. Se comprueba con `pgrep -f <marca>`, porque |
| 12 | // `pgrep -P` solo ve hijos directos del bridge y un huérfano deja de serlo. Y un |
| 13 | // «stop» que sale justo detrás del «exec» no se pierde. |
| 14 | // |
| 15 | // Necesita el puerto 8765 (el del bridge, fijo en bridge.js) y servir la web en |
| 16 | // http://localhost:8799 (el único origen local que el bridge acepta). |
| 17 | import { chromium } from 'playwright'; |
| 18 | import { spawn, execFileSync } from 'node:child_process'; |
| 19 | import { mkdtempSync, realpathSync, writeFileSync, existsSync } from 'node:fs'; |
| 20 | import { tmpdir } from 'node:os'; |
| 21 | import { join } from 'node:path'; |
| 22 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 23 | const BRIDGE_BIN = process.env.BRIDGE_BIN |
| 24 | || new URL('../web/bridge-dl/elffuss-bridge-mac-arm64', import.meta.url).pathname; |
| 25 | const PORT = 8765; // puerto real que usa bridge.js (fijo) |
| 26 | const TOKEN = 'test-token-e2e-' + Math.random().toString(36).slice(2); |
| 27 | // La ejecución está acotada a una carpeta raíz (-root). La carpeta de trabajo que |
| 28 | // se pone en la UI tiene que estar DENTRO; antes se arrancaba sin -root (raíz = |
| 29 | // la carpeta desde la que se lanzaba el test) y se ponía /tmp, que el bridge |
| 30 | // rechaza con razón. |
| 31 | const ROOT = realpathSync(process.env.BRIDGE_ROOT || mkdtempSync(join(tmpdir(), 'elffuss-bridge-'))); |
| 32 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 33 | |
| 34 | // Grupo de procesos propio: al terminar se mata el bridge Y lo que haya lanzado. |
| 35 | const bp = spawn(BRIDGE_BIN, ['-port', String(PORT), '-token', TOKEN, '-root', ROOT], { stdio: 'pipe', detached: true }); |
| 36 | let bridgeLog = ''; |
| 37 | bp.stdout.on('data', d => bridgeLog += d.toString()); |
| 38 | bp.stderr.on('data', d => bridgeLog += d.toString()); |
| 39 | await new Promise(r => setTimeout(r, 800)); // que el bridge levante el puerto |
| 40 | const hijosDelBridge = () => { try { return execFileSync('pgrep', ['-P', String(bp.pid)]).toString().trim().split('\n').filter(Boolean); } catch { return []; } }; |
| 41 | const vivos = marca => { try { return execFileSync('pgrep', ['-f', marca]).toString().trim().split('\n').filter(Boolean).length; } catch { return 0; } }; |
| 42 | const esperar = ms => new Promise(r => setTimeout(r, ms)); |
| 43 | |
| 44 | const b = await chromium.launch(); |
| 45 | const ctx = await b.newContext({ locale: 'es-ES' }); |
| 46 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); |
| 47 | const p = await ctx.newPage({ viewport: { width: 1300, height: 900 } }); |
| 48 | p.on('console', m => { if (m.type() === 'error' && !/allow-same-origin/.test(m.text())) console.log(' err:', m.text().slice(0, 160)); }); |
| 49 | try { |
| 50 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1500); |
| 51 | |
| 52 | ok('el bridge real arrancó y escucha', /Escuchando SOLO en 127\.0\.0\.1/.test(bridgeLog), bridgeLog.slice(0, 80)); |
| 53 | const probed = await p.evaluate(async () => (await import('/js/bridge.js')).probe()); |
| 54 | ok('la web detecta el bridge escuchando (/ping)', probed); |
| 55 | |
| 56 | // abrir Ajustes, pegar el token real, conectar — flujo real de usuario |
| 57 | await p.click('#btn-settings'); await p.waitForTimeout(400); |
| 58 | await p.fill('#br-token', TOKEN); |
| 59 | await p.fill('#br-folder', ROOT); |
| 60 | await p.click('#br-connect'); |
| 61 | await p.waitForTimeout(1200); |
| 62 | ok('el punto de estado pasa a "conectado" (verde)', await p.evaluate(() => document.getElementById('br-dot')?.classList.contains('on'))); |
| 63 | ok('el texto de estado confirma la conexión', /conectado/.test(await p.locator('#br-status').innerText())); |
| 64 | ok('fuegos artificiales al conectar (canvas de celebración)', await p.locator('#fireworks-fx').count() > 0); |
| 65 | |
| 66 | // capabilities() ya refleja el bridge conectado |
| 67 | const caps = await p.evaluate(async () => (await import('/js/shell.js')).capabilities()); |
| 68 | ok('shell.capabilities() confirma bridge:true', caps.bridge === true, JSON.stringify(caps)); |
| 69 | |
| 70 | // EJECUCIÓN REAL: node -e con una marca única que solo un node real produce. |
| 71 | // (Aserción ESTRICTA: sin "syntax error" ni el eco del comando roto — antes |
| 72 | // un bug de comillas hacía que el propio mensaje de error "aprobara" el test |
| 73 | // por casualidad, al repetir la marca dentro de la línea rota.) |
| 74 | const MARK = 'REAL-NODE-' + Math.floor(Math.random() * 1e6); |
| 75 | const nodeOut = await p.evaluate(async (mark) => { |
| 76 | const s = await import('/js/shell.js'); |
| 77 | return s.stripAnsi(await s.exec(`node -e "console.log('${mark}')"`)); |
| 78 | }, MARK); |
| 79 | ok('node ejecuta de VERDAD en la máquina real (vía el bridge)', nodeOut.trim() === MARK, nodeOut); |
| 80 | |
| 81 | // python3 también, otra marca distinta |
| 82 | const MARK2 = 'REAL-PY-' + Math.floor(Math.random() * 1e6); |
| 83 | const pyOut = await p.evaluate(async (mark) => { |
| 84 | const s = await import('/js/shell.js'); |
| 85 | return s.stripAnsi(await s.exec(`python3 -c "print('${mark}')"`)); |
| 86 | }, MARK2); |
| 87 | ok('python3 ejecuta de VERDAD en la máquina real (vía el bridge)', pyOut.trim() === MARK2, pyOut); |
| 88 | |
| 89 | // el tool terminal.run del AGENTE también lo usa (mismo camino real) |
| 90 | const agentOut = await p.evaluate(async (mark) => { |
| 91 | const t = await import('/js/tools/index.js'); |
| 92 | return t.runTool('terminal.run', { command: `node -e "console.log('${mark}')"` }); |
| 93 | }, MARK + '-agent'); |
| 94 | ok('la elfa (terminal.run) también ejecuta de verdad vía el bridge', agentOut.trim() === MARK + '-agent', agentOut.slice(0, 60)); |
| 95 | |
| 96 | // ── PARAR ──────────────────────────────────────────────────────────────── |
| 97 | // 1. `sleep 30` con la señal abortada a mitad: resuelve en el acto con 130 y |
| 98 | // el bridge mata el proceso (deja de ser hijo suyo). |
| 99 | const r1 = await p.evaluate(async () => { |
| 100 | const br = await import('/js/bridge.js'); |
| 101 | const ac = new AbortController(); |
| 102 | const prom = br.exec('sleep 30', { signal: ac.signal }); |
| 103 | await new Promise(r => setTimeout(r, 700)); |
| 104 | ac.abort(); |
| 105 | // 5 s de margen frente a los 30 del comando: si espera al proceso, no llega. |
| 106 | return Promise.race([prom, new Promise(r => setTimeout(() => r('SIGUE ESPERANDO'), 5000))]); |
| 107 | }); |
| 108 | ok('`sleep 30` parado con la señal: resuelve en el acto con código 130', r1 === 130, String(r1)); |
| 109 | await esperar(500); |
| 110 | ok(' …y el bridge mató el proceso (ya no es hijo suyo)', hijosDelBridge().length === 0, `${hijosDelBridge().length} hijos vivos`); |
| 111 | |
| 112 | // 1b. Una cadena `a; b`: el sh lanza node y espera. Parar mata los dos (antes |
| 113 | // solo el sh: node seguía vivo y el «; echo» no importaba). |
| 114 | const MARK_CADENA = 'CADENA-' + Math.floor(Math.random() * 1e6); |
| 115 | const r1b = await p.evaluate(async (mark) => { |
| 116 | const br = await import('/js/bridge.js'); |
| 117 | const ac = new AbortController(); |
| 118 | let out = ''; |
| 119 | const prom = br.exec(`node -e "setTimeout(()=>{},30000)" ${mark}; echo despues-${mark}`, { signal: ac.signal, onOut: t => { out += t; } }); |
| 120 | await new Promise(r => setTimeout(r, 900)); |
| 121 | ac.abort(); |
| 122 | const code = await prom; |
| 123 | await new Promise(r => setTimeout(r, 600)); |
| 124 | return { code, out }; |
| 125 | }, MARK_CADENA); |
| 126 | await esperar(1500); |
| 127 | ok('`node …; echo` parado: resuelve con 130', r1b.code === 130, String(r1b.code)); |
| 128 | ok(' …y node, que lanzó el sh, también muere', vivos(MARK_CADENA) === 0, `${vivos(MARK_CADENA)} procesos con la marca`); |
| 129 | ok(' …y la segunda mitad de la cadena no llega a correr', !r1b.out.includes('despues-'), JSON.stringify(r1b.out)); |
| 130 | |
| 131 | // 1c. `npm run dev` (la línea exacta que arma shell.js) con un script que |
| 132 | // lanza node: parar mata el node del script, no solo el npm. |
| 133 | const MARK_NPM = 'NPMDEV-' + Math.floor(Math.random() * 1e6); |
| 134 | writeFileSync(join(ROOT, 'package.json'), JSON.stringify({ name: 'parar-npm', version: '1.0.0', scripts: { dev: `node -e "setTimeout(()=>{},30000)" ${MARK_NPM}` } })); |
| 135 | const r1c = p.evaluate(async () => { |
| 136 | const br = await import('/js/bridge.js'); |
| 137 | window.__acNpm = new AbortController(); |
| 138 | return br.exec(`npm 'run' 'dev'`, { signal: window.__acNpm.signal }); |
| 139 | }); |
| 140 | let antesNpm = 0; |
| 141 | for (let i = 0; i < 40 && !antesNpm; i++) { await esperar(250); antesNpm = vivos(MARK_NPM); } |
| 142 | await p.evaluate(() => window.__acNpm.abort()); |
| 143 | const codeNpm = await r1c; |
| 144 | await esperar(2500); |
| 145 | ok('`npm run dev` corría de verdad (su node tenía la marca)', antesNpm >= 1, `${antesNpm} procesos con la marca`); |
| 146 | ok(' …parado: resuelve con 130 y el node del script muere', codeNpm === 130 && vivos(MARK_NPM) === 0, `código ${codeNpm} · ${vivos(MARK_NPM)} procesos con la marca`); |
| 147 | |
| 148 | // 1d. Un «stop» justo detrás del «exec» (en el mismo tick, o uno después): |
| 149 | // antes el bridge aún no había apuntado el proceso, ignoraba el «stop» y el |
| 150 | // comando corría entero aunque la web ya lo diera por parado. |
| 151 | const r1d = await p.evaluate(async (root) => { |
| 152 | const br = await import('/js/bridge.js'); |
| 153 | const codes = []; |
| 154 | for (let i = 0; i < 12; i++) { |
| 155 | const ac = new AbortController(); |
| 156 | const prom = br.exec(`sleep 1; touch '${root}/pronto-${i}'`, { signal: ac.signal }); |
| 157 | if (i % 2) await new Promise(r => setTimeout(r, 0)); // uno de cada dos, con un turno de por medio |
| 158 | ac.abort(); |
| 159 | codes.push(await prom); |
| 160 | } |
| 161 | return codes; |
| 162 | }, ROOT); |
| 163 | await esperar(2000); |
| 164 | const corrieron = Array.from({ length: 12 }, (_, i) => i).filter(i => existsSync(join(ROOT, `pronto-${i}`))); |
| 165 | ok('«stop» justo detrás del «exec»: ninguno de los 12 comandos llega a terminar', r1d.every(c => c === 130) && corrieron.length === 0, |
| 166 | `códigos ${[...new Set(r1d)].join(',')} · terminaron ${corrieron.length}`); |
| 167 | |
| 168 | // 2. Cerrar el socket con un comando en marcha: el trabajo se resuelve (-1) y |
| 169 | // se avisa, en vez de quedarse pendiente para siempre. |
| 170 | const r2 = await p.evaluate(async () => { |
| 171 | const br = await import('/js/bridge.js'); |
| 172 | let err = ''; |
| 173 | const prom = br.exec('sleep 30', { onErr: t => { err += t; } }); |
| 174 | await new Promise(r => setTimeout(r, 500)); |
| 175 | br.disconnect(); |
| 176 | const code = await Promise.race([prom, new Promise(r => setTimeout(() => r('SIGUE ESPERANDO'), 5000))]); |
| 177 | return { code, err }; |
| 178 | }); |
| 179 | ok('cerrar el socket suelta el trabajo pendiente (resuelve con -1)', r2.code === -1, String(r2.code)); |
| 180 | ok(' …y lo dice: «[bridge desconectado]»', /\[bridge desconectado\]/.test(r2.err), JSON.stringify(r2.err)); |
| 181 | // 2b. …y el bridge mata lo que corría por ese socket, con lo que haya lanzado. |
| 182 | const reconecta2 = 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); |
| 183 | const MARK_SOCK = 'SOCKET-' + Math.floor(Math.random() * 1e6); |
| 184 | const r2b = await p.evaluate(async (mark) => { |
| 185 | const br = await import('/js/bridge.js'); |
| 186 | const prom = br.exec(`node -e "setTimeout(()=>{},30000)" ${mark}; true`); |
| 187 | await new Promise(r => setTimeout(r, 900)); |
| 188 | br.disconnect(); |
| 189 | return prom; |
| 190 | }, MARK_SOCK); |
| 191 | await esperar(1500); |
| 192 | ok('cerrar el socket mata el comando en marcha y lo que lanzó', reconecta2 === true && r2b === -1 && vivos(MARK_SOCK) === 0, |
| 193 | `reconectado ${reconecta2} · código ${r2b} · ${vivos(MARK_SOCK)} procesos con la marca`); |
| 194 | // reconectar para lo que sigue |
| 195 | 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); |
| 196 | ok('se vuelve a conectar tras el corte', reconecta === true, String(reconecta)); |
| 197 | |
| 198 | // 3. Ctrl+C en el terminal corta el comando en curso (antes se ignoraba). |
| 199 | const MARK3 = 'CTRLC-' + Math.floor(Math.random() * 1e6); |
| 200 | await p.click('#act-term'); |
| 201 | await p.waitForTimeout(1500); |
| 202 | await p.locator('#terminal-host').click(); |
| 203 | await p.locator('#terminal-host .xterm-helper-textarea').focus().catch(() => {}); |
| 204 | // 'FI'+'N-…': la marca de final no aparece tal cual en la línea tecleada, |
| 205 | // solo en la salida si el comando llegara a terminar. |
| 206 | await p.keyboard.type(`node -e "setTimeout(()=>console.log('FI'+'N-${MARK3}'),30000)" ${MARK3}`); |
| 207 | await p.keyboard.press('Enter'); |
| 208 | await p.waitForTimeout(1200); |
| 209 | const corriendo = vivos(MARK3); |
| 210 | await p.keyboard.press('Control+C'); |
| 211 | await p.waitForTimeout(1200); |
| 212 | const rows = await p.locator('#terminal-host .xterm-rows').innerText().catch(() => ''); |
| 213 | ok('el comando largo estaba corriendo de verdad antes del Ctrl+C', corriendo >= 1, `${corriendo} procesos con la marca`); |
| 214 | ok('Ctrl+C mata el proceso', vivos(MARK3) === 0, `${vivos(MARK3)} procesos con la marca`); |
| 215 | 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), |
| 216 | rows.replace(/\n+/g, ' | ').slice(-200)); |
| 217 | await p.keyboard.type('echo de-vuelta'); |
| 218 | await p.keyboard.press('Enter'); |
| 219 | await p.waitForTimeout(600); |
| 220 | const rows2 = await p.locator('#terminal-host .xterm-rows').innerText().catch(() => ''); |
| 221 | ok(' …y el terminal vuelve a aceptar órdenes', /de-vuelta[\s\S]*de-vuelta/.test(rows2), rows2.replace(/\n+/g, ' | ').slice(-120)); |
| 222 | |
| 223 | // 4. La elfa parada a mitad de un terminal.run largo: la señal del turno llega |
| 224 | // por runTool → shell → bridge y mata el proceso. Antes runTool no pasaba |
| 225 | // nada a la herramienta y el turno esperaba al comando entero. |
| 226 | const MARK4 = 'AGENTE-' + Math.floor(Math.random() * 1e6); |
| 227 | const r4 = await p.evaluate(async (mark) => { |
| 228 | const { Agent } = await import('/js/agent.js'); |
| 229 | let llamadas = 0; |
| 230 | const llamada = { tool: 'terminal.run', args: { command: `node -e "setTimeout(()=>{},30000)" ${mark}` } }; |
| 231 | const ag = new Agent({ chat: async () => { llamadas++; return '```tool\n' + JSON.stringify(llamada) + '\n```'; } }); |
| 232 | const tipos = []; |
| 233 | const run = ag.handle('lanza algo largo', ev => tipos.push(ev.type)); |
| 234 | await new Promise(r => setTimeout(r, 1200)); |
| 235 | ag.stop(); |
| 236 | const fin = await Promise.race([run.then(() => 'terminó'), new Promise(r => setTimeout(() => r('SIGUE ESPERANDO'), 5000))]); |
| 237 | return { fin, tipos: [...new Set(tipos)], llamadas }; |
| 238 | }, MARK4); |
| 239 | 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, |
| 240 | `${r4.fin} · ${r4.tipos.join(',')} · ${r4.llamadas} llamadas`); |
| 241 | await esperar(300); |
| 242 | ok(' …y el comando muere en la máquina', vivos(MARK4) === 0, `${vivos(MARK4)} procesos con la marca`); |
| 243 | |
| 244 | // origen NO permitido: el bridge debe rechazar conexiones de otro origen |
| 245 | const originCheck = await fetch(`http://127.0.0.1:${PORT}/ping`, { headers: { Origin: 'https://evil.example' } }).then(r => r.status).catch(() => 'err'); |
| 246 | ok('el bridge RECHAZA orígenes no permitidos (seguridad)', originCheck === 403, `status ${originCheck}`); |
| 247 | |
| 248 | // Cerrar el BRIDGE (Ctrl+C en su ventana) con un comando en marcha: cada |
| 249 | // comando va en su propio grupo de procesos y la señal ya no le llega sola, |
| 250 | // así que es el bridge el que los para antes de salir. Va al final: después |
| 251 | // ya no hay bridge. |
| 252 | const MARK_CIERRE = 'CIERRE-' + Math.floor(Math.random() * 1e6); |
| 253 | await p.evaluate(async (mark) => { const br = await import('/js/bridge.js'); br.exec(`node -e "setTimeout(()=>{},30000)" ${mark}; true`); }, MARK_CIERRE); |
| 254 | let antesCierre = 0; |
| 255 | for (let i = 0; i < 20 && !antesCierre; i++) { await esperar(200); antesCierre = vivos(MARK_CIERRE); } |
| 256 | const salio = new Promise(r => bp.once('exit', () => r(true))); |
| 257 | process.kill(bp.pid, 'SIGINT'); // solo al bridge, como el Ctrl+C de su ventana |
| 258 | const bridgeSalio = await Promise.race([salio, esperar(6000).then(() => false)]); |
| 259 | await esperar(500); |
| 260 | ok('Ctrl+C al bridge con un comando en marcha: el bridge sale y el comando muere', |
| 261 | antesCierre >= 1 && bridgeSalio && vivos(MARK_CIERRE) === 0, `antes ${antesCierre} · salió ${bridgeSalio} · ${vivos(MARK_CIERRE)} procesos con la marca`); |
| 262 | } finally { |
| 263 | await b.close().catch(() => {}); |
| 264 | try { process.kill(-bp.pid, 'SIGTERM'); } catch { /* ya no estaba */ } |
| 265 | } |
| 266 | |
| 267 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ BRIDGE LOCAL OK — conexión real + ejecución real + parar + seguridad de origen'); |
| 268 | process.exit(fails ? 1 : 0); |