| 1 | // Qué broker pide cada modelo. Corre en node, sin navegador: un DOM de mentira |
| 2 | // donde solo los orígenes que sirven la página del broker (models, m1, m2… de |
| 3 | // elffuss.com o del dominio anterior) contestan «elffuss-broker-ready». |
| 4 | // Es la misma comprobación que tests/broker-origenes.mjs de Elffuss Claw, sin |
| 5 | // las páginas del broker ni el canal del Translator, que aquí no están. |
| 6 | let fallos = 0; |
| 7 | const ok = (nombre, cond, extra = '') => { |
| 8 | console.log(`${cond ? '✅' : '❌'} ${nombre}${extra ? ' — ' + extra : ''}`); |
| 9 | if (!cond) fallos++; |
| 10 | }; |
| 11 | |
| 12 | const bus = new EventTarget(); |
| 13 | globalThis.addEventListener = (t, h) => bus.addEventListener(t, h); |
| 14 | globalThis.removeEventListener = (t, h) => bus.removeEventListener(t, h); |
| 15 | const entregar = (data, source) => bus.dispatchEvent(Object.assign(new Event('message'), { data, source })); |
| 16 | const SIRVE_BROKER = /^https:\/\/(models|m\d+)\.elffuss\.(com|utopiaia\.com)\/$/; |
| 17 | const iframes = []; |
| 18 | const RESPUESTA = { |
| 19 | 'elffuss-model-get': () => ({ kind: 'file', file: { size: 42 } }), |
| 20 | 'elffuss-model-has': () => ({ kind: 'has', cached: true, size: 42 }), |
| 21 | 'elffuss-broker-diag': () => ({ kind: 'diag', usado: 7200, quota: 20000 }), |
| 22 | 'elffuss-model-clear': () => ({ kind: 'cleared', liberado: 7200, restante: 0 }), |
| 23 | }; |
| 24 | globalThis.document = { |
| 25 | createElement() { |
| 26 | const el = { src: '', style: {}, enviados: [], setAttribute() {}, addEventListener() {} }; |
| 27 | el.contentWindow = { |
| 28 | postMessage(msg, destino) { |
| 29 | el.enviados.push({ msg, destino }); |
| 30 | if (destino !== new URL(el.src).origin) return; |
| 31 | const r = RESPUESTA[msg.type]?.(); |
| 32 | if (r) setTimeout(() => entregar({ id: msg.id, ...r }, el.contentWindow), 0); |
| 33 | }, |
| 34 | }; |
| 35 | return el; |
| 36 | }, |
| 37 | body: { |
| 38 | appendChild(el) { |
| 39 | iframes.push(el); |
| 40 | if (SIRVE_BROKER.test(el.src)) setTimeout(() => entregar({ kind: 'elffuss-broker-ready' }, el.contentWindow), 0); |
| 41 | }, |
| 42 | }, |
| 43 | }; |
| 44 | const sesion = new Map(); |
| 45 | globalThis.sessionStorage = { getItem: k => sesion.get(k) ?? null, setItem: (k, v) => sesion.set(k, String(v)) }; |
| 46 | const embebidos = () => iframes.map(f => f.src); |
| 47 | |
| 48 | const mb = await import('../web/js/runtime/model-broker.js'); |
| 49 | const BROKER = 'https://models.elffuss.com/'; |
| 50 | ok('el broker por defecto es models.elffuss.com', mb.BROKER_URL === BROKER, mb.BROKER_URL); |
| 51 | |
| 52 | // Un modelo de Hugging Face (los de litert.js lo son) va al broker compartido: |
| 53 | // ni embebe huggingface.co ni se come el timeout de 8 s. |
| 54 | { |
| 55 | const store = await import('../web/js/runtime/model-store.js'); |
| 56 | const t0 = Date.now(); |
| 57 | const f = await Promise.race([ |
| 58 | store.getModelFile('https://huggingface.co/litert-community/x/resolve/main/m.litertlm'), |
| 59 | new Promise(r => setTimeout(() => r('timeout'), 3000)), |
| 60 | ]); |
| 61 | ok('getModelFile(Hugging Face) sale del broker compartido', f?.size === 42, |
| 62 | `${typeof f === 'string' ? f : 'ok'} en ${Date.now() - t0} ms`); |
| 63 | ok(' y no embebe huggingface.co', !embebidos().some(s => s.includes('huggingface.co')), embebidos().join(' ')); |
| 64 | const enviado = iframes.find(x => x.src === BROKER)?.enviados.at(-1); |
| 65 | ok(' la petición va con models.elffuss.com como destino', enviado?.destino === 'https://models.elffuss.com', enviado?.destino); |
| 66 | ok(' y el broker no queda marcado como caído', sesion.get('elffuss.broker.down') !== '1'); |
| 67 | } |
| 68 | |
| 69 | if (typeof mb.brokerFor !== 'function') { |
| 70 | console.log('— brokerFor() no está en este árbol (un solo broker para todo): se salta'); |
| 71 | } else { |
| 72 | // El origen del propio fichero solo cuando sirve la página del broker. Una web |
| 73 | // de la app (claw, code, git…) no la sirve: embeberla sería esperar 8 s para |
| 74 | // nada y dar el broker por caído el resto de la sesión. |
| 75 | const CASOS = [ |
| 76 | ['https://huggingface.co/litert-community/x/resolve/main/m.litertlm', BROKER], |
| 77 | ['https://m1.elffuss.com/bonsai-27b.p0', 'https://m1.elffuss.com/'], |
| 78 | ['https://m2.elffuss.utopiaia.com/bonsai-27b.p1', 'https://m2.elffuss.utopiaia.com/'], |
| 79 | ['https://models.elffuss.com/x.onnx', BROKER], |
| 80 | ['https://code.elffuss.com/__e4b.litertlm', BROKER], |
| 81 | ['https://claw.elffuss.com/models/qwen38-27b.gguf', BROKER], |
| 82 | ['https://git.elffuss.com/a/b/raw/main/m.gguf', BROKER], |
| 83 | ['https://key.elffuss.utopiaia.com/m.gguf', BROKER], |
| 84 | ['http://m1.elffuss.com/x', BROKER], |
| 85 | ['https://m1.elffuss.com.evil.net/x', BROKER], |
| 86 | ]; |
| 87 | for (const [url, esperado] of CASOS) { |
| 88 | const r = mb.brokerFor(url); |
| 89 | ok(`brokerFor(${new URL(url).origin})`, r === esperado, r); |
| 90 | } |
| 91 | let lanzo = false; |
| 92 | try { mb.brokerFor('models/x.gguf'); } catch { lanzo = true; } |
| 93 | ok('una URL relativa lanza en vez de ir a un broker que la resolvería mal', lanzo); |
| 94 | |
| 95 | const f = await mb.getSharedModel('https://m1.elffuss.com/bonsai-27b.p0'); |
| 96 | ok('un fragmento de m1 lo guarda el broker de m1', f?.size === 42 && embebidos().includes('https://m1.elffuss.com/')); |
| 97 | } |
| 98 | |
| 99 | // Esto vale con un broker o con uno por origen: un modelo servido desde una web |
| 100 | // de la app (o desde git.*) nunca hace de broker. |
| 101 | for (const url of ['https://code.elffuss.com/__e4b.litertlm', 'https://git.elffuss.com/a/b/raw/main/m.gguf']) { |
| 102 | const t0 = Date.now(); |
| 103 | const g = await Promise.race([ |
| 104 | mb.getSharedModel(url), |
| 105 | new Promise(r => setTimeout(() => r('timeout'), 3000)), |
| 106 | ]); |
| 107 | const o = new URL(url).origin; |
| 108 | ok(`un modelo servido desde ${o} sale del compartido, sin esperar`, g?.size === 42, |
| 109 | `${typeof g === 'string' ? g : 'ok'} en ${Date.now() - t0} ms`); |
| 110 | ok(' y no embebe ese origen como broker', !embebidos().includes(o + '/'), embebidos().join(' ')); |
| 111 | } |
| 112 | |
| 113 | if (typeof mb.sharedUsage !== 'function' || typeof mb.clearShared !== 'function') { |
| 114 | console.log('— sharedUsage()/clearShared() no están en este árbol: se saltan'); |
| 115 | } else { |
| 116 | const uso = await mb.sharedUsage().catch(e => ({ error: e.message })); |
| 117 | ok('sharedUsage() devuelve lo que dice el broker', uso.ok === true && uso.usage === 7200 && uso.quota === 20000, JSON.stringify(uso)); |
| 118 | const vac = await mb.clearShared().catch(e => ({ error: e.message })); |
| 119 | ok('clearShared() devuelve lo liberado', vac.ok === true && vac.liberado === 7200, JSON.stringify(vac)); |
| 120 | } |
| 121 | |
| 122 | console.log(fallos ? `\n❌ ${fallos} fallo(s)` : '\n✅ brokers OK'); |
| 123 | process.exit(fallos ? 1 : 0); |