Elffuss BraidHub

utopia-ia/elffuss-code public

Storage helpers that tell the truth: write hook, feedback result, model bytes

db.js: onWrite(fn) is called after every set/del, so the workspace can know
that a store it mirrors to disk changed. Nothing called workspace.touch(),
so "Save automatically" never wrote anything.

telemetry.js: post() returns whether the server accepted the report
(res.ok), and sendFeedback() passes that on. It returned nothing, so the
feedback panel said "sent" on a 404 or with no network.

model-cache.js: modelUsage() counts only model weights (the OPFS model
store, the old Cache Storage and transformers.js' cache, plus the broker's
shared store when the broker can measure it) instead of
navigator.storage.estimate() for the whole origin, which mixed in
conversations and project data. clearModels() clears all of those and
returns how much was really freed (measured before and after) and what
could not be cleared. The shared store is used only when model-broker.js
exposes sharedUsage/clearShared; otherwise sharedOk is false so the UI can
say it could not check it.

workspace.js: the root of the browser's private storage (OPFS) has an
empty name, which status() reported as "no folder", so it could not be used
as the workspace folder. It is named "OPFS (navegador)" now.

The UI that uses these comes in the next commit.
Changeset4eb6a3c2f5a87f2dc9ee6d0c34831f5d6a2f658d1ce91e34289c98b60bc1c7fa
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 16:19 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:13 +02:00
Parents9255fd1f0dc0

Browse the files at this changeset

4 files changed

