| 1 | // Selector de modelo. |
| 2 | // · Nombre accesible propio y estado del punto con palabras. |
| 3 | // · Si el cerebro elegido no carga, se vuelve al que FUNCIONABA (no a Básico), |
| 4 | // también si es un Gemma (su respaldo ligero es solo para cuando no había otro). |
| 5 | // · Mientras carga, el selector está desactivado (sin cargas en paralelo). |
| 6 | // · Cambiar de cerebro no te saca de la pestaña en la que estás. |
| 7 | // · Barra de progreso accesible; ⓘ a la ficha del modelo; etiquetas en inglés. |
| 8 | // |
| 9 | // BASE=http://localhost:8743 node tests/ux-modelo.mjs |
| 10 | import { createServer } from 'node:http'; |
| 11 | import { navegador, contexto, ok, hasta, espera, escribir, reposo, avisos, fin, BASE } from './ux-comun.mjs'; |
| 12 | |
| 13 | const servidor = createServer((req, res) => { |
| 14 | const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'content-type, authorization', 'Access-Control-Allow-Methods': 'POST, OPTIONS' }; |
| 15 | if (req.method === 'OPTIONS') { res.writeHead(204, cors); res.end(); return; } |
| 16 | req.resume(); |
| 17 | req.on('end', () => { |
| 18 | res.writeHead(200, { ...cors, 'Content-Type': 'text/event-stream' }); |
| 19 | res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: 'respuesta de ollama' } }] })}\n\n`); |
| 20 | res.write('data: [DONE]\n\n'); res.end(); |
| 21 | }); |
| 22 | }); |
| 23 | await new Promise(r => servidor.listen(0, '127.0.0.1', r)); |
| 24 | const PROV = JSON.stringify({ |
| 25 | ollama: { enabled: true, baseURL: `http://localhost:${servidor.address().port}/v1`, model: 'falso', apiKey: 'ollama' }, |
| 26 | openai: { enabled: true, baseURL: 'https://api.openai.com/v1', model: 'gpt-4o-mini', apiKey: '' }, // sin clave: no carga |
| 27 | }); |
| 28 | const b = await navegador(); |
| 29 | const { ctx } = await contexto(b, { model: 'ext:ollama', extraInit: { 'elffuss.providers': PROV } }); |
| 30 | const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } }); |
| 31 | const errores = []; |
| 32 | p.on('pageerror', e => { if (!/allow-same-origin/.test(e.message)) errores.push(e.message); }); |
| 33 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 34 | const listo = () => p.evaluate(() => document.getElementById('model-select').value === 'ext:ollama' && document.getElementById('model-status').classList.contains('on')); |
| 35 | ok('Ollama (de prueba) cargado', await hasta(listo)); |
| 36 | // Un cerebro que carga al momento no deja puesto el escaparate de descarga |
| 37 | // («Preparando tu sistema operativo…»): su módulo llegaba DESPUÉS de que la |
| 38 | // carga terminara, y se montaba para quedarse. |
| 39 | ok('un cerebro que carga al momento no deja el escaparate de descarga en la Vista', await hasta(() => p.evaluate(() => |
| 40 | !document.getElementById('loading-stage') && !document.getElementById('vista-empty').hidden)), |
| 41 | await p.evaluate(() => document.getElementById('loading-stage') ? 'escaparate puesto' : 'sin placeholder')); |
| 42 | ok('el selector se llama «Cerebro (modelo de IA)» y el punto dice su estado', await p.getAttribute('#model-select', 'aria-label') === 'Cerebro (modelo de IA)' |
| 43 | && await p.getAttribute('#model-status', 'aria-label') === 'Modelo listo'); |
| 44 | // …y lo dice también a la vista, con palabras: el punto solo era un color. |
| 45 | ok('junto al punto, el estado en palabras («Listo»), visible', await p.evaluate(() => { |
| 46 | const t = document.getElementById('model-status-txt'); |
| 47 | return t?.textContent === 'Listo' && t.getClientRects().length > 0 && getComputedStyle(t).visibility !== 'hidden'; |
| 48 | })); |
| 49 | |
| 50 | await p.click('#tabs button[data-tab="ajustes"]'); |
| 51 | await p.evaluate(() => { |
| 52 | window.__desactivado = []; |
| 53 | const s = document.getElementById('model-select'); |
| 54 | new MutationObserver(() => window.__desactivado.push(s.disabled)).observe(s, { attributes: true, attributeFilter: ['disabled'] }); |
| 55 | s.value = 'ext:openai'; |
| 56 | s.dispatchEvent(new Event('change')); |
| 57 | }); |
| 58 | ok('si el elegido no carga, lo dice y sigue con el que funcionaba', await hasta(async () => |
| 59 | (await avisos(p)).some(t => /Sigo con Ollama/.test(t)) && await listo()), (await avisos(p)).join(' | ')); |
| 60 | ok('…mientras cargaba el selector estuvo desactivado y luego se reactivó', await p.evaluate(() => |
| 61 | window.__desactivado.includes(true) && !document.getElementById('model-select').disabled)); |
| 62 | ok('…y no te sacó de Ajustes para enseñar la descarga', await p.evaluate(() => document.querySelector('#tabs [aria-selected="true"]').dataset.tab === 'ajustes')); |
| 63 | // Con el teclado: el selector se desactiva mientras carga (y pierde el foco); |
| 64 | // al terminar, el foco vuelve a él (antes se quedaba en <body>). |
| 65 | await p.focus('#model-select'); |
| 66 | await p.selectOption('#model-select', 'ext:openai'); |
| 67 | ok('elegir cerebro con el teclado: al acabar la carga el foco vuelve al selector', await hasta(async () => |
| 68 | await listo() && await p.evaluate(() => !document.getElementById('model-select').disabled && document.activeElement?.id === 'model-select')), |
| 69 | await p.evaluate(() => document.activeElement?.id || document.activeElement?.tagName)); |
| 70 | await escribir(p, 'hola'); |
| 71 | ok('el cerebro que funcionaba sigue contestando', await hasta(async () => /respuesta de ollama/.test(await p.locator('#log').innerText()))); |
| 72 | await reposo(p); |
| 73 | |
| 74 | // ── un Gemma que no carga, con otro cerebro funcionando: se vuelve a ESE ───── |
| 75 | // (antes el respaldo de Gemma iba primero y te dejaba en Qwen3.5-0.8B, otra |
| 76 | // descarga de ~600 MB, aunque Ollama funcionaba). Gemma y Qwen son dobles: el |
| 77 | // Gemma falla al cargar y el Qwen cargaría bien, para que se note a cuál va. |
| 78 | await p.route('**/js/providers/litert.js', r => r.fulfill({ contentType: 'text/javascript', |
| 79 | body: 'export function configure(){} export async function load(){ throw new Error("sin memoria (prueba)"); } export async function chat(){ return ""; }' })); |
| 80 | await p.route('**/js/providers/onnx.js', r => r.fulfill({ contentType: 'text/javascript', |
| 81 | body: 'window.__qwen = 0; export function configure(){} export async function load(){ window.__qwen++; } export async function chat(h, s, cb){ cb && cb("respuesta de qwen"); return "respuesta de qwen"; }' })); |
| 82 | const elegir = id => p.evaluate(id => { |
| 83 | const s = document.getElementById('model-select'); |
| 84 | if (![...s.options].some(o => o.value === id)) { const o = document.createElement('option'); o.value = id; o.textContent = id; s.appendChild(o); } |
| 85 | s.value = id; |
| 86 | s.dispatchEvent(new Event('change')); |
| 87 | }, id); |
| 88 | await elegir('litert:gemma-e4b'); |
| 89 | ok('un Gemma que no carga, con Ollama funcionando: vuelve a Ollama', await hasta(async () => |
| 90 | (await avisos(p)).some(t => /No se pudo cargar .*gemma.*Sigo con Ollama/i.test(t)) && await listo()), (await avisos(p)).join(' | ')); |
| 91 | ok('…sin pasar por el ligero (Qwen no se carga)', await p.evaluate(() => !window.__qwen && localStorage.getItem('elffuss.model') === 'ext:ollama')); |
| 92 | await escribir(p, 'sigues ahí'); |
| 93 | ok('…y contesta Ollama', await hasta(async () => /respuesta de ollama[\s\S]*respuesta de ollama/.test(await p.locator('#log').innerText()))); |
| 94 | await reposo(p); |
| 95 | // Sin otro cerebro (desde Básico), el respaldo ligero sigue existiendo. |
| 96 | await elegir('rules'); |
| 97 | await hasta(() => p.evaluate(() => document.getElementById('model-select').value === 'rules' && !document.getElementById('model-select').disabled)); |
| 98 | await elegir('litert:gemma-e4b'); |
| 99 | ok('desde Básico, un Gemma que no carga cae al ligero', await hasta(() => p.evaluate(() => |
| 100 | window.__qwen === 1 && document.getElementById('model-select').value === 'onnx:qwen3.5-0.8b')), (await avisos(p)).join(' | ')); |
| 101 | await elegir('ext:ollama'); |
| 102 | await hasta(listo); |
| 103 | await p.unroute('**/js/providers/litert.js'); |
| 104 | await p.unroute('**/js/providers/onnx.js'); |
| 105 | |
| 106 | // ── barra de progreso y ficha del modelo ──────────────────────────────────── |
| 107 | const prog = await p.evaluate(async () => { |
| 108 | const ui = await import('/js/ui.js'); |
| 109 | ui.modelProgress('Descargando el cerebro · 42 %'); |
| 110 | const t = document.querySelector('#model-progress .track'); |
| 111 | const r = { visible: !document.getElementById('model-progress').hidden, role: t.getAttribute('role'), now: t.getAttribute('aria-valuenow') }; |
| 112 | ui.modelProgress(null); |
| 113 | ui.setFichaModelo('https://huggingface.co/onnx-community/Qwen3.5-0.8B-ONNX', 'Qwen3.5-0.8B'); |
| 114 | const a = document.getElementById('model-card'); |
| 115 | r.ficha = { hidden: a.hidden, href: a.href, rel: a.rel, label: a.getAttribute('aria-label') }; |
| 116 | return r; |
| 117 | }); |
| 118 | ok('fuera de la Vista, el progreso va en la caja flotante con role=progressbar y aria-valuenow', prog.visible && prog.role === 'progressbar' && prog.now === '42', JSON.stringify(prog)); |
| 119 | ok('ⓘ enlaza la ficha del modelo (pestaña nueva, sin referrer) con nombre', !prog.ficha.hidden && /huggingface\.co\/onnx-community/.test(prog.ficha.href) |
| 120 | && prog.ficha.rel === 'noopener noreferrer' && /Qwen3\.5-0\.8B/.test(prog.ficha.label), JSON.stringify(prog.ficha)); |
| 121 | |
| 122 | // ── en inglés, las coletillas del selector ────────────────────────────────── |
| 123 | { |
| 124 | const { ctx: c2 } = await contexto(b, { locale: 'en-US' }); |
| 125 | const e = await c2.newPage(); |
| 126 | await e.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 127 | await e.waitForFunction(() => !!window.elffuss?.agent); |
| 128 | const ops = await e.$$eval('#model-select option', os => os.map(o => o.textContent)); |
| 129 | ok('en inglés: «Basic (no model)» y sin coletillas en español', ops.includes('Basic (no model)') && !ops.some(o => /sin modelo|ligero|por defecto/.test(o)), JSON.stringify(ops)); |
| 130 | ok('en inglés: el selector se llama «Brain (AI model)»', await e.getAttribute('#model-select', 'aria-label') === 'Brain (AI model)'); |
| 131 | await c2.close(); |
| 132 | } |
| 133 | |
| 134 | ok('sin errores de página', errores.length === 0, errores.slice(0, 3).join(' | ')); |
| 135 | servidor.close(); |
| 136 | await fin(b, 'SELECTOR DE MODELO: vuelve al que funcionaba, se bloquea al cargar y no te mueve de pestaña'); |