| 1 | // Arranque de la caché de modelos: (1) pide almacenamiento PERSISTENTE para que |
| 2 | // el navegador no desaloje los pesos cacheados, y (2) registra el service worker |
| 3 | // (sw.js) y espera a que CONTROLE la página antes de descargar nada — así hasta |
| 4 | // la primera descarga queda cacheada. Idempotente y a prueba de fallos. |
| 5 | let started = null; |
| 6 | |
| 7 | export function ensureModelCache() { |
| 8 | if (started) return started; |
| 9 | started = (async () => { |
| 10 | try { |
| 11 | if (navigator.storage && navigator.storage.persist) { |
| 12 | const persisted = navigator.storage.persisted ? await navigator.storage.persisted() : false; |
| 13 | const ok = persisted || await navigator.storage.persist(); |
| 14 | console.log('[elffuss] almacenamiento persistente:', ok); |
| 15 | } |
| 16 | } catch { /* no soportado */ } |
| 17 | |
| 18 | if (!('serviceWorker' in navigator)) return false; |
| 19 | try { |
| 20 | await navigator.serviceWorker.register('sw.js'); |
| 21 | await navigator.serviceWorker.ready; |
| 22 | if (!navigator.serviceWorker.controller) { |
| 23 | await new Promise(res => { |
| 24 | const t = setTimeout(res, 1500); |
| 25 | navigator.serviceWorker.addEventListener('controllerchange', () => { clearTimeout(t); res(); }, { once: true }); |
| 26 | }); |
| 27 | } |
| 28 | console.log('[elffuss] caché de modelos activa (service worker)'); |
| 29 | return true; |
| 30 | } catch (e) { |
| 31 | console.warn('[elffuss] service worker no disponible:', e.message); |
| 32 | return false; |
| 33 | } |
| 34 | })(); |
| 35 | return started; |
| 36 | } |
| 37 | |
| 38 | // Espacio ocupado por la caché (para mostrarlo en Ajustes). |
| 39 | export async function cacheEstimate() { |
| 40 | try { |
| 41 | const e = await navigator.storage.estimate(); |
| 42 | return { usage: e.usage || 0, quota: e.quota || 0, persisted: navigator.storage.persisted ? await navigator.storage.persisted() : false }; |
| 43 | } catch { return { usage: 0, quota: 0, persisted: false }; } |
| 44 | } |
| 45 | |
| 46 | // Vaciar la caché de modelos (botón en Ajustes). |
| 47 | export async function clearModelCache() { |
| 48 | if (navigator.serviceWorker && navigator.serviceWorker.controller) |
| 49 | navigator.serviceWorker.controller.postMessage('clear-models'); |
| 50 | try { await caches.delete('elffuss-models-v1'); } catch { /* */ } |
| 51 | } |
| 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 | // |
| 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…». |
| 96 | async function brokerApi() { |
| 97 | try { |
| 98 | const b = await import('./runtime/model-broker.js'); |
| 99 | if (typeof b.sharedUsage !== 'function') return null; |
| 100 | let origenes = []; |
| 101 | // Puede devolver la lista o una promesa de ella: se espera siempre. |
| 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])] }; |
| 106 | } catch { return null; } |
| 107 | } |
| 108 | |
| 109 | // { local, shared, total, sharedOk }: `sharedOk` es false cuando el almacén |
| 110 | // compartido no se pudo consultar (puede haber más guardado del que se cuenta). |
| 111 | export async function modelUsage() { |
| 112 | const local = (await opfsModelBytes()) + (await cacheModelBytes()); |
| 113 | let shared = 0, sharedOk = false; |
| 114 | const api = await brokerApi(); |
| 115 | if (api) { |
| 116 | try { const r = await api.b.sharedUsage(api.origenes); shared = r.usage || 0; sharedOk = !!r.ok; } |
| 117 | catch { sharedOk = false; } |
| 118 | } |
| 119 | return { local, shared, total: local + shared, sharedOk }; |
| 120 | } |
| 121 | |
| 122 | // Vacía TODO lo que son pesos de modelo y devuelve cuánto se liberó DE VERDAD |
| 123 | // (se mide antes y después), más lo que no se pudo tocar. |
| 124 | export async function clearModels() { |
| 125 | const antes = await modelUsage(); |
| 126 | const fallos = []; |
| 127 | if (navigator.serviceWorker?.controller) navigator.serviceWorker.controller.postMessage('clear-models'); |
| 128 | if (typeof caches !== 'undefined') { |
| 129 | for (const name of await caches.keys().catch(() => [])) { |
| 130 | if (!MODEL_CACHES.includes(name) && !name.startsWith('transformers')) continue; |
| 131 | try { await caches.delete(name); } catch (e) { fallos.push(name + ': ' + (e?.message || e)); } |
| 132 | } |
| 133 | } |
| 134 | try { |
| 135 | const { clearAll } = await import('./runtime/model-store.js'); |
| 136 | await clearAll(); |
| 137 | } catch (e) { fallos.push('OPFS: ' + (e?.message || e)); } |
| 138 | const api = await brokerApi(); |
| 139 | if (api && typeof api.b.clearShared === 'function') { |
| 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 | })); |
| 147 | } |
| 148 | const despues = await modelUsage(); |
| 149 | return { liberado: Math.max(0, antes.total - despues.total), antes, despues, fallos, sharedOk: antes.sharedOk }; |
| 150 | } |