modified web/js/db.js +12 −2
@@ -25,8 +25,18 @@
2525 }));
2626 }
2727
28+// Quien necesite saber que algo se escribió (el espacio de trabajo, que copia
29+// conversaciones y skills a tu disco con «Guardar solo») se apunta aquí. Un
30+// fallo de quien escucha nunca rompe la escritura.
31+const oyentes = [];
32+export function onWrite(fn) {
33+ oyentes.push(fn);
34+ return () => { const i = oyentes.indexOf(fn); if (i >= 0) oyentes.splice(i, 1); };
35+}
36+const avisa = (store, key) => (r) => { for (const f of oyentes) { try { f(store, key); } catch { /* */ } } return r; };
37+
2838 export const get = (store, key) => tx(store, 'readonly', s => s.get(key));
29-export const set = (store, key, val) => tx(store, 'readwrite', s => s.put(val, key));
30-export const del = (store, key) => tx(store, 'readwrite', s => s.delete(key));
39+export const set = (store, key, val) => tx(store, 'readwrite', s => s.put(val, key)).then(avisa(store, key));
40+export const del = (store, key) => tx(store, 'readwrite', s => s.delete(key)).then(avisa(store, key));
3141 export const keys = (store) => tx(store, 'readonly', s => s.getAllKeys());
3242 export const all = (store) => tx(store, 'readonly', s => s.getAll());
modified web/js/model-cache.js +89 −0
@@ -49,3 +49,92 @@
4949 navigator.serviceWorker.controller.postMessage('clear-models');
5050 try { await caches.delete('elffuss-models-v1'); } catch { /* */ }
5151 }
52+
53+// ── Lo que ocupan los MODELOS, y vaciarlos de verdad ─────────────────────────
54+// El chip 💾 y «Vaciar caché» medían `navigator.storage.estimate()` (el origen
55+// ENTERO: conversaciones, el proyecto de prueba en OPFS…) y lo llamaban
56+// «modelos guardados», y al vaciar solo borraban la Cache Storage vieja. Pero
57+// los pesos viven en otros sitios: la carpeta OPFS del almacén de modelos
58+// (runtime/model-store.js), la caché de transformers.js (el modelo ONNX) y el
59+// almacén COMPARTIDO del broker, que está en otro origen. Ahora se cuenta y se
60+// vacía cada uno, y se dice lo que de verdad se liberó.
61+const MODEL_CACHES = ['elffuss-models-v1', 'transformers-cache'];
62+const MODEL_DIR = 'elffuss-models';
63+
64+async function opfsModelBytes() {
65+ try {
66+ const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle(MODEL_DIR);
67+ let n = 0;
68+ for await (const e of dir.values()) if (e.kind === 'file') n += (await e.getFile()).size;
69+ return n;
70+ } catch { return 0; } // no existe todavía: nada guardado
71+}
72+async function cacheModelBytes() {
73+ if (typeof caches === 'undefined') return 0;
74+ let n = 0;
75+ for (const name of await caches.keys().catch(() => [])) {
76+ if (!MODEL_CACHES.includes(name) && !name.startsWith('transformers')) continue;
77+ try {
78+ const c = await caches.open(name);
79+ for (const req of await c.keys()) {
80+ const res = await c.match(req);
81+ const len = +(res?.headers.get('content-length') || 0);
82+ n += len || (res ? (await res.blob()).size : 0);
83+ }
84+ } catch { /* una caché ilegible no rompe la cuenta */ }
85+ }
86+ return n;
87+}
88+// El almacén compartido vive en el origen del broker: solo se puede medir y
89+// vaciar si el broker sabe hacerlo (sharedUsage / clearShared). Si no, se dice.
90+async function brokerApi() {
91+ try {
92+ const b = await import('./runtime/model-broker.js');
93+ if (typeof b.sharedUsage !== 'function') return null;
94+ let origenes;
95+ try { const r = await import('./engine/registro.js'); origenes = r.origenesAlmacen ? r.origenesAlmacen() : undefined; }
96+ catch { /* sin motor: el broker por defecto */ }
97+ return { b, origenes };
98+ } catch { return null; }
99+}
100+
101+// { local, shared, total, sharedOk }: `sharedOk` es false cuando el almacén
102+// compartido no se pudo consultar (puede haber más guardado del que se cuenta).
103+export async function modelUsage() {
104+ const local = (await opfsModelBytes()) + (await cacheModelBytes());
105+ let shared = 0, sharedOk = false;
106+ const api = await brokerApi();
107+ if (api) {
108+ try { const r = await api.b.sharedUsage(api.origenes); shared = r.usage || 0; sharedOk = !!r.ok; }
109+ catch { sharedOk = false; }
110+ }
111+ return { local, shared, total: local + shared, sharedOk };
112+}
113+
114+// Vacía TODO lo que son pesos de modelo y devuelve cuánto se liberó DE VERDAD
115+// (se mide antes y después), más lo que no se pudo tocar.
116+export async function clearModels() {
117+ const antes = await modelUsage();
118+ const fallos = [];
119+ if (navigator.serviceWorker?.controller) navigator.serviceWorker.controller.postMessage('clear-models');
120+ if (typeof caches !== 'undefined') {
121+ for (const name of await caches.keys().catch(() => [])) {
122+ if (!MODEL_CACHES.includes(name) && !name.startsWith('transformers')) continue;
123+ try { await caches.delete(name); } catch (e) { fallos.push(name + ': ' + (e?.message || e)); }
124+ }
125+ }
126+ try {
127+ const { clearAll } = await import('./runtime/model-store.js');
128+ await clearAll();
129+ } catch (e) { fallos.push('OPFS: ' + (e?.message || e)); }
130+ const api = await brokerApi();
131+ if (api && typeof api.b.clearShared === 'function') {
132+ const lista = Array.isArray(api.origenes) && api.origenes.length ? [...new Set(api.origenes)] : [undefined];
133+ for (const o of lista) {
134+ try { const r = await api.b.clearShared(o); if (!r?.ok) fallos.push('broker ' + (o || '')); }
135+ catch (e) { fallos.push('broker ' + (o || '') + ': ' + (e?.message || e)); }
136+ }
137+ }
138+ const despues = await modelUsage();
139+ return { liberado: Math.max(0, antes.total - despues.total), antes, despues, fallos, sharedOk: antes.sharedOk };
140+}
modified web/js/telemetry.js +7 −3
@@ -23,10 +23,13 @@
2323 if (enabled) hookGlobalErrors();
2424 }
2525
26+// Devuelve si el servidor lo aceptó DE VERDAD (respuesta 2xx). Antes no
27+// devolvía nada y el panel de feedback decía «¡enviado!» aunque el servidor
28+// contestara 404 o no hubiera red.
2629 async function post(kind, message, opts = {}) {
27- if (!enabled) return;
30+ if (!enabled) return false;
2831 try {
29- await fetch('/proxy/report', {
32+ const res = await fetch('/proxy/report', {
3033 method: 'POST',
3134 headers: { 'Content-Type': 'application/json' },
3235 body: JSON.stringify({
@@ -36,7 +39,8 @@
3639 extra: String(opts.extra || '').slice(0, 2000),
3740 }),
3841 });
39- } catch { /* sin conexión o proxy caído: se descarta, no hay reintento */ }
42+ return res.ok;
43+ } catch { return false; /* sin conexión o proxy caído: se descarta, no hay reintento */ }
4044 }
4145
4246 export function reportError(message, opts = {}) { return post('error', message, opts); }
modified web/js/workspace.js +9 −5
@@ -38,9 +38,13 @@
3838 const emit = () => { const s = statusSync(); listeners.forEach(f => { try { f(s); } catch { /* */ } }); };
3939 export function onChange(fn) { listeners.push(fn); return () => { listeners = listeners.filter(f => f !== fn); }; }
4040
41+// La raíz del almacenamiento privado del navegador (OPFS) no tiene nombre: ''
42+// se leía como «sin carpeta» y la carpeta elegida no se podía usar.
43+const nombreDe = h => h ? (h.name || 'OPFS (navegador)') : null;
44+
4145 function statusSync() {
4246 return {
43- supported: supported(), folder: dirHandle ? dirHandle.name : null, ready,
47+ supported: supported(), folder: nombreDe(dirHandle), ready,
4448 dirty: [...dirty], lastSaveAt, lastError, autosave: autosaveCfg.enabled,
4549 };
4650 }
@@ -62,7 +66,7 @@
6266 dirHandle = h;
6367 ready = await perm(h);
6468 emit();
65- return { name: h.name, ready, reason: ready ? null : 'prompt' };
69+ return { name: nombreDe(h), ready, reason: ready ? null : 'prompt' };
6670 }
6771
6872 // Elegir carpeta (requiere gesto de usuario).
@@ -73,7 +77,7 @@
7377 ready = true;
7478 await cfg.db.set('kv', HANDLE_KEY, h);
7579 emit();
76- return { name: h.name, ready: true };
80+ return { name: nombreDe(h), ready: true };
7781 }
7882
7983 // Reutilizar un handle que la app ya tiene (Code: la carpeta del proyecto).
@@ -83,7 +87,7 @@
8387 ready = await perm(handle);
8488 await cfg.db.set('kv', HANDLE_KEY, handle);
8589 emit();
86- return { name: handle.name, ready };
90+ return { name: nombreDe(handle), ready };
8791 }
8892
8993 // Re-conceder permiso tras recargar (requiere gesto de usuario).
@@ -95,7 +99,7 @@
9599 ready = ok;
96100 emit();
97101 if (!ok) throw new Error('permiso denegado');
98- return { name: dirHandle.name, ready: true };
102+ return { name: nombreDe(dirHandle), ready: true };
99103 }
100104
101105 export async function forget() {