| 1 | // E2E contra PRODUCCIÓN: Claw con el Bonsai 27B del motor propio, elegido en el |
| 2 | // selector como lo haría un usuario, grabado en vídeo. |
| 3 | // |
| 4 | // node tests/e2e-bonsai-prod.mjs |
| 5 | // |
| 6 | // Qué comprueba (sale con 1 si falla cualquiera): |
| 7 | // · el registro de producción tiene un modelo cuyos fragmentos son los de Bonsai |
| 8 | // · la opción aparece en el selector y se puede elegir |
| 9 | // · el modelo carga sin error (indicador en GPU, selector y localStorage en él, |
| 10 | // traza «[engine] … listo desde …», ningún «fallo cargando modelo») |
| 11 | // · cada respuesta la produce el motor local (una traza «[engine] turno: salieron |
| 12 | // N tokens» con N > 0 dentro de la ventana de esa pregunta) |
| 13 | // · cada respuesta no está vacía y no es un mensaje de error |
| 14 | // · ninguna petición sale a un host que no sea el propio sitio, los hosts del |
| 15 | // modelo (m1/m2/models) o las CDN de jsdelivr / Hugging Face — en particular, |
| 16 | // ninguna a una API de LLM |
| 17 | // · la página no lanza errores no capturados ni se cae |
| 18 | // |
| 19 | // Antes de tocar la GPU mira si hay otros inquilinos TRABAJANDO (llama.cpp, |
| 20 | // ollama con modelo cargado, servidores MLX, otro navegador con WebGPU, o la GPU |
| 21 | // ocupada): si los hay, espera hasta 10 min mirando cada minuto y, si siguen, |
| 22 | // aborta con código 2. Un servidor residente pero parado se anota y no bloquea. |
| 23 | // |
| 24 | // Perfil DEDICADO y persistente (no el de otras pruebas): la primera vez baja el |
| 25 | // modelo entero; las siguientes lo leen del almacén. FRESCO=1 lo borra antes. |
| 26 | // |
| 27 | // Variables: SITIO, OUTDIR, PERFIL, FRESCO, MAXTOK, P1, P2, CARGA_MAX_MIN, |
| 28 | // RESP_MAX_MIN, ESPERA_INQUILINOS_MIN, IGNORA_INQUILINOS. |
| 29 | import { chromium } from 'playwright'; |
| 30 | import { CHROME_ARGS } from './chrome-args.mjs'; |
| 31 | import { execFileSync, spawn } from 'node:child_process'; |
| 32 | import { mkdirSync, writeFileSync, renameSync, rmSync, existsSync, readdirSync } from 'node:fs'; |
| 33 | import { homedir, tmpdir } from 'node:os'; |
| 34 | import { join, basename } from 'node:path'; |
| 35 | |
| 36 | const SITIO = (process.env.SITIO || 'https://claw.elffuss.utopiaia.com').replace(/\/$/, ''); |
| 37 | const ORIGEN = new URL(SITIO).origin; |
| 38 | const OUTDIR = process.env.OUTDIR || join(homedir(), 'work2026', 'elffuss-assets', '_recording', 'bonsai-claw'); |
| 39 | const PERFIL = process.env.PERFIL || join(tmpdir(), 'elffuss-e2e-bonsai-perfil'); |
| 40 | const MAXTOK = +(process.env.MAXTOK || 200); |
| 41 | const P1 = process.env.P1 || '¿Quién eres?'; |
| 42 | const P2 = process.env.P2 || 'Explica en dos frases la diferencia entre «ser» y «estar» en español, con un ejemplo donde cambiar uno por otro cambie el significado.'; |
| 43 | const CARGA_MAX = +(process.env.CARGA_MAX_MIN || 60) * 60000; |
| 44 | const RESP_MAX = +(process.env.RESP_MAX_MIN || 20) * 60000; |
| 45 | const ESPERA_INQ = +(process.env.ESPERA_INQUILINOS_MIN || 10); |
| 46 | const W = 1280, H = 800; |
| 47 | |
| 48 | const t0 = Date.now(); |
| 49 | const ms = () => Date.now() - t0; |
| 50 | const sello = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); |
| 51 | const log = s => console.log(`[${String(Math.round(ms() / 1000)).padStart(5)}s] ${s}`); |
| 52 | mkdirSync(OUTDIR, { recursive: true }); |
| 53 | |
| 54 | const resultado = { |
| 55 | prueba: 'e2e-bonsai-prod', fecha: new Date().toISOString(), sitio: SITIO, |
| 56 | modelo: null, preguntas: [P1, P2], maxTokens: MAXTOK, |
| 57 | perfil: basename(PERFIL), perfilFresco: false, |
| 58 | asserts: [], fases: {}, respuestas: [], red: {}, erroresPagina: [], erroresConsola: [], |
| 59 | trazaEngine: [], inquilinos: {}, video: null, veredicto: null, |
| 60 | }; |
| 61 | const asserts = resultado.asserts; |
| 62 | function aserta(nombre, ok, detalle = '') { |
| 63 | asserts.push({ nombre, ok: !!ok, detalle }); |
| 64 | log(`${ok ? 'PASA' : 'FALLA'} · ${nombre}${detalle ? ' — ' + detalle : ''}`); |
| 65 | return !!ok; |
| 66 | } |
| 67 | function guardar() { |
| 68 | const fallos = asserts.filter(a => !a.ok).length; |
| 69 | resultado.veredicto = resultado.veredicto || (fallos ? `FALLA (${fallos} de ${asserts.length})` : `PASA (${asserts.length} de ${asserts.length})`); |
| 70 | resultado.fases.total_ms = ms(); |
| 71 | writeFileSync(join(OUTDIR, `bonsai-claw-${sello}.json`), JSON.stringify(resultado, null, 2)); |
| 72 | } |
| 73 | |
| 74 | // ── Otros inquilinos de la GPU ────────────────────────────────────────────── |
| 75 | function inquilinos() { |
| 76 | let ps = ''; |
| 77 | try { ps = execFileSync('ps', ['-Ao', 'pid=,pcpu=,command='], { encoding: 'utf8', maxBuffer: 1 << 26 }); } catch { return []; } |
| 78 | const out = []; |
| 79 | for (const l of ps.split('\n')) { |
| 80 | const m = /^\s*(\d+)\s+([\d.]+)\s+(.*)$/.exec(l); |
| 81 | if (!m) continue; |
| 82 | const [, pid, cpu, cmd] = m; |
| 83 | if (+pid === process.pid || cmd.includes(basename(PERFIL))) continue; // nuestro navegador no cuenta |
| 84 | let tipo = null; |
| 85 | if (/llama-server|llama-cli|llama-bench|llama-imatrix/.test(cmd)) tipo = 'llama.cpp'; |
| 86 | else if (/ollama runner|ollama_llama_server/.test(cmd)) tipo = 'ollama con modelo cargado'; |
| 87 | else if (/omlx-server|mlx_lm|mlx-lm|mlx_vlm/.test(cmd)) tipo = 'servidor MLX'; |
| 88 | else if (/--enable-unsafe-webgpu/.test(cmd) && !/--type=/.test(cmd)) tipo = 'navegador con WebGPU'; |
| 89 | if (tipo) out.push({ pid: +pid, cpu: +cpu, tipo, cmd: cmd.split(' ')[0].split('/').pop().slice(0, 60) }); |
| 90 | } |
| 91 | return out; |
| 92 | } |
| 93 | function usoGPU() { |
| 94 | try { |
| 95 | const s = execFileSync('ioreg', ['-r', '-d', '1', '-w', '0', '-c', 'IOAccelerator'], { encoding: 'utf8' }); |
| 96 | const m = /"Device Utilization %"=(\d+)/.exec(s); |
| 97 | return m ? +m[1] : null; |
| 98 | } catch { return null; } |
| 99 | } |
| 100 | async function sondeoInquilinos() { |
| 101 | const muestras = []; |
| 102 | for (let i = 0; i < 5; i++) { muestras.push(usoGPU()); await new Promise(r => setTimeout(r, 1000)); } |
| 103 | const validas = muestras.filter(v => v != null).sort((a, b) => a - b); |
| 104 | const gpuMediana = validas.length ? validas[Math.floor(validas.length / 2)] : null; |
| 105 | const lista = inquilinos(); |
| 106 | const activos = lista.filter(x => x.cpu > 5); |
| 107 | const ocupado = activos.length > 0 || (gpuMediana != null && gpuMediana > 15); |
| 108 | return { ocupado, gpuMediana, activos, residentes: lista.filter(x => x.cpu <= 5) }; |
| 109 | } |
| 110 | |
| 111 | let sondeo = await sondeoInquilinos(); |
| 112 | resultado.inquilinos.inicio = sondeo; |
| 113 | if (sondeo.residentes.length) log('residentes parados (no bloquean): ' + sondeo.residentes.map(x => `${x.tipo} pid ${x.pid}`).join(', ')); |
| 114 | if (sondeo.ocupado && process.env.IGNORA_INQUILINOS !== '1') { |
| 115 | for (let min = 1; min <= ESPERA_INQ && sondeo.ocupado; min++) { |
| 116 | log(`GPU ocupada (uso ${sondeo.gpuMediana} %, activos: ${sondeo.activos.map(x => x.tipo + ' ' + x.pid).join(', ') || 'ninguno'}) · espera ${min}/${ESPERA_INQ} min`); |
| 117 | await new Promise(r => setTimeout(r, 60000)); |
| 118 | sondeo = await sondeoInquilinos(); |
| 119 | } |
| 120 | resultado.inquilinos.trasEspera = sondeo; |
| 121 | if (sondeo.ocupado) { |
| 122 | resultado.veredicto = 'ABORTADO: otros inquilinos siguen usando la GPU'; |
| 123 | guardar(); |
| 124 | log(resultado.veredicto); |
| 125 | process.exit(2); |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | // Que el equipo no se duerma a media descarga (ERR_NETWORK_IO_SUSPENDED). |
| 130 | try { spawn('caffeinate', ['-dims', '-w', String(process.pid)], { stdio: 'ignore' }).on('error', () => {}); } catch { /* si el sistema no lo trae, da igual */ } |
| 131 | |
| 132 | if (process.env.FRESCO === '1') { rmSync(PERFIL, { recursive: true, force: true }); } |
| 133 | resultado.perfilFresco = !existsSync(PERFIL); |
| 134 | log(`perfil ${resultado.perfilFresco ? 'NUEVO (bajará el modelo entero)' : 'reutilizado (puede tenerlo guardado)'}`); |
| 135 | |
| 136 | // ── Navegador ──────────────────────────────────────────────────────────────── |
| 137 | const ARGS = ['--enable-unsafe-webgpu', ...CHROME_ARGS]; |
| 138 | const DIR_VIDEO = join(OUTDIR, `.video-${sello}`); |
| 139 | const opciones = { |
| 140 | headless: false, args: ARGS, locale: 'es-ES', |
| 141 | viewport: { width: W, height: H }, |
| 142 | recordVideo: { dir: DIR_VIDEO, size: { width: W, height: H } }, |
| 143 | }; |
| 144 | let ctx; |
| 145 | try { ctx = await chromium.launchPersistentContext(PERFIL, opciones); } |
| 146 | catch (e) { |
| 147 | log('Chromium de Playwright no arrancó (' + String(e.message).split('\n')[0].slice(0, 80) + '), pruebo Chrome'); |
| 148 | ctx = await chromium.launchPersistentContext(PERFIL, { ...opciones, channel: 'chrome' }); |
| 149 | } |
| 150 | |
| 151 | // Sin autocarga: el modelo se elige en el selector, como un usuario. Solo en el |
| 152 | // origen de la app — los iframes del broker (m1/m2) tienen su propio almacén. |
| 153 | await ctx.addInitScript(({ origen }) => { |
| 154 | if (location.origin !== origen) return; |
| 155 | try { |
| 156 | localStorage.setItem('elffuss.welcomed', '1'); |
| 157 | localStorage.setItem('elffuss.grants', '[]'); |
| 158 | localStorage.setItem('elffuss.model', 'rules'); |
| 159 | } catch { /* sin localStorage */ } |
| 160 | }, { origen: ORIGEN }); |
| 161 | |
| 162 | const peticiones = []; |
| 163 | ctx.on('request', r => { |
| 164 | const u = r.url(); |
| 165 | if (!/^https?:/i.test(u)) return; |
| 166 | peticiones.push({ t: ms(), url: u, metodo: r.method(), tipo: r.resourceType() }); |
| 167 | }); |
| 168 | |
| 169 | const p = ctx.pages()[0] || await ctx.newPage(); |
| 170 | const consola = []; |
| 171 | let muerta = ''; |
| 172 | p.on('console', m => { |
| 173 | const texto = m.text(); |
| 174 | consola.push({ t: ms(), tipo: m.type(), texto: texto.slice(0, 600) }); |
| 175 | if (/\[engine\]/.test(texto)) log(' [engine] ' + texto.slice(0, 170)); |
| 176 | else if (m.type() === 'error') { resultado.erroresConsola.push({ t: ms(), texto: texto.slice(0, 300) }); log(' consola error: ' + texto.slice(0, 170)); } |
| 177 | }); |
| 178 | p.on('pageerror', e => { resultado.erroresPagina.push({ t: ms(), mensaje: String(e.message).slice(0, 400) }); log(' pageerror: ' + String(e.message).slice(0, 170)); }); |
| 179 | p.on('crash', () => { muerta = 'la pestaña ha crasheado'; log(' ' + muerta); }); |
| 180 | ctx.on('close', () => { muerta = muerta || 'el navegador se ha cerrado'; }); |
| 181 | |
| 182 | const _video = p.video(); |
| 183 | const rutaVideo = _video ? await _video.path().catch(() => null) : null; |
| 184 | const trazas = re => consola.filter(c => re.test(c.texto)); |
| 185 | |
| 186 | // Red y errores: se evalúan en TODAS las salidas, también cuando la carga falla |
| 187 | // (que no llegue a hablar no quita que no deba haber llamado a ninguna API). |
| 188 | let redEvaluada = false; |
| 189 | function evaluarRedYErrores() { |
| 190 | if (redEvaluada) return; |
| 191 | redEvaluada = true; |
| 192 | const hostsModelo = new Set((resultado.modelo?.hosts) || []); |
| 193 | const permitido = h => h === new URL(SITIO).host || hostsModelo.has(h) || /^m\d+\.elffuss\.utopiaia\.com$/.test(h) |
| 194 | || h === 'models.elffuss.utopiaia.com' || h === 'cdn.jsdelivr.net' |
| 195 | || /(^|\.)huggingface\.co$/.test(h) || /(^|\.)hf\.co$/.test(h); |
| 196 | const LLM_HOST = /(^|\.)(openai\.com|anthropic\.com|generativelanguage\.googleapis\.com|aiplatform\.googleapis\.com|mistral\.ai|groq\.com|openrouter\.ai|together\.xyz|deepseek\.com|cohere\.(ai|com)|x\.ai|perplexity\.ai|fireworks\.ai)$/i; |
| 197 | const LLM_RUTA = /\/v1\/(chat\/)?completions|\/v1\/messages|\/v1\/responses|\/api\/(chat|generate)\b/i; |
| 198 | const porHost = {}; |
| 199 | const prohibidas = []; |
| 200 | for (const r of peticiones) { |
| 201 | let u; try { u = new URL(r.url); } catch { continue; } |
| 202 | porHost[u.host] = (porHost[u.host] || 0) + 1; |
| 203 | const llm = LLM_HOST.test(u.hostname) || LLM_RUTA.test(u.pathname) || /^(localhost|127\.0\.0\.1|\[::1\])$/.test(u.hostname); |
| 204 | if (!permitido(u.host) || llm) prohibidas.push({ t: r.t, metodo: r.metodo, url: (u.origin + u.pathname).slice(0, 160), motivo: llm ? 'API de LLM' : 'host no permitido' }); |
| 205 | } |
| 206 | resultado.red = { peticiones: peticiones.length, porHost, prohibidas: prohibidas.slice(0, 50) }; |
| 207 | aserta('ninguna petición a APIs de LLM ni a hosts fuera de la lista', prohibidas.length === 0, |
| 208 | prohibidas.length ? prohibidas.slice(0, 5).map(x => `${x.motivo}: ${x.metodo} ${x.url}`).join(' | ') |
| 209 | : Object.entries(porHost).map(([h, n]) => `${h}×${n}`).join(', ')); |
| 210 | aserta('la página no tiene errores no capturados ni se cae', resultado.erroresPagina.length === 0 && !muerta, |
| 211 | muerta || resultado.erroresPagina.slice(0, 3).map(e => e.mensaje.slice(0, 120)).join(' | ')); |
| 212 | } |
| 213 | |
| 214 | async function cerrarYSalir(codigo) { |
| 215 | evaluarRedYErrores(); |
| 216 | if (asserts.some(a => !a.ok) && codigo === 0) codigo = 1; |
| 217 | resultado.inquilinos.fin = { lista: inquilinos(), gpu: usoGPU() }; |
| 218 | await Promise.race([ctx.close(), new Promise(r => setTimeout(r, 30000))]).catch(() => {}); |
| 219 | // El vídeo de la pestaña va con el nombre de la toma; cualquier otro que haya |
| 220 | // grabado Playwright (una página en blanco inicial, un popup) se conserva |
| 221 | // aparte con sufijo, sin mezclarlo. |
| 222 | const finalV = join(OUTDIR, `bonsai-claw-${sello}.webm`); |
| 223 | if (rutaVideo && existsSync(rutaVideo)) { |
| 224 | try { renameSync(rutaVideo, finalV); resultado.video = basename(finalV); log('vídeo: ' + finalV); } |
| 225 | catch { resultado.video = basename(rutaVideo); log('vídeo: ' + rutaVideo); } |
| 226 | } |
| 227 | try { |
| 228 | let n = 0; |
| 229 | for (const f of readdirSync(DIR_VIDEO)) { |
| 230 | const extra = join(OUTDIR, `bonsai-claw-${sello}-extra-${++n}.webm`); |
| 231 | renameSync(join(DIR_VIDEO, f), extra); |
| 232 | (resultado.videosExtra ||= []).push(basename(extra)); |
| 233 | } |
| 234 | rmSync(DIR_VIDEO, { recursive: true, force: true }); |
| 235 | } catch { /* sin extras */ } |
| 236 | resultado.trazaEngine = trazas(/\[engine\]/).map(c => ({ t: c.t, texto: c.texto })); |
| 237 | guardar(); |
| 238 | log('resultado: ' + join(OUTDIR, `bonsai-claw-${sello}.json`)); |
| 239 | console.log('\n' + asserts.map(a => `${a.ok ? 'PASA ' : 'FALLA'} ${a.nombre}${a.detalle ? ' — ' + a.detalle : ''}`).join('\n')); |
| 240 | console.log('\n' + resultado.veredicto); |
| 241 | process.exit(codigo); |
| 242 | } |
| 243 | const fallidos = () => asserts.some(a => !a.ok); |
| 244 | |
| 245 | // ── 1. Abrir ───────────────────────────────────────────────────────────────── |
| 246 | log('abriendo ' + SITIO); |
| 247 | await p.goto(SITIO + '/', { waitUntil: 'domcontentloaded', timeout: 120000 }); |
| 248 | await p.waitForSelector('#model-select', { timeout: 60000 }); |
| 249 | resultado.fases.abrir_ms = ms(); |
| 250 | // Perfil reutilizado: la conversación de la vuelta anterior se restauraría y |
| 251 | // entraría en el prompt. Se vacía con el propio botón de la app (recarga). |
| 252 | await p.waitForTimeout(3000); |
| 253 | // (el saludo fijo `.msg.sys` no cuenta como conversación) |
| 254 | if (await p.locator('#log .msg.user, #log .msg.assistant, #log .msg.tool').count().catch(() => 0)) { |
| 255 | log('había conversación restaurada: se vacía con el botón de la app'); |
| 256 | await Promise.all([p.waitForEvent('domcontentloaded', { timeout: 60000 }).catch(() => {}), p.click('#btn-clear')]); |
| 257 | await p.waitForSelector('#model-select', { timeout: 60000 }); |
| 258 | await p.waitForTimeout(2000); |
| 259 | } |
| 260 | |
| 261 | // ── 2. El registro de producción dice qué id lleva a los fragmentos de Bonsai ─ |
| 262 | const reg = await p.evaluate(async () => { |
| 263 | const r = await import('/js/engine/registro.js'); |
| 264 | for (const [id, m] of Object.entries(r.MODELS || {})) { |
| 265 | const urls = Array.isArray(m.url) ? m.url.map(f => f.url) : [m.url]; |
| 266 | if (urls.some(u => /bonsai-27b\.p0$/.test(u)) && urls.some(u => /bonsai-27b\.p1$/.test(u))) |
| 267 | return { id, label: m.label, urls, bytes: m.bytes }; |
| 268 | } |
| 269 | return null; |
| 270 | }).catch(e => ({ error: String(e.message).slice(0, 200) })); |
| 271 | if (!aserta('registro de producción con los fragmentos de Bonsai (p0/p1)', reg && reg.id, |
| 272 | reg?.id ? `${reg.id} · ${reg.label} · ${reg.urls.map(u => new URL(u).host).join(' + ')}` : JSON.stringify(reg))) { |
| 273 | await cerrarYSalir(1); |
| 274 | } |
| 275 | const MODELO = 'engine:' + reg.id; |
| 276 | resultado.modelo = { selector: MODELO, label: reg.label, hosts: reg.urls.map(u => new URL(u).host), bytes: reg.bytes }; |
| 277 | |
| 278 | // ── 3. Elegirlo en el selector ─────────────────────────────────────────────── |
| 279 | const tOpcion0 = ms(); |
| 280 | const hayOpcion = await p.waitForSelector(`#model-select option[value="${MODELO}"]`, { state: 'attached', timeout: 120000 }) |
| 281 | .then(() => true).catch(() => false); |
| 282 | resultado.fases.opcionEnSelector_ms = ms() - tOpcion0; |
| 283 | if (!aserta('Bonsai ofrecido en el selector', hayOpcion, hayOpcion ? '' : 'la opción no apareció en 120 s (¿sin WebGPU, o el sondeo de m1/m2 falló?)')) { |
| 284 | await cerrarYSalir(1); |
| 285 | } |
| 286 | await p.waitForTimeout(1500); |
| 287 | await p.evaluate(() => { const l = document.querySelector('.model-pick') || document.getElementById('model-select'); if (l) { l.style.outline = '3px solid #f5b400'; l.style.outlineOffset = '3px'; } }); |
| 288 | await p.selectOption('#model-select', MODELO); |
| 289 | const tCarga0 = ms(); |
| 290 | log(`elegido en el selector: ${MODELO} (${reg.label})`); |
| 291 | await p.waitForTimeout(3000); |
| 292 | await p.evaluate(() => { const l = document.querySelector('.model-pick') || document.getElementById('model-select'); if (l) { l.style.outline = ''; l.style.outlineOffset = ''; } }); |
| 293 | |
| 294 | // ── 4. Carga, con el progreso a la vista ───────────────────────────────────── |
| 295 | const hitos = {}; |
| 296 | const marca = (k) => { if (hitos[k] == null) { hitos[k] = ms() - tCarga0; log(` hito ${k} @ ${(hitos[k] / 1000).toFixed(0)} s`); } }; |
| 297 | let visto = '', ultimoPct = -10, estado = '', cargado = false, vioCargando = false; |
| 298 | while (ms() - tCarga0 < CARGA_MAX && !muerta) { |
| 299 | let s; |
| 300 | try { |
| 301 | s = await p.evaluate(() => ({ |
| 302 | est: document.querySelector('#model-status')?.className || '', |
| 303 | txt: (document.querySelector('#loading-stage .ls-progtext')?.textContent |
| 304 | || document.querySelector('#model-progress-text')?.textContent || '').trim(), |
| 305 | })); |
| 306 | } catch (e) { muerta = 'la página dejó de responder: ' + String(e.message).split('\n')[0].slice(0, 100); break; } |
| 307 | estado = s.est; |
| 308 | if (/\bloading\b/.test(estado)) vioCargando = true; |
| 309 | const t = s.txt; |
| 310 | if (/Encendiendo la GPU/.test(t)) marca('gpu_encendida'); |
| 311 | if (/parte 1/.test(t)) marca('parte1'); |
| 312 | if (/parte 2/.test(t)) marca('parte2'); |
| 313 | if (/Leyendo el modelo por partes|Leyendo el modelo repartido/.test(t)) marca('lectura_repartida'); |
| 314 | if (/Leyendo el índice/.test(t)) marca('indice'); |
| 315 | if (/subiéndolo a la GPU|Subiendo el modelo a la GPU/.test(t)) marca('subida_gpu'); |
| 316 | if (t && t !== visto) { |
| 317 | const pct = +((/(\d+)\s*%/.exec(t) || [])[1] ?? -1); |
| 318 | const base = t.replace(/\d+\s*%.*$/, ''); |
| 319 | if (base !== visto.replace(/\d+\s*%.*$/, '') || pct < 0 || pct - ultimoPct >= 10 || pct === 100) { |
| 320 | log('carga: ' + t.slice(0, 110)); ultimoPct = pct; |
| 321 | } |
| 322 | visto = t; |
| 323 | } |
| 324 | if (/\b(on|gpu)\b/.test(estado)) { cargado = true; break; } |
| 325 | if (vioCargando && /\boff\b/.test(estado)) break; // changeModel volvió a básico: falló |
| 326 | if (trazas(/fallo cargando modelo/).length) break; |
| 327 | await p.waitForTimeout(2000).catch(() => {}); |
| 328 | } |
| 329 | resultado.fases.carga_ms = ms() - tCarga0; |
| 330 | resultado.fases.cargaHitos_ms = hitos; |
| 331 | const listo = trazas(/\[engine\].*listo desde/).pop(); |
| 332 | resultado.fases.cargaDesde = listo ? (/listo desde (.*?) ·/.exec(listo.texto) || [])[1] || '' : ''; |
| 333 | const enPagina = muerta ? {} : await p.evaluate(async () => { |
| 334 | let nombre = null; |
| 335 | try { nombre = (await import('/js/engine/provider.js')).name; } catch { /* */ } |
| 336 | let guardado = null; |
| 337 | try { guardado = localStorage.getItem('elffuss.model'); } catch { /* */ } |
| 338 | return { select: document.getElementById('model-select')?.value, guardado, nombre, |
| 339 | etiqueta: document.getElementById('model-select')?.selectedOptions?.[0]?.textContent || '' }; |
| 340 | }).catch(() => ({})); |
| 341 | const falloCarga = trazas(/fallo cargando modelo/).map(c => c.texto).join(' | '); |
| 342 | aserta('modelo cargado sin error', cargado && enPagina.select === MODELO && enPagina.guardado === MODELO && !!listo && !falloCarga, |
| 343 | cargado ? `indicador ${estado} · selector «${(enPagina.etiqueta || '').slice(0, 60)}» · desde ${resultado.fases.cargaDesde}` |
| 344 | : `${muerta || 'indicador ' + estado} · último progreso «${visto.slice(0, 80)}»${falloCarga ? ' · ' + falloCarga.slice(0, 200) : ''}`); |
| 345 | aserta('el proveedor activo es el motor local con Bonsai', !!enPagina.nombre && enPagina.nombre.includes(reg.label), String(enPagina.nombre)); |
| 346 | if (!cargado) await cerrarYSalir(1); |
| 347 | log(`${reg.label} en la GPU · ${(resultado.fases.carga_ms / 1000).toFixed(0)} s`); |
| 348 | |
| 349 | if (MAXTOK > 0) { |
| 350 | await p.evaluate(async mt => { (await import('/js/engine/provider.js')).setSampling({ maxTokens: mt }); }, MAXTOK) |
| 351 | .catch(e => log(' no se pudo acotar la longitud: ' + String(e.message).slice(0, 80))); |
| 352 | } |
| 353 | |
| 354 | // ── 5. Preguntas ───────────────────────────────────────────────────────────── |
| 355 | const ERROR_TEXTO = /^(⚠️|El modelo falló|No se pudo|El modelo todavía no está cargado|las instrucciones ocupan|tu mensaje ocupa|Se ha perdido la GPU)/i; |
| 356 | const soloLetras = s => String(s || '').toLowerCase().normalize('NFD').replace(/[^a-z0-9ñ]/g, ''); |
| 357 | |
| 358 | async function preguntar(texto, n) { |
| 359 | const antesMsgs = await p.locator('.msg.assistant').count().catch(() => 0); |
| 360 | const desdeConsola = consola.length; |
| 361 | const fase = { pregunta: texto }; |
| 362 | log(`P${n} → «${texto}»`); |
| 363 | await p.fill('#prompt', texto); |
| 364 | await p.waitForTimeout(600); |
| 365 | await p.press('#prompt', 'Enter'); |
| 366 | const tE = ms(); |
| 367 | let hecho = false; |
| 368 | while (ms() - tE < RESP_MAX && !muerta) { |
| 369 | const nuevas = consola.slice(desdeConsola); |
| 370 | if (fase.prefijo_ms == null && nuevas.some(c => /\[engine\] prefijo/.test(c.texto))) fase.prefijo_ms = ms() - tE; |
| 371 | const pr = nuevas.find(c => /\[engine\] turno: prompt/.test(c.texto)); |
| 372 | if (pr && fase.prefill_ms == null) { fase.prefill_ms = pr.t - tE; fase.tokensPrompt = +((/prompt (\d+) tokens/.exec(pr.texto) || [])[1] || 0); } |
| 373 | let st; |
| 374 | try { |
| 375 | st = await p.evaluate(() => { |
| 376 | const th = document.querySelector('.msg.thinking'); |
| 377 | return { pensando: !!th, escribe: !!th && /\d/.test(th.querySelector('.label')?.textContent || ''), |
| 378 | n: document.querySelectorAll('.msg.assistant').length }; |
| 379 | }); |
| 380 | } catch (e) { muerta = muerta || 'la página dejó de responder: ' + String(e.message).split('\n')[0].slice(0, 100); break; } |
| 381 | if (st.escribe && fase.primerToken_ms == null) fase.primerToken_ms = ms() - tE; |
| 382 | if (st.n > antesMsgs && !st.pensando) { hecho = true; break; } |
| 383 | if ((ms() - tE) % 30000 < 1000) log(` … ${((ms() - tE) / 1000).toFixed(0)} s${st.escribe ? ' · escribiendo' : ' · leyendo el prompt'}`); |
| 384 | await p.waitForTimeout(1000).catch(() => {}); |
| 385 | } |
| 386 | fase.total_ms = ms() - tE; |
| 387 | const msgs = await p.evaluate(a => [...document.querySelectorAll('.msg.assistant')].slice(a) |
| 388 | .map(d => ({ texto: (d.innerText || d.textContent || '').trim(), err: d.classList.contains('err') })), antesMsgs).catch(() => []); |
| 389 | const respuesta = msgs.map(m => m.texto).join('\n').trim(); |
| 390 | const turnos = consola.slice(desdeConsola).filter(c => /\[engine\] turno: salieron/.test(c.texto)); |
| 391 | const tokens = turnos.map(c => +((/salieron (\d+) tokens/.exec(c.texto) || [])[1] || 0)); |
| 392 | const ultimo = turnos[turnos.length - 1]; |
| 393 | let crudo = ''; |
| 394 | if (ultimo) { const m = /empieza por (".*")$/.exec(ultimo.texto); if (m) { try { crudo = JSON.parse(m[1]); } catch { /* */ } } } |
| 395 | const a = soloLetras(respuesta).slice(0, 12), b = soloLetras(crudo).slice(0, 12); |
| 396 | const coincide = !!a && !!b && (a.startsWith(b) || b.startsWith(a)); |
| 397 | fase.tokensSalida = tokens; |
| 398 | resultado.fases[`p${n}`] = fase; |
| 399 | resultado.respuestas.push({ pregunta: texto, respuesta, esError: msgs.some(m => m.err), turnosMotor: tokens.length, coincideConMotor: coincide }); |
| 400 | log(`R${n} (${(fase.total_ms / 1000).toFixed(0)} s): ${JSON.stringify(respuesta.slice(0, 300))}`); |
| 401 | await p.screenshot({ path: join(OUTDIR, `bonsai-claw-${sello}-p${n}.png`) }).catch(() => {}); |
| 402 | |
| 403 | aserta(`P${n}: respuesta producida por el motor local`, hecho && tokens.length > 0 && tokens.some(k => k > 0), |
| 404 | tokens.length ? `${tokens.length} turno(s) del motor · ${tokens.join('+')} tokens · texto ${coincide ? 'coincide' : 'NO coincide'} con la salida del motor` : (hecho ? 'sin traza [engine] turno' : (muerta || 'sin respuesta en plazo'))); |
| 405 | aserta(`P${n}: respuesta no vacía y sin error`, hecho && respuesta.length >= 2 && !msgs.some(m => m.err) && !ERROR_TEXTO.test(respuesta), |
| 406 | hecho ? `${respuesta.length} car.` : (muerta || `no terminó en ${RESP_MAX / 60000} min`)); |
| 407 | return hecho; |
| 408 | } |
| 409 | |
| 410 | if (await preguntar(P1, 1) && !muerta) { |
| 411 | await p.waitForTimeout(2500); |
| 412 | await preguntar(P2, 2); |
| 413 | } |
| 414 | await p.waitForTimeout(3000).catch(() => {}); |
| 415 | |
| 416 | // ── 6. Red y errores (dentro de cerrarYSalir) ──────────────────────────────── |
| 417 | await cerrarYSalir(fallidos() ? 1 : 0); |