| 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 | // Ningún broker de verdad: sus páginas las contesta un doble local. |
| 16 | // |
| 17 | // BASE=http://127.0.0.1:8898 node tests/storage-honest.mjs |
| 18 | import { chromium } from 'playwright'; |
| 19 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 20 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 21 | |
| 22 | const b = await chromium.launch(); |
| 23 | // Ningún broker de verdad: las páginas de broker (models, m1, m2… de elffuss) las |
| 24 | // contesta un doble local que dice «listo», mide 0 y vacía. Con el SDK de broker |
| 25 | // que sabe del almacén compartido (el de main), este test cargaba las páginas de |
| 26 | // producción y esperaba sus tiempos muertos. |
| 27 | const BROKER_FALSO = `<!doctype html><script> |
| 28 | parent.postMessage({ kind: 'elffuss-broker-ready' }, '*'); |
| 29 | addEventListener('message', e => { |
| 30 | const d = e.data || {}; |
| 31 | if (d.type === 'elffuss-broker-diag') e.source.postMessage({ kind: 'diag', id: d.id, usado: 0, quota: 0 }, e.origin); |
| 32 | if (d.type === 'elffuss-model-clear') e.source.postMessage({ kind: 'cleared', id: d.id, liberado: 0 }, e.origin); |
| 33 | }); |
| 34 | <\/script>`; |
| 35 | const BROKERS = /^https:\/\/(models|m\d+)\.elffuss\.(com|utopiaia\.com)\//; |
| 36 | const brokersPedidos = []; |
| 37 | const ctx = await b.newContext({ locale: 'es-ES' }); |
| 38 | await ctx.route(BROKERS, r => { brokersPedidos.push(r.request().url()); return r.fulfill({ status: 200, contentType: 'text/html', body: BROKER_FALSO }); }); |
| 39 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} window.confirm = () => true; }); |
| 40 | const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } }); |
| 41 | const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160))); |
| 42 | |
| 43 | const MB = 1048576; |
| 44 | await p.goto(BASE + '/manifest.json'); |
| 45 | await p.evaluate(async (MB) => { |
| 46 | const root = await navigator.storage.getDirectory(); |
| 47 | 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(); }; |
| 48 | await escribe(root, 'datos-del-proyecto.bin', 3 * MB); // NO es un modelo |
| 49 | await escribe(await root.getDirectoryHandle('elffuss-models', { create: true }), 'pesos.bin', 2 * MB); |
| 50 | const c = await caches.open('transformers-cache'); |
| 51 | await c.put('https://huggingface.co/x/onnx/model.onnx', new Response(new Uint8Array(1 * MB), { headers: { 'content-length': String(1 * MB) } })); |
| 52 | }, MB); |
| 53 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 54 | await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.() && !document.getElementById('disk-chip').hidden, null, { timeout: 20000 }).catch(() => {}); |
| 55 | |
| 56 | // 3 · el chip cuenta solo los modelos |
| 57 | const chip = await p.evaluate(() => ({ txt: document.getElementById('disk-chip').textContent, title: document.getElementById('disk-chip').title })); |
| 58 | 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)); |
| 59 | await p.click('#disk-chip'); |
| 60 | await p.waitForFunction(() => /Liberados/.test(document.getElementById('statusbar').textContent), null, { timeout: 10000 }).catch(() => {}); |
| 61 | const tras = await p.evaluate(async () => { |
| 62 | const root = await navigator.storage.getDirectory(); |
| 63 | const hay = async (n) => { try { await root.getDirectoryHandle(n); return true; } catch { return false; } }; |
| 64 | const fichero = async (n) => { try { return (await (await root.getFileHandle(n)).getFile()).size; } catch { return -1; } }; |
| 65 | return { |
| 66 | estado: document.getElementById('statusbar').textContent, modelos: await hay('elffuss-models'), |
| 67 | transformers: (await caches.keys()).includes('transformers-cache'), proyecto: await fichero('datos-del-proyecto.bin'), |
| 68 | chipOculto: document.getElementById('disk-chip').hidden, |
| 69 | }; |
| 70 | }); |
| 71 | ok('3 · vaciar borra el almacén de modelos y la caché de transformers', !tras.modelos && !tras.transformers, JSON.stringify(tras)); |
| 72 | ok('3 · …sin tocar los datos del proyecto', tras.proyecto === 3 * MB, JSON.stringify(tras)); |
| 73 | ok('3 · …y dice cuánto liberó', /Liberados 3 MB/.test(tras.estado), tras.estado); |
| 74 | ok('3 · el chip desaparece cuando no queda ningún modelo', tras.chipOculto); |
| 75 | |
| 76 | // 3 · «Vaciar caché» de Ajustes usa la misma rutina |
| 77 | await p.evaluate(async (MB) => { |
| 78 | const root = await navigator.storage.getDirectory(); |
| 79 | const w = await (await (await root.getDirectoryHandle('elffuss-models', { create: true })).getFileHandle('otro.bin', { create: true })).createWritable(); |
| 80 | await w.write(new Uint8Array(1 * MB)); await w.close(); |
| 81 | }, MB); |
| 82 | await p.click('#btn-settings'); |
| 83 | await p.waitForTimeout(500); |
| 84 | const tarjeta = await p.evaluate(() => [...document.querySelectorAll('#settings-panel .prov-card')].map(c => c.textContent).find(t => /modelos guardados|Ningún modelo/.test(t)) || ''); |
| 85 | ok('3 · la tarjeta de Ajustes habla de modelos guardados (1 MB)', /1 MB en modelos guardados/.test(tarjeta), tarjeta.slice(0, 120)); |
| 86 | await p.locator('#settings-panel button', { hasText: 'Vaciar caché' }).click(); |
| 87 | await p.waitForTimeout(800); |
| 88 | const ajustes = await p.evaluate(async () => { |
| 89 | const root = await navigator.storage.getDirectory(); |
| 90 | let hay = true; try { await root.getDirectoryHandle('elffuss-models'); } catch { hay = false; } |
| 91 | return { hay, msg: [...document.querySelectorAll('#settings-panel [role="status"]')].map(n => n.textContent).join(' | ') }; |
| 92 | }); |
| 93 | ok('3 · «Vaciar caché» de Ajustes vacía los modelos y lo dice', !ajustes.hay && /Liberados 1 MB/.test(ajustes.msg), JSON.stringify(ajustes)); |
| 94 | |
| 95 | // 2 · Feedback: el 404 del servidor local NO es «enviado» |
| 96 | await p.fill('#tel-feedback', 'un fallo que vi'); |
| 97 | await p.click('#tel-send'); |
| 98 | await p.waitForTimeout(600); |
| 99 | const f1 = await p.evaluate(() => ({ msg: document.getElementById('tel-msg').textContent, texto: document.getElementById('tel-feedback').value })); |
| 100 | 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)); |
| 101 | ok('2 · …y conserva el texto', f1.texto === 'un fallo que vi', JSON.stringify(f1)); |
| 102 | await p.route('**/proxy/report', r => r.fulfill({ status: 200, contentType: 'application/json', body: '{"ok":true}' })); |
| 103 | await p.click('#tel-send'); |
| 104 | await p.waitForTimeout(600); |
| 105 | const f2 = await p.evaluate(() => ({ msg: document.getElementById('tel-msg').textContent, texto: document.getElementById('tel-feedback').value })); |
| 106 | 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)); |
| 107 | await p.unroute('**/proxy/report'); |
| 108 | |
| 109 | // 1 · «Guardar solo» guarda de verdad |
| 110 | await p.locator('#settings-panel button', { hasText: 'Usar la del proyecto' }).click(); |
| 111 | await p.waitForTimeout(400); |
| 112 | const auto = p.locator('#settings-panel label', { hasText: 'Guardar solo' }).locator('input[type=checkbox]'); |
| 113 | await auto.check(); |
| 114 | await p.click('#btn-settings'); // cerrar Ajustes |
| 115 | await p.fill('#prompt', 'mensaje que tiene que acabar en disco'); |
| 116 | await p.press('#prompt', 'Enter'); |
| 117 | await p.waitForTimeout(4500); // el autoguardado espera 3 s a que paren los cambios |
| 118 | const disco = await p.evaluate(async () => { |
| 119 | const root = await navigator.storage.getDirectory(); |
| 120 | try { |
| 121 | const app = await (await root.getDirectoryHandle('.elffuss')).getDirectoryHandle('code'); |
| 122 | const idx = JSON.parse(await (await (await app.getFileHandle('index.json')).getFile()).text()); |
| 123 | const conv = await app.getDirectoryHandle('conversations'); |
| 124 | let contiene = false; |
| 125 | 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; |
| 126 | return { razon: idx.reason, contiene }; |
| 127 | } catch (e) { return { error: e.message }; } |
| 128 | }); |
| 129 | ok('1 · con «Guardar solo», el mensaje nuevo acaba en .elffuss/code/ sin pulsar Guardar', disco.razon === 'auto' && disco.contiene, JSON.stringify(disco)); |
| 130 | |
| 131 | // 3 · con un SDK de broker que SÍ sabe del almacén compartido (como el de main) |
| 132 | // Doble local: el model-broker.js de este árbol más sharedUsage/clearShared que |
| 133 | // apuntan lo que se les pide, y un registro del motor con dos hosts de pesos. |
| 134 | { |
| 135 | const DOBLE = ` |
| 136 | export async function sharedUsage(o) { (window.__comp ||= []).push(['medir', JSON.stringify(o)]); return { usage: 0, quota: 0, ok: true }; } |
| 137 | export async function clearShared(o) { |
| 138 | window.__vuelo = (window.__vuelo || 0) + 1; window.__maxVuelo = Math.max(window.__maxVuelo || 0, window.__vuelo); |
| 139 | (window.__comp ||= []).push(['vaciar', o]); |
| 140 | await new Promise(r => setTimeout(r, 400)); |
| 141 | window.__vuelo--; |
| 142 | return { liberado: 0, ok: true }; |
| 143 | }`; |
| 144 | const c2 = await b.newContext({ locale: 'es-ES' }); |
| 145 | await c2.route(BROKERS, r => { brokersPedidos.push(r.request().url()); return r.fulfill({ status: 200, contentType: 'text/html', body: BROKER_FALSO }); }); |
| 146 | await c2.route('**/js/runtime/model-broker.js*', async route => { |
| 147 | const r = await route.fetch(); |
| 148 | await route.fulfill({ response: r, body: (await r.text()) + DOBLE, headers: { ...r.headers(), 'content-type': 'text/javascript' } }); |
| 149 | }); |
| 150 | await c2.route('**/js/engine/registro.js*', r => r.fulfill({ status: 200, contentType: 'text/javascript', |
| 151 | body: "export const MODELS = {}; export async function disponible() { return false; } export function origenesAlmacen() { return ['https://m1.elffuss.com/', 'https://m2.elffuss.com/']; }" })); |
| 152 | await c2.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} window.confirm = () => true; }); |
| 153 | const q = await c2.newPage(); |
| 154 | q.on('pageerror', e => errs.push(e.message.slice(0, 160))); |
| 155 | await q.goto(BASE + '/manifest.json'); |
| 156 | const r = await q.evaluate(async () => { |
| 157 | const mc = await import('/js/model-cache.js'); |
| 158 | await mc.modelUsage(); |
| 159 | const v = await mc.clearModels(); |
| 160 | return { comp: window.__comp || [], max: window.__maxVuelo || 0, fallos: v.fallos }; |
| 161 | }); |
| 162 | const medido = r.comp.find(([k]) => k === 'medir')?.[1] || ''; |
| 163 | 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)', |
| 164 | /m1\.elffuss/.test(medido) && /m2\.elffuss/.test(medido) && /models\.elffuss/.test(medido), medido); |
| 165 | const vaciados = r.comp.filter(([k]) => k === 'vaciar').map(([, o]) => o); |
| 166 | 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)); |
| 167 | ok('3 · …y a la vez, no uno detrás de otro (un broker mudo no suma esperas)', r.max === 3, JSON.stringify(r)); |
| 168 | await c2.close(); |
| 169 | } |
| 170 | console.log(' páginas de broker pedidas (todas las contesta el doble, ninguna sale a la red):', brokersPedidos.length ? brokersPedidos.join(' ') : 'ninguna'); |
| 171 | |
| 172 | console.log('\n errores JS:', errs[0] || 'ninguno'); |
| 173 | ok('sin errores de página', errs.length === 0, errs.join(' | ')); |
| 174 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ AJUSTES QUE HACEN LO QUE DICEN'); |
| 175 | await b.close(); |
| 176 | process.exit(fails ? 1 : 0); |