utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | d8fe98d222ea363cb16a90d18f57017d6de6f614ab9d8d34497134538c4b0dcd |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-09-28 19:29 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-09-28 19:29 +02:00 |
| Parents | 7962e52be63e |
10 files changed
added tests/reanuda.mjs +150 −0
| @@ -0,0 +1,150 @@ | ||
| 1 | +// ¿Se reanuda de verdad una descarga cortada, o solo lo parece? | |
| 2 | +// | |
| 3 | +// Antes, un corte borraba lo ya escrito y la vez siguiente empezaba de cero. | |
| 4 | +// Con un modelo de gigas eso convierte un tropiezo de red en media hora | |
| 5 | +// perdida, y el usuario lo vive como «vuelve a descargar el modelo». | |
| 6 | +// | |
| 7 | +// La prueba corta la descarga A PROPÓSITO a mitad y vuelve a pedirla. Lo que se | |
| 8 | +// comprueba no es que «funcione» sino las dos cosas que pueden ir mal: | |
| 9 | +// · que la segunda vez pida sólo el RESTO (si no, no hay reanudación); | |
| 10 | +// · que el fichero final sea BYTE A BYTE el original (si no, la reanudación | |
| 11 | +// ha empalmado mal y tendríamos un modelo corrupto que carga y da basura, | |
| 12 | +// que es peor que volver a bajarlo). | |
| 13 | +// | |
| 14 | +// Se usa un fichero pequeño servido en local, no el modelo de 7 GB: lo que se | |
| 15 | +// prueba es la lógica de reanudación, y para eso da igual el tamaño. | |
| 16 | +import { createServer } from 'node:http'; | |
| 17 | +import { existsSync, readFileSync, writeFileSync, mkdtempSync } from 'node:fs'; | |
| 18 | +import { join } from 'node:path'; | |
| 19 | +import { homedir, tmpdir } from 'node:os'; | |
| 20 | +import { createHash } from 'node:crypto'; | |
| 21 | + | |
| 22 | +let fails = 0; | |
| 23 | +const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; | |
| 24 | + | |
| 25 | +// ── Un servidor que habla rangos y que puede CORTAR a mitad ──────────────── | |
| 26 | +const TAM = 3 * 1024 * 1024; | |
| 27 | +const DATOS = Buffer.alloc(TAM); | |
| 28 | +for (let i = 0; i < TAM; i++) DATOS[i] = (i * 7 + 13) & 0xff; // patrón, no ceros: | |
| 29 | +// con ceros, un empalme mal hecho seguiría dando el mismo hash y pasaría. | |
| 30 | +const SHA = createHash('sha256').update(DATOS).digest('hex'); | |
| 31 | + | |
| 32 | +let cortar = false; // cuando está puesto, el servidor corta a la mitad | |
| 33 | +const peticiones = []; | |
| 34 | +const srv = createServer((req, res) => { | |
| 35 | + const rango = req.headers.range; | |
| 36 | + const m = rango && /bytes=(\d+)-/.exec(rango); | |
| 37 | + const desde = m ? +m[1] : 0; | |
| 38 | + peticiones.push({ rango: rango || null, desde }); | |
| 39 | + // El sondeo de un byte se responde BIEN aunque estemos simulando un corte: una | |
| 40 | + // red que se cae a mitad de una descarga de gigas no impide hacer una | |
| 41 | + // petición de un byte. La primera versión cortaba también el sondeo, así que | |
| 42 | + // la descarga moría a nivel de red antes de escribir nada y no había nada que | |
| 43 | + // reanudar — el banco marcaba en rojo por culpa del banco. | |
| 44 | + const sondeo = /bytes=0-0$/.test(rango || ''); | |
| 45 | + const hasta = sondeo ? 0 : TAM - 1; | |
| 46 | + const cuerpo = DATOS.subarray(desde, hasta + 1); | |
| 47 | + res.setHeader('Accept-Ranges', 'bytes'); | |
| 48 | + res.setHeader('Access-Control-Allow-Origin', '*'); | |
| 49 | + res.setHeader('Access-Control-Expose-Headers', 'Content-Range, Accept-Ranges, Content-Length'); | |
| 50 | + if (m) { | |
| 51 | + res.statusCode = 206; | |
| 52 | + res.setHeader('Content-Range', `bytes ${desde}-${hasta}/${TAM}`); | |
| 53 | + } | |
| 54 | + res.setHeader('Content-Length', String(cuerpo.length)); | |
| 55 | + if (cortar && !sondeo && cuerpo.length > 1024) { | |
| 56 | + // Se manda la mitad, se deja que LLEGUE, y entonces se corta. Destruir el | |
| 57 | + // socket en el mismo tick hacía que Chrome invalidara la respuesta entera y | |
| 58 | + // rechazara el `fetch`: no llegaba un solo byte a la aplicación, y entonces | |
| 59 | + // no hay nada que reanudar. Una red que se cae de verdad entrega lo que ya | |
| 60 | + // iba en camino y corta después; esto reproduce eso. | |
| 61 | + res.write(cuerpo.subarray(0, Math.floor(cuerpo.length / 2))); | |
| 62 | + setTimeout(() => { try { res.destroy(); } catch { /* — */ } }, 400); | |
| 63 | + return; | |
| 64 | + } | |
| 65 | + res.end(cuerpo); | |
| 66 | +}); | |
| 67 | +await new Promise(r => srv.listen(0, '127.0.0.1', r)); | |
| 68 | +const PUERTO = srv.address().port; | |
| 69 | +const BASE = `http://127.0.0.1:${PUERTO}`; | |
| 70 | + | |
| 71 | +// La página tiene que servirse por HTTP para tener OPFS: se sirve desde el | |
| 72 | +// mismo servidor una página mínima que importa el almacén de verdad. | |
| 73 | +const RAIZ = join(homedir(), 'work2026/elffuss-code/web'); | |
| 74 | +const srv2 = createServer((req, res) => { | |
| 75 | + const ruta = req.url.split('?')[0]; | |
| 76 | + if (ruta === '/') { | |
| 77 | + res.setHeader('Content-Type', 'text/html'); | |
| 78 | + return res.end('<!doctype html><meta charset=utf-8><title>reanuda</title>'); | |
| 79 | + } | |
| 80 | + const f = join(RAIZ, ruta); | |
| 81 | + if (!existsSync(f)) { res.statusCode = 404; return res.end('no'); } | |
| 82 | + res.setHeader('Content-Type', ruta.endsWith('.js') ? 'text/javascript' : 'text/plain'); | |
| 83 | + res.end(readFileSync(f)); | |
| 84 | +}); | |
| 85 | +await new Promise(r => srv2.listen(0, '127.0.0.1', r)); | |
| 86 | +const APP = `http://127.0.0.1:${srv2.address().port}`; | |
| 87 | + | |
| 88 | +const rutas = [join(homedir(), 'work2026/elffuss-claw/tests/node_modules/playwright-core/index.mjs'), | |
| 89 | + join(homedir(), '.claude/skills/browser-post/node_modules/playwright-core/index.mjs')]; | |
| 90 | +const { chromium } = await import(rutas.find(existsSync)); | |
| 91 | +const perfil = mkdtempSync(join(tmpdir(), 'reanuda-')); | |
| 92 | +const ctx = await chromium.launchPersistentContext(perfil, { | |
| 93 | + channel: 'chrome', ignoreDefaultArgs: ['--use-mock-keychain'], | |
| 94 | +}); | |
| 95 | +const p = await ctx.newPage(); | |
| 96 | +p.on('pageerror', e => console.log('· PAGEERROR: ' + e.message.slice(0, 120))); | |
| 97 | + | |
| 98 | +try { | |
| 99 | + await p.goto(APP + '/', { waitUntil: 'domcontentloaded' }); | |
| 100 | + | |
| 101 | + const baja = async (url) => p.evaluate(async (u) => { | |
| 102 | + const m = await import('/js/runtime/model-store.js'); | |
| 103 | + try { | |
| 104 | + const f = await m.getModelFile(u, () => {}); | |
| 105 | + if (!f) return { err: 'sin fichero' }; | |
| 106 | + const buf = new Uint8Array(await f.arrayBuffer()); | |
| 107 | + let h = 0; const cr = await crypto.subtle.digest('SHA-256', buf); | |
| 108 | + void h; | |
| 109 | + return { size: f.size, sha: [...new Uint8Array(cr)].map(b => b.toString(16).padStart(2, '0')).join('') }; | |
| 110 | + } catch (e) { return { err: String(e.message || e), pila: String(e.stack || '').split('\n').slice(0, 4).join(' | ') }; } | |
| 111 | + }, url); | |
| 112 | + | |
| 113 | + const url = BASE + '/modelo.bin'; | |
| 114 | + | |
| 115 | + // 1) Primer intento CORTADO a la mitad. | |
| 116 | + cortar = true; | |
| 117 | + const a = await baja(url); | |
| 118 | + ok('el primer intento falla (la red se corta)', !!a.err, (a.err || '') + ' :: ' + (a.pila || '')); | |
| 119 | + | |
| 120 | + // Qué quedó en disco tras el corte: es lo que decide si hay reanudación. | |
| 121 | + const estado = await p.evaluate(async () => { | |
| 122 | + const out = { ficheros: [] }; | |
| 123 | + try { | |
| 124 | + const root = await navigator.storage.getDirectory(); | |
| 125 | + const dir = await root.getDirectoryHandle('elffuss-models', { create: true }); | |
| 126 | + for await (const [n, h] of dir.entries()) { | |
| 127 | + const f = await h.getFile(); | |
| 128 | + out.ficheros.push({ n, size: f.size, txt: f.size < 200 ? await f.text() : '' }); | |
| 129 | + } | |
| 130 | + } catch (e) { out.err = String(e.message || e); } | |
| 131 | + return out; | |
| 132 | + }); | |
| 133 | + console.log('· en disco tras el corte: ' + (estado.err || JSON.stringify(estado.ficheros))); | |
| 134 | + | |
| 135 | + // 2) Segundo intento, servidor sano: tiene que pedir el RESTO, no todo. | |
| 136 | + cortar = false; | |
| 137 | + peticiones.length = 0; | |
| 138 | + const b = await baja(url); | |
| 139 | + const conRango = peticiones.filter(x => x.desde > 0); | |
| 140 | + ok('la segunda vez pide sólo el resto', conRango.length > 0, | |
| 141 | + peticiones.map(x => x.rango || 'sin rango').join(' · ')); | |
| 142 | + ok('el fichero queda completo', b.size === TAM, `${b.size} de ${TAM}`); | |
| 143 | + // Lo que de verdad importa: que no se haya empalmado mal. | |
| 144 | + ok('el contenido es byte a byte el original', b.sha === SHA, | |
| 145 | + b.sha ? `${b.sha.slice(0, 16)}… contra ${SHA.slice(0, 16)}…` : JSON.stringify(b)); | |
| 146 | +} finally { | |
| 147 | + await ctx.close(); srv.close(); srv2.close(); | |
| 148 | +} | |
| 149 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ REANUDA OK — un corte ya no cuesta la descarga entera'); | |
| 150 | +process.exit(fails ? 1 : 0); |
modified web/css/code.css +103 −0
| @@ -525,3 +525,106 @@ | ||
| 525 | 525 | .view-hint { color: var(--muted); font-size: .72rem; margin-left: 8px; } |
| 526 | 526 | .view-loading { display: flex; align-items: center; justify-content: center; height: 100%; color: var(--muted); font-size: .9rem; } |
| 527 | 527 | #city-canvas { width: 100%; height: 100%; display: block; } |
| 528 | + | |
| 529 | +/* ── Compositor: la caja de escribir es lo más grande de la barra ────────── | |
| 530 | + Antes era un <input> de una línea compartiendo fila con seis botones de | |
| 531 | + colores: acababa siendo una píldora estrecha con el texto recortado («Ask | |
| 532 | + Elffu»), indistinguible de sus vecinas. En un chat, el sitio donde se | |
| 533 | + escribe tiene que ser lo primero que se ve. */ | |
| 534 | +#composer { | |
| 535 | + display: flex; | |
| 536 | + flex-wrap: wrap; | |
| 537 | + gap: 8px; | |
| 538 | + align-items: center; | |
| 539 | +} | |
| 540 | +#composer #prompt { | |
| 541 | + /* Dos ids a propósito: más arriba hay un `#composer #prompt { flex: 1 }` que | |
| 542 | + gana por especificidad a un `#prompt` suelto. Se iguala en vez de usar | |
| 543 | + !important, que solo traslada la pelea al siguiente que llegue. */ | |
| 544 | + flex: 1 0 100%; | |
| 545 | + min-width: 100%; | |
| 546 | + order: -1; /* fila propia y la primera, pase lo que pase */ | |
| 547 | + min-height: 84px; | |
| 548 | + max-height: 40vh; /* crece con el texto, pero no se come el chat */ | |
| 549 | + resize: vertical; | |
| 550 | + overflow-y: auto; | |
| 551 | + padding: 14px 16px; | |
| 552 | + font: inherit; | |
| 553 | + font-size: 1rem; | |
| 554 | + line-height: 1.45; | |
| 555 | + color: var(--fg); | |
| 556 | + background: var(--bg3); | |
| 557 | + border: 1.5px solid var(--line); | |
| 558 | + border-radius: 14px; | |
| 559 | + outline: none; | |
| 560 | + transition: border-color .15s ease, box-shadow .15s ease; | |
| 561 | +} | |
| 562 | +#prompt::placeholder { color: var(--fg3, #8b8b9e); opacity: 1; } | |
| 563 | +#prompt:focus { | |
| 564 | + border-color: var(--accent2); | |
| 565 | + box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent2) 22%, transparent); | |
| 566 | +} | |
| 567 | + | |
| 568 | +/* ── Modos: un desplegable EXPLICADO ────────────────────────────────────── | |
| 569 | + «Auto», «Goal» y «Hard Work» sueltos en la barra no dicen qué hacen. Los | |
| 570 | + mismos botones siguen existiendo con los mismos ids —el JS no se entera— | |
| 571 | + pero dentro de un menú donde cada uno lleva su explicación. */ | |
| 572 | +#modos { position: relative; } | |
| 573 | +#modos-menu { | |
| 574 | + position: absolute; | |
| 575 | + bottom: calc(100% + 8px); | |
| 576 | + left: 0; | |
| 577 | + z-index: 40; | |
| 578 | + display: flex; | |
| 579 | + flex-direction: column; | |
| 580 | + gap: 4px; | |
| 581 | + min-width: 300px; | |
| 582 | + padding: 8px; | |
| 583 | + background: var(--bg2); | |
| 584 | + border: 1px solid var(--line); | |
| 585 | + border-radius: 12px; | |
| 586 | + box-shadow: 0 14px 40px rgba(0, 0, 0, .55); | |
| 587 | +} | |
| 588 | +#modos-menu[hidden] { display: none; } | |
| 589 | +/* Sin degradado. `#composer button` lo pone a todos, y en una fila de seis son | |
| 590 | + seis manchas de color compitiendo entre ellas y con el texto — y dentro de un | |
| 591 | + menú, donde lo que importa es LEER qué hace cada modo, el degradado solo | |
| 592 | + estorba. Se deja el color para el estado activo, que es cuando dice algo. */ | |
| 593 | +#modos-menu .cbtn { | |
| 594 | + background: transparent; | |
| 595 | + color: var(--fg); | |
| 596 | + border: 1px solid transparent; | |
| 597 | + display: block; | |
| 598 | + width: 100%; | |
| 599 | + /* `.cbtn` trae `height: 32px` fija, pensada para la barra. Dentro del menú | |
| 600 | + cada opción lleva su explicación debajo y tiene que CRECER: con la altura | |
| 601 | + fija el texto se salía del botón y se pisaba con el de abajo. */ | |
| 602 | + height: auto; | |
| 603 | + min-height: 0; | |
| 604 | + text-align: left; | |
| 605 | + white-space: normal; | |
| 606 | + padding: 10px 12px; | |
| 607 | + line-height: 1.35; | |
| 608 | +} | |
| 609 | +#modos-menu .modo-que { display: block; font-size: .78rem; opacity: .68; margin-top: 3px; font-weight: 400; } | |
| 610 | +#modos-menu .cbtn:hover { background: var(--bg3); border-color: var(--line); } | |
| 611 | +/* El degradado se reserva para el modo ENCENDIDO: ahí el color informa. */ | |
| 612 | +#modos-menu .cbtn.on { | |
| 613 | + background: linear-gradient(135deg, var(--accent), var(--accent2)); | |
| 614 | + color: #fff; | |
| 615 | + border-color: transparent; | |
| 616 | +} | |
| 617 | +#modos-menu .cbtn.on .modo-que { opacity: .85; } | |
| 618 | + | |
| 619 | +/* ── El chat a toda la ventana ──────────────────────────────────────────── | |
| 620 | + Mismo patrón que `hide-tree`, que ya existía. El editor no se destruye: se | |
| 621 | + le da cero de ancho, así que volver es instantáneo y no se pierde estado. */ | |
| 622 | +#btn-ancho { | |
| 623 | + position: absolute; top: 6px; right: 8px; z-index: 30; | |
| 624 | + background: transparent; border: 1px solid var(--line); color: var(--fg2, #aaa); | |
| 625 | + border-radius: 8px; padding: 2px 8px; cursor: pointer; font-size: .9rem; | |
| 626 | +} | |
| 627 | +#btn-ancho:hover { color: var(--fg); border-color: var(--accent2); } | |
| 628 | +#chat { position: relative; } | |
| 629 | +body.chat-full main { grid-template-columns: 46px 0 0 minmax(0, 1fr); } | |
| 630 | +body.chat-full #chat { border-left: none; } |
added web/img/icon-192.png +0 −0
Binary content is not shown. View the file.
added web/img/icon-512.png +0 −0
Binary content is not shown. View the file.
modified web/index.html +11 −2
| @@ -18,7 +18,10 @@ | ||
| 18 | 18 | <meta name="twitter:image" content="https://code.elffuss.utopiaia.com/og.png"> |
| 19 | 19 | <meta name="description" content="Open a local folder and code with Elffuss: a web IDE plus an AI agent that runs on your own GPU (WebGPU). Nothing leaves your machine."> |
| 20 | 20 | <link rel="icon" href="img/elffuss-code.svg"> |
| 21 | -<link rel="stylesheet" href="css/code.css"> | |
| 21 | +<link rel="manifest" href="manifest.json"> | |
| 22 | + <meta name="theme-color" content="#0e0c18"> | |
| 23 | + <link rel="apple-touch-icon" href="img/icon-192.png"> | |
| 24 | + <link rel="stylesheet" href="css/code.css"> | |
| 22 | 25 | <!-- import map: la ciudad 3D (VibeCodeViewer vendorizado en js/vcc) usa import 'three' --> |
| 23 | 26 | <script type="importmap"> |
| 24 | 27 | { "imports": { |
| @@ -115,6 +118,7 @@ | ||
| 115 | 118 | <div id="statusbar"></div> |
| 116 | 119 | </section> |
| 117 | 120 | <section id="chat"> |
| 121 | + <button type="button" id="btn-ancho" title="Ensanchar el chat a toda la ventana (vuelve a pulsar para recuperar el editor)">⇔</button> | |
| 118 | 122 | <div id="conv-tabs"></div> |
| 119 | 123 | <div id="history-panel" hidden></div> |
| 120 | 124 | <div id="chat-log"></div> |
| @@ -127,10 +131,15 @@ | ||
| 127 | 131 | <form id="composer"> |
| 128 | 132 | <button type="button" id="btn-plus" class="cbtn" title="Adjuntar archivo del proyecto (@)"></button> |
| 129 | 133 | <button type="button" id="btn-slash" class="cbtn" title="Comandos"></button> |
| 130 | - <input id="prompt" autocomplete="off" placeholder="Pídele código a Elffuss…"> | |
| 134 | + <textarea id="prompt" rows="3" autocomplete="off" placeholder="Escribe aquí lo que quieres. Enter envía · Mayús+Enter salta de línea · @ para adjuntar un archivo"></textarea> | |
| 135 | + <div id="modos"> | |
| 136 | + <button type="button" id="btn-modos" class="cbtn" title="Modos de trabajo">⚙︎ Modos ▾</button> | |
| 137 | + <div id="modos-menu" hidden> | |
| 131 | 138 | <button type="button" id="btn-autoedit" class="cbtn autoedit on" title="Editar archivos automáticamente"><span class="ae-ico"></></span> <span class="ae-txt">Auto</span></button> |
| 132 | 139 | <button type="button" id="btn-goal" class="cbtn goal" title="Modo Objetivo: descompone el mensaje en tareas y las ejecuta una a una (planificador + ejecutor)">🎯 <span class="goal-txt">Goal</span></button> |
| 133 | 140 | <button type="button" id="btn-hardwork" class="cbtn hardwork" title="Hard Work (RLM): lee tu proyecto ENTERO por partes — audita, resume o busca en código que no cabe en el modelo. Tarda, pero lo abarca todo.">⛏ <span class="hw-txt">Hard Work</span></button> |
| 141 | + </div> | |
| 142 | + </div> | |
| 134 | 143 | <button type="submit" id="btn-send" title="Enviar"></button> |
| 135 | 144 | </form> |
| 136 | 145 | </div> |
modified web/js/i18n.js +9 −6
| @@ -5,11 +5,11 @@ | ||
| 5 | 5 | // usuarios españoles — con inglés de fallback. Sustitución simple {var}. |
| 6 | 6 | const L = { |
| 7 | 7 | es: { |
| 8 | - ph: 'Pídele código a Elffuss…', | |
| 8 | + ph: 'Escribe aquí… (@ adjunta un archivo)', | |
| 9 | 9 | thinking: 'Elffuss está pensando', writing: 'Elffuss escribe · {n} car.', using: 'Elffuss usa {name}', |
| 10 | 10 | modelLoading: 'Descargando el modelo IA · {pct}% · {loaded}/{total} MB', |
| 11 | - modelReady: 'Modelo IA listo', modelReadyBadge: 'Modelo IA listo · готово ✳', | |
| 12 | - welcome: 'Привіт 👋 Proyecto «{name}» abierto. Pregúntame por el código, pídeme cambios o dime «árbol». Todo se queda en tu máquina.', | |
| 11 | + modelReady: 'Modelo IA listo', modelReadyBadge: 'Modelo IA listo ✳', | |
| 12 | + welcome: '👋 Proyecto «{name}» abierto. Pregúntame por el código, pídeme cambios o dime «árbol». Todo se queda en tu máquina.', | |
| 13 | 13 | mindTitle: 'MENTE DE ELFFUSS', avatarTitle: 'Mente de Elffuss — cerebro autónomo', |
| 14 | 14 | // landing (estático) + tooltips de la barra/toolbar |
| 15 | 15 | tagline: 'Abre tu carpeta de código y programa con una elfa al lado.', |
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | tTermClose: 'cerrar (Ctrl+`)', tTermResize: 'arrastra para redimensionar', |
| 24 | 24 | tCtx: 'contexto acumulado en la conversación', tPlus: 'Adjuntar archivo del proyecto (@)', |
| 25 | 25 | tAutoedit: 'Editar archivos automáticamente', |
| 26 | + tHardwork: 'Hard Work: lee tu proyecto entero por partes — audita, resume o busca en código que no cabe en el modelo', | |
| 26 | 27 | tGoal: 'Modo Objetivo: descompone el mensaje en tareas y las ejecuta una a una (planificador + ejecutor)', |
| 27 | 28 | tFlip: 'cambiar entre chat y editor', tSlash: 'Comandos', |
| 28 | 29 | // pass-3: chrome profundo del IDE (paleta, menús, historial, ajustes, notifs) |
| @@ -118,11 +119,11 @@ | ||
| 118 | 119 | setModelRulesName: "Básico (sin modelo)", |
| 119 | 120 | }, |
| 120 | 121 | en: { |
| 121 | - ph: 'Ask Elffuss for code…', | |
| 122 | + ph: 'Type here… (@ attaches a file)', | |
| 122 | 123 | thinking: 'Elffuss is thinking', writing: 'Elffuss writes · {n} chars', using: 'Elffuss uses {name}', |
| 123 | 124 | modelLoading: 'Downloading AI model · {pct}% · {loaded}/{total} MB', |
| 124 | - modelReady: 'AI model ready', modelReadyBadge: 'AI model ready · готово ✳', | |
| 125 | - welcome: 'Привіт 👋 Project “{name}” open. Ask me about the code, request changes, or say “tree”. Everything stays on your machine.', | |
| 125 | + modelReady: 'AI model ready', modelReadyBadge: 'AI model ready ✳', | |
| 126 | + welcome: '👋 Project “{name}” open. Ask me about the code, request changes, or say “tree”. Everything stays on your machine.', | |
| 126 | 127 | mindTitle: 'ELFFUSS MIND', avatarTitle: 'Elffuss Mind — autonomous brain', |
| 127 | 128 | tagline: 'Open your code folder and program with an elf by your side.', |
| 128 | 129 | tagline2: 'VS Code–style editor + agent <b>in your browser</b>. Nothing leaves your machine. 😉', |
| @@ -135,6 +136,7 @@ | ||
| 135 | 136 | tTermClose: 'close (Ctrl+`)', tTermResize: 'drag to resize', |
| 136 | 137 | tCtx: 'context accumulated in the conversation', tPlus: 'Attach a project file (@)', |
| 137 | 138 | tAutoedit: 'Edit files automatically', |
| 139 | + tHardwork: 'Hard Work: reads your whole project in chunks — audits, summarises or searches code that does not fit in the model', | |
| 138 | 140 | tGoal: 'Goal mode: breaks the message into tasks and runs them one by one (planner + executor)', |
| 139 | 141 | tFlip: 'switch between chat and editor', tSlash: 'Commands', |
| 140 | 142 | tabClose: 'Close tab (doesn’t delete the conversation)', newConv: 'New conversation', |
| @@ -262,6 +264,7 @@ | ||
| 262 | 264 | '#git-branch': 'tGitBranch', '#btn-history': 'tHistory', '#btn-settings': 'tTopSettings', |
| 263 | 265 | '#term-close': 'tTermClose', '#term-resize': 'tTermResize', '#ctx-meter': 'tCtx', |
| 264 | 266 | '#btn-plus': 'tPlus', '#btn-autoedit': 'tAutoedit', '#btn-goal': 'tGoal', |
| 267 | + '#btn-hardwork': 'tHardwork', | |
| 265 | 268 | '#code-flip': 'tFlip', '#btn-slash': 'tSlash', |
| 266 | 269 | }; |
| 267 | 270 | for (const [sel, key] of Object.entries(titles)) set(sel, 'title', key); |
modified web/js/main.js +171 −13
| @@ -428,7 +428,13 @@ | ||
| 428 | 428 | } catch { return (MODEL27_READY = false); } |
| 429 | 429 | })(); |
| 430 | 430 | |
| 431 | -function modelOptions() { | |
| 431 | +// Los modelos LOCALES, en un solo sitio. Los usan el desplegable y las tarjetas | |
| 432 | +// de los ajustes: hasta ahora eran dos listas escritas a mano y la de ajustes se | |
| 433 | +// quedó vieja — no ofrecía NI el motor propio ni el 27B, así que desde ahí era | |
| 434 | +// imposible elegir Bonsai por mucho que el motor lo sirviera. Es justo el modo | |
| 435 | +// de fallo que avisa el comentario de `modelo27Check`: un nombre duplicado es un | |
| 436 | +// nombre que se queda viejo. | |
| 437 | +function modelOptionsLocales() { | |
| 432 | 438 | const opts = []; |
| 433 | 439 | if (realGPU) opts.push({ id: 'litert:gemma-e4b', label: 'Gemma-4 E4B · LiteRT-LM (~4 GB) ★' }); |
| 434 | 440 | if (realGPU) opts.push({ id: 'litert:gemma-e2b', label: 'Gemma-4 E2B · LiteRT-LM (~2 GB)' }); |
| @@ -441,7 +447,11 @@ | ||
| 441 | 447 | // cae entera antes de la primera palabra. |
| 442 | 448 | if (realGPU && ENGINE_READY && MODEL27_READY) opts.push({ id: 'engine:qwen38-27b', label: `${MODEL27_LABEL} · Elffuss Engine (${MODEL27_GB.toFixed(1)} GB, se guarda: solo se baja la primera vez) — lento`, group: '⚠ Avanzado' }); |
| 443 | 449 | opts.push({ id: 'rules', label: t('setModelRulesName') }); |
| 444 | - return [...opts, ...settings.enabledExternals()]; | |
| 450 | + return opts; | |
| 451 | +} | |
| 452 | + | |
| 453 | +function modelOptions() { | |
| 454 | + return [...modelOptionsLocales(), ...settings.enabledExternals()]; | |
| 445 | 455 | } |
| 446 | 456 | |
| 447 | 457 | function rebuildSelect() { |
| @@ -507,6 +517,11 @@ | ||
| 507 | 517 | } |
| 508 | 518 | }); |
| 509 | 519 | conv.setProvider(mod); |
| 520 | + // El medidor de contexto pasa a hablar del modelo QUE ESTÁ CARGADO. Quien no | |
| 521 | + // sepa decir su contexto deja el valor de reserva, así que esto no puede | |
| 522 | + // romper a un proveedor que no lo implemente. | |
| 523 | + try { if (typeof mod.contextTokens === 'function') setCtxBudget(mod.contextTokens()); } | |
| 524 | + catch { /* el medidor no vale un fallo de carga */ } | |
| 510 | 525 | activeModel = id; |
| 511 | 526 | localStorage.setItem('elffusscode.model', id); |
| 512 | 527 | $('model-dot').className = 'dot on'; |
| @@ -637,13 +652,24 @@ | ||
| 637 | 652 | |
| 638 | 653 | // --- Cerebro (modelo) --- |
| 639 | 654 | box.append(el('div', 'sk-h', t("setBrainTitle"))); |
| 640 | - const LOCAL = [ | |
| 641 | - { id: 'litert:gemma-e4b', name: 'Gemma-4 E4B ★', sub: t("setModelE4bSub"), need: 'gpu' }, | |
| 642 | - { id: 'litert:gemma-e2b', name: 'Gemma-4 E2B', sub: t("setModelE2bSub"), need: 'gpu' }, | |
| 643 | - { id: 'onnx', name: 'Elffuss LM (healed)', sub: t("setModelOnnxSub") }, | |
| 644 | - { id: 'onnx:qwen3.5-0.8b', name: 'Qwen3.5-0.8B', sub: 'Qwen en el navegador vía WebGPU · ~600 MB · con «thinking»' }, | |
| 645 | - { id: 'rules', name: t('setModelRulesName'), sub: t("setModelRulesSub") }, | |
| 646 | - ]; | |
| 655 | + // De `modelOptionsLocales()`, no de una copia: así lo que se puede elegir aquí | |
| 656 | + // es exactamente lo que se puede elegir en el desplegable, hoy y cuando se | |
| 657 | + // añada el siguiente modelo. El texto de debajo sigue siendo a medida cuando | |
| 658 | + // lo hay; si no, se saca de la propia etiqueta. | |
| 659 | + const SUBS = { | |
| 660 | + 'litert:gemma-e4b': t("setModelE4bSub"), | |
| 661 | + 'litert:gemma-e2b': t("setModelE2bSub"), | |
| 662 | + 'onnx': t("setModelOnnxSub"), | |
| 663 | + 'rules': t("setModelRulesSub"), | |
| 664 | + }; | |
| 665 | + const LOCAL = modelOptionsLocales().map((o) => { | |
| 666 | + const partes = String(o.label).split(' · '); | |
| 667 | + return { | |
| 668 | + id: o.id, | |
| 669 | + name: partes[0].trim(), | |
| 670 | + sub: SUBS[o.id] || partes.slice(1).join(' · ').trim(), | |
| 671 | + }; | |
| 672 | + }); | |
| 647 | 673 | const grid = el('div', 'model-grid'); |
| 648 | 674 | for (const m of LOCAL) { |
| 649 | 675 | if (m.need === 'gpu' && !realGPU) continue; |
| @@ -1335,11 +1361,24 @@ | ||
| 1335 | 1361 | // ---------- composer estilo plugin: +, /, medidor de contexto, Auto ---------- |
| 1336 | 1362 | |
| 1337 | 1363 | // medidor de contexto: chars del historial / presupuesto (~4 chars/token) |
| 1338 | -// Al máximo del modelo de serie: LFM2.5-1.2B soporta 32K nativo; reservamos | |
| 1339 | -// ~2K de sistema + 2K de generación → 28K para historial. | |
| 1340 | -const CTX_BUDGET_TOK = 28000; | |
| 1364 | +// | |
| 1365 | +// El presupuesto se le PREGUNTA al proveedor cargado, no se escribe aquí. Era un | |
| 1366 | +// 28.000 fijo, calculado para el LFM2.5 de serie, y enseñaba «ctx 0 / 28k» con | |
| 1367 | +// cualquier modelo: con el motor propio a 65.536 mentía por más del doble, y al | |
| 1368 | +// revés con uno pequeño habría dicho que cabe lo que no cabe. Un número escrito | |
| 1369 | +// a mano en la interfaz es un número que se queda viejo — el mismo fallo que la | |
| 1370 | +// lista de modelos de los ajustes. | |
| 1371 | +const CTX_BUDGET_FALLBACK = 28000; // solo si el proveedor no sabe decirlo | |
| 1372 | +let ctxBudgetTok = CTX_BUDGET_FALLBACK; | |
| 1373 | +export function setCtxBudget(tokens) { | |
| 1374 | + // Se reserva sitio para el prompt de sistema y para la respuesta: el techo del | |
| 1375 | + // modelo NO es lo que cabe de conversación. | |
| 1376 | + const RESERVA = 4000; | |
| 1377 | + if (Number.isFinite(tokens) && tokens > RESERVA) ctxBudgetTok = tokens - RESERVA; | |
| 1378 | +} | |
| 1341 | 1379 | function updateCtxMeter() { |
| 1342 | 1380 | if (!$('ctx-text')) return; // aún en la landing |
| 1381 | + const CTX_BUDGET_TOK = ctxBudgetTok; | |
| 1343 | 1382 | const chars = (conv.getActive()?.agent.history || []).reduce((s, m) => s + (m.content || '').length, 0); |
| 1344 | 1383 | const tok = Math.round(chars / 4); |
| 1345 | 1384 | const pct = Math.min(100, Math.round(tok / CTX_BUDGET_TOK * 100)); |
| @@ -1383,7 +1422,10 @@ | ||
| 1383 | 1422 | ])); |
| 1384 | 1423 | |
| 1385 | 1424 | // [+] adjuntar archivo del proyecto como @ruta |
| 1386 | -$('btn-plus').addEventListener('click', async () => { | |
| 1425 | +// El menú de ficheros, en una función: lo abren el botón `+` Y escribir `@` en | |
| 1426 | +// la conversación, que es lo natural y lo que ya prometía el título del botón | |
| 1427 | +// («Adjuntar archivo del proyecto (@)») sin que nada lo implementara. | |
| 1428 | +async function abreMenuFicheros() { | |
| 1387 | 1429 | let tree = ''; |
| 1388 | 1430 | try { tree = await codeTools.tree({ depth: 3 }); } catch { /* sin proyecto */ } |
| 1389 | 1431 | const files = tree.split('\n').filter(l => l.trim() && !l.includes('📁')).map(l => l.trim()).slice(0, 40); |
| @@ -1393,7 +1435,21 @@ | ||
| 1393 | 1435 | for (const f of files.filter(f => f !== currentFile).slice(0, 20)) |
| 1394 | 1436 | items.push({ label: '@' + f, run: () => attach(f) }); |
| 1395 | 1437 | openMenu(items.length > 1 ? items : [{ sep: t('openProjFirst') }]); |
| 1438 | +} | |
| 1439 | +$('btn-plus').addEventListener('click', abreMenuFicheros); | |
| 1440 | + | |
| 1441 | +// Escribir `@` abre la lista de ficheros. Se mira el carácter ANTERIOR al | |
| 1442 | +// cursor: así `correo@dominio` no dispara el menú a media palabra, y `@` al | |
| 1443 | +// principio o tras un espacio sí. La condición es sobre lo que el usuario | |
| 1444 | +// acaba de teclear, no sobre el valor entero, para no reabrirlo cada vez que | |
| 1445 | +// toca una tecla con un `@` ya escrito antes. | |
| 1446 | +$('prompt').addEventListener('input', (e) => { | |
| 1447 | + if (e.inputType !== 'insertText' || e.data !== '@') return; | |
| 1448 | + const v = e.target.value, i = e.target.selectionStart - 1; | |
| 1449 | + const previo = i > 0 ? v[i - 1] : ''; | |
| 1450 | + if (previo === '' || /\s/.test(previo)) abreMenuFicheros(); | |
| 1396 | 1451 | }); |
| 1452 | + | |
| 1397 | 1453 | function attach(path) { |
| 1398 | 1454 | const p = $('prompt'); |
| 1399 | 1455 | p.value = (p.value + ' @' + path).trim() + ' '; |
| @@ -1806,3 +1862,105 @@ | ||
| 1806 | 1862 | setInterval(paint, 20000); |
| 1807 | 1863 | } |
| 1808 | 1864 | mountDiskChip(); |
| 1865 | + | |
| 1866 | +// ── Compositor: menú de modos, ancho del chat y caja que crece ────────────── | |
| 1867 | +// Los tres botones de modo siguen siendo los mismos elementos con los mismos | |
| 1868 | +// ids: lo único que cambia es que viven dentro de un desplegable. Así el JS que | |
| 1869 | +// ya los escuchaba no se entera de nada. | |
| 1870 | +{ | |
| 1871 | + const modos = $('btn-modos'), menu = $('modos-menu'); | |
| 1872 | + if (modos && menu) { | |
| 1873 | + // Cada modo lleva DEBAJO lo que hace. El texto sale del `title` que ya | |
| 1874 | + // tenía el botón: estaba escrito y bien, pero solo lo veía quien dejara el | |
| 1875 | + // ratón quieto encima — o sea casi nadie, y en móvil nadie. «Auto», «Goal» | |
| 1876 | + // y «Hard Work» sueltos no dicen nada a quien llega nuevo. | |
| 1877 | + for (const b of menu.querySelectorAll('.cbtn')) { | |
| 1878 | + const que = b.getAttribute('title'); | |
| 1879 | + if (!que || b.querySelector('.modo-que')) continue; | |
| 1880 | + const span = document.createElement('span'); | |
| 1881 | + span.className = 'modo-que'; | |
| 1882 | + // Cortar por el primer paréntesis dejaba «Hard Work (RLM): lee tu | |
| 1883 | + // proyecto…» en «Hard Work», o sea una explicación que repite el nombre | |
| 1884 | + // del botón y no explica nada. Lo que sobra es el PREFIJO —«Nombre | |
| 1885 | + // (SIGLAS):»— no lo que viene detrás, que es justo la frase útil. | |
| 1886 | + span.textContent = que | |
| 1887 | + .replace(/^[^:]{0,40}:\s*/, '') // fuera «Hard Work (RLM): » | |
| 1888 | + .split('.')[0] // la primera frase | |
| 1889 | + .replace(/\s*\([^)]*\)\s*/g, ' ') // sin incisos entre paréntesis | |
| 1890 | + .replace(/\s+/g, ' ') | |
| 1891 | + .trim() | |
| 1892 | + .slice(0, 120); | |
| 1893 | + b.appendChild(span); | |
| 1894 | + // Ya está a la vista: dejar el title duplicaría el texto en un tooltip. | |
| 1895 | + b.removeAttribute('title'); | |
| 1896 | + } | |
| 1897 | + modos.addEventListener('click', (e) => { e.stopPropagation(); menu.hidden = !menu.hidden; }); | |
| 1898 | + // Cerrar al elegir y al pulsar fuera. Sin lo segundo, el menú se queda | |
| 1899 | + // abierto tapando la conversación y hay que adivinar cómo cerrarlo. | |
| 1900 | + menu.addEventListener('click', () => { menu.hidden = true; }); | |
| 1901 | + document.addEventListener('click', (e) => { | |
| 1902 | + if (!e.target.closest('#modos')) menu.hidden = true; | |
| 1903 | + }); | |
| 1904 | + } | |
| 1905 | + | |
| 1906 | + // El chat a toda la ventana. Al editor se le da cero de ancho en vez de | |
| 1907 | + // quitarlo: volver es instantáneo y no se pierde lo que hubiera abierto. | |
| 1908 | + const ancho = $('btn-ancho'); | |
| 1909 | + if (ancho) { | |
| 1910 | + const pinta = () => { | |
| 1911 | + const full = document.body.classList.contains('chat-full'); | |
| 1912 | + ancho.textContent = full ? '⇥' : '⇔'; | |
| 1913 | + ancho.title = full ? 'Recuperar el editor' : 'Ensanchar el chat a toda la ventana'; | |
| 1914 | + }; | |
| 1915 | + try { if (localStorage.getItem('elffusscode.chatfull') === '1') document.body.classList.add('chat-full'); } | |
| 1916 | + catch { /* sin localStorage se queda como está */ } | |
| 1917 | + pinta(); | |
| 1918 | + ancho.addEventListener('click', () => { | |
| 1919 | + document.body.classList.toggle('chat-full'); | |
| 1920 | + try { localStorage.setItem('elffusscode.chatfull', document.body.classList.contains('chat-full') ? '1' : '0'); } | |
| 1921 | + catch { /* — */ } | |
| 1922 | + pinta(); | |
| 1923 | + }); | |
| 1924 | + } | |
| 1925 | + | |
| 1926 | + // La caja crece con el texto hasta el tope que pone el CSS. Se recalcula | |
| 1927 | + // desde cero (`auto`) antes de medir: si no, una vez crecida ya no encoge al | |
| 1928 | + // borrar, y acaba ocupando media pantalla vacía. | |
| 1929 | + const caja = $('prompt'); | |
| 1930 | + if (caja && caja.tagName === 'TEXTAREA') { | |
| 1931 | + const crece = () => { | |
| 1932 | + caja.style.height = 'auto'; | |
| 1933 | + caja.style.height = Math.min(caja.scrollHeight, window.innerHeight * 0.4) + 'px'; | |
| 1934 | + }; | |
| 1935 | + caja.addEventListener('input', crece); | |
| 1936 | + // Al enviar, el valor se vacía desde fuera y no salta `input`: sin esto la | |
| 1937 | + // caja se queda alta y vacía después de cada mensaje. | |
| 1938 | + new MutationObserver(crece).observe(caja, { attributes: true, attributeFilter: ['value'] }); | |
| 1939 | + $('composer')?.addEventListener('submit', () => setTimeout(crece, 0)); | |
| 1940 | + } | |
| 1941 | +} | |
| 1942 | + | |
| 1943 | +// ── Instalable: es lo único que consigue almacenamiento persistente ───────── | |
| 1944 | +// Medido en este proyecto: `navigator.storage.persist()` devuelve false en un | |
| 1945 | +// perfil normal, así que Chrome puede desalojar los gigas del modelo cuando le | |
| 1946 | +// falte disco — y lo hizo. Chrome concede la persistencia a los sitios | |
| 1947 | +// instalados, y solo ofrece instalar si hay manifiesto Y un service worker con | |
| 1948 | +// manejador de `fetch`. De ahí `sw.js`, que no cachea nada a propósito. | |
| 1949 | +// | |
| 1950 | +// El registro va tras `load` para no competir con la carga del modelo, que es | |
| 1951 | +// lo que el usuario está esperando de verdad. | |
| 1952 | +if ('serviceWorker' in navigator) { | |
| 1953 | + addEventListener('load', () => { | |
| 1954 | + navigator.serviceWorker.register('sw.js').then(async () => { | |
| 1955 | + // Se vuelve a pedir la persistencia DESPUÉS de registrar: si el usuario ya | |
| 1956 | + // tenía el sitio instalado de una visita anterior, aquí es donde se | |
| 1957 | + // concede, y sin pedirla otra vez nadie se enteraría. | |
| 1958 | + try { | |
| 1959 | + if (navigator.storage?.persist && !(await navigator.storage.persisted())) { | |
| 1960 | + const ok = await navigator.storage.persist(); | |
| 1961 | + console.log('[elffuss] almacenamiento persistente: ' + (ok ? 'concedido' : 'denegado — instala la app para que el navegador no borre el modelo')); | |
| 1962 | + } | |
| 1963 | + } catch { /* el diagnóstico no vale un error */ } | |
| 1964 | + }).catch(e => console.warn('[elffuss] service worker no registrado: ' + e.message)); | |
| 1965 | + }); | |
| 1966 | +} |
modified web/js/runtime/model-store.js +90 −10
| @@ -83,32 +83,112 @@ | ||
| 83 | 83 | |
| 84 | 84 | if (!(await opfsWritableSupported(dir))) return null; // iOS main-thread: que decida el llamador |
| 85 | 85 | |
| 86 | - // descargar → OPFS por chunks (no en RAM) | |
| 87 | - const net = await fetch(url); | |
| 88 | - if (!net.ok || !net.body) throw new Error('descarga del modelo falló: HTTP ' + net.status); | |
| 89 | - const total = +net.headers.get('content-length') || 0; | |
| 90 | - | |
| 91 | - // limpiar restos de un intento previo cortado | |
| 86 | + // ── Descarga REANUDABLE ──────────────────────────────────────────────── | |
| 87 | + // Antes, un corte borraba lo bajado y la vez siguiente empezaba de cero. Con | |
| 88 | + // un modelo de gigas eso convierte un tropiezo de red —o que el equipo se | |
| 89 | + // duerma— en media hora perdida, y el usuario lo vive como «vuelve a | |
| 90 | + // descargar el modelo». Ahora lo ya escrito se conserva y se pide el resto | |
| 91 | + // con `Range`. | |
| 92 | + // | |
| 93 | + // El peligro de reanudar es empalmar dos ficheros DISTINTOS si el de origen | |
| 94 | + // cambió: saldría un modelo corrupto que carga y devuelve basura, que es | |
| 95 | + // peor que volver a bajarlo. Por eso se guarda la huella del origen (ETag o | |
| 96 | + // Last-Modified) junto a los bytes, y si no coincide se empieza de nuevo. | |
| 97 | + const parteName = key + '.parte'; // huella del intento | |
| 98 | + let ya = 0, huellaPrevia = null; | |
| 99 | + try { | |
| 100 | + huellaPrevia = JSON.parse(await (await (await dir.getFileHandle(parteName)).getFile()).text()); | |
| 101 | + ya = (await (await dir.getFileHandle(key)).getFile()).size; | |
| 102 | + } catch { ya = 0; huellaPrevia = null; } | |
| 103 | + | |
| 104 | + // Se pregunta primero POR LA CABECERA qué hay al otro lado: es una petición | |
| 105 | + // de un byte, y decide si lo que tenemos sirve. | |
| 106 | + let huella = null, total = 0, aceptaRangos = false; | |
| 107 | + try { | |
| 108 | + const cab = await fetch(url, { headers: { Range: 'bytes=0-0' } }); | |
| 109 | + aceptaRangos = cab.status === 206; | |
| 110 | + huella = cab.headers.get('etag') || cab.headers.get('last-modified') || null; | |
| 111 | + const cr = cab.headers.get('content-range'); | |
| 112 | + total = cr ? +cr.split('/')[1] : (+cab.headers.get('content-length') || 0); | |
| 113 | + try { await cab.arrayBuffer(); } catch { /* — */ } | |
| 114 | + } catch { /* sin cabecera: se baja entero */ } | |
| 115 | + | |
| 116 | + // La huella preferida es el ETag, pero CORS solo expone Content-Range, | |
| 117 | + // Accept-Ranges y Content-Length: desde el navegador `etag` sale NULL y una | |
| 118 | + // reanudación que dependiera de él no se activaría jamás. Se cae al TAMAÑO | |
| 119 | + // TOTAL, que Content-Range sí deja leer y que el registro del motor fija al | |
| 120 | + // byte — si el fichero de origen cambiara, cambiaría de tamaño y la | |
| 121 | + // reanudación se descarta sola. Es más débil que un ETag y suficiente aquí. | |
| 122 | + const mismaHuella = huellaPrevia && ( | |
| 123 | + (huella && huellaPrevia.huella === huella) || | |
| 124 | + (!huella && !huellaPrevia.huella && huellaPrevia.total === total)); | |
| 125 | + const puedeReanudar = ya > 0 && aceptaRangos && total > 0 && ya < total && mismaHuella; | |
| 126 | + if (ya > 0 && !puedeReanudar) { | |
| 127 | + // Lo guardado no sirve (otro fichero, o el servidor no da rangos). | |
| 128 | + await dir.removeEntry(key).catch(() => {}); | |
| 129 | + ya = 0; | |
| 130 | + } | |
| 131 | + | |
| 132 | + const net = await fetch(url, puedeReanudar ? { headers: { Range: `bytes=${ya}-` } } : undefined); | |
| 133 | + const okEstado = puedeReanudar ? net.status === 206 : net.ok; | |
| 134 | + if (!okEstado || !net.body) throw new Error('descarga del modelo falló: HTTP ' + net.status); | |
| 135 | + if (!total) total = (+net.headers.get('content-length') || 0) + ya; | |
| 136 | + | |
| 92 | 137 | await dir.removeEntry(doneName).catch(() => {}); |
| 93 | 138 | const fh = await dir.getFileHandle(key, { create: true }); |
| 94 | - const writable = await fh.createWritable(); // stream a disco | |
| 139 | + // `keepExistingData` conserva lo ya escrito; sin él, createWritable() TRUNCA | |
| 140 | + // el fichero a cero y la reanudación sería una forma cara de empezar de nuevo. | |
| 141 | + // Se confirma POR TRAMOS. `createWritable()` es atómico: lo escrito no existe | |
| 142 | + // en el fichero hasta el `close()`, así que un corte tira TODO aunque nadie | |
| 143 | + // borre nada — que es exactamente lo que medía el banco de reanudación | |
| 144 | + // fallando. Cerrando y reabriendo cada tramo, lo confirmado sobrevive al | |
| 145 | + // corte y la próxima vez se continúa desde ahí. | |
| 146 | + // Proporcional al fichero, no fijo: con un tramo de 64 MB un fichero de 3 MB | |
| 147 | + // no llegaba a confirmar NUNCA y la reanudación no existía para él —lo | |
| 148 | + // destapó el banco, que usa un fichero pequeño a propósito—. Así se confirma | |
| 149 | + // una quincena de veces sea cual sea el tamaño, con suelo para no castigar a | |
| 150 | + // los diminutos y techo para no confirmar cada dos por tres en los de gigas. | |
| 151 | + const TRAMO = Math.max(512 * 1024, Math.min(64 * 1024 * 1024, Math.floor((total || 0) / 16) || (64 * 1024 * 1024))); | |
| 152 | + const anota = async () => { | |
| 153 | + try { | |
| 154 | + const ph = await dir.getFileHandle(parteName, { create: true }); | |
| 155 | + const pw = await ph.createWritable(); | |
| 156 | + await pw.write(new TextEncoder().encode(JSON.stringify({ huella, total }))); | |
| 157 | + await pw.close(); | |
| 158 | + } catch { /* sin anotación se pierde la reanudación, no los datos */ } | |
| 159 | + }; | |
| 160 | + let writable = await fh.createWritable({ keepExistingData: puedeReanudar }); | |
| 161 | + if (puedeReanudar) await writable.seek(ya); | |
| 95 | 162 | const t0 = performance.now(); |
| 96 | - let loaded = 0; | |
| 163 | + let loaded = ya; | |
| 164 | + if (puedeReanudar) onProgress(`Reanudando la descarga desde ${(ya / 1e9).toFixed(1)} GB…`); | |
| 165 | + await anota(); | |
| 97 | 166 | try { |
| 98 | 167 | const reader = net.body.getReader(); |
| 168 | + let enTramo = 0; | |
| 99 | 169 | for (;;) { |
| 100 | 170 | const { done, value } = await reader.read(); |
| 101 | 171 | if (done) break; |
| 102 | 172 | await writable.write(value); |
| 103 | 173 | loaded += value.byteLength; |
| 174 | + enTramo += value.byteLength; | |
| 175 | + if (enTramo >= TRAMO) { | |
| 176 | + enTramo = 0; | |
| 177 | + await writable.close(); // confirma lo del tramo | |
| 178 | + writable = await fh.createWritable({ keepExistingData: true }); | |
| 179 | + await writable.seek(loaded); | |
| 180 | + } | |
| 104 | 181 | onProgress(fmt(loaded, total, t0)); |
| 105 | 182 | } |
| 106 | 183 | await writable.close(); |
| 107 | 184 | } catch (e) { |
| 108 | - try { await writable.abort(); } catch { /* — */ } | |
| 109 | - await dir.removeEntry(key).catch(() => {}); // no dejar basura a medias | |
| 185 | + // Se cierra para CONFIRMAR lo del tramo en curso. `abort()` lo descartaría, | |
| 186 | + // que es justo lo contrario de lo que se quiere al reanudar. | |
| 187 | + try { await writable.close(); } catch { /* lo confirmado en tramos ya está */ } | |
| 110 | 188 | throw e; |
| 111 | 189 | } |
| 190 | + // Completado: fuera la marca de intento a medias. | |
| 191 | + await dir.removeEntry(parteName).catch(() => {}); | |
| 112 | 192 | |
| 113 | 193 | // marcar completado (con el tamaño esperado, para validar en el futuro) |
| 114 | 194 | const dh = await dir.getFileHandle(doneName, { create: true }); |
added web/manifest.json +15 −0
| @@ -0,0 +1,15 @@ | ||
| 1 | +{ | |
| 2 | + "name": "Elffuss Code", | |
| 3 | + "short_name": "Elffuss Code", | |
| 4 | + "description": "Editor de código con un modelo de IA que corre entero en tu navegador. Nada sale de tu máquina.", | |
| 5 | + "start_url": "/", | |
| 6 | + "scope": "/", | |
| 7 | + "display": "standalone", | |
| 8 | + "background_color": "#0e0c18", | |
| 9 | + "theme_color": "#0e0c18", | |
| 10 | + "icons": [ | |
| 11 | + { "src": "img/icon-192.png", "sizes": "192x192", "type": "image/png" }, | |
| 12 | + { "src": "img/icon-512.png", "sizes": "512x512", "type": "image/png" }, | |
| 13 | + { "src": "img/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" } | |
| 14 | + ] | |
| 15 | +} |
modified web/sw.js +13 −0
| @@ -41,3 +41,16 @@ | ||
| 41 | 41 | } |
| 42 | 42 | })()); |
| 43 | 43 | }); |
| 44 | + | |
| 45 | +// ── Manejador de `fetch`, añadido para poder INSTALAR el sitio ────────────── | |
| 46 | +// Chrome solo ofrece instalar si hay manifiesto Y un service worker con | |
| 47 | +// manejador de `fetch`. Y la instalación no es cosmética: es lo único que | |
| 48 | +// consigue que conceda almacenamiento PERSISTENTE —medido: sin ella | |
| 49 | +// `navigator.storage.persist()` devuelve false— y sin persistencia el navegador | |
| 50 | +// desaloja los gigas del modelo cuando le falta disco, que es lo que pasó. | |
| 51 | +// | |
| 52 | +// NO intercepta: no llama a `respondWith`, así que cada petición sigue su curso | |
| 53 | +// normal por la red. Eso importa aquí más que en otros sitios — la cabecera de | |
| 54 | +// este fichero cuenta que un SW que SÍ interceptaba rompió la carga del ONNX, | |
| 55 | +// y no se trata de repetirlo por querer un botón de instalar. | |
| 56 | +self.addEventListener('fetch', () => { /* a la red, sin tocar nada */ }); |