Elffuss BraidHub

utopia-ia/elffuss-code public

model-cache: always include the default broker, clear brokers in parallel, keep tests off real brokers

Both problems show up with main's broker SDK (sharedUsage/clearShared),
which is when this path starts to run.

- modelUsage() and clearModels() covered only origenesAlmacen(), which
  lists the engine's Elffuss hosts (m1, m2) and never the default broker.
  The default broker holds every model from other hosts: the LiteRT Gemma
  and the engine's Qwen3.5-0.8B, both from Hugging Face. "Clear cache" and
  the 💾 chip would stop freeing them and still say "Freed X". The default
  broker is now always in the list (deduplicated).
- clearModels() asked one origin after another. A broker page without the
  clear handler made each call wait for its own timeout, so the chip and
  the button stayed busy through all of them. The per-origin clears now
  run together.

storage-honest.mjs now answers every broker page (models, m1, m2…) with a
local fake broker, so it never loads production broker pages, and stands
in a broker SDK that knows the shared store (this tree's model-broker.js
plus recording stubs, and an engine registry with two hosts) to check
that the default broker is measured and cleared and that the clears run
in parallel. Those three checks fail on the previous tree. A separate
probe with main's own model-broker.js against the fake broker page also
measured and cleared all three origins with no failures and no request
leaving the machine.

A broker page without the elffuss-model-clear handler (it lives in
elffuss-claw/server/broker/index.html) is reported as failed, now after
one wait and not one per broker.
Changeset5bde40f10cb424295fc37095edd2e0443c6d9f47510b1524b4ebbe612c08e685
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 19:27 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:15 +02:00
Parents32452296a328

Browse the files at this changeset

2 files changed

modified tests/storage-honest.mjs +60 −1
@@ -9,7 +9,10 @@
99 // 3. Chip 💾 y «Vaciar caché»: contaban el origen ENTERO como «modelos» y al
1010 // vaciar solo borraban una caché vieja. Ahora cuentan solo los modelos
1111 // (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ó.
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.
1316 //
1417 // BASE=http://127.0.0.1:8898 node tests/storage-honest.mjs
1518 import { chromium } from 'playwright';
@@ -17,7 +20,22 @@
1720 let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
1821
1922 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 = [];
2037 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 }); });
2139 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} window.confirm = () => true; });
2240 const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } });
2341 const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
@@ -110,6 +128,47 @@
110128 });
111129 ok('1 · con «Guardar solo», el mensaje nuevo acaba en .elffuss/code/ sin pulsar Guardar', disco.razon === 'auto' && disco.contiene, JSON.stringify(disco));
112130
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+
113172 console.log('\n errores JS:', errs[0] || 'ninguno');
114173 ok('sin errores de página', errs.length === 0, errs.join(' | '));
115174 console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ AJUSTES QUE HACEN LO QUE DICEN');
modified web/js/model-cache.js +18 −9
@@ -87,15 +87,22 @@
8787 }
8888 // El almacén compartido vive en el origen del broker: solo se puede medir y
8989 // vaciar si el broker sabe hacerlo (sharedUsage / clearShared). Si no, se dice.
90+//
91+// Los orígenes son los del registro del motor (m1, m2…: los hosts de sus pesos)
92+// MÁS SIEMPRE el broker por defecto. El registro solo da los hosts de Elffuss,
93+// y en el broker por defecto vive todo lo que viene de otros sitios: el Gemma
94+// de LiteRT y el Qwen3.5-0.8B del motor, que se bajan de Hugging Face. Sin él,
95+// «Vaciar caché» dejaba esos modelos guardados y aun así decía «Liberados…».
9096 async function brokerApi() {
9197 try {
9298 const b = await import('./runtime/model-broker.js');
9399 if (typeof b.sharedUsage !== 'function') return null;
94- let origenes;
100+ let origenes = [];
95101 // Puede devolver la lista o una promesa de ella: se espera siempre.
96- try { const r = await import('./engine/registro.js'); origenes = r.origenesAlmacen ? await r.origenesAlmacen() : undefined; }
97- catch { /* sin motor: el broker por defecto */ }
98- return { b, origenes };
102+ try { const r = await import('./engine/registro.js'); origenes = (r.origenesAlmacen ? await r.origenesAlmacen() : null) || []; }
103+ catch { /* sin motor: solo el broker por defecto */ }
104+ const porDefecto = b.BROKER_URL || 'https://models.elffuss.com/';
105+ return { b, origenes: [...new Set([...(Array.isArray(origenes) ? origenes : []), porDefecto])] };
99106 } catch { return null; }
100107 }
101108
@@ -130,11 +137,13 @@
130137 } catch (e) { fallos.push('OPFS: ' + (e?.message || e)); }
131138 const api = await brokerApi();
132139 if (api && typeof api.b.clearShared === 'function') {
133- const lista = Array.isArray(api.origenes) && api.origenes.length ? [...new Set(api.origenes)] : [undefined];
134- for (const o of lista) {
135- try { const r = await api.b.clearShared(o); if (!r?.ok) fallos.push('broker ' + (o || '')); }
136- catch (e) { fallos.push('broker ' + (o || '') + ': ' + (e?.message || e)); }
137- }
140+ // Todos A LA VEZ: uno tras otro, cada broker que no contesta (una página de
141+ // broker sin el manejador de «vaciar») sumaba su tiempo de espera, y el chip y
142+ // el botón se quedaban ocupados todo ese rato antes de decir que falló.
143+ await Promise.all(api.origenes.map(async o => {
144+ try { const r = await api.b.clearShared(o); if (!r?.ok) fallos.push('broker ' + o); }
145+ catch (e) { fallos.push('broker ' + o + ': ' + (e?.message || e)); }
146+ }));
138147 }
139148 const despues = await modelUsage();
140149 return { liberado: Math.max(0, antes.total - despues.total), antes, despues, fallos, sharedOk: antes.sharedOk };