| 1 | // El 27B contra el código LOCAL: ¿carga y CONTESTA? |
| 2 | // ───────────────────────────────────────────────────────────────────────────── |
| 3 | // El humo de producción (`claw-prod27.mjs`) dice si funciona lo DESPLEGADO. Este |
| 4 | // dice si funciona lo que se acaba de tocar, sin desplegar nada. |
| 5 | // |
| 6 | // Sirve `web/` desde disco y hace de espejo por rangos del GGUF que está en |
| 7 | // producción, TODO en el mismo origen. Eso importa por dos motivos: el servidor |
| 8 | // del modelo no manda cabeceras CORS (leerlo desde otro puerto lo bloquea el |
| 9 | // navegador), y el kernel solo ofrece el 27B si un HEAD al fichero responde — |
| 10 | // contra un servidor que no lo tiene, la opción ni aparece en el selector. |
| 11 | // |
| 12 | // node tests/local27.mjs # ~7,6 GB por la red, unos minutos |
| 13 | // MODELO=file:///ruta/al.gguf node tests/local27.mjs # si lo tienes en disco |
| 14 | import { chromium } from 'playwright'; |
| 15 | import { CHROME_ARGS } from './chrome-args.mjs'; |
| 16 | import { createServer } from 'http'; |
| 17 | import { createReadStream, statSync, readFileSync } from 'fs'; |
| 18 | import { Readable } from 'stream'; |
| 19 | import { pipeline } from 'stream/promises'; |
| 20 | import { extname, join, normalize } from 'path'; |
| 21 | import { fileURLToPath } from 'url'; |
| 22 | import { execSync } from 'child_process'; |
| 23 | |
| 24 | const WEB = join(fileURLToPath(new URL('.', import.meta.url)), '..', 'web'); |
| 25 | const ORIGEN = process.env.MODELO || 'https://claw.elffuss.com/models/qwen38-27b.gguf'; |
| 26 | // El mismo guion sirve para el hermano pequeño: mismo motor, mismo proveedor, |
| 27 | // mismo camino de chat, pero 800 MB en vez de 7,6 GB. Cuando el grande se muere |
| 28 | // a mitad —le pasa—, esto sigue diciendo si el CÓDIGO está bien. |
| 29 | // MODELO_ID=engine:qwen35-0.8b node tests/local27.mjs |
| 30 | const MODELO_ID = process.env.MODELO_ID || 'engine:qwen38-27b'; |
| 31 | const PUERTO = +(process.env.PUERTO || 8643); |
| 32 | const RUTA_MODELO = '/models/qwen38-27b.gguf'; |
| 33 | |
| 34 | const TIPOS = { |
| 35 | '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', |
| 36 | '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', |
| 37 | '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', |
| 38 | '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', |
| 39 | '.wasm': 'application/wasm', '.ico': 'image/x-icon', '.woff2': 'font/woff2', |
| 40 | }; |
| 41 | |
| 42 | // Espejo del modelo: reenvía el Range tal cual y devuelve el 206 con su |
| 43 | // Content-Range. Sin reenviar el rango, el navegador se traería los 7,6 GB de |
| 44 | // golpe en cada petición de 32 MB. |
| 45 | async function espejoModelo(req, res) { |
| 46 | const local = ORIGEN.startsWith('file://'); |
| 47 | if (local) { |
| 48 | const ruta = fileURLToPath(ORIGEN); |
| 49 | const size = statSync(ruta).size; |
| 50 | const m = /^bytes=(\d+)-(\d*)$/.exec(req.headers.range || ''); |
| 51 | if (!m) { res.writeHead(200, { 'Content-Length': size, 'Accept-Ranges': 'bytes' }); return req.method === 'HEAD' ? res.end() : createReadStream(ruta).pipe(res); } |
| 52 | const ini = +m[1], fin = Math.min(m[2] ? +m[2] : size - 1, size - 1); |
| 53 | res.writeHead(206, { |
| 54 | 'Content-Type': 'application/octet-stream', |
| 55 | 'Content-Range': `bytes ${ini}-${fin}/${size}`, |
| 56 | 'Content-Length': fin - ini + 1, |
| 57 | 'Accept-Ranges': 'bytes', |
| 58 | }); |
| 59 | return req.method === 'HEAD' ? res.end() : createReadStream(ruta, { start: ini, end: fin }).pipe(res); |
| 60 | } |
| 61 | const r = await fetch(ORIGEN, { |
| 62 | method: req.method === 'HEAD' ? 'HEAD' : 'GET', |
| 63 | headers: req.headers.range ? { Range: req.headers.range } : {}, |
| 64 | }); |
| 65 | const cab = { 'Content-Type': 'application/octet-stream', 'Accept-Ranges': 'bytes' }; |
| 66 | for (const k of ['content-range', 'content-length']) { |
| 67 | const v = r.headers.get(k); |
| 68 | if (v) cab[k === 'content-range' ? 'Content-Range' : 'Content-Length'] = v; |
| 69 | } |
| 70 | res.writeHead(r.status, cab); |
| 71 | if (req.method === 'HEAD' || !r.body) return res.end(); |
| 72 | // El navegador ABORTA rangos a mitad —lo hace, y es normal—. Con un pipe pelado |
| 73 | // eso lanza un error de stream que nadie escucha, y en Node eso no se queda en |
| 74 | // un aviso: se lleva por delante el proceso del test… y con él el navegador. |
| 75 | // Media hora buscando por qué «se moría la pestaña» era esto. |
| 76 | try { await pipeline(Readable.fromWeb(r.body), res); } catch { res.destroy(); } |
| 77 | } |
| 78 | |
| 79 | const server = createServer(async (req, res) => { |
| 80 | const ruta = decodeURIComponent(new URL(req.url, 'http://x').pathname); |
| 81 | try { |
| 82 | if (ruta === RUTA_MODELO) return await espejoModelo(req, res); |
| 83 | const rel = normalize(ruta === '/' ? '/index.html' : ruta).replace(/^(\.\.[/\\])+/, ''); |
| 84 | const f = join(WEB, rel); |
| 85 | const cuerpo = readFileSync(f); |
| 86 | res.writeHead(200, { 'Content-Type': TIPOS[extname(f)] || 'application/octet-stream', 'Cache-Control': 'no-store' }); |
| 87 | res.end(cuerpo); |
| 88 | } catch { |
| 89 | res.writeHead(404); res.end('no está'); |
| 90 | } |
| 91 | }); |
| 92 | await new Promise(r => server.listen(PUERTO, r)); |
| 93 | const BASE = `http://localhost:${PUERTO}`; |
| 94 | const t0 = Date.now(); |
| 95 | const seg = () => ((Date.now() - t0) / 1000).toFixed(0).padStart(4); |
| 96 | const log = s => console.log(`[${seg()}s] ${s}`); |
| 97 | log(`sirviendo ${WEB} y el modelo desde ${ORIGEN.startsWith('file') ? 'disco' : 'producción'}`); |
| 98 | |
| 99 | let fallos = 0; |
| 100 | const ok = (n, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (extra ? ' — ' + extra : '')); if (!c) fallos++; }; |
| 101 | |
| 102 | // CHROMELOG=1 saca por stderr lo que dice el propio navegador. Cuando el que se |
| 103 | // muere es él, es la única voz que queda: desde fuera solo se ve que ya no está. |
| 104 | // Va con DEBUG=pw:browser, que es quien enseña ese stderr. |
| 105 | const ARGS = ['--enable-unsafe-webgpu', ...CHROME_ARGS, |
| 106 | ...(process.env.CHROMELOG ? ['--enable-logging=stderr'] : [])]; |
| 107 | const b = await chromium.launch({ args: ARGS }) |
| 108 | .catch(() => chromium.launch({ channel: 'chrome', args: ARGS })); |
| 109 | const ctx = await b.newContext({ locale: 'es-ES' }); |
| 110 | await ctx.addInitScript(id => { |
| 111 | try { |
| 112 | localStorage.setItem('elffuss.welcomed', '1'); |
| 113 | localStorage.setItem('elffuss.grants', JSON.stringify([])); |
| 114 | localStorage.setItem('elffuss.model', id); |
| 115 | } catch { /* — */ } |
| 116 | }, MODELO_ID); |
| 117 | const p = await ctx.newPage({ viewport: { width: 1280, height: 900 } }); |
| 118 | p.on('console', m => { const t = m.text(); if (/\[engine\]|No se pudo|no cabe|OOM|memoria|liberad/i.test(t)) log(' consola: ' + t.slice(0, 180)); }); |
| 119 | p.on('pageerror', e => log(' pageerror: ' + String(e.message).slice(0, 160))); |
| 120 | let muerta = ''; |
| 121 | p.on('crash', () => { muerta = 'la pestaña ha CRASHEADO (el renderer)'; log(' ⚠️ ' + muerta); }); |
| 122 | p.on('close', () => { muerta = muerta || 'la pestaña se ha CERRADO (no crash: alguien la cerró)'; log(' ⚠️ ' + muerta); }); |
| 123 | // Y el navegador ENTERO también se puede ir: con 7,6 GB en la GPU no siempre se |
| 124 | // muere solo la pestaña, y entonces el evento de arriba no llega nunca. |
| 125 | b.on('disconnected', () => { muerta = muerta || 'el NAVEGADOR entero se ha ido'; log(' ⚠️ ' + muerta); }); |
| 126 | |
| 127 | // Testigos de fuera del navegador: si lo que se agota es la máquina, se ve aquí |
| 128 | // aunque el proceso que se muere no llegue a contarlo. |
| 129 | const sh = c => { try { return execSync(c, { encoding: 'utf8' }).trim(); } catch { return '?'; } }; |
| 130 | const libreGB = async () => { |
| 131 | const v = sh('vm_stat | head -2 | tail -1'); |
| 132 | const paginas = +(/(\d+)/.exec(v)?.[1] || 0); |
| 133 | return (paginas * 16384 / 1073741824).toFixed(1); |
| 134 | }; |
| 135 | const chromiumRSS = () => { |
| 136 | const kb = +sh(`ps -Ao rss,args | grep -i chrom | grep -v grep | awk '{s+=$1} END {print s+0}'`); |
| 137 | return kb ? (kb / 1048576).toFixed(1) + ' GB' : 'no está'; |
| 138 | }; |
| 139 | // Memoria POR PROCESO del navegador. Importa la distinción: en un Mac la memoria |
| 140 | // de la GPU sale del mismo saco que la del sistema, así que si lo que crece es |
| 141 | // el proceso de GPU y no el de la pestaña, lo que se está agotando son los |
| 142 | // buffers del modelo y no el JavaScript. |
| 143 | const porProceso = () => { |
| 144 | const filas = sh(`ps -Ao rss,args | grep -i "chromium\\|chrome" | grep -v grep`).split('\n'); |
| 145 | const suma = {}; |
| 146 | for (const f of filas) { |
| 147 | const rss = +(/^\s*(\d+)/.exec(f)?.[1] || 0); |
| 148 | if (!rss) continue; |
| 149 | const tipo = /--type=([a-z-]+)/.exec(f)?.[1] || 'navegador'; |
| 150 | suma[tipo] = (suma[tipo] || 0) + rss; |
| 151 | } |
| 152 | return Object.entries(suma).sort((a, b) => b[1] - a[1]).slice(0, 3) |
| 153 | .map(([t, kb]) => `${t} ${(kb / 1048576).toFixed(1)} GB`).join(' · ') || 'no está'; |
| 154 | }; |
| 155 | |
| 156 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 157 | |
| 158 | let estado = '', ultimo = '', cargado = false, ultimoPct = -1; |
| 159 | while (Date.now() - t0 < 40 * 60 * 1000 && !muerta) { |
| 160 | let s; |
| 161 | try { |
| 162 | s = await p.evaluate(() => ({ |
| 163 | est: document.querySelector('#model-status')?.className || '', |
| 164 | txt: document.querySelector('#loading-stage .ls-progtext')?.textContent |
| 165 | || document.querySelector('#model-progress-text')?.textContent || '', |
| 166 | })); |
| 167 | } catch (e) { muerta = muerta || 'la página dejó de responder: ' + String(e.message).split('\n')[0].slice(0, 90); break; } |
| 168 | estado = s.est; |
| 169 | if (s.txt && s.txt !== ultimo) { |
| 170 | ultimo = s.txt; |
| 171 | // Cada 10 % se apunta también la memoria: cuando se muere a mitad, lo único |
| 172 | // que queda es la última foto de antes. |
| 173 | const pct = +(/(\d+)\s*%/.exec(ultimo)?.[1] || -1); |
| 174 | const foto = pct >= 0 && pct % 10 === 0 && pct !== ultimoPct; |
| 175 | if (foto) ultimoPct = pct; |
| 176 | log(ultimo.trim().slice(0, 110) + (foto ? ` · libres ${await libreGB()} GB · ${porProceso()}` : '')); |
| 177 | } |
| 178 | if (/\b(on|gpu)\b/.test(estado)) { cargado = true; break; } |
| 179 | if (/\berr(or)?\b/.test(estado)) break; |
| 180 | await p.waitForTimeout(5000).catch(() => {}); |
| 181 | } |
| 182 | ok('el 27B carga entero por rangos', cargado, muerta || 'indicador: ' + estado + ' · ' + ultimo); |
| 183 | if (cargado) log(`con el modelo ya en la GPU: ${await libreGB()} GB de RAM libres · navegador ${chromiumRSS()}`); |
| 184 | |
| 185 | if (cargado) { |
| 186 | // Tope corto de respuesta: con el modelo lento, ocho tokens bastan para saber |
| 187 | // si contesta y separan el prefill (una pasada por todo el prompt) del decode |
| 188 | // (muchas pasadas cortas). Si se cae, se cae en la primera, y eso ya es un dato. |
| 189 | // El import devuelve la MISMA instancia del módulo que usa el kernel. |
| 190 | await p.evaluate(async () => { |
| 191 | const m = await import('./js/engine/provider.js'); |
| 192 | m.setSampling({ maxTokens: 8 }); |
| 193 | }).catch(e => log(' no se pudo acotar la respuesta: ' + String(e.message).slice(0, 80))); |
| 194 | |
| 195 | log('preguntando…'); |
| 196 | await p.fill('#prompt', 'Di solo: hola'); |
| 197 | await p.press('#prompt', 'Enter'); |
| 198 | let texto = ''; |
| 199 | const tGen = Date.now(); |
| 200 | while (Date.now() - tGen < 15 * 60 * 1000) { |
| 201 | // Con timeout CORTO y sin tragarse el fallo: una pestaña muerta devolvía '' |
| 202 | // en cada vuelta y el test la contaba como «no ha contestado» durante quince |
| 203 | // minutos, cuando lo que había pasado es que el navegador ya no estaba. |
| 204 | try { |
| 205 | texto = (await p.locator('.msg.assistant').last().textContent({ timeout: 10000 })) || ''; |
| 206 | } catch (e) { |
| 207 | if (muerta || !p.context().browser()?.isConnected()) { |
| 208 | log(' 💀 ' + (muerta || 'el navegador se ha ido') + ` a los ${((Date.now() - tGen) / 1000).toFixed(0)} s de empezar a generar`); |
| 209 | break; |
| 210 | } |
| 211 | texto = ''; // ocupada, no muerta: se vuelve a mirar |
| 212 | } |
| 213 | if (texto.trim().length > 2) break; |
| 214 | // El montón de JS importa además de la RAM del sistema: la app tiene un |
| 215 | // vigilante que, si pasa del 92 % del tope, SUELTA el modelo —destruye el |
| 216 | // GPUDevice— sin mirar si hay un forward en marcha. Si el navegador se cae |
| 217 | // justo después de que este número se dispare, ya sabemos quién ha sido. |
| 218 | const heap = await p.evaluate(() => { |
| 219 | const m = performance.memory; |
| 220 | return m ? `${Math.round(m.usedJSHeapSize / 1048576)}/${Math.round(m.jsHeapSizeLimit / 1048576)} MB (${Math.round(m.usedJSHeapSize / m.jsHeapSizeLimit * 100)} %)` : 'sin dato'; |
| 221 | }).catch(() => 'no responde'); |
| 222 | log(` … generando (${((Date.now() - tGen) / 1000).toFixed(0)} s) · RAM libre ${await libreGB()} GB · montón JS ${heap}`); |
| 223 | await new Promise(r => setTimeout(r, 10000)); |
| 224 | } |
| 225 | const t = texto.trim(); |
| 226 | ok('contesta algo', t.length > 2, JSON.stringify(t.slice(0, 120))); |
| 227 | // Esta es LA guardia del arreglo: antes contestaba, sí, pero contestaba |
| 228 | // «El modelo falló: la caché se llena: 1333 tokens sobre 512 de contexto». |
| 229 | ok('y no es el error de contexto', !/caché se llena|El modelo falló/i.test(t), JSON.stringify(t.slice(0, 120))); |
| 230 | await p.screenshot({ path: '/tmp/claw-local27.png' }).catch(() => {}); |
| 231 | } |
| 232 | |
| 233 | // b.close() se queda colgado con 7,6 GB en la GPU: se le da un margen y se sigue. |
| 234 | await Promise.race([b.close(), new Promise(r => setTimeout(r, 15000))]).catch(() => {}); |
| 235 | server.close(); |
| 236 | console.log(fallos ? `\n${fallos} fallo(s)` : '\nTodo verde'); |
| 237 | process.exit(fallos ? 1 : 0); |