| 1 | // Ajustes: lo que ofrecen tiene que ser lo correcto, y usarse sin ratón. |
| 2 | // |
| 3 | // 1. Bridge para un Mac ARM: antes se ofrecía la versión Intel (todos los Mac |
| 4 | // dicen «MacIntel» en navigator.platform). Si no se puede saber la |
| 5 | // arquitectura, se ofrecen las dos versiones de Mac. |
| 6 | // 2. Token y carpeta del bridge con su etiqueta asociada; «Olvidar token» y |
| 7 | // «Desconectar» existen (antes no había forma). |
| 8 | // 3. El permiso dice lo que controla (ficheros), no «y comandos de terminal». |
| 9 | // 4. Los interruptores de proveedores externos tienen nombre accesible. |
| 10 | // 5. El punto del modelo dice con palabras qué modelo y en qué estado, y es |
| 11 | // un botón que lleva a Ajustes. |
| 12 | // 6. Al elegir un modelo, su tarjeta dice «cargando…» y, al terminar, queda |
| 13 | // resaltada (antes el resaltado se quedaba en el anterior). Lo escrito en |
| 14 | // Ajustes mientras carga no se pierde y el foco no se va a <body>. |
| 15 | // 5. El punto del modelo lleva el foco a la tarjeta del modelo activo. |
| 16 | // El modelo es de mentira: page.route sirve un providers/onnx.js propio. |
| 17 | // |
| 18 | // BASE=http://127.0.0.1:8898 node tests/settings-ux.mjs |
| 19 | import { chromium } from 'playwright'; |
| 20 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 21 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 22 | |
| 23 | const MAC_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36'; |
| 24 | const FALSO = `export const name = 'onnx falso'; export function configure() {} |
| 25 | export async function load(onProgress = () => {}) { onProgress('cargando falso'); await new Promise(r => setTimeout(r, 900)); } |
| 26 | export async function chat() { return 'hola'; }`; |
| 27 | |
| 28 | const b = await chromium.launch(); |
| 29 | const errs = []; |
| 30 | const abre = async (arch) => { |
| 31 | const ctx = await b.newContext({ locale: 'es-ES', userAgent: MAC_UA }); |
| 32 | await ctx.addInitScript((arch) => { |
| 33 | try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.bridgeToken', 'tok-de-prueba'); } catch {} |
| 34 | const datos = arch === null ? undefined : { getHighEntropyValues: async () => ({ architecture: arch }) }; |
| 35 | Object.defineProperty(Navigator.prototype, 'userAgentData', { get: () => datos, configurable: true }); |
| 36 | // WebGPU simulada y pequeña: desde d526a74 la tarjeta del ONNX ligero solo |
| 37 | // sale con WebGPU, y el navegador de pruebas tiene navigator.gpu sin adaptador. |
| 38 | const falsa = { requestAdapter: async () => ({ limits: { maxBufferSize: 2 ** 28 }, features: new Set(), info: {}, requestDevice: async () => { throw new Error('no hace falta'); } }) }; |
| 39 | try { Object.defineProperty(Navigator.prototype, 'gpu', { get() { return falsa; }, configurable: true }); } catch { /* */ } |
| 40 | }, arch); |
| 41 | const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } }); |
| 42 | p.on('pageerror', e => errs.push(e.message.slice(0, 160))); |
| 43 | await p.route('**/js/providers/onnx.js*', r => r.fulfill({ status: 200, contentType: 'text/javascript', body: FALSO })); |
| 44 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 45 | await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.(), null, { timeout: 15000 }); |
| 46 | return { ctx, p }; |
| 47 | }; |
| 48 | const descargas = (p) => p.evaluate(() => [...document.querySelectorAll('#br-dl a')].map(a => a.dataset.file)); |
| 49 | |
| 50 | // 1 · Mac ARM |
| 51 | let { ctx, p } = await abre('arm'); |
| 52 | await p.click('#btn-settings'); |
| 53 | await p.waitForTimeout(500); |
| 54 | ok('1 · en un Mac ARM se ofrece la versión Apple Silicon', JSON.stringify(await descargas(p)) === '["elffuss-bridge-mac-arm64"]', JSON.stringify(await descargas(p))); |
| 55 | |
| 56 | // 2 · etiquetas, Olvidar token |
| 57 | const etiquetas = await p.evaluate(() => ['br-token', 'br-folder'].map(id => document.getElementById(id).labels?.length || 0)); |
| 58 | ok('2 · token y carpeta tienen su etiqueta asociada', etiquetas.every(n => n === 1), JSON.stringify(etiquetas)); |
| 59 | ok('2 · con un token guardado se ofrece «Olvidar token»', await p.locator('#br-forget').isVisible()); |
| 60 | await p.click('#br-forget'); |
| 61 | await p.waitForTimeout(150); |
| 62 | const olvido = await p.evaluate(() => ({ ls: localStorage.getItem('elffusscode.bridgeToken'), input: document.getElementById('br-token').value, msg: document.querySelector('.bridge-card .br-msg')?.textContent || '' })); |
| 63 | ok('2 · «Olvidar token» lo borra del navegador y lo dice', olvido.ls === null && olvido.input === '' && /olvidado/.test(olvido.msg), JSON.stringify(olvido)); |
| 64 | const disc = await p.evaluate(() => !!document.getElementById('br-disconnect')); |
| 65 | ok('2 · existe «Desconectar» (visible cuando el bridge está conectado)', disc); |
| 66 | |
| 67 | // 3 · permiso |
| 68 | const permiso = await p.evaluate(() => document.querySelector('#perm-autoedit').closest('label').textContent); |
| 69 | ok('3 · el permiso dice que controla escribir y editar ficheros', /Escribir y editar ficheros/.test(permiso) && !/comandos de terminal/.test(permiso), permiso); |
| 70 | |
| 71 | // 4 · proveedores |
| 72 | const nombres = await p.evaluate(() => [...document.querySelectorAll('#settings-panel .prov-head input[type=checkbox]')].map(c => c.getAttribute('aria-label'))); |
| 73 | ok('4 · cada interruptor de proveedor tiene nombre accesible', nombres.length >= 3 && nombres.every(n => /^Activar /.test(n || '')), JSON.stringify(nombres)); |
| 74 | |
| 75 | // 6 · tarjeta de modelo: cargando… y resaltada al terminar |
| 76 | const tarjetaQwen = p.locator('#settings-panel .model-card', { hasText: 'Qwen3.5-0.8B' }).first(); |
| 77 | await tarjetaQwen.click(); |
| 78 | await p.waitForTimeout(150); |
| 79 | const durante = await p.evaluate(() => { const c = [...document.querySelectorAll('#settings-panel .model-card')].find(x => /Qwen3.5-0.8B/.test(x.textContent)); return { busy: c?.getAttribute('aria-busy'), txt: c?.textContent }; }); |
| 80 | ok('6 · al elegir un modelo, su tarjeta dice «cargando…» (aria-busy)', durante.busy === 'true' && /cargando/.test(durante.txt), JSON.stringify(durante)); |
| 81 | // …y mientras carga se puede seguir escribiendo en Ajustes: al terminar la carga |
| 82 | // el panel ya no se rehace entero (antes se borraba el texto y el foco iba a <body>) |
| 83 | await p.locator('#tel-feedback').fill('texto a medio escribir'); |
| 84 | await p.waitForTimeout(1500); |
| 85 | const tras = await p.evaluate(() => { const c = [...document.querySelectorAll('#settings-panel .model-card')].find(x => /Qwen3.5-0.8B/.test(x.textContent)); return { activa: c?.classList.contains('active'), pressed: c?.getAttribute('aria-pressed') }; }); |
| 86 | ok('6 · al terminar, la tarjeta del modelo cargado queda resaltada', tras.activa && tras.pressed === 'true', JSON.stringify(tras)); |
| 87 | const escrito = await p.evaluate(() => ({ valor: document.getElementById('tel-feedback')?.value, foco: document.activeElement?.id || document.activeElement?.tagName })); |
| 88 | ok('6 · lo escrito en Ajustes mientras cargaba sigue ahí, con el foco', escrito.valor === 'texto a medio escribir' && escrito.foco === 'tel-feedback', JSON.stringify(escrito)); |
| 89 | // Con el teclado: Enter en una tarjeta deja el foco en ELLA (antes, en <body>) |
| 90 | const enfocada = () => p.evaluate(() => { const a = document.activeElement; return a?.classList.contains('model-card') ? a.querySelector('b')?.textContent : (a?.id || a?.tagName); }); |
| 91 | await p.locator('#settings-panel .model-card', { hasText: 'Básico' }).first().focus(); |
| 92 | await p.keyboard.press('Enter'); |
| 93 | await p.waitForTimeout(200); |
| 94 | ok('6 · Enter en la tarjeta «Básico» deja el foco en esa tarjeta', /Básico/.test(await enfocada() || ''), await enfocada()); |
| 95 | await tarjetaQwen.focus(); |
| 96 | await p.keyboard.press('Enter'); |
| 97 | await p.waitForTimeout(150); |
| 98 | const focoCargando = await enfocada(); |
| 99 | await p.waitForTimeout(1500); |
| 100 | ok('6 · Enter en una tarjeta que carga: el foco sigue en ella durante y después de la carga', /Qwen3.5-0.8B/.test(focoCargando || '') && /Qwen3.5-0.8B/.test(await enfocada() || ''), |
| 101 | JSON.stringify({ focoCargando, despues: await enfocada() })); |
| 102 | |
| 103 | // 5 · el punto del modelo |
| 104 | await p.click('#btn-settings'); // cierra |
| 105 | const punto = await p.evaluate(() => { const d = document.getElementById('model-dot'); return { tag: d.tagName, aria: d.getAttribute('aria-label') }; }); |
| 106 | ok('5 · el punto del modelo es un botón que dice qué modelo y su estado', punto.tag === 'BUTTON' && /Qwen3.5-0.8B/.test(punto.aria) && /listo/.test(punto.aria), JSON.stringify(punto)); |
| 107 | await p.click('#model-dot'); |
| 108 | await p.waitForTimeout(300); |
| 109 | ok('5 · …y lleva a Ajustes', await p.evaluate(() => !document.getElementById('settings-panel').hidden && !!document.querySelector('#settings-panel .model-grid'))); |
| 110 | ok('5 · …con el foco en la tarjeta del modelo ACTIVO (no en la primera)', await p.evaluate(() => |
| 111 | document.activeElement?.classList.contains('model-card') && document.activeElement.classList.contains('active') && /Qwen3.5-0.8B/.test(document.activeElement.textContent)), |
| 112 | await p.evaluate(() => document.activeElement?.textContent?.slice(0, 40))); |
| 113 | await ctx.close(); |
| 114 | |
| 115 | // 1 · Mac sin datos de arquitectura (Safari): las dos versiones |
| 116 | ({ ctx, p } = await abre(null)); |
| 117 | await p.click('#btn-settings'); |
| 118 | await p.waitForTimeout(500); |
| 119 | ok('1 · si no se sabe la arquitectura del Mac, se ofrecen las dos versiones', JSON.stringify(await descargas(p)) === '["elffuss-bridge-mac-arm64","elffuss-bridge-mac-intel"]', JSON.stringify(await descargas(p))); |
| 120 | await ctx.close(); |
| 121 | |
| 122 | console.log('\n errores JS:', errs[0] || 'ninguno'); |
| 123 | ok('sin errores de página', errs.length === 0, errs.join(' | ')); |
| 124 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ AJUSTES: LO QUE OFRECEN ES LO CORRECTO'); |
| 125 | await b.close(); |
| 126 | process.exit(fails ? 1 : 0); |