Elffuss BraidHub

utopia-ia/elffuss-claw public

main · 4.8 KiBRawPermalink
1// cachedModelBlob de litert.js: el .litertlm se baja una vez y la segunda sale
2// sin red, por los dos caminos que tiene.
3//
4// 1. El de siempre desde 9ad584a: el almacén de modelos (runtime/model-store.js,
5// caché compartida del broker o la OPFS de este origen). Antes esta prueba
6// solo miraba Cache Storage, que ya no es por donde pasa el modelo.
7// 2. El respaldo, cuando no hay OPFS: Cache Storage ('elffuss-models-v1').
8//
9// El fichero es de mentira (page.route) y el broker se da por caído: no sale
10// nada a la red ni se baja ningún modelo de verdad.
11//
12// BASE=http://localhost:8742 node tests/litertcache.mjs
13import { chromium } from 'playwright';
14const BASE = process.env.BASE || 'http://localhost:8742';
15const SIZE = 120000;
16let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
17const DATOS = Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 256));
18
19const b = await chromium.launch();
20async function pagina({ sinOPFS = false } = {}) {
21 const ctx = await b.newContext();
22 await ctx.addInitScript(sin => {
23 try { sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* */ }
24 // Un navegador sin OPFS (o donde falla): el almacén devuelve null y litert.js
25 // tiene que caer a Cache Storage.
26 if (sin) try { Object.defineProperty(StorageManager.prototype, 'getDirectory', { value: undefined, configurable: true }); } catch { /* */ }
27 }, sinOPFS);
28 const p = await ctx.newPage();
29 const peticiones = [];
30 await p.route('**/__litert_fixture.litertlm', route => {
31 const rango = route.request().headers().range || '';
32 peticiones.push(rango || 'entero');
33 const m = /bytes=(\d+)-(\d*)/.exec(rango);
34 if (!m) return route.fulfill({ status: 200, body: DATOS, headers: { 'content-type': 'application/octet-stream', 'content-length': String(SIZE) } });
35 const desde = +m[1], hasta = m[2] ? +m[2] : SIZE - 1;
36 return route.fulfill({ status: 206, body: DATOS.subarray(desde, hasta + 1), headers: { 'content-range': `bytes ${desde}-${hasta}/${SIZE}`, 'accept-ranges': 'bytes' } });
37 });
38 await p.goto(BASE + '/robots.txt'); // una página del mismo origen, sin arrancar la app
39 return { ctx, p, peticiones };
40}
41const llama = (p, u) => p.evaluate(async u => {
42 const m = await import('/js/providers/litert.js');
43 const msgs = [];
44 const r = await m.cachedModelBlob(u, s => msgs.push(String(s)));
45 const blob = r instanceof Blob ? r : null;
46 let malos = -1;
47 if (blob) { const v = new Uint8Array(await blob.arrayBuffer()); malos = 0; for (let i = 0; i < v.length; i++) if (v[i] !== i % 256) malos++; }
48 return { esBlob: !!blob, size: blob ? blob.size : 0, malos, primero: msgs[0] || '', tipo: typeof r };
49}, u);
50
51// 1 · camino normal: el almacén de modelos (OPFS)
52{
53 const { ctx, p, peticiones } = await pagina();
54 const FIX = BASE + '/__litert_fixture.litertlm';
55 let r = await llama(p, FIX);
56 ok('OPFS · 1ª vez → el modelo entero (lo baja y lo guarda)', r.esBlob && r.size === SIZE && r.malos === 0, JSON.stringify(r));
57 const enOPFS = await p.evaluate(async () => {
58 try { const d = await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-models'); for await (const [n] of d.entries()) if (n.endsWith('.done')) return true; } catch { /* */ }
59 return false;
60 });
61 ok('OPFS · quedó guardado en el almacén de modelos (no en Cache Storage)', enOPFS && !(await p.evaluate(async () => (await caches.keys()).includes('elffuss-models-v1'))));
62 peticiones.length = 0;
63 await ctx.setOffline(true);
64 r = await llama(p, FIX);
65 await ctx.setOffline(false);
66 ok('OPFS · 2ª vez SIN RED → desde disco, sin una petición', r.esBlob && r.size === SIZE && r.malos === 0 && peticiones.length === 0 && /disco/.test(r.primero), `${JSON.stringify(r)} · ${peticiones.length} peticiones`);
67 await ctx.close();
68}
69
70// 2 · respaldo sin OPFS: Cache Storage
71{
72 const { ctx, p, peticiones } = await pagina({ sinOPFS: true });
73 const FIX = BASE + '/__litert_fixture.litertlm';
74 let r = await llama(p, FIX);
75 ok('sin OPFS · 1ª vez → el modelo entero, por Cache Storage', r.esBlob && r.size === SIZE && r.malos === 0, JSON.stringify(r));
76 ok('sin OPFS · quedó en Cache Storage', await p.evaluate(async u => !!(await (await caches.open('elffuss-models-v1')).match(u)), FIX));
77 peticiones.length = 0;
78 await ctx.setOffline(true);
79 r = await llama(p, FIX);
80 await ctx.setOffline(false);
81 ok('sin OPFS · 2ª vez SIN RED → desde la caché, sin una petición', r.esBlob && r.size === SIZE && peticiones.length === 0 && /cach[eé]/i.test(r.primero), `${JSON.stringify(r)} · ${peticiones.length} peticiones`);
82 await ctx.close();
83}
84
85console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ LiteRT OK — se baja una vez y sirve sin red, con OPFS y sin ella');
86await b.close(); process.exit(fails ? 1 : 0);