| 1 | // El botón de parar de verdad para: proveedor simulado que genera lento y sigue |
| 2 | // pidiendo tools; se aborta a mitad y se comprueba que corta y no ejecuta más. |
| 3 | // Además: la parada que llega DE FUERA (la conversación, el modo Objetivo, el |
| 4 | // cerebro CEO) por `handle(texto, onEvent, { signal })`, y que un proveedor que |
| 5 | // lanza AbortError cuenta como «parado» y no como error del modelo. |
| 6 | // |
| 7 | // BASE=http://localhost:8799 node tests/stop.mjs |
| 8 | import { chromium } from 'playwright'; |
| 9 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 10 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 11 | |
| 12 | const b = await chromium.launch(); |
| 13 | const ctx = await b.newContext(); |
| 14 | // Modo Básico: sin esto, al abrir la página main.js se pone a cargar el modelo |
| 15 | // local por defecto (preloadModel) en mitad de la prueba, que no lo necesita. |
| 16 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); |
| 17 | const p = await ctx.newPage(); |
| 18 | // Telemetría: se cuentan los informes en vez de dejarlos salir. |
| 19 | let informes = 0; |
| 20 | await p.route('**/proxy/report', route => { informes++; return route.fulfill({ status: 204, body: '' }); }); |
| 21 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 22 | await p.waitForTimeout(1200); |
| 23 | |
| 24 | // 1. stop() a mitad de generación |
| 25 | const r = await p.evaluate(async () => { |
| 26 | const { Agent } = await import('/js/agent.js'); |
| 27 | const eventos = []; |
| 28 | let llamadas = 0; |
| 29 | // proveedor que SIEMPRE pide una tool y respeta la señal (espera y comprueba) |
| 30 | const lento = { chat: async (h, s, cb, signal) => { |
| 31 | llamadas++; |
| 32 | for (let i = 0; i < 20; i++) { if (signal?.aborted) break; await new Promise(r => setTimeout(r, 50)); } |
| 33 | return '```tool\n{"tool":"code.tree","args":{}}\n```'; |
| 34 | }}; |
| 35 | const ag = new Agent(lento); |
| 36 | const run = ag.handle('haz algo largo', ev => eventos.push(ev.type)); |
| 37 | await new Promise(r => setTimeout(r, 300)); // deja arrancar |
| 38 | const llamadasAntes = llamadas; |
| 39 | ag.stop(); // ← PARAR a mitad |
| 40 | await run; // debe terminar pronto, no agotar MAX_STEPS |
| 41 | return { eventos: [...new Set(eventos)], llamadasAntes, llamadasTotal: llamadas, abortado: eventos.includes('aborted') }; |
| 42 | }); |
| 43 | ok('stop() a mitad: emite «aborted» y no sigue el bucle', r.abortado && r.llamadasTotal <= r.llamadasAntes + 1, |
| 44 | `eventos ${r.eventos.join(',')} · llamadas antes ${r.llamadasAntes}, total ${r.llamadasTotal}`); |
| 45 | |
| 46 | // 2. Parada de fuera: ya abortada antes de empezar, y abortada a mitad |
| 47 | const r2 = await p.evaluate(async () => { |
| 48 | const { Agent } = await import('/js/agent.js'); |
| 49 | let llamadas = 0; |
| 50 | const lento = { chat: async (h, s, cb, signal) => { |
| 51 | llamadas++; |
| 52 | for (let i = 0; i < 40; i++) { |
| 53 | if (signal?.aborted) throw new DOMException('Parado', 'AbortError'); |
| 54 | cb('x'); await new Promise(r => setTimeout(r, 25)); |
| 55 | } |
| 56 | return 'respuesta completa'; |
| 57 | }}; |
| 58 | const ag = new Agent(lento); |
| 59 | const ya = new AbortController(); ya.abort(); |
| 60 | const ev1 = []; |
| 61 | await ag.handle('no debería ni empezar', ev => ev1.push(ev.type), { signal: ya.signal }); |
| 62 | const tras1 = { llamadas, historial: ag.history.length, eventos: ev1 }; |
| 63 | |
| 64 | const ac = new AbortController(); |
| 65 | const ev2 = []; |
| 66 | const run = ag.handle('para a mitad', ev => { ev2.push(ev.type); if (ev.type === 'token' && ev2.filter(t => t === 'token').length === 3) ac.abort(); }, { signal: ac.signal }); |
| 67 | await run; |
| 68 | return { tras1, llamadas, eventos2: [...new Set(ev2)], tokens: ev2.filter(t => t === 'token').length, ultimo: ag.history.at(-1)?.role }; |
| 69 | }); |
| 70 | ok('parada de fuera ya abortada: «aborted» sin llamar al modelo', r2.tras1.llamadas === 0 && r2.tras1.eventos.join() === 'aborted', |
| 71 | `llamadas ${r2.tras1.llamadas} · eventos ${r2.tras1.eventos.join(',')}`); |
| 72 | ok(' …y sin apuntar el mensaje en el historial', r2.tras1.historial === 0, `historial ${r2.tras1.historial}`); |
| 73 | ok('parada de fuera a mitad de turno: «aborted», ni un token más', r2.eventos2.includes('aborted') && !r2.eventos2.includes('error') && r2.tokens === 3, |
| 74 | `eventos ${r2.eventos2.join(',')} · tokens ${r2.tokens}`); |
| 75 | ok(' …y la respuesta parada no entra en el historial', r2.ultimo === 'user', `último ${r2.ultimo}`); |
| 76 | |
| 77 | // 3. Un proveedor que lanza AbortError es «parado», no un fallo del modelo, |
| 78 | // y no va a telemetría. Control positivo: un Error normal sí es error y sí se |
| 79 | // informa (si no, el contador de informes no probaría nada). |
| 80 | const r3 = await p.evaluate(async () => { |
| 81 | const tel = await import('/js/telemetry.js'); |
| 82 | tel.setEnabled(true); |
| 83 | const { Agent } = await import('/js/agent.js'); |
| 84 | const ev1 = []; |
| 85 | await new Agent({ chat: async () => { throw new DOMException('cortado', 'AbortError'); } }) |
| 86 | .handle('hola', ev => ev1.push(ev.type)); |
| 87 | await new Promise(r => setTimeout(r, 300)); |
| 88 | const ev2 = []; |
| 89 | await new Agent({ chat: async () => { throw new Error('reventó de verdad'); } }) |
| 90 | .handle('hola', ev => ev2.push(ev.type)); |
| 91 | await new Promise(r => setTimeout(r, 300)); |
| 92 | tel.setEnabled(false); |
| 93 | return { ev1, ev2 }; |
| 94 | }); |
| 95 | ok('proveedor que lanza AbortError → «aborted», no «error»', r3.ev1.includes('aborted') && !r3.ev1.includes('error'), r3.ev1.join(',')); |
| 96 | ok('control: un Error normal sigue siendo «error»', r3.ev2.includes('error'), r3.ev2.join(',')); |
| 97 | ok('a telemetría solo llega el error de verdad (1 informe, no 2)', informes === 1, `${informes} informes`); |
| 98 | |
| 99 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ PARAR OK — de dentro y de fuera, y parar no es un error'); |
| 100 | await b.close(); |
| 101 | process.exit(fails ? 1 : 0); |