| 1 | // Ajustes que decían una cosa y hacían otra: |
| 2 | // |
| 3 | // 1. Espacio de trabajo · «Guardar solo»: no guardaba NUNCA (nada llamaba a |
| 4 | // workspace.touch()). Ahora un mensaje nuevo acaba en .elffuss/code/ del |
| 5 | // disco sin pulsar «Guardar ahora». |
| 6 | // 2. Feedback · Enviar: decía «¡enviado, gracias!» aunque el servidor |
| 7 | // contestara 404, y borraba el texto. Ahora dice que falló y lo conserva; |
| 8 | // cuando el servidor lo acepta, sí lo da por enviado. |
| 9 | // 3. Chip 💾 y «Vaciar caché»: contaban el origen ENTERO como «modelos» y al |
| 10 | // vaciar solo borraban una caché vieja. Ahora cuentan solo los modelos |
| 11 | // (almacén OPFS de modelos + caché de transformers) y los vacían de verdad |
| 12 | // sin tocar lo demás, diciendo cuánto se liberó. Con un SDK de broker que |
| 13 | // sabe del almacén compartido, se cuentan y vacían también el broker por |
| 14 | // defecto y los hosts del motor, todos a la vez. |
| 15 | // 4. Con el teclado, el foco no se pierde: Enviar y «Vaciar caché» lo |
| 16 | // conservan mientras trabajan (antes se deshabilitaban con el foco dentro |
| 17 | // y caía a <body>), y el chip 💾, que desaparece al vaciar, lo pasa al |
| 18 | // control de al lado. |
| 19 | // Ningún broker de verdad: sus páginas las contesta un doble local. |
| 20 | // |
| 21 | // BASE=http://127.0.0.1:8898 node tests/storage-honest.mjs |
| 22 | import { chromium } from 'playwright'; |
| 23 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 24 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 25 | |
| 26 | const b = await chromium.launch(); |
| 27 | // Ningún broker de verdad: las páginas de broker (models, m1, m2… de elffuss) las |
| 28 | // contesta un doble local que dice «listo», mide 0 y vacía. Con el SDK de broker |
| 29 | // que sabe del almacén compartido (el de main), este test cargaba las páginas de |
| 30 | // producción y esperaba sus tiempos muertos. |
| 31 | const BROKER_FALSO = `<!doctype html><script> |
| 32 | parent.postMessage({ kind: 'elffuss-broker-ready' }, '*'); |
| 33 | addEventListener('message', e => { |
| 34 | const d = e.data || {}; |
| 35 | if (d.type === 'elffuss-broker-diag') e.source.postMessage({ kind: 'diag', id: d.id, usado: 0, quota: 0 }, e.origin); |
| 36 | if (d.type === 'elffuss-model-clear') e.source.postMessage({ kind: 'cleared', id: d.id, liberado: 0 }, e.origin); |
| 37 | }); |
| 38 | <\/script>`; |
| 39 | const BROKERS = /^https:\/\/(models|m\d+)\.elffuss\.(com|utopiaia\.com)\//; |
| 40 | const brokersPedidos = []; |
| 41 | const ctx = await b.newContext({ locale: 'es-ES' }); |
| 42 | await ctx.route(BROKERS, r => { brokersPedidos.push(r.request().url()); return r.fulfill({ status: 200, contentType: 'text/html', body: BROKER_FALSO }); }); |
| 43 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} window.confirm = () => true; }); |
| 44 | // Cada vez que el foco se pierde sin ir a ningún sitio (un botón que se |
| 45 | // deshabilita o se esconde con el foco dentro), queda apuntado aquí. |
| 46 | await ctx.addInitScript(() => { |
| 47 | window.__focoPerdido = []; |
| 48 | document.addEventListener('focusout', e => { if (!e.relatedTarget) window.__focoPerdido.push(e.target.id || e.target.tagName); }, true); |
| 49 | }); |
| 50 | const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } }); |
| 51 | const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160))); |
| 52 | // Pulsa con el teclado (como quien no usa ratón) y dice dónde acabó el foco y |
| 53 | // si se perdió por el camino. |
| 54 | const conTeclado = async sel => { await p.focus(sel); await p.evaluate(() => { window.__focoPerdido = []; }); await p.keyboard.press('Enter'); }; |
| 55 | const foco = () => p.evaluate(() => ({ en: document.activeElement?.id || document.activeElement?.tagName, perdido: window.__focoPerdido })); |
| 56 | |
| 57 | const MB = 1048576; |
| 58 | await p.goto(BASE + '/manifest.json'); |
| 59 | await p.evaluate(async (MB) => { |
| 60 | const root = await navigator.storage.getDirectory(); |
| 61 | const escribe = async (dir, name, bytes) => { const w = await (await dir.getFileHandle(name, { create: true })).createWritable(); await w.write(new Uint8Array(bytes)); await w.close(); }; |
| 62 | await escribe(root, 'datos-del-proyecto.bin', 3 * MB); // NO es un modelo |
| 63 | await escribe(await root.getDirectoryHandle('elffuss-models', { create: true }), 'pesos.bin', 2 * MB); |
| 64 | const c = await caches.open('transformers-cache'); |
| 65 | await c.put('https://huggingface.co/x/onnx/model.onnx', new Response(new Uint8Array(1 * MB), { headers: { 'content-length': String(1 * MB) } })); |
| 66 | }, MB); |
| 67 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 68 | await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.() && !document.getElementById('disk-chip').hidden, null, { timeout: 20000 }).catch(() => {}); |
| 69 | |
| 70 | // 3 · el chip cuenta solo los modelos |
| 71 | const chip = await p.evaluate(() => ({ txt: document.getElementById('disk-chip').textContent, title: document.getElementById('disk-chip').title })); |
| 72 | ok('3 · el chip cuenta solo los modelos (3 MB), no los 3 MB de datos del proyecto', /💾 3 MB/.test(chip.txt), JSON.stringify(chip)); |
| 73 | await conTeclado('#disk-chip'); |
| 74 | await p.waitForFunction(() => /Liberados/.test(document.getElementById('statusbar').textContent), null, { timeout: 10000 }).catch(() => {}); |
| 75 | await p.waitForFunction(() => document.getElementById('disk-chip').hidden, null, { timeout: 5000 }).catch(() => {}); |
| 76 | const fChip = await foco(); |
| 77 | ok('3 · con el teclado: al desaparecer el chip, el foco pasa al control de al lado, nunca a <body>', |
| 78 | fChip.en === 'btn-history' && !fChip.perdido.length, JSON.stringify(fChip)); |
| 79 | const tras = await p.evaluate(async () => { |
| 80 | const root = await navigator.storage.getDirectory(); |
| 81 | const hay = async (n) => { try { await root.getDirectoryHandle(n); return true; } catch { return false; } }; |
| 82 | const fichero = async (n) => { try { return (await (await root.getFileHandle(n)).getFile()).size; } catch { return -1; } }; |
| 83 | return { |
| 84 | estado: document.getElementById('statusbar').textContent, modelos: await hay('elffuss-models'), |
| 85 | transformers: (await caches.keys()).includes('transformers-cache'), proyecto: await fichero('datos-del-proyecto.bin'), |
| 86 | chipOculto: document.getElementById('disk-chip').hidden, |
| 87 | }; |
| 88 | }); |
| 89 | ok('3 · vaciar borra el almacén de modelos y la caché de transformers', !tras.modelos && !tras.transformers, JSON.stringify(tras)); |
| 90 | ok('3 · …sin tocar los datos del proyecto', tras.proyecto === 3 * MB, JSON.stringify(tras)); |
| 91 | ok('3 · …y dice cuánto liberó', /Liberados 3 MB/.test(tras.estado), tras.estado); |
| 92 | ok('3 · el chip desaparece cuando no queda ningún modelo', tras.chipOculto); |
| 93 | |
| 94 | // 3 · «Vaciar caché» de Ajustes usa la misma rutina |
| 95 | await p.evaluate(async (MB) => { |
| 96 | const root = await navigator.storage.getDirectory(); |
| 97 | const w = await (await (await root.getDirectoryHandle('elffuss-models', { create: true })).getFileHandle('otro.bin', { create: true })).createWritable(); |
| 98 | await w.write(new Uint8Array(1 * MB)); await w.close(); |
| 99 | }, MB); |
| 100 | await p.click('#btn-settings'); |
| 101 | await p.waitForTimeout(500); |
| 102 | const tarjeta = await p.evaluate(() => [...document.querySelectorAll('#settings-panel .prov-card')].map(c => c.textContent).find(t => /modelos guardados|Ningún modelo/.test(t)) || ''); |
| 103 | ok('3 · la tarjeta de Ajustes habla de modelos guardados (1 MB)', /1 MB en modelos guardados/.test(tarjeta), tarjeta.slice(0, 120)); |
| 104 | await p.evaluate(() => { const b = [...document.querySelectorAll('#settings-panel button')].find(x => x.textContent === 'Vaciar caché'); if (b) b.id = 'prueba-vaciar'; }); |
| 105 | await conTeclado('#prueba-vaciar'); |
| 106 | await p.waitForTimeout(800); |
| 107 | const ajustes = await p.evaluate(async () => { |
| 108 | const root = await navigator.storage.getDirectory(); |
| 109 | let hay = true; try { await root.getDirectoryHandle('elffuss-models'); } catch { hay = false; } |
| 110 | return { hay, msg: [...document.querySelectorAll('#settings-panel [role="status"]')].map(n => n.textContent).join(' | ') }; |
| 111 | }); |
| 112 | ok('3 · «Vaciar caché» de Ajustes vacía los modelos y lo dice', !ajustes.hay && /Liberados 1 MB/.test(ajustes.msg), JSON.stringify(ajustes)); |
| 113 | const fVaciar = await foco(); |
| 114 | ok('3 · …y con el teclado el foco se queda en el botón todo el rato (antes se deshabilitaba y caía a <body>)', |
| 115 | fVaciar.en === 'prueba-vaciar' && !fVaciar.perdido.length, JSON.stringify(fVaciar)); |
| 116 | |
| 117 | // 2 · Feedback: el 404 del servidor local NO es «enviado» |
| 118 | await p.fill('#tel-feedback', 'un fallo que vi'); |
| 119 | await conTeclado('#tel-send'); |
| 120 | await p.waitForTimeout(600); |
| 121 | const f1 = await p.evaluate(() => ({ msg: document.getElementById('tel-msg').textContent, texto: document.getElementById('tel-feedback').value })); |
| 122 | ok('2 · si el servidor no lo acepta, dice que falló', /No se pudo enviar/.test(f1.msg) && !/enviado, gracias/.test(f1.msg), JSON.stringify(f1)); |
| 123 | ok('2 · …y conserva el texto', f1.texto === 'un fallo que vi', JSON.stringify(f1)); |
| 124 | const fEnviar = await foco(); |
| 125 | ok('2 · con el teclado el foco sigue en «Enviar» mientras manda y después (antes caía a <body>)', |
| 126 | fEnviar.en === 'tel-send' && !fEnviar.perdido.length, JSON.stringify(fEnviar)); |
| 127 | // El servidor lo acepta (y tarda un poco en contestar): mientras manda, el botón |
| 128 | // está ocupado (aria-busy) y un segundo Enter no manda otro. |
| 129 | let envios = 0; |
| 130 | await p.route('**/proxy/report', async r => { envios++; await new Promise(res => setTimeout(res, 300)); return r.fulfill({ status: 200, contentType: 'application/json', body: '{"ok":true}' }); }); |
| 131 | await conTeclado('#tel-send'); |
| 132 | const ocupado = await p.evaluate(() => document.getElementById('tel-send').getAttribute('aria-busy')); |
| 133 | await p.keyboard.press('Enter'); |
| 134 | await p.waitForFunction(() => /enviado, gracias/.test(document.getElementById('tel-msg').textContent), null, { timeout: 10000 }).catch(() => {}); |
| 135 | const f2 = await p.evaluate(() => ({ msg: document.getElementById('tel-msg').textContent, texto: document.getElementById('tel-feedback').value })); |
| 136 | ok('2 · si el servidor lo acepta, lo da por enviado y vacía la caja', /enviado, gracias/.test(f2.msg) && f2.texto === '', JSON.stringify(f2)); |
| 137 | ok('2 · mientras manda está ocupado (aria-busy) y un segundo Enter no manda otro', ocupado === 'true' && envios === 1, `aria-busy ${ocupado} · ${envios} envíos`); |
| 138 | await p.unroute('**/proxy/report'); |
| 139 | |
| 140 | // 1 · «Guardar solo» guarda de verdad |
| 141 | await p.locator('#settings-panel button', { hasText: 'Usar la del proyecto' }).click(); |
| 142 | await p.waitForTimeout(400); |
| 143 | const auto = p.locator('#settings-panel label', { hasText: 'Guardar solo' }).locator('input[type=checkbox]'); |
| 144 | await auto.check(); |
| 145 | await p.click('#btn-settings'); // cerrar Ajustes |
| 146 | await p.fill('#prompt', 'mensaje que tiene que acabar en disco'); |
| 147 | await p.press('#prompt', 'Enter'); |
| 148 | await p.waitForTimeout(4500); // el autoguardado espera 3 s a que paren los cambios |
| 149 | const disco = await p.evaluate(async () => { |
| 150 | const root = await navigator.storage.getDirectory(); |
| 151 | try { |
| 152 | const app = await (await root.getDirectoryHandle('.elffuss')).getDirectoryHandle('code'); |
| 153 | const idx = JSON.parse(await (await (await app.getFileHandle('index.json')).getFile()).text()); |
| 154 | const conv = await app.getDirectoryHandle('conversations'); |
| 155 | let contiene = false; |
| 156 | for await (const e of conv.values()) if (e.kind === 'file' && (await (await e.getFile()).text()).includes('mensaje que tiene que acabar en disco')) contiene = true; |
| 157 | return { razon: idx.reason, contiene }; |
| 158 | } catch (e) { return { error: e.message }; } |
| 159 | }); |
| 160 | ok('1 · con «Guardar solo», el mensaje nuevo acaba en .elffuss/code/ sin pulsar Guardar', disco.razon === 'auto' && disco.contiene, JSON.stringify(disco)); |
| 161 | |
| 162 | // 3 · con el SDK de broker que sabe del almacén compartido (el de main) |
| 163 | // Doble local: el model-broker.js de este árbol con sharedUsage/clearShared que |
| 164 | // apuntan lo que se les pide, y un registro del motor con dos hosts de pesos. |
| 165 | { |
| 166 | const DOBLE = ` |
| 167 | export async function sharedUsage(o) { (window.__comp ||= []).push(['medir', JSON.stringify(o)]); return { usage: 0, quota: 0, ok: true }; } |
| 168 | export async function clearShared(o) { |
| 169 | window.__vuelo = (window.__vuelo || 0) + 1; window.__maxVuelo = Math.max(window.__maxVuelo || 0, window.__vuelo); |
| 170 | (window.__comp ||= []).push(['vaciar', o]); |
| 171 | await new Promise(r => setTimeout(r, 400)); |
| 172 | window.__vuelo--; |
| 173 | return { liberado: 0, ok: true }; |
| 174 | }`; |
| 175 | const c2 = await b.newContext({ locale: 'es-ES' }); |
| 176 | await c2.route(BROKERS, r => { brokersPedidos.push(r.request().url()); return r.fulfill({ status: 200, contentType: 'text/html', body: BROKER_FALSO }); }); |
| 177 | await c2.route('**/js/runtime/model-broker.js*', async route => { |
| 178 | const r = await route.fetch(); |
| 179 | // El SDK de main YA trae sharedUsage/clearShared: los suyos se renombran y se |
| 180 | // ponen los dobles. Añadir los dobles sin más duplicaba los export y el |
| 181 | // módulo entero no cargaba (y model-cache.js se quedaba sin broker). |
| 182 | const propio = (await r.text()) |
| 183 | .replace(/export async function sharedUsage\(/, 'async function sharedUsageReal(') |
| 184 | .replace(/export async function clearShared\(/, 'async function clearSharedReal('); |
| 185 | await route.fulfill({ response: r, body: propio + DOBLE, headers: { ...r.headers(), 'content-type': 'text/javascript' } }); |
| 186 | }); |
| 187 | await c2.route('**/js/engine/registro.js*', r => r.fulfill({ status: 200, contentType: 'text/javascript', |
| 188 | body: "export const MODELS = {}; export async function disponible() { return false; } export function origenesAlmacen() { return ['https://m1.elffuss.com/', 'https://m2.elffuss.com/']; }" })); |
| 189 | await c2.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} window.confirm = () => true; }); |
| 190 | const q = await c2.newPage(); |
| 191 | q.on('pageerror', e => errs.push(e.message.slice(0, 160))); |
| 192 | await q.goto(BASE + '/manifest.json'); |
| 193 | const r = await q.evaluate(async () => { |
| 194 | const mc = await import('/js/model-cache.js'); |
| 195 | await mc.modelUsage(); |
| 196 | const v = await mc.clearModels(); |
| 197 | return { comp: window.__comp || [], max: window.__maxVuelo || 0, fallos: v.fallos }; |
| 198 | }); |
| 199 | const medido = r.comp.find(([k]) => k === 'medir')?.[1] || ''; |
| 200 | ok('3 · el almacén compartido se mide en los hosts del motor Y en el broker por defecto (donde están los modelos de Hugging Face)', |
| 201 | /m1\.elffuss/.test(medido) && /m2\.elffuss/.test(medido) && /models\.elffuss/.test(medido), medido); |
| 202 | const vaciados = r.comp.filter(([k]) => k === 'vaciar').map(([, o]) => o); |
| 203 | ok('3 · «Vaciar» los vacía todos, también el broker por defecto', vaciados.length === 3 && vaciados.some(o => /models\.elffuss/.test(o)), JSON.stringify(vaciados)); |
| 204 | ok('3 · …y a la vez, no uno detrás de otro (un broker mudo no suma esperas)', r.max === 3, JSON.stringify(r)); |
| 205 | await c2.close(); |
| 206 | } |
| 207 | console.log(' páginas de broker pedidas (todas las contesta el doble, ninguna sale a la red):', brokersPedidos.length ? brokersPedidos.join(' ') : 'ninguna'); |
| 208 | |
| 209 | console.log('\n errores JS:', errs[0] || 'ninguno'); |
| 210 | ok('sin errores de página', errs.length === 0, errs.join(' | ')); |
| 211 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ AJUSTES QUE HACEN LO QUE DICEN'); |
| 212 | await b.close(); |
| 213 | process.exit(fails ? 1 : 0); |