| 1 | // Elffuss Runtime · almacén de modelos en OPFS (persistente, en disco). |
| 2 | // ───────────────────────────────────────────────────────────────────────────── |
| 3 | // Sustituye a Cache Storage para los PESOS del modelo. Motivo real (bug de móvil): |
| 4 | // Cache Storage se desaloja en iOS/Android → el modelo se re-descargaba en CADA |
| 5 | // visita. OPFS (Origin Private File System) + navigator.storage.persist() aguanta |
| 6 | // entre sesiones y se lee como File respaldado por DISCO (no vuelca todo a RAM). |
| 7 | // |
| 8 | // Además es la capa de almacenamiento del loader por shards: el motor leerá los |
| 9 | // pesos por rangos desde el File sin cargar los gigabytes enteros en memoria. |
| 10 | // |
| 11 | // Licencia: código propio (Apache-2.0). Sin dependencias externas. |
| 12 | |
| 13 | const DIR = 'elffuss-models'; |
| 14 | |
| 15 | // Los modelos se guardan PARTIDOS en trozos de este tamaño, y no por gusto: el |
| 16 | // navegador impone un tope POR FICHERO muy por debajo de su cuota declarada. |
| 17 | // Medido escribiendo de verdad en OPFS hasta que el navegador se planta |
| 18 | // (tests/modelparts.mjs comprueba la lógica; el tope se midió a mano): |
| 19 | // |
| 20 | // · un ÚNICO fichero se corta MUY por debajo de la cuota anunciada por |
| 21 | // storage.estimate() — en torno a la quinta parte de lo que promete; |
| 22 | // · el mismo contenido repartido en trozos llega a más del TRIPLE, y con eso |
| 23 | // un modelo de varios GB entra sin problema; |
| 24 | // · el error es el mismo en los dos casos («exceed its storage quota»), así |
| 25 | // que el número anunciado no sirve para decidir nada: hay que escribir para |
| 26 | // saberlo, y no se puede deducir de storage.estimate(). |
| 27 | // |
| 28 | // 1 GiB —y no menos— por una razón concreta: se abre parte nueva solo AL |
| 29 | // llenarse la actual, así que con este corte todos los modelos en uso hoy |
| 30 | // (gemma 760 MB, qwen 0.8B) siguen siendo UN fichero y su camino no cambia ni |
| 31 | // un byte; LiteRT sigue recibiendo el mismo File de siempre. Y queda a la mitad |
| 32 | // del tope observado, que es margen de sobra para otras máquinas. |
| 33 | let PART = 1024 * 1024 * 1024; |
| 34 | |
| 35 | // Solo para tests: la lógica de fronteras (repartir un chunk de red entre dos |
| 36 | // partes, leer un rango a caballo) no depende del tamaño, y con 1 GiB haría |
| 37 | // falta bajar gigabytes para ejercitarla. El valor real lo justifica la medición |
| 38 | // de arriba; lo que hay que probar es la aritmética. |
| 39 | export function _setPartSize(n) { PART = Math.max(1, n | 0); } |
| 40 | |
| 41 | // Nombre de fichero estable y seguro a partir de la URL (sin barras ni query). |
| 42 | function keyFor(url) { |
| 43 | return String(url).replace(/[?#].*$/, '').replace(/[^\w.\-]+/g, '_').slice(-180); |
| 44 | } |
| 45 | |
| 46 | // El marcador «.done» lleva dentro cuántas partes hay. Sin él, un modelo a |
| 47 | // medias se serviría como si estuviera entero. |
| 48 | async function leerManifiesto(dir, key) { |
| 49 | try { |
| 50 | const f = await (await dir.getFileHandle(key + '.done')).getFile(); |
| 51 | const m = JSON.parse(await f.text()); |
| 52 | return m && typeof m === 'object' ? m : {}; |
| 53 | } catch { return null; } // no existe, o descarga cortada |
| 54 | } |
| 55 | |
| 56 | // Abre las partes ya guardadas, o null si falta alguna. `parts` ausente = modelo |
| 57 | // guardado por una versión anterior en un solo fichero: se sigue leyendo igual. |
| 58 | async function abrirPartes(dir, key, man) { |
| 59 | const n = Number.isInteger(man.parts) && man.parts > 0 ? man.parts : null; |
| 60 | const nombres = n === null ? [key] : Array.from({ length: n }, (_, i) => `${key}.p${i}`); |
| 61 | const out = []; |
| 62 | for (const nombre of nombres) { |
| 63 | try { |
| 64 | const f = await (await dir.getFileHandle(nombre)).getFile(); |
| 65 | if (!f.size) return null; |
| 66 | out.push(f); |
| 67 | } catch { return null; } // parte perdida: no servir un modelo roto |
| 68 | } |
| 69 | // El tamaño total tiene que cuadrar con el declarado. Un fichero truncado por |
| 70 | // un desalojo del navegador se lee sin error y el parser saldría con basura. |
| 71 | const suma = out.reduce((s, f) => s + f.size, 0); |
| 72 | if (man.size && suma !== man.size) return null; |
| 73 | return out; |
| 74 | } |
| 75 | |
| 76 | async function requestPersist() { |
| 77 | try { |
| 78 | if (navigator.storage?.persist) { |
| 79 | const already = navigator.storage.persisted ? await navigator.storage.persisted() : false; |
| 80 | return already || await navigator.storage.persist(); |
| 81 | } |
| 82 | } catch { /* no bloquea */ } |
| 83 | return false; |
| 84 | } |
| 85 | |
| 86 | async function dirHandle() { |
| 87 | const root = await navigator.storage.getDirectory(); // lanza si no hay OPFS |
| 88 | return await root.getDirectoryHandle(DIR, { create: true }); |
| 89 | } |
| 90 | |
| 91 | // ¿Hay soporte para escribir en OPFS de forma útil en este navegador? |
| 92 | // Chrome/escritorio: createWritable (stream a disco). iOS Safari: solo |
| 93 | // createSyncAccessHandle (en worker) → en este primer incremento, si no hay |
| 94 | // createWritable en el hilo principal, devolvemos null y el llamador cae a Cache. |
| 95 | async function opfsWritableSupported(dir) { |
| 96 | try { |
| 97 | const test = await dir.getFileHandle('.probe', { create: true }); |
| 98 | if (typeof test.createWritable !== 'function') { await dir.removeEntry('.probe').catch(() => {}); return false; } |
| 99 | const w = await test.createWritable(); |
| 100 | await w.close(); |
| 101 | await dir.removeEntry('.probe').catch(() => {}); |
| 102 | return true; |
| 103 | } catch { return false; } |
| 104 | } |
| 105 | |
| 106 | // ¿Se puede escribir OPFS desde un Worker en este navegador? Se PRUEBA, no se |
| 107 | // deduce del user-agent: la detección por cadena de navegador envejece mal y |
| 108 | // aquí equivocarse significa bajarse gigabytes para tirarlos. |
| 109 | // |
| 110 | // Devuelve el escritor listo, o null si no hay forma — y en ese caso el |
| 111 | // llamador cae a Cache Storage, que es peor pero funciona. |
| 112 | async function abrirWorkerOPFS() { |
| 113 | if (typeof Worker !== 'function' || !navigator.storage?.getDirectory) return null; |
| 114 | let w = null; |
| 115 | try { |
| 116 | w = new Worker(new URL('./opfs-worker.js', import.meta.url), { type: 'module' }); |
| 117 | const esc = escritorWorker(w); |
| 118 | // Prueba de verdad: abrir, escribir un byte y cerrar. Si el navegador dice |
| 119 | // que tiene la API pero falla al usarla, aquí se entera y no al 97 % de una |
| 120 | // descarga de gigabytes. |
| 121 | await esc.abrir('.probe-worker'); |
| 122 | await esc.write(new Uint8Array([0])); |
| 123 | await esc.close(); |
| 124 | const raiz = await navigator.storage.getDirectory(); |
| 125 | const dir = await raiz.getDirectoryHandle(DIR, { create: true }); |
| 126 | await dir.removeEntry('.probe-worker').catch(() => {}); |
| 127 | return esc; |
| 128 | } catch { |
| 129 | try { w && w.terminate(); } catch {} |
| 130 | return null; |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // ESCRITOR POR WORKER — el camino de iOS. |
| 135 | // |
| 136 | // Expone `write(bytes)` y `close()`, o sea la misma forma que el `writable` de |
| 137 | // `createWritable`, para que el bucle de descarga sea UNO solo y no dos copias |
| 138 | // que se desincronizan. Por dentro manda los trozos a `opfs-worker.js`, que es |
| 139 | // el único sitio donde iOS deja escribir OPFS. |
| 140 | // |
| 141 | // Cada escritura ESPERA su acuse. Sin esperar, el hilo principal lee de la red |
| 142 | // mucho más rápido de lo que el worker escribe, la cola de mensajes crece sin |
| 143 | // límite y los gigabytes acaban en RAM — justo lo que este almacén existe para |
| 144 | // evitar. |
| 145 | function escritorWorker(worker) { |
| 146 | let seq = 0; |
| 147 | const pendientes = new Map(); |
| 148 | worker.onmessage = (ev) => { |
| 149 | const { id, ok, r, error } = ev.data || {}; |
| 150 | const p = pendientes.get(id); |
| 151 | if (!p) return; |
| 152 | pendientes.delete(id); |
| 153 | ok ? p.res(r) : p.rej(new Error(error || 'fallo en el worker de OPFS')); |
| 154 | }; |
| 155 | // Un worker que revienta dejaría todas las esperas colgadas para siempre: la |
| 156 | // descarga se quedaría quieta sin mensaje. Se rechazan todas. |
| 157 | worker.onerror = (e) => { |
| 158 | const err = new Error('el worker de OPFS falló: ' + (e.message || e.type)); |
| 159 | for (const p of pendientes.values()) p.rej(err); |
| 160 | pendientes.clear(); |
| 161 | }; |
| 162 | const pedir = (msg, transfer) => new Promise((res, rej) => { |
| 163 | const id = ++seq; |
| 164 | pendientes.set(id, { res, rej }); |
| 165 | worker.postMessage({ ...msg, id }, transfer || []); |
| 166 | }); |
| 167 | return { |
| 168 | abrir: (nombre) => pedir({ op: 'abrir', carpeta: DIR, nombre }), |
| 169 | write: (bytes) => { |
| 170 | // Se COPIA antes de transferir: `bytes` es una vista del buffer del |
| 171 | // lector de red, y transferir ese buffer lo dejaría neutralizado para el |
| 172 | // resto del chunk, que todavía hay que repartir entre partes. |
| 173 | const buf = bytes.slice().buffer; |
| 174 | return pedir({ op: 'escribir', buf }, [buf]); |
| 175 | }, |
| 176 | close: () => pedir({ op: 'cerrar' }), |
| 177 | // `abort()` existe porque el camino de ERROR lo llama. Sin él, un fallo de |
| 178 | // cuota se convertiría en «writable.abort is not a function» y taparía la |
| 179 | // causa real justo cuando más falta hace verla. Aquí abortar es cerrar: el |
| 180 | // fichero a medias lo borra después `borrarPartes`. |
| 181 | abort: () => pedir({ op: 'cerrar' }).catch(() => {}), |
| 182 | fin: () => worker.terminate(), |
| 183 | }; |
| 184 | } |
| 185 | |
| 186 | // Devuelve un Blob (respaldado en disco) del modelo, entero. |
| 187 | // Para los modelos grandes conviene más `openRanged`, que lee por rangos sin |
| 188 | // juntar las partes. Ver `getModelParts` para el detalle. |
| 189 | export async function getModelFile(url, onProgress = () => {}) { |
| 190 | const partes = await getModelParts(url, onProgress); |
| 191 | if (!partes) return null; |
| 192 | // Concatenar Blobs no copia los bytes (el navegador guarda referencias a los |
| 193 | // ficheros), pero el motor NO depende de eso: usa openRanged, que va parte a |
| 194 | // parte de forma explícita. |
| 195 | return partes.length === 1 ? partes[0] : new Blob(partes); |
| 196 | } |
| 197 | |
| 198 | // Devuelve las PARTES del modelo (Files respaldados en disco). Descarga por |
| 199 | // chunks a OPFS la primera vez (con progreso real), lo sirve desde disco a |
| 200 | // partir de entonces. Un marcador «<key>.done» evita servir una descarga |
| 201 | // cortada a medias. |
| 202 | // Devuelve null si OPFS no está disponible/escribible → el llamador usa su |
| 203 | // respaldo (Cache Storage) sin romperse. |
| 204 | export async function getModelParts(url, onProgress = () => {}) { |
| 205 | // 1) Caché COMPARTIDA (broker en origen Elffuss): un modelo bajado en CUALQUIER |
| 206 | // web de Elffuss se reutiliza aquí sin re-descargar. Fast-fail por sesión si |
| 207 | // el broker no está disponible → caemos a la OPFS local de este origen. |
| 208 | let brokerDown = false; |
| 209 | try { brokerDown = sessionStorage.getItem('elffuss.broker.down') === '1'; } catch { /* — */ } |
| 210 | if (!brokerDown) { |
| 211 | try { |
| 212 | const { getSharedModel } = await import('./model-broker.js'); |
| 213 | const blob = await getSharedModel(url, onProgress); |
| 214 | if (blob && blob.size) return [blob]; |
| 215 | } catch { try { sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* — */ } } |
| 216 | } |
| 217 | |
| 218 | if (!navigator.storage?.getDirectory) return null; |
| 219 | let dir; |
| 220 | try { dir = await dirHandle(); } catch { return null; } |
| 221 | await requestPersist(); |
| 222 | |
| 223 | const key = keyFor(url); |
| 224 | const doneName = key + '.done'; |
| 225 | |
| 226 | // ¿ya está entero en disco? |
| 227 | const man = await leerManifiesto(dir, key); |
| 228 | if (man) { |
| 229 | const partes = await abrirPartes(dir, key, man); |
| 230 | if (partes) { |
| 231 | onProgress('Cargando el modelo desde disco (OPFS, sin descargar)…'); |
| 232 | return partes; |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // TRES caminos, no dos. Antes aquí se devolvía null en cuanto no había |
| 237 | // `createWritable`, y eso mandaba a iOS a Cache Storage — que se desaloja, |
| 238 | // así que el teléfono se bajaba el modelo entero en cada visita. |
| 239 | let porWorker = null; |
| 240 | if (!(await opfsWritableSupported(dir))) { |
| 241 | porWorker = await abrirWorkerOPFS(); |
| 242 | if (!porWorker) return null; // ni una cosa ni la otra: que decida el llamador |
| 243 | } |
| 244 | |
| 245 | // descargar → OPFS por chunks (no en RAM), partiendo cada PART bytes |
| 246 | const net = await fetch(url); |
| 247 | if (!net.ok || !net.body) throw new Error('descarga del modelo falló: HTTP ' + net.status); |
| 248 | const total = +net.headers.get('content-length') || 0; |
| 249 | |
| 250 | // Aviso temprano. Bajar gigabytes para que el navegador lo rechace al 97% y |
| 251 | // quedarse sin nada es la peor forma de enterarse de que no cabe — y pasa, con |
| 252 | // los modelos grandes es el caso normal, no el raro. |
| 253 | // |
| 254 | // Esto NO garantiza que quepa: la cuota anunciada es bastante mayor que lo que |
| 255 | // de verdad se deja escribir. Descarta el caso claro sin gastar la descarga, y |
| 256 | // el que se cuela lo caza el mensaje del catch. |
| 257 | if (total) { |
| 258 | const est = await navigator.storage.estimate().catch(() => null); |
| 259 | const libre = est ? (est.quota || 0) - (est.usage || 0) : 0; |
| 260 | if (est && libre > 0 && total > libre) { |
| 261 | // El mensaje manda a Ajustes y no «al disco»: lo que ocupa el sitio son |
| 262 | // casi siempre los modelos que ya se han descargado antes, y eso se vacía |
| 263 | // con un botón dentro de la app. Mandar a limpiar el disco duro es mandar |
| 264 | // al sitio equivocado a alguien que tiene la solución a un clic. |
| 265 | throw new Error(`Este modelo ocupa ${gb(total)} y en el navegador solo quedan ` + |
| 266 | `${gb(libre)}. Vacía la caché de modelos en Ajustes —ahí se ve cuánto ` + |
| 267 | `ocupan los que ya has descargado— o elige un modelo más pequeño.`); |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | // limpiar restos de un intento previo cortado |
| 272 | await dir.removeEntry(doneName).catch(() => {}); |
| 273 | await borrarPartes(dir, key); |
| 274 | const t0 = performance.now(); |
| 275 | let loaded = 0, nPartes = 0, enParte = 0, writable = null; |
| 276 | |
| 277 | const abrirParte = async () => { |
| 278 | const nombre = `${key}.p${nPartes}`; |
| 279 | if (porWorker) { |
| 280 | await porWorker.abrir(nombre); |
| 281 | writable = porWorker; // misma forma: write/close |
| 282 | } else { |
| 283 | const fh = await dir.getFileHandle(nombre, { create: true }); |
| 284 | writable = await fh.createWritable(); // stream a disco |
| 285 | } |
| 286 | nPartes++; enParte = 0; |
| 287 | }; |
| 288 | |
| 289 | try { |
| 290 | await abrirParte(); |
| 291 | const reader = net.body.getReader(); |
| 292 | for (;;) { |
| 293 | const { done, value } = await reader.read(); |
| 294 | if (done) break; |
| 295 | // Un chunk de red no respeta la frontera de parte: se reparte. Sin esto, |
| 296 | // una parte se pasaría del tope y volvería el error de cuota justo al |
| 297 | // final de una descarga de gigabytes. |
| 298 | let off = 0; |
| 299 | while (off < value.byteLength) { |
| 300 | if (enParte >= PART) { await writable.close(); await abrirParte(); } |
| 301 | const cabe = Math.min(PART - enParte, value.byteLength - off); |
| 302 | await writable.write(value.subarray(off, off + cabe)); |
| 303 | off += cabe; enParte += cabe; loaded += cabe; |
| 304 | } |
| 305 | onProgress(fmt(loaded, total, t0)); |
| 306 | } |
| 307 | await writable.close(); |
| 308 | writable = null; |
| 309 | } catch (e) { |
| 310 | if (writable) { try { await writable.abort(); } catch { /* — */ } } |
| 311 | await borrarPartes(dir, key); // no dejar basura a medias |
| 312 | // El mensaje del navegador («exceed its storage quota») no dice ni cuánto |
| 313 | // entró ni qué hacer, y se le enseña TAL CUAL al usuario. Traducirlo con la |
| 314 | // cifra real es la diferencia entre «algo ha fallado» y saber qué pasa. |
| 315 | if (/quota/i.test(String((e && e.message) || e))) { |
| 316 | const err = new Error(`No cabe: el navegador dejó de admitir datos tras guardar ` + |
| 317 | `${gb(loaded)} de ${gb(total)}. Su límite real es menor que el espacio que ` + |
| 318 | `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; |
| 325 | } |
| 326 | throw e; |
| 327 | } finally { |
| 328 | // Soltar el worker SIEMPRE, también al fallar: un worker vivo se queda con |
| 329 | // el handle del fichero abierto y el siguiente intento no podría truncarlo. |
| 330 | if (porWorker) { try { porWorker.fin(); } catch { /* — */ } porWorker = null; } |
| 331 | } |
| 332 | |
| 333 | // ¿Llegó ENTERO? Un stream que se corta a mitad termina sin lanzar: el bucle |
| 334 | // ve `done` y sale como si hubiera acabado bien. Sin esta comprobación se |
| 335 | // marcaba como completo lo que se hubiera escrito, y la validación de después |
| 336 | // pasaba —comprueba que las partes sumen lo APUNTADO, no lo que debía pesar—, |
| 337 | // así que un modelo truncado quedaba cacheado para siempre: pesos corruptos, |
| 338 | // sin error, en cada visita. Es el mismo fallo que un rango corto entrando |
| 339 | // como pesos, un piso más arriba. |
| 340 | if (total && loaded !== total) { |
| 341 | await borrarPartes(dir, key); |
| 342 | throw new Error(`La descarga se cortó: llegaron ${gb(loaded)} de ${gb(total)}. ` + |
| 343 | `No se guarda a medias porque el modelo no funcionaría. Vuelve a intentarlo.`); |
| 344 | } |
| 345 | |
| 346 | // marcar completado: el tamaño ESPERADO (no el escrito) y el número de partes, |
| 347 | // que es lo que hace falta para volver a montarlo y para detectar que el |
| 348 | // navegador haya truncado algo después. |
| 349 | const dh = await dir.getFileHandle(doneName, { create: true }); |
| 350 | const dw = await dh.createWritable(); |
| 351 | await dw.write(new TextEncoder().encode(JSON.stringify({ size: loaded, total, parts: nPartes }))); |
| 352 | await dw.close(); |
| 353 | |
| 354 | return await abrirPartes(dir, key, { size: loaded, parts: nPartes }); |
| 355 | } |
| 356 | |
| 357 | // Borra las partes de un modelo (y el fichero único de versiones anteriores). |
| 358 | async function borrarPartes(dir, key) { |
| 359 | await dir.removeEntry(key).catch(() => {}); // formato antiguo |
| 360 | const pref = key + '.p'; |
| 361 | try { |
| 362 | const nombres = []; |
| 363 | for await (const nombre of dir.keys()) if (nombre.startsWith(pref)) nombres.push(nombre); |
| 364 | for (const n of nombres) await dir.removeEntry(n).catch(() => {}); |
| 365 | } catch { |
| 366 | // Sin iteración de directorio: borrar por número hasta que falten dos |
| 367 | // seguidas (una sola ausencia podría ser un hueco de un borrado a medias). |
| 368 | let fallos = 0; |
| 369 | for (let i = 0; i < 512 && fallos < 2; i++) { |
| 370 | const ok = await dir.removeEntry(`${pref}${i}`).then(() => true, () => false); |
| 371 | fallos = ok ? 0 : fallos + 1; |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | // Abre un handle de lectura por rangos (para el loader por shards del motor): |
| 377 | // devuelve una función slice(offset, length) → Promise<ArrayBuffer> que lee del |
| 378 | // disco sin cargar el fichero entero. File.slice() es perezoso en disco. |
| 379 | export async function openRanged(url, onProgress = () => {}) { |
| 380 | const partes = await getModelParts(url, onProgress); |
| 381 | if (!partes || !partes.length) return null; |
| 382 | |
| 383 | // Índice de comienzos para traducir un offset ABSOLUTO a (parte, offset). |
| 384 | const inicio = []; |
| 385 | let size = 0; |
| 386 | for (const p of partes) { inicio.push(size); size += p.size; } |
| 387 | |
| 388 | const parteDe = abs => { // búsqueda binaria |
| 389 | let lo = 0, hi = inicio.length - 1; |
| 390 | while (lo < hi) { const m = (lo + hi + 1) >> 1; if (inicio[m] <= abs) lo = m; else hi = m - 1; } |
| 391 | return lo; |
| 392 | }; |
| 393 | |
| 394 | return { |
| 395 | size, |
| 396 | async slice(offset, length) { |
| 397 | // Math.trunc y no |0: estos ficheros pasan de 2 GiB y el bitwise trunca a |
| 398 | // 32 bits con signo — un offset de 4 GiB saldría negativo. |
| 399 | const from = Math.max(0, Math.min(size, Math.trunc(offset) || 0)); |
| 400 | const want = Math.max(0, Math.min(size - from, Math.trunc(length) || 0)); |
| 401 | if (want === 0) return new ArrayBuffer(0); |
| 402 | |
| 403 | // Caso normal: el rango cae entero dentro de una parte y no se copia nada. |
| 404 | const i0 = parteDe(from); |
| 405 | const d0 = from - inicio[i0]; |
| 406 | if (d0 + want <= partes[i0].size) { |
| 407 | return await partes[i0].slice(d0, d0 + want).arrayBuffer(); |
| 408 | } |
| 409 | |
| 410 | // A caballo entre partes. Pasa de verdad: los tensores no se alinean con |
| 411 | // los 512 MiB, así que uno de cada pocos cruza la frontera. |
| 412 | const out = new Uint8Array(want); |
| 413 | let puesto = 0; |
| 414 | for (let i = i0; i < partes.length && puesto < want; i++) { |
| 415 | const d = i === i0 ? d0 : 0; |
| 416 | const trozo = Math.min(partes[i].size - d, want - puesto); |
| 417 | if (trozo <= 0) continue; |
| 418 | out.set(new Uint8Array(await partes[i].slice(d, d + trozo).arrayBuffer()), puesto); |
| 419 | puesto += trozo; |
| 420 | } |
| 421 | return puesto === want ? out.buffer : out.buffer.slice(0, puesto); |
| 422 | }, |
| 423 | }; |
| 424 | } |
| 425 | |
| 426 | // Borrar un modelo cacheado (para el «liberar espacio» de la UI). |
| 427 | export async function removeModel(url) { |
| 428 | try { |
| 429 | const dir = await dirHandle(); |
| 430 | const key = keyFor(url); |
| 431 | await dir.removeEntry(key + '.done').catch(() => {}); |
| 432 | await borrarPartes(dir, key); |
| 433 | return true; |
| 434 | } catch { return false; } |
| 435 | } |
| 436 | |
| 437 | // Borra TODOS los modelos guardados en OPFS. |
| 438 | // Existe porque el botón «liberar espacio» de Ajustes solo vaciaba Cache |
| 439 | // Storage: un modelo descargado por este almacén se quedaba ocupando disco sin |
| 440 | // forma de borrarlo desde la interfaz. Y como navigator.storage.estimate() SÍ |
| 441 | // lo cuenta, el usuario veía gigas que el botón no bajaba nunca. |
| 442 | export async function clearAll() { |
| 443 | try { |
| 444 | const root = await navigator.storage.getDirectory(); |
| 445 | await root.removeEntry(DIR, { recursive: true }); |
| 446 | return true; |
| 447 | } catch { return false; } // no existe o no hay OPFS: nada que borrar |
| 448 | } |
| 449 | |
| 450 | // Bytes ocupados por los modelos en OPFS (aprox, para diagnóstico). |
| 451 | export async function usage() { |
| 452 | try { |
| 453 | const est = await navigator.storage.estimate(); |
| 454 | return { usage: est.usage || 0, quota: est.quota || 0 }; |
| 455 | } catch { return { usage: 0, quota: 0 }; } |
| 456 | } |
| 457 | |
| 458 | // Tamaños para mensajes de usuario: GB decimales, que es como los cuenta todo |
| 459 | // el mundo fuera de un terminal. |
| 460 | function gb(n) { return (n / 1e9).toFixed(1).replace('.', ',') + ' GB'; } |
| 461 | |
| 462 | function fmt(loaded, total, t0) { |
| 463 | const mb = n => (n / 1048576).toFixed(0); |
| 464 | const secs = (performance.now() - t0) / 1000; |
| 465 | const spd = secs > 0 ? (loaded / 1048576 / secs).toFixed(1) : '0'; |
| 466 | // Incluir el % cuando se conoce el total: el escaparate lo extrae para llenar |
| 467 | // la barra, y el texto queda corto (no envuelve en móvil). |
| 468 | return total |
| 469 | ? `Descargando el cerebro · ${mb(loaded)}/${mb(total)} MB · ${Math.round(loaded / total * 100)}%` |
| 470 | : `Descargando el cerebro · ${mb(loaded)} MB · ${spd} MB/s`; |
| 471 | } |