Elffuss BraidHub

utopia-ia/elffuss-claw public

LiteRT says when the model could not be saved to the browser's disk

Found while porting Elffuss Code's modelcache_honest test (8647e97): when
writing the model to OPFS failed for lack of space, Claw's model store
replaced the browser's QuotaExceededError with a plain Error ("No cabe: …").
litert.js recognises a storage failure by the error's name, so it took this
for a network error, fell back to Cache Storage without a word, and the user
was left to download the model again next session without knowing why, after
the progress had promised to keep it.

The store keeps the browser's error name on its translated message, and
litert.js now says so in the progress ("No se pudo guardar el modelo en el
disco del navegador…"), as it already did for Cache Storage.

tests/modelcache_honest.mjs (Code's, with Claw's same-origin page): a normal
save says nothing; a full OPFS says so, with the likely cause, and the model
still arrives through the cache; with nowhere to save it says so and the load
goes on with the URL. The two "full OPFS" checks fail on the previous store.
Changeset4623b5edd8bfd93031aa2cd53406586c776900ad2069a014ba8bc71fe87f3819
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-11 18:57 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 18:57 +02:00
Parentsd9c1fae2b99e

Browse the files at this changeset

2 files changed

added tests/modelcache_honest.mjs +84 −0
@@ -0,0 +1,84 @@
1+// Guardia: si NO se puede guardar el modelo, hay que DECIRLO.
2+// Bug real (ago-2026): cachedModelBlob prometía en el progreso «se cachea para
3+// la próxima vez», y si cache.put fallaba (ventana privada, disco lleno, cuota)
4+// se tragaba la excepción y devolvía la URL. El usuario se re-bajaba GIGABYTES
5+// cada sesión sin enterarse de por qué. Es la misma enfermedad que el resto de
6+// la ronda: fallo silencioso presentado como éxito.
7+//
8+// Desde a2d33ec el modelo se guarda primero en el almacén de modelos (OPFS) y
9+// Cache Storage es el respaldo: esta prueba fallaba sobre Cache Storage, que ya
10+// no es el camino normal. Ahora se fuerza el fallo donde se guarda de verdad:
11+// 1. normal: se guarda en disco y no se avisa de nada;
12+// 2. falla la OPFS (cuota): se dice, y el modelo sigue llegando por la caché;
13+// 3. fallan las dos: se dice con la causa probable, y la carga sigue (URL).
14+// Determinista: fichero de mentira (page.route) y broker dado por caído.
15+//
16+// BASE=http://localhost:8742 node tests/modelcache_honest.mjs
17+import { chromium } from 'playwright';
18+const BASE = process.env.BASE || 'http://localhost:8742';
19+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
20+const SIZE = 50000;
21+const DATOS = Buffer.alloc(SIZE, 7);
22+
23+const b = await chromium.launch();
24+async function pagina({ opfsLlena = false, cacheLlena = false } = {}) {
25+ const ctx = await b.newContext();
26+ await ctx.addInitScript(({ opfsLlena, cacheLlena }) => {
27+ try { sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* */ }
28+ const cuota = () => { const e = new Error('Quota exceeded'); e.name = 'QuotaExceededError'; return e; };
29+ // Disco lleno para la OPFS: abrir el fichero se puede, escribir bytes no.
30+ if (opfsLlena) FileSystemWritableFileStream.prototype.write = async function () { throw cuota(); };
31+ if (cacheLlena) Cache.prototype.put = async function () { throw cuota(); };
32+ }, { opfsLlena, cacheLlena });
33+ const p = await ctx.newPage();
34+ await p.route('**/__honest_fixture.litertlm', route => {
35+ const rango = route.request().headers().range || '';
36+ if (/bytes=0-0$/.test(rango)) return route.fulfill({ status: 206, body: DATOS.subarray(0, 1), headers: { 'content-range': `bytes 0-0/${SIZE}`, 'accept-ranges': 'bytes' } });
37+ return route.fulfill({ status: 200, body: DATOS, headers: { 'content-type': 'application/octet-stream', 'content-length': String(SIZE) } });
38+ });
39+ await p.goto(BASE + '/robots.txt'); // una página del mismo origen, sin arrancar la app
40+ return { ctx, p };
41+}
42+const carga = p => p.evaluate(async u => {
43+ const m = await import('/js/providers/litert.js');
44+ const msgs = [];
45+ let res, err = null;
46+ try { res = await m.cachedModelBlob(u, s => msgs.push(String(s))); } catch (e) { err = e.message; }
47+ return {
48+ err, esBlob: res instanceof Blob, size: res instanceof Blob ? res.size : 0, esURL: typeof res === 'string',
49+ aviso: msgs.find(s => /No se pudo guardar/.test(s)) || '',
50+ explica: msgs.some(s => /No se pudo guardar/.test(s) && /privada|espacio/i.test(s)),
51+ };
52+}, BASE + '/__honest_fixture.litertlm');
53+
54+// 1) normal: se guarda en disco y no avisa de ningún fallo
55+{
56+ const { ctx, p } = await pagina();
57+ const r = await carga(p);
58+ ok('normal: devuelve el modelo guardado', r.esBlob && r.size === SIZE, JSON.stringify(r));
59+ ok('normal: no avisa de fallo cuando SÍ lo guarda', !r.aviso, r.aviso);
60+ await ctx.close();
61+}
62+
63+// 2) la OPFS no puede guardarlo (cuota): lo dice, y sigue por Cache Storage
64+{
65+ const { ctx, p } = await pagina({ opfsLlena: true });
66+ const r = await carga(p);
67+ ok('disco lleno (OPFS): NO revienta la carga, el modelo llega por la caché', !r.err && r.esBlob && r.size === SIZE, r.err || JSON.stringify(r));
68+ ok('disco lleno (OPFS): lo DICE en el progreso (no silencioso)', /disco del navegador/.test(r.aviso), r.aviso.slice(0, 120));
69+ ok('disco lleno (OPFS): explica la causa probable', r.explica);
70+ await ctx.close();
71+}
72+
73+// 3) no se puede guardar en ningún sitio: lo dice y la carga sigue con la URL
74+{
75+ const { ctx, p } = await pagina({ opfsLlena: true, cacheLlena: true });
76+ const r = await carga(p);
77+ ok('sin sitio donde guardarlo: NO revienta la carga (devuelve la URL)', !r.err && r.esURL, r.err || JSON.stringify(r));
78+ ok('sin sitio donde guardarlo: lo DICE, con la causa probable', !!r.aviso && r.explica, r.aviso.slice(0, 120));
79+ await ctx.close();
80+}
81+
82+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ caché de modelo HONESTA — si no lo guarda, lo dice');
83+await b.close();
84+process.exit(fails ? 1 : 0);
modified web/js/runtime/model-store.js +7 −1
@@ -313,9 +313,15 @@
313313 // entró ni qué hacer, y se le enseña TAL CUAL al usuario. Traducirlo con la
314314 // cifra real es la diferencia entre «algo ha fallado» y saber qué pasa.
315315 if (/quota/i.test(String((e && e.message) || e))) {
316- throw new Error(`No cabe: el navegador dejó de admitir datos tras guardar ` +
316+ const err = new Error(`No cabe: el navegador dejó de admitir datos tras guardar ` +
317317 `${gb(loaded)} de ${gb(total)}. Su límite real es menor que el espacio que ` +
318318 `anuncia. Vacía la caché de modelos en Ajustes o elige uno más pequeño.`);
319+ // Con el nombre del error del navegador (QuotaExceededError…): así quien
320+ // llama distingue un fallo al GUARDAR de uno de red, y lo dice (litert.js
321+ // avisa en el progreso). Con un Error a secas se lo tragaba en silencio y
322+ // el modelo se volvía a bajar entero en cada sesión.
323+ err.name = e?.name && e.name !== 'Error' ? e.name : 'QuotaExceededError';
324+ throw err;
319325 }
320326 throw e;
321327 } finally {