Elffuss BraidHub

utopia-ia/elffuss-claw public

c7179c489e0d · 3.4 KiBRawPermalink
1// Verifica la caché de modelos por service worker: descarga una vez, se sirve
2// desde Cache Storage (incluso OFFLINE) y soporta range requests. Usa un fixture
3// .litertlm determinista (byte[i] = i%256) para no bajar los GB reales.
4import { chromium } from 'playwright';
5import { writeFileSync, rmSync } from 'node:fs';
6import { fileURLToPath } from 'node:url';
7import { dirname, join } from 'node:path';
8const BASE = process.env.BASE || 'http://localhost:8788';
9const FIX = BASE + '/__test_fixture.litertlm';
10const SIZE = 100000;
11let fails = 0;
12const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
13
14// fixture determinista (byte[i]=i%256) en web/, autolimpiado al terminar
15const WEB = join(dirname(fileURLToPath(import.meta.url)), '..', 'web');
16const FIXPATH = join(WEB, '__test_fixture.litertlm');
17writeFileSync(FIXPATH, Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 256)));
18const cleanup = () => { try { rmSync(FIXPATH); } catch {} };
19process.on('exit', cleanup);
20
21const b = await chromium.launch({ args: ['--enable-unsafe-webgpu', '--use-angle=metal'] });
22const ctx = await b.newContext();
23await ctx.addInitScript(() => { try { localStorage.setItem('elffuss.model', 'rules'); } catch {} });
24const p = await ctx.newPage({ viewport: { width: 1200, height: 800 } });
25await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
26
27// esperar a que el SW controle la página
28const controlled = await p.waitForFunction(() => navigator.serviceWorker && navigator.serviceWorker.controller != null, null, { timeout: 10000 }).then(() => true).catch(() => false);
29ok('el service worker controla la página', controlled);
30
31const fetchInfo = (u, opts) => p.evaluate(async ({ u, opts }) => {
32 const r = await fetch(u, opts);
33 const buf = new Uint8Array(await r.arrayBuffer());
34 return { status: r.status, len: buf.length, cr: r.headers.get('content-range'), first: [...buf.slice(0, 4)], sample: [...buf.slice(0, 12)] };
35}, { u, opts });
36
37// 1) primera descarga (el SW baja el fichero completo y lo cachea)
38const r1 = await fetchInfo(FIX);
39ok('primera petición devuelve el fichero completo', r1.status === 200 && r1.len === SIZE, `status ${r1.status}, ${r1.len}B`);
40
41// 2) OFFLINE: si está cacheado, se sigue sirviendo sin red
42await ctx.setOffline(true);
43const r2 = await fetchInfo(FIX).catch(e => ({ status: 0, err: String(e) }));
44ok('OFFLINE se sirve desde la caché (prueba de que quedó cacheado)', r2.status === 200 && r2.len === SIZE, `status ${r2.status}, ${r2.len}B`);
45
46// 3) range request servido desde el blob cacheado (bytes 10..19)
47const r3 = await fetchInfo(FIX, { headers: { Range: 'bytes=10-19' } });
48const expected = Array.from({ length: 10 }, (_, i) => (10 + i) % 256);
49ok('range request → 206 con los bytes correctos', r3.status === 206 && r3.len === 10 && JSON.stringify(r3.sample.slice(0, 10)) === JSON.stringify(expected), `status ${r3.status}, cr=${r3.cr}, bytes=${r3.sample}`);
50await ctx.setOffline(false);
51
52// 4) el estimate reporta uso (>0) tras cachear
53const est = await p.evaluate(() => navigator.storage.estimate().then(e => ({ usage: e.usage, persisted: null })).catch(() => ({ usage: 0 })));
54ok('storage.estimate refleja el uso cacheado', est.usage > 0, `${(est.usage / 1024 / 1024).toFixed(1)} MB`);
55
56console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ DE MODELOS OK — descarga 1 vez, persiste y sirve offline + ranges');
57await b.close();
58process.exit(fails ? 1 : 0);