| 1 | // 🎯 Parar un objetivo a media tarea. Antes: las tareas que faltaban se quedaban |
| 2 | // «pendientes» y el plan terminaba en «completado»; y la tarea interrumpida |
| 3 | // contaba como «no usó ninguna herramienta» y se REINTENTABA, o sea que parar |
| 4 | // volvía a llamar al modelo. Ahora: tarea en curso «parada», el resto |
| 5 | // «saltadas», ningún reintento y el plan en 'stopped'. |
| 6 | // |
| 7 | // Proveedor con guion (mismo patrón que goalfail.mjs): la 1.ª llamada es el |
| 8 | // planificador y devuelve tres tareas; la 2.ª es la tarea 1, lenta, y se para. |
| 9 | // |
| 10 | // BASE=http://localhost:8799 node tests/goalstop.mjs |
| 11 | import { chromium } from 'playwright'; |
| 12 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 13 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 14 | |
| 15 | const b = await chromium.launch(); |
| 16 | const ctx = await b.newContext(); |
| 17 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); |
| 18 | const p = await ctx.newPage(); |
| 19 | const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 120))); |
| 20 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 21 | await p.waitForTimeout(1500); |
| 22 | |
| 23 | // El guion vive en la página: window.__guion() crea uno nuevo con su contador. |
| 24 | await p.evaluate(() => { |
| 25 | window.__guion = () => { |
| 26 | const g = { llamadas: 0, vistasTrasParar: 0 }; |
| 27 | const PLAN = JSON.stringify({ plan: 'tres pasos', tasks: [ |
| 28 | { title: 'Paso uno', description: 'mira el árbol' }, |
| 29 | { title: 'Paso dos', description: 'lee el README' }, |
| 30 | { title: 'Paso tres', description: 'resume' }, |
| 31 | ] }); |
| 32 | g.chat = async (h, s, cb, signal) => { |
| 33 | g.llamadas++; |
| 34 | if (/^ROL: PLANIFICADOR/.test(s || '')) return PLAN; |
| 35 | for (let i = 0; i < 200; i++) { |
| 36 | if (signal?.aborted) throw new DOMException('Parado', 'AbortError'); |
| 37 | cb('.'); await new Promise(r => setTimeout(r, 20)); |
| 38 | } |
| 39 | return '```tool\n{"tool":"code.tree","args":{}}\n```'; |
| 40 | }; |
| 41 | return g; |
| 42 | }; |
| 43 | }); |
| 44 | |
| 45 | // A. runGoal con la señal del turno (lo que le pasa conversations.js) |
| 46 | const a = await p.evaluate(async () => { |
| 47 | const { runGoal } = await import('/js/goal.js'); |
| 48 | const { Agent } = await import('/js/agent.js'); |
| 49 | const g = window.__guion(); |
| 50 | const conv = { agent: new Agent(g), stopped: false, plan: null }; |
| 51 | const ac = new AbortController(); |
| 52 | const tipos = []; |
| 53 | let ultimoPlan = null; |
| 54 | await runGoal(conv, 'objetivo de prueba', ev => { |
| 55 | tipos.push(ev.type); |
| 56 | if (ev.plan) ultimoPlan = ev.plan; |
| 57 | if (ev.type === 'token' && !ac.signal.aborted) ac.abort(); // parar en cuanto la tarea 1 escribe |
| 58 | }, { signal: ac.signal }); |
| 59 | return { |
| 60 | llamadas: g.llamadas, status: conv.plan?.status, eventoFinal: ultimoPlan?.status, |
| 61 | tareas: conv.plan?.tasks.map(t => t.status), reintentos: conv.plan?.tasks[0]?.retries, |
| 62 | abortados: tipos.filter(t => t === 'aborted').length, errores: tipos.filter(t => t === 'error').length, |
| 63 | completo: tipos.includes('plan_complete'), |
| 64 | }; |
| 65 | }); |
| 66 | ok('A · el plan acaba en «stopped», no en «completado»', a.status === 'stopped' && a.eventoFinal === 'stopped', `${a.status} / evento ${a.eventoFinal}`); |
| 67 | ok('A · exactamente 2 llamadas al modelo (planificador + tarea 1), sin reintentos', a.llamadas === 2 && a.reintentos === 0, `${a.llamadas} llamadas, ${a.reintentos} reintentos`); |
| 68 | ok('A · tarea 1 «stopped», tareas 2 y 3 «skipped»', JSON.stringify(a.tareas) === '["stopped","skipped","skipped"]', JSON.stringify(a.tareas)); |
| 69 | ok('A · un solo «(Parado.)» y ningún error', a.abortados === 1 && a.errores === 0, `${a.abortados} aborted, ${a.errores} error`); |
| 70 | ok('A · se emite plan_complete (la tarjeta se cierra)', a.completo); |
| 71 | |
| 72 | // A2. Parada que llega mientras se PLANIFICA: no se ejecuta ninguna tarea. |
| 73 | const a2 = await p.evaluate(async () => { |
| 74 | const { runGoal } = await import('/js/goal.js'); |
| 75 | const { Agent } = await import('/js/agent.js'); |
| 76 | let llamadas = 0; |
| 77 | const ac = new AbortController(); |
| 78 | const lentoPlanificando = { chat: async (h, s, cb, signal) => { |
| 79 | llamadas++; |
| 80 | for (let i = 0; i < 200; i++) { |
| 81 | if (signal?.aborted) throw new DOMException('Parado', 'AbortError'); |
| 82 | await new Promise(r => setTimeout(r, 20)); |
| 83 | } |
| 84 | return '{"plan":"x","tasks":[{"title":"a","description":"a"}]}'; |
| 85 | }}; |
| 86 | const conv = { agent: new Agent(lentoPlanificando), stopped: false, plan: null }; |
| 87 | const tipos = []; |
| 88 | setTimeout(() => ac.abort(), 150); |
| 89 | await runGoal(conv, 'objetivo', ev => tipos.push(ev.type), { signal: ac.signal }); |
| 90 | return { llamadas, status: conv.plan?.status, tareas: conv.plan?.tasks.length, tipos: [...new Set(tipos)] }; |
| 91 | }); |
| 92 | ok('A2 · parar mientras planifica: «stopped», 1 llamada, sin error', a2.status === 'stopped' && a2.llamadas === 1 && !a2.tipos.includes('error'), |
| 93 | `${a2.status} · ${a2.llamadas} llamadas · ${a2.tipos.join(',')}`); |
| 94 | |
| 95 | // B. Por la conversación, como el botón ■: startGoal + stopActive |
| 96 | const bRes = await p.evaluate(async () => { |
| 97 | const conv = await import('/js/conversations.js'); |
| 98 | const g = window.__guion(); |
| 99 | const prev = conv.getProvider(); |
| 100 | conv.setProvider(g); |
| 101 | const c = conv.getActive(); |
| 102 | conv.startGoal(c.id, 'objetivo por la conversación'); |
| 103 | const hasta = async (f, n = 300) => { for (let i = 0; i < n && !f(); i++) await new Promise(r => setTimeout(r, 20)); return f(); }; |
| 104 | await hasta(() => g.llamadas >= 2); |
| 105 | await new Promise(r => setTimeout(r, 100)); // la tarea 1 ya está escribiendo |
| 106 | const paro = conv.stopActive(); |
| 107 | const terminado = await hasta(() => !c.pumping); |
| 108 | await new Promise(r => setTimeout(r, 200)); |
| 109 | conv.setProvider(prev); |
| 110 | return { paro, terminado, llamadas: g.llamadas, status: c.plan?.status, tareas: c.plan?.tasks.map(t => t.status), cola: c.queue.length }; |
| 111 | }); |
| 112 | ok('B · stopActive() durante la tarea 1 termina el turno', bRes.paro && bRes.terminado, `stopActive ${bRes.paro}, terminado ${bRes.terminado}`); |
| 113 | ok('B · plan «stopped», tareas [stopped, skipped, skipped]', bRes.status === 'stopped' && JSON.stringify(bRes.tareas) === '["stopped","skipped","skipped"]', |
| 114 | `${bRes.status} ${JSON.stringify(bRes.tareas)}`); |
| 115 | ok('B · exactamente 2 llamadas al modelo', bRes.llamadas === 2, `${bRes.llamadas}`); |
| 116 | ok('B · la cola queda vacía', bRes.cola === 0, `${bRes.cola}`); |
| 117 | |
| 118 | console.log('\n errores JS:', errs[0] || 'ninguno'); |
| 119 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ PARAR UN OBJETIVO OK — se para, no reintenta y no se anuncia como completado'); |
| 120 | await b.close(); |
| 121 | process.exit(fails ? 1 : 0); |