| 1 | <!doctype html> |
| 2 | <html lang="es"><head><meta charset="utf-8"><title>Elffuss · broker de modelos</title> |
| 3 | <meta name="robots" content="noindex"> |
| 4 | <style>body{margin:0;background:#090a11;color:#8b929c;font:13px system-ui;display:grid;place-items:center;height:100vh}</style> |
| 5 | </head><body> |
| 6 | <div>Elffuss · caché compartida de modelos. Esta página no se usa directamente.</div> |
| 7 | <script type="module"> |
| 8 | // ───────────────────────────────────────────────────────────────────────────── |
| 9 | // BROKER DE MODELOS · caché OPFS compartida entre todas las webs de Elffuss. |
| 10 | // Se embebe como iframe oculto desde cada propiedad (claw/translator/copilot/…). |
| 11 | // Como todas son subdominios de elffuss.com (mismo «site»), este iframe es |
| 12 | // first-party en todas y comparte UNA sola OPFS → el modelo se descarga UNA vez |
| 13 | // y se reutiliza en todas. (Un tercero que lo integre tiene su propia partición |
| 14 | // por privacidad del navegador: se baja una vez POR SU site. Los hosts viejos de |
| 15 | // elffuss.utopiaia.com son, para el navegador, otro site distinto.) |
| 16 | // API postMessage: {type:'elffuss-model-get', id, url} → {kind:'progress'}* → |
| 17 | // {kind:'file', file} | {kind:'error', message}. {type:'elffuss-model-has', id, url} |
| 18 | // {type:'elffuss-model-clear', id} → {kind:'cleared', liberado, restante}: vacia |
| 19 | // este almacen. Lo necesita el boton «vaciar cache» de las webs, que sin esto |
| 20 | // solo borraba lo de SU origen y dejaba aqui el modelo grande. |
| 21 | // (Aquí ponía que la respuesta venían trozos de ArrayBuffer, que es la versión |
| 22 | // ANTERIOR: ahora se manda el File de OPFS por referencia, justamente para no |
| 23 | // copiar los gigabytes a la RAM del renderer. La descripción vieja hizo perder |
| 24 | // media hora escribiendo un cliente que esperaba mensajes que ya no llegan.) |
| 25 | // ───────────────────────────────────────────────────────────────────────────── |
| 26 | const DIR = 'elffuss-models'; |
| 27 | const CHUNK = 8 * 1024 * 1024; |
| 28 | // Orígenes permitidos: las webs de Elffuss que embeben este broker, y nada más. |
| 29 | // NO todo *.utopiaia.com, que es lo que ponía antes: ese dominio aloja más cosas |
| 30 | // que Elffuss. Y tampoco todo *.elffuss.com: git.* es un Gitea que pinta markdown |
| 31 | // escrito por cualquiera, y key.* no tiene nada que pedirle al broker. Como son |
| 32 | // del mismo «site», un script colado ahí hablaría con este iframe en su caché |
| 33 | // compartida: vería lo que hay guardado y podría llenarla de descargas. |
| 34 | // · elffuss.com y claw, code, t2t, translator, copilot, models, m1, m2… .elffuss.com |
| 35 | // · lo mismo bajo elffuss.utopiaia.com (el dominio anterior: se sigue aceptando |
| 36 | // mientras dure el cambio de dominio) |
| 37 | // · los alias más viejos elffuss-claw y elffuss-code .utopiaia.com |
| 38 | // Las integraciones de terceros se añaden por query (?allow=https://otra.com) |
| 39 | // — cada una en su propia partición. |
| 40 | const extra = new URLSearchParams(location.search).getAll('allow'); |
| 41 | const WEBS = /^https:\/\/((claw|code|t2t|translator|copilot|models|m\d+)\.)?elffuss\.(com|utopiaia\.com)$/; |
| 42 | function allowed(origin) { |
| 43 | if (WEBS.test(origin)) return true; |
| 44 | if (/^https:\/\/(elffuss-(claw|code)|burn-my-computer)\.utopiaia\.com$/.test(origin)) return true; // alias antiguos y Burn My Computer |
| 45 | if (/^http:\/\/localhost(:\d+)?$/.test(origin)) return true; // desarrollo |
| 46 | return extra.includes(origin); |
| 47 | } |
| 48 | const keyFor = u => String(u).replace(/[?#].*$/, '').replace(/[^\w.\-]+/g, '_').slice(-180); |
| 49 | async function requestPersist(){ try{ if(navigator.storage?.persist){ return (await navigator.storage.persisted?.()) || await navigator.storage.persist(); } }catch{} return false; } |
| 50 | async function dir(){ const root = await navigator.storage.getDirectory(); return root.getDirectoryHandle(DIR, { create:true }); } |
| 51 | |
| 52 | async function cachedFile(url){ |
| 53 | try{ const d = await dir(); const k = keyFor(url); |
| 54 | const marca = JSON.parse(await (await (await d.getFileHandle(k + '.done')).getFile()).text()); |
| 55 | const f = await juntar(d, k, marca.parts || 1); |
| 56 | // El tamaño tiene que cuadrar con el apuntado: un fichero truncado por un |
| 57 | // desalojo se lee sin error y el modelo saldría con basura dentro. |
| 58 | return (f.size > 0 && (!marca.size || f.size === marca.size)) ? f : null; |
| 59 | }catch{ return null; } |
| 60 | } |
| 61 | async function juntar(d, k, n){ |
| 62 | const partes = []; |
| 63 | for (let i = 0; i < n; i++) partes.push(await (await d.getFileHandle(k + '.p' + i)).getFile()); |
| 64 | return partes.length === 1 ? partes[0] : new Blob(partes); |
| 65 | } |
| 66 | // Borra TODAS las partes de una entrada, no solo las que creemos que hay. |
| 67 | // |
| 68 | // Aquí había un `removeEntry(k)`, y `k` no existe: los ficheros se llaman |
| 69 | // `k.p0`, `k.p1`… O sea que al fallar una descarga los trozos ya escritos se |
| 70 | // quedaban en disco ocupando cuota para siempre. La caché se ENVENENABA sola: |
| 71 | // un fallo dejaba 3 GB huérfanos, el intento siguiente pedía 3,8 GB más y moría |
| 72 | // con «exceed its storage quota» —que suena a disco lleno del usuario y era |
| 73 | // basura nuestra—, y cada reintento lo empeoraba. |
| 74 | // |
| 75 | // Se listan las entradas de verdad en vez de contar índices —así da igual |
| 76 | // cuántas partes dejara la descarga anterior—, y solo si el navegador no sabe |
| 77 | // iterar el directorio se cae a borrar por número. Misma forma que la de |
| 78 | // `model-store.js`, que ya lo hacía bien; el fallo estaba solo en este lado. |
| 79 | async function borrarPartes(d, k){ |
| 80 | await d.removeEntry(k + '.done').catch(()=>{}); |
| 81 | const pref = k + '.p'; |
| 82 | try{ |
| 83 | const nombres = []; |
| 84 | for await (const n of d.keys()) if (n.startsWith(pref)) nombres.push(n); |
| 85 | for (const n of nombres) await d.removeEntry(n).catch(()=>{}); |
| 86 | }catch{ |
| 87 | // Sin iteración: por número, hasta que falten DOS seguidas (una sola |
| 88 | // ausencia puede ser el hueco de un borrado a medias). |
| 89 | for (let i = 0, huecos = 0; i < 512 && huecos < 2; i++) { |
| 90 | const ok = await d.removeEntry(pref + i).then(()=>true, ()=>false); |
| 91 | huecos = ok ? 0 : huecos + 1; |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | async function downloadToOPFS(url, onProgress){ |
| 96 | await requestPersist(); |
| 97 | const d = await dir(); const k = keyFor(url); |
| 98 | const PARTE = 1024 * 1024 * 1024; |
| 99 | // ── REANUDAR ──────────────────────────────────────────────────────────── |
| 100 | // Las partes de 1 GiB ya completadas están CERRADAS, o sea durables en |
| 101 | // disco. Al fallar se borraban todas, así que un corte al 90 % de un modelo |
| 102 | // de gigas costaba la descarga entera y el usuario lo vivía como «vuelve a |
| 103 | // descargar el modelo». Ahora se conservan y se pide sólo el resto. |
| 104 | // |
| 105 | // Se empalma sólo si el fichero de origen sigue siendo el mismo tamaño: si |
| 106 | // cambió, empalmar daría un modelo corrupto que carga y devuelve basura, que |
| 107 | // es peor que volver a bajarlo. El tamaño se lee de Content-Range, que es de |
| 108 | // las pocas cabeceras que CORS deja ver desde el navegador (el ETag no). |
| 109 | let completas = 0, totalPrevio = 0; |
| 110 | try { |
| 111 | const ph = await d.getFileHandle(k + '.parte'); |
| 112 | totalPrevio = JSON.parse(await (await ph.getFile()).text()).total || 0; |
| 113 | for (;;) { |
| 114 | const f = await (await d.getFileHandle(k + '.p' + completas)).getFile(); |
| 115 | if (f.size !== PARTE) break; // la última, a medias: no cuenta |
| 116 | completas++; |
| 117 | } |
| 118 | } catch { /* nada que reanudar */ } |
| 119 | |
| 120 | let total = 0, aceptaRangos = false; |
| 121 | try { |
| 122 | const cab = await fetch(url, { headers: { Range: 'bytes=0-0' } }); |
| 123 | aceptaRangos = cab.status === 206; |
| 124 | const cr = cab.headers.get('content-range'); |
| 125 | total = cr ? +cr.split('/')[1] : (+cab.headers.get('content-length') || 0); |
| 126 | try { await cab.arrayBuffer(); } catch {} |
| 127 | } catch {} |
| 128 | |
| 129 | const desde = completas * PARTE; |
| 130 | const reanuda = completas > 0 && aceptaRangos && total > 0 && desde < total && totalPrevio === total; |
| 131 | if (!reanuda) { await borrarPartes(d, k); completas = 0; } |
| 132 | else { |
| 133 | // La parte incompleta de la cola SÍ se tira: no se sabe cuánto de ella es |
| 134 | // bueno, y reescribirla cuesta un giga como mucho. |
| 135 | await d.removeEntry(k + '.p' + completas).catch(()=>{}); |
| 136 | await d.removeEntry(k + '.done').catch(()=>{}); |
| 137 | onProgress?.({ loaded: desde, total, reanudando: true }); |
| 138 | } |
| 139 | |
| 140 | const net = await fetch(url, reanuda ? { headers: { Range: `bytes=${desde}-` } } : undefined); |
| 141 | const okEstado = reanuda ? net.status === 206 : net.ok; |
| 142 | if (!okEstado || !net.body) throw new Error('descarga falló: HTTP ' + net.status); |
| 143 | if (!total) total = (+net.headers.get('content-length') || 0) + desde; |
| 144 | // La huella, para que el próximo intento sepa si lo guardado sirve. |
| 145 | try { const ph = await d.getFileHandle(k + '.parte', { create:true }); |
| 146 | const pw = await ph.createWritable(); |
| 147 | await pw.write(new TextEncoder().encode(JSON.stringify({ total }))); |
| 148 | await pw.close(); } catch {} |
| 149 | // TROCEADO en partes de 1 GiB. Un fichero suelto lo corta el navegador sobre |
| 150 | // los 1,94 GB —medido— pase lo que pase con la cuota, así que un modelo de |
| 151 | // 3,8 GB era IMPOSIBLE de cachear aquí y fallaba con «exceed its storage |
| 152 | // quota», que despista porque suena a falta de espacio y no lo es. |
| 153 | let nPartes = completas, enParte = 0, w = null; |
| 154 | const abrirParte = async () => { |
| 155 | const fh = await d.getFileHandle(k + '.p' + nPartes, { create:true }); |
| 156 | w = await fh.createWritable(); nPartes++; enParte = 0; |
| 157 | }; |
| 158 | let loaded = desde; const reader = net.body.getReader(); |
| 159 | try{ |
| 160 | await abrirParte(); |
| 161 | for(;;){ const { done, value } = await reader.read(); if (done) break; |
| 162 | // Un trozo de red no respeta la frontera de parte: se reparte. |
| 163 | let off = 0; |
| 164 | while (off < value.byteLength) { |
| 165 | if (enParte >= PARTE) { await w.close(); await abrirParte(); } |
| 166 | const cabe = Math.min(PARTE - enParte, value.byteLength - off); |
| 167 | await w.write(value.subarray(off, off + cabe)); |
| 168 | off += cabe; enParte += cabe; loaded += cabe; |
| 169 | } |
| 170 | onProgress?.({ loaded, total }); } |
| 171 | await w.close(); w = null; |
| 172 | }catch(e){ |
| 173 | // El motivo se GUARDA, no solo se lanza: desde fuera «no está cacheado» y |
| 174 | // «falló al cachear» se ven igual, y llevan a sitios opuestos. Nos costó |
| 175 | // media investigación no poder distinguirlos. |
| 176 | try { const eh = await d.getFileHandle('.ultimo-error', { create:true }); |
| 177 | const ew = await eh.createWritable(); |
| 178 | await ew.write(new TextEncoder().encode(String(e && e.message || e).slice(0,200))); |
| 179 | await ew.close(); } catch {} |
| 180 | // NO se borran las partes: cerrar confirma la que iba a medias y las |
| 181 | // completas ya estaban en disco. Es justo lo que permite reanudar. |
| 182 | try{ await w.close(); }catch{ try{ await w.abort(); }catch{} } throw e; } |
| 183 | await d.removeEntry(k + '.parte').catch(()=>{}); |
| 184 | const dh = await d.getFileHandle(k + '.done', { create:true }); const dw = await dh.createWritable(); |
| 185 | await dw.write(new TextEncoder().encode(JSON.stringify({ size: loaded, parts: nPartes }))); await dw.close(); |
| 186 | return await juntar(d, k, nPartes); |
| 187 | } |
| 188 | |
| 189 | let inflight = new Map(); // url → Promise<File> (colapsa descargas simultáneas) |
| 190 | async function getFile(url, onProgress){ |
| 191 | const hit = await cachedFile(url); if (hit) return hit; |
| 192 | if (inflight.has(url)) return inflight.get(url); |
| 193 | const p = downloadToOPFS(url, onProgress).finally(()=> inflight.delete(url)); |
| 194 | inflight.set(url, p); return p; |
| 195 | } |
| 196 | |
| 197 | addEventListener('message', async e => { |
| 198 | if (!allowed(e.origin)) return; |
| 199 | const d = e.data || {}; const { type, id, url } = d; |
| 200 | const post = (msg, transfer) => { try{ e.source.postMessage({ id, ...msg }, e.origin, transfer || []); }catch{} }; |
| 201 | if (e.data?.type === 'elffuss-broker-diag') { |
| 202 | // Diagnóstico: qué hay REALMENTE en MI almacén. Sin esto, «no está |
| 203 | // cacheado» y «no puedo verlo desde aquí» son indistinguibles desde |
| 204 | // fuera, y llevan a sitios opuestos. |
| 205 | let ficheros = [], est = null, err = null, escritura = null; |
| 206 | // Intento de escritura REAL: crear el fichero no demuestra nada, hay que |
| 207 | // ver si los bytes llegan. Aquí es donde se rompía en silencio. |
| 208 | try { |
| 209 | const root0 = await navigator.storage.getDirectory(); |
| 210 | const d0 = await root0.getDirectoryHandle(DIR, { create: true }); |
| 211 | // Cuánto admite DE VERDAD este contexto. La cuota anunciada miente: |
| 212 | // dice gigabytes y luego revienta mucho antes. Se escribe hasta que |
| 213 | // falla, en trozos de 64 MiB, con un tope para no tardar una eternidad. |
| 214 | const tope = (e.data.probar || 0) * 1048576; |
| 215 | if (tope) { |
| 216 | const ph = await d0.getFileHandle('.techo-test', { create: true }); |
| 217 | const pw = await ph.createWritable(); |
| 218 | const bloque = new Uint8Array(64 * 1048576); |
| 219 | let n = 0; |
| 220 | try { while (n < tope) { await pw.write(bloque); n += bloque.length; } await pw.close(); } |
| 221 | catch (x) { try { await pw.abort(); } catch {} } |
| 222 | escritura = 'techo real: ' + (n / 1048576).toFixed(0) + ' MiB de ' + (tope / 1048576) + ' intentados'; |
| 223 | await d0.removeEntry('.techo-test').catch(() => {}); |
| 224 | e.source.postMessage({ id: e.data.id, kind: 'diag', escritura, quota: (await navigator.storage.estimate()).quota }, e.origin); |
| 225 | return; |
| 226 | } |
| 227 | const fh = await d0.getFileHandle('.escritura-test', { create: true }); |
| 228 | if (typeof fh.createWritable !== 'function') escritura = 'sin createWritable en este contexto'; |
| 229 | else { |
| 230 | const w = await fh.createWritable(); |
| 231 | await w.write(new Uint8Array(1024)); |
| 232 | await w.close(); |
| 233 | escritura = 'escritos ' + (await fh.getFile()).size + ' de 1024 bytes'; |
| 234 | } |
| 235 | await d0.removeEntry('.escritura-test').catch(() => {}); |
| 236 | } catch (x) { escritura = 'ERROR: ' + String(x.message || x).slice(0, 110); } |
| 237 | try { |
| 238 | est = await navigator.storage.estimate(); |
| 239 | const root = await navigator.storage.getDirectory(); |
| 240 | const d = await root.getDirectoryHandle(DIR, { create: true }); |
| 241 | for await (const [n, h] of d.entries()) { |
| 242 | ficheros.push(n + (h.kind === 'file' ? ':' + (await h.getFile()).size : '/')); |
| 243 | } |
| 244 | } catch (x) { err = String(x.message || x).slice(0, 90); } |
| 245 | e.source.postMessage({ id: e.data.id, kind: 'diag', origen: location.origin, |
| 246 | ficheros, quota: est?.quota, usado: est?.usage, err, escritura }, e.origin); |
| 247 | return; |
| 248 | } |
| 249 | if (type === 'elffuss-model-has') { |
| 250 | const f = await cachedFile(url); post({ kind:'has', cached: !!f, size: f?f.size:0 }); return; |
| 251 | } |
| 252 | // Vaciar MI almacén. Hasta ahora no habia forma de pedirlo desde fuera, y eso |
| 253 | // hacia que el boton «vaciar cache» de las webs mintiera: borraba la cache de |
| 254 | // SU origen y dejaba aqui el modelo grande —que es el que ocupa casi todo—, |
| 255 | // asi que quien queria recuperar espacio no lo conseguia y encima no se |
| 256 | // enteraba, porque el contador de la web tampoco ve este origen. |
| 257 | // |
| 258 | // Se devuelve cuanto se ha liberado DE VERDAD, midiendo antes y despues, en |
| 259 | // vez de dar por hecho que el borrado funciono: si el navegador se niega a |
| 260 | // soltar algo, quien llama tiene que poder decirlo. |
| 261 | if (type === 'elffuss-model-clear') { |
| 262 | try { |
| 263 | const antes = (await navigator.storage.estimate()).usage || 0; |
| 264 | const root = await navigator.storage.getDirectory(); |
| 265 | // `recursive` borra el directorio entero sin tener que enumerar: los |
| 266 | // ficheros aqui se llaman por una clave derivada de la URL y troceados en |
| 267 | // partes, asi que enumerar para borrar uno a uno es justo la forma de |
| 268 | // dejarse alguna atras. |
| 269 | await root.removeEntry(DIR, { recursive: true }).catch(() => {}); |
| 270 | const despues = (await navigator.storage.estimate()).usage || 0; |
| 271 | post({ kind: 'cleared', liberado: Math.max(0, antes - despues), restante: despues }); |
| 272 | } catch (err) { post({ kind: 'error', message: String(err?.message || err) }); } |
| 273 | return; |
| 274 | } |
| 275 | if (type === 'elffuss-model-get') { |
| 276 | try{ |
| 277 | const file = await getFile(url, p => post({ kind:'progress', ...p })); |
| 278 | // El File de OPFS es un Blob respaldado en DISCO: structured-clone lo pasa |
| 279 | // POR REFERENCIA (Chromium: vive en el proceso de navegador, ref-contado, |
| 280 | // paginado a disco) → NO copia los GB a la RAM de ningún renderer. El padre |
| 281 | // lo lee perezosamente con file.stream(). Mantener este iframe vivo mientras |
| 282 | // el padre lee (el Blob vivo mantiene referenciados los datos en OPFS). |
| 283 | post({ kind:'file', file }); |
| 284 | }catch(err){ post({ kind:'error', message: String(err?.message || err) }); } |
| 285 | } |
| 286 | }); |
| 287 | // avisar a quien nos embebe que estamos listos |
| 288 | try{ parent.postMessage({ kind:'elffuss-broker-ready' }, '*'); }catch{} |
| 289 | </script> |
| 290 | </body></html> |