| 1 | // demo-corto27.mjs — TOMA de vídeo del Qwen3.8-27B contestando dentro del |
| 2 | // navegador, y a la vez SONDA de por qué la toma anterior se quedó muda. |
| 3 | // |
| 4 | // Qué cambia respecto a demo-record27.mjs (que se quedó muda durante toda la toma): |
| 5 | // |
| 6 | // 1) Mide la latencia AL PRIMER TOKEN, no al mensaje terminado. La toma anterior |
| 7 | // esperaba a `.msg.assistant`, que la interfaz solo crea cuando la respuesta |
| 8 | // está ENTERA; mientras el modelo prefila y escribe solo existe |
| 9 | // `.msg.thinking .gen`. Un modelo escribiendo perfectamente se veía igual que |
| 10 | // uno colgado. Aquí se vigilan las dos cosas por separado. |
| 11 | // |
| 12 | // 2) Puede forzar el prompt CORTO. `agent.js` elige el prompt compacto (111 |
| 13 | // tokens) solo si el contexto del modelo es < CTX_MINIMO_COMPLETO (1.600); al |
| 14 | // subir el `ctx` del 27B de 512 a 2.048 para que la caché KV no reventara, esa |
| 15 | // condición dejó de cumplirse y el 27B volvió a recibir el prompt ENTERO. Con |
| 16 | // PROMPT=corto se parchea la constante AL SERVIR (no se toca el árbol) para |
| 17 | // que vuelva a coger el compacto. PROMPT=largo deja la app tal cual está. |
| 18 | // |
| 19 | // 3) MODELO puede ser un file:// local: el mismo GGUF que sirve producción, ya |
| 20 | // descargado, para no pagar 7,6 GB por intento. |
| 21 | // |
| 22 | // PROMPT=corto MODELO=file:///tmp/qwen38-27b.gguf node tests/demo-corto27.mjs |
| 23 | import { chromium } from 'playwright'; |
| 24 | import { CHROME_ARGS } from './chrome-args.mjs'; |
| 25 | import { createServer } from 'http'; |
| 26 | import { createReadStream, statSync, readFileSync, mkdirSync } from 'fs'; |
| 27 | import { Readable } from 'stream'; |
| 28 | import { extname, join, normalize } from 'path'; |
| 29 | import { fileURLToPath } from 'url'; |
| 30 | |
| 31 | const WEB = join(fileURLToPath(new URL('.', import.meta.url)), '..', 'web'); |
| 32 | const ORIGEN = process.env.MODELO || 'https://claw.elffuss.com/models/qwen38-27b.gguf'; |
| 33 | const PUERTO = +(process.env.PUERTO || 8646); |
| 34 | const RUTA_MODELO = '/models/qwen38-27b.gguf'; |
| 35 | const VIDEODIR = process.env.VIDEODIR || '/tmp/claw-demo-corto'; |
| 36 | const MAXTOK = +(process.env.MAXTOK || 120); |
| 37 | const CORTO = (process.env.PROMPT || 'corto') === 'corto'; |
| 38 | const ESPERA = +(process.env.ESPERA || 900); // s de margen por pregunta |
| 39 | |
| 40 | const P1 = process.env.P1 || 'Preséntate en una frase.'; |
| 41 | const P2 = process.env.P2 || 'Un bate y una pelota cuestan 1,10 € en total. El bate cuesta 1 € más que la pelota. ¿Cuánto cuesta la pelota? Contesta en una frase.'; |
| 42 | |
| 43 | const TIPOS = { |
| 44 | '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', |
| 45 | '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', |
| 46 | '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', |
| 47 | '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', |
| 48 | '.wasm': 'application/wasm', '.ico': 'image/x-icon', '.woff2': 'font/woff2', |
| 49 | }; |
| 50 | |
| 51 | // El parche del prompt se hace al servir, no en disco: hay otra sesión editando |
| 52 | // este repo. Y si el texto esperado no aparece, se ABORTA: un parche que no |
| 53 | // aplica en silencio convierte la toma en una medida falsa. |
| 54 | const MARCA = 'export const CTX_MINIMO_COMPLETO = 1600;'; |
| 55 | function parchear(rel, cuerpo) { |
| 56 | if (!CORTO || rel !== 'js/agent.js') return cuerpo; |
| 57 | const txt = cuerpo.toString('utf8'); |
| 58 | if (!txt.includes(MARCA)) throw new Error(`agent.js ya no contiene «${MARCA}»: el parche del prompt corto no aplica`); |
| 59 | return Buffer.from(txt.replace(MARCA, 'export const CTX_MINIMO_COMPLETO = 1e9;'), 'utf8'); |
| 60 | } |
| 61 | |
| 62 | async function espejoModelo(req, res) { |
| 63 | if (ORIGEN.startsWith('file://')) { |
| 64 | const ruta = fileURLToPath(ORIGEN); |
| 65 | const size = statSync(ruta).size; |
| 66 | const m = /^bytes=(\d+)-(\d*)$/.exec(req.headers.range || ''); |
| 67 | if (!m) { res.writeHead(200, { 'Content-Length': size, 'Accept-Ranges': 'bytes' }); return req.method === 'HEAD' ? res.end() : createReadStream(ruta).pipe(res); } |
| 68 | const ini = +m[1], fin = Math.min(m[2] ? +m[2] : size - 1, size - 1); |
| 69 | res.writeHead(206, { 'Content-Type': 'application/octet-stream', 'Content-Range': `bytes ${ini}-${fin}/${size}`, 'Content-Length': fin - ini + 1, 'Accept-Ranges': 'bytes' }); |
| 70 | return req.method === 'HEAD' ? res.end() : createReadStream(ruta, { start: ini, end: fin }).pipe(res); |
| 71 | } |
| 72 | const r = await fetch(ORIGEN, { method: req.method === 'HEAD' ? 'HEAD' : 'GET', headers: req.headers.range ? { Range: req.headers.range } : {} }); |
| 73 | const cab = { 'Content-Type': 'application/octet-stream', 'Accept-Ranges': 'bytes' }; |
| 74 | for (const k of ['content-range', 'content-length']) { const v = r.headers.get(k); if (v) cab[k === 'content-range' ? 'Content-Range' : 'Content-Length'] = v; } |
| 75 | res.writeHead(r.status, cab); |
| 76 | if (req.method === 'HEAD' || !r.body) return res.end(); |
| 77 | Readable.fromWeb(r.body).pipe(res); |
| 78 | } |
| 79 | |
| 80 | const server = createServer(async (req, res) => { |
| 81 | const ruta = decodeURIComponent(new URL(req.url, 'http://x').pathname); |
| 82 | try { |
| 83 | if (ruta === RUTA_MODELO) return await espejoModelo(req, res); |
| 84 | const rel = normalize(ruta === '/' ? '/index.html' : ruta).replace(/^\/+/, '').replace(/^(\.\.[/\\])+/, ''); |
| 85 | const cuerpo = parchear(rel, readFileSync(join(WEB, rel))); |
| 86 | res.writeHead(200, { 'Content-Type': TIPOS[extname(rel)] || 'application/octet-stream', 'Cache-Control': 'no-store' }); |
| 87 | res.end(cuerpo); |
| 88 | } catch (e) { |
| 89 | if (/no aplica/.test(e.message)) { console.error('❌ ' + e.message); process.exit(2); } |
| 90 | res.writeHead(404); res.end('no está'); |
| 91 | } |
| 92 | }); |
| 93 | await new Promise(r => server.listen(PUERTO, r)); |
| 94 | const BASE = `http://localhost:${PUERTO}`; |
| 95 | const t0 = Date.now(); |
| 96 | const seg = () => ((Date.now() - t0) / 1000).toFixed(0).padStart(4); |
| 97 | const log = s => console.log(`[${seg()}s] ${s}`); |
| 98 | mkdirSync(VIDEODIR, { recursive: true }); |
| 99 | log(`prompt ${CORTO ? 'CORTO (compacto forzado)' : 'LARGO (app tal cual)'} · modelo desde ${ORIGEN.startsWith('file') ? 'disco local' : 'producción'} · ${MAXTOK} tokens de tope`); |
| 100 | |
| 101 | const ARGS = ['--enable-unsafe-webgpu', ...CHROME_ARGS]; |
| 102 | const b = await chromium.launch({ args: ARGS }).catch(() => chromium.launch({ channel: 'chrome', args: ARGS })); |
| 103 | const ctx = await b.newContext({ |
| 104 | locale: 'es-ES', |
| 105 | viewport: { width: 1280, height: 900 }, |
| 106 | recordVideo: { dir: VIDEODIR, size: { width: 1280, height: 900 } }, |
| 107 | }); |
| 108 | await ctx.addInitScript(() => { |
| 109 | try { |
| 110 | localStorage.setItem('elffuss.welcomed', '1'); |
| 111 | localStorage.setItem('elffuss.grants', JSON.stringify([])); |
| 112 | localStorage.setItem('elffuss.model', 'engine:qwen38-27b'); |
| 113 | } catch { /* — */ } |
| 114 | }); |
| 115 | // Ensayo en seco: comprueba que el parche del prompt hace lo que dice ANTES de |
| 116 | // gastar 7,6 GB y una GPU en descubrir que no. Abre la misma app servida por el |
| 117 | // mismo servidor, pero con el modelo `rules` (no descarga nada). |
| 118 | if (process.env.SOLO_PROMPT) { |
| 119 | const q = await b.newContext({ locale: 'es-ES' }); |
| 120 | await q.addInitScript(() => { try { localStorage.setItem('elffuss.model', 'rules'); localStorage.setItem('elffuss.welcomed', '1'); } catch { /* — */ } }); |
| 121 | const pg = await q.newPage(); |
| 122 | await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 123 | await pg.waitForTimeout(800); |
| 124 | const r = await pg.evaluate(async () => { |
| 125 | const [a, pr] = await Promise.all([import('./js/agent.js'), import('./js/engine/provider.js')]); |
| 126 | pr.configure('qwen38-27b'); |
| 127 | const ctxTok = pr.contextTokens(); |
| 128 | const compacto = ctxTok > 0 && ctxTok < a.CTX_MINIMO_COMPLETO; |
| 129 | return { ctxTok, umbral: a.CTX_MINIMO_COMPLETO, compacto, chars: a.systemPrompt('', { compacto }).length }; |
| 130 | }); |
| 131 | console.log('ensayo en seco:', JSON.stringify(r)); |
| 132 | console.log(r.compacto ? '✅ el agente elegiría el prompt COMPACTO' : '❌ el agente elegiría el prompt COMPLETO'); |
| 133 | await b.close(); server.close(); |
| 134 | process.exit(r.compacto === CORTO ? 0 : 1); |
| 135 | } |
| 136 | |
| 137 | const p = await ctx.newPage(); |
| 138 | let muerta = ''; |
| 139 | p.on('crash', () => { muerta = 'la pestaña ha crasheado'; log(' ⚠️ ' + muerta); }); |
| 140 | b.on('disconnected', () => { muerta = muerta || 'el navegador se ha ido'; log(' ⚠️ ' + muerta); }); |
| 141 | const engineLines = []; |
| 142 | p.on('console', m => { |
| 143 | const t = m.text(); |
| 144 | if (/\[engine\]/i.test(t)) { engineLines.push(t.slice(0, 200)); log(' [engine] ' + t.slice(0, 150)); } |
| 145 | else if (/No se pudo|no cabe|OOM|memoria|liberad|falló|caché se llena|instrucciones ocupan/i.test(t)) log(' consola: ' + t.slice(0, 160)); |
| 146 | }); |
| 147 | |
| 148 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 149 | |
| 150 | // 1) esperar a que el 27B esté en la GPU |
| 151 | let estado = '', ultimo = '', cargado = false; |
| 152 | while (Date.now() - t0 < 40 * 60 * 1000 && !muerta) { |
| 153 | let s; |
| 154 | try { |
| 155 | s = await p.evaluate(() => ({ |
| 156 | est: document.querySelector('#model-status')?.className || '', |
| 157 | txt: document.querySelector('#loading-stage .ls-progtext')?.textContent || document.querySelector('#model-progress-text')?.textContent || '', |
| 158 | })); |
| 159 | } catch (e) { muerta = 'la página dejó de responder: ' + String(e.message).split('\n')[0].slice(0, 80); break; } |
| 160 | estado = s.est; |
| 161 | if (s.txt && s.txt !== ultimo) { ultimo = s.txt; log('carga: ' + ultimo.trim().slice(0, 100)); } |
| 162 | if (/\b(on|gpu)\b/.test(estado)) { cargado = true; break; } |
| 163 | if (/\berr(or)?\b/.test(estado)) break; |
| 164 | await p.waitForTimeout(5000).catch(() => {}); |
| 165 | } |
| 166 | if (!cargado) { log('❌ no cargó: ' + (muerta || estado)); await cerrar(); process.exit(1); } |
| 167 | const tCarga = (Date.now() - t0) / 1000; |
| 168 | log(`✅ 27B en la GPU (${tCarga.toFixed(0)}s). Empieza la demo.`); |
| 169 | |
| 170 | await p.evaluate(async (mt) => { const m = await import('./js/engine/provider.js'); m.setSampling({ maxTokens: mt }); }, MAXTOK) |
| 171 | .catch(e => log(' no se pudo fijar maxTokens: ' + String(e.message).slice(0, 80))); |
| 172 | |
| 173 | // Cuántos tokens le entran de verdad: el mismo tokenizador del GGUF que usa el |
| 174 | // motor, sobre el mismo prompt de sistema que va a montar el agente. Es LA cifra |
| 175 | // que explica la espera, así que se mide, no se supone. |
| 176 | const medida = await p.evaluate(async () => { |
| 177 | const [a, pr] = await Promise.all([import('./js/agent.js'), import('./js/engine/provider.js')]); |
| 178 | const ctxTok = pr.contextTokens(); |
| 179 | const compacto = ctxTok > 0 && ctxTok < a.CTX_MINIMO_COMPLETO; |
| 180 | const texto = a.systemPrompt('', { compacto }); |
| 181 | return { ctxTok, umbral: a.CTX_MINIMO_COMPLETO, compacto, chars: texto.length }; |
| 182 | }).catch(e => ({ error: String(e.message).slice(0, 120) })); |
| 183 | log(`prompt de sistema: ${JSON.stringify(medida)}`); |
| 184 | |
| 185 | async function preguntar(texto, etiqueta) { |
| 186 | const antes = await p.locator('.msg.assistant').count().catch(() => 0); |
| 187 | log(`${etiqueta} → «${texto}»`); |
| 188 | await p.fill('#prompt', texto); |
| 189 | await p.press('#prompt', 'Enter'); |
| 190 | |
| 191 | const tG = Date.now(); |
| 192 | let primer = 0, ultimoN = -1, final = ''; |
| 193 | while (Date.now() - tG < ESPERA * 1000 && !muerta) { |
| 194 | let s; |
| 195 | try { |
| 196 | s = await p.evaluate((n) => ({ |
| 197 | gen: document.querySelector('.msg.thinking .gen')?.textContent || '', |
| 198 | etiq: document.querySelector('.msg.thinking .label')?.textContent || '', |
| 199 | listo: document.querySelectorAll('.msg.assistant').length > n |
| 200 | ? document.querySelectorAll('.msg.assistant')[document.querySelectorAll('.msg.assistant').length - 1].textContent : '', |
| 201 | }), antes); |
| 202 | } catch { if (muerta || !b.isConnected()) break; await p.waitForTimeout(1000); continue; } |
| 203 | |
| 204 | if (s.listo) { final = s.listo.trim(); break; } |
| 205 | if (!primer && s.gen.length > 0) { primer = (Date.now() - tG) / 1000; log(` ⚡ PRIMER TOKEN a los ${primer.toFixed(0)}s — «${s.gen.slice(0, 60)}»`); } |
| 206 | if (s.gen.length !== ultimoN) { ultimoN = s.gen.length; if (primer) log(` … ${((Date.now() - tG) / 1000).toFixed(0)}s · ${s.gen.length} car`); } |
| 207 | else if ((Date.now() - tG) % 30000 < 1600 && !primer) log(` … prefill (${((Date.now() - tG) / 1000).toFixed(0)}s, aún sin primer token)`); |
| 208 | await p.waitForTimeout(1500); |
| 209 | } |
| 210 | const total = (Date.now() - tG) / 1000; |
| 211 | if (!final && !primer) log(` ❌ ni un token en ${total.toFixed(0)}s`); |
| 212 | else if (!final) log(` ⚠️ empezó a los ${primer.toFixed(0)}s pero no terminó en ${total.toFixed(0)}s`); |
| 213 | else log(` ✅ ${etiqueta}: primer token ${primer ? primer.toFixed(0) + 's' : '—'} · completa ${total.toFixed(0)}s`); |
| 214 | log(`${etiqueta} respuesta: ${JSON.stringify(final.slice(0, 300))}`); |
| 215 | await p.screenshot({ path: `/tmp/claw-corto-${etiqueta}.png` }).catch(() => {}); |
| 216 | return { final, primer, total }; |
| 217 | } |
| 218 | |
| 219 | const r1 = await preguntar(P1, 'q1'); |
| 220 | await p.waitForTimeout(2500); |
| 221 | const r2 = muerta ? { final: '' } : await preguntar(P2, 'q2'); |
| 222 | |
| 223 | log('── transcripción ──'); |
| 224 | log('P1: ' + P1); log('R1: ' + r1.final); |
| 225 | log('P2: ' + P2); log('R2: ' + r2.final); |
| 226 | if (engineLines.length) { log('── traza [engine] ──'); engineLines.forEach(l => log(' ' + l)); } |
| 227 | |
| 228 | let videoPath = ''; |
| 229 | try { videoPath = await p.video().path(); } catch { /* — */ } |
| 230 | async function cerrar() { |
| 231 | await Promise.race([ctx.close(), new Promise(r => setTimeout(r, 20000))]).catch(() => {}); |
| 232 | await Promise.race([b.close(), new Promise(r => setTimeout(r, 10000))]).catch(() => {}); |
| 233 | server.close(); |
| 234 | } |
| 235 | await cerrar(); |
| 236 | log('🎬 vídeo: ' + (videoPath || '(mira ' + VIDEODIR + ')')); |
| 237 | console.log(muerta ? `\n⚠️ terminó con: ${muerta}` : `\n✅ toma completa · carga ${tCarga.toFixed(0)}s · q1 ${r1.primer ? r1.primer.toFixed(0) + 's al primer token' : 'muda'}`); |
| 238 | process.exit(0); |