utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | 6da87834a6d9d19802a11177cb62b22d6152093ab2e2c6a926072912155b74b5 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-10 16:19 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 14:13 +02:00 |
| Parents | 4eb6a3c2f5a8 |
3 files changed
added tests/storage-honest.mjs +117 −0
| @@ -0,0 +1,117 @@ | ||
| 1 | +// Ajustes que decían una cosa y hacían otra: | |
| 2 | +// | |
| 3 | +// 1. Espacio de trabajo · «Guardar solo»: no guardaba NUNCA (nada llamaba a | |
| 4 | +// workspace.touch()). Ahora un mensaje nuevo acaba en .elffuss/code/ del | |
| 5 | +// disco sin pulsar «Guardar ahora». | |
| 6 | +// 2. Feedback · Enviar: decía «¡enviado, gracias!» aunque el servidor | |
| 7 | +// contestara 404, y borraba el texto. Ahora dice que falló y lo conserva; | |
| 8 | +// cuando el servidor lo acepta, sí lo da por enviado. | |
| 9 | +// 3. Chip 💾 y «Vaciar caché»: contaban el origen ENTERO como «modelos» y al | |
| 10 | +// vaciar solo borraban una caché vieja. Ahora cuentan solo los modelos | |
| 11 | +// (almacén OPFS de modelos + caché de transformers) y los vacían de verdad | |
| 12 | +// sin tocar lo demás, diciendo cuánto se liberó. | |
| 13 | +// | |
| 14 | +// BASE=http://127.0.0.1:8898 node tests/storage-honest.mjs | |
| 15 | +import { chromium } from 'playwright'; | |
| 16 | +const BASE = process.env.BASE || 'http://localhost:8799'; | |
| 17 | +let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; | |
| 18 | + | |
| 19 | +const b = await chromium.launch(); | |
| 20 | +const ctx = await b.newContext({ locale: 'es-ES' }); | |
| 21 | +await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} window.confirm = () => true; }); | |
| 22 | +const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } }); | |
| 23 | +const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160))); | |
| 24 | + | |
| 25 | +const MB = 1048576; | |
| 26 | +await p.goto(BASE + '/manifest.json'); | |
| 27 | +await p.evaluate(async (MB) => { | |
| 28 | + const root = await navigator.storage.getDirectory(); | |
| 29 | + const escribe = async (dir, name, bytes) => { const w = await (await dir.getFileHandle(name, { create: true })).createWritable(); await w.write(new Uint8Array(bytes)); await w.close(); }; | |
| 30 | + await escribe(root, 'datos-del-proyecto.bin', 3 * MB); // NO es un modelo | |
| 31 | + await escribe(await root.getDirectoryHandle('elffuss-models', { create: true }), 'pesos.bin', 2 * MB); | |
| 32 | + const c = await caches.open('transformers-cache'); | |
| 33 | + await c.put('https://huggingface.co/x/onnx/model.onnx', new Response(new Uint8Array(1 * MB), { headers: { 'content-length': String(1 * MB) } })); | |
| 34 | +}, MB); | |
| 35 | +await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); | |
| 36 | +await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.() && !document.getElementById('disk-chip').hidden, null, { timeout: 20000 }).catch(() => {}); | |
| 37 | + | |
| 38 | +// 3 · el chip cuenta solo los modelos | |
| 39 | +const chip = await p.evaluate(() => ({ txt: document.getElementById('disk-chip').textContent, title: document.getElementById('disk-chip').title })); | |
| 40 | +ok('3 · el chip cuenta solo los modelos (3 MB), no los 3 MB de datos del proyecto', /💾 3 MB/.test(chip.txt), JSON.stringify(chip)); | |
| 41 | +await p.click('#disk-chip'); | |
| 42 | +await p.waitForFunction(() => /Liberados/.test(document.getElementById('statusbar').textContent), null, { timeout: 10000 }).catch(() => {}); | |
| 43 | +const tras = await p.evaluate(async () => { | |
| 44 | + const root = await navigator.storage.getDirectory(); | |
| 45 | + const hay = async (n) => { try { await root.getDirectoryHandle(n); return true; } catch { return false; } }; | |
| 46 | + const fichero = async (n) => { try { return (await (await root.getFileHandle(n)).getFile()).size; } catch { return -1; } }; | |
| 47 | + return { | |
| 48 | + estado: document.getElementById('statusbar').textContent, modelos: await hay('elffuss-models'), | |
| 49 | + transformers: (await caches.keys()).includes('transformers-cache'), proyecto: await fichero('datos-del-proyecto.bin'), | |
| 50 | + chipOculto: document.getElementById('disk-chip').hidden, | |
| 51 | + }; | |
| 52 | +}); | |
| 53 | +ok('3 · vaciar borra el almacén de modelos y la caché de transformers', !tras.modelos && !tras.transformers, JSON.stringify(tras)); | |
| 54 | +ok('3 · …sin tocar los datos del proyecto', tras.proyecto === 3 * MB, JSON.stringify(tras)); | |
| 55 | +ok('3 · …y dice cuánto liberó', /Liberados 3 MB/.test(tras.estado), tras.estado); | |
| 56 | +ok('3 · el chip desaparece cuando no queda ningún modelo', tras.chipOculto); | |
| 57 | + | |
| 58 | +// 3 · «Vaciar caché» de Ajustes usa la misma rutina | |
| 59 | +await p.evaluate(async (MB) => { | |
| 60 | + const root = await navigator.storage.getDirectory(); | |
| 61 | + const w = await (await (await root.getDirectoryHandle('elffuss-models', { create: true })).getFileHandle('otro.bin', { create: true })).createWritable(); | |
| 62 | + await w.write(new Uint8Array(1 * MB)); await w.close(); | |
| 63 | +}, MB); | |
| 64 | +await p.click('#btn-settings'); | |
| 65 | +await p.waitForTimeout(500); | |
| 66 | +const tarjeta = await p.evaluate(() => [...document.querySelectorAll('#settings-panel .prov-card')].map(c => c.textContent).find(t => /modelos guardados|Ningún modelo/.test(t)) || ''); | |
| 67 | +ok('3 · la tarjeta de Ajustes habla de modelos guardados (1 MB)', /1 MB en modelos guardados/.test(tarjeta), tarjeta.slice(0, 120)); | |
| 68 | +await p.locator('#settings-panel button', { hasText: 'Vaciar caché' }).click(); | |
| 69 | +await p.waitForTimeout(800); | |
| 70 | +const ajustes = await p.evaluate(async () => { | |
| 71 | + const root = await navigator.storage.getDirectory(); | |
| 72 | + let hay = true; try { await root.getDirectoryHandle('elffuss-models'); } catch { hay = false; } | |
| 73 | + return { hay, msg: [...document.querySelectorAll('#settings-panel [role="status"]')].map(n => n.textContent).join(' | ') }; | |
| 74 | +}); | |
| 75 | +ok('3 · «Vaciar caché» de Ajustes vacía los modelos y lo dice', !ajustes.hay && /Liberados 1 MB/.test(ajustes.msg), JSON.stringify(ajustes)); | |
| 76 | + | |
| 77 | +// 2 · Feedback: el 404 del servidor local NO es «enviado» | |
| 78 | +await p.fill('#tel-feedback', 'un fallo que vi'); | |
| 79 | +await p.click('#tel-send'); | |
| 80 | +await p.waitForTimeout(600); | |
| 81 | +const f1 = await p.evaluate(() => ({ msg: document.getElementById('tel-msg').textContent, texto: document.getElementById('tel-feedback').value })); | |
| 82 | +ok('2 · si el servidor no lo acepta, dice que falló', /No se pudo enviar/.test(f1.msg) && !/enviado, gracias/.test(f1.msg), JSON.stringify(f1)); | |
| 83 | +ok('2 · …y conserva el texto', f1.texto === 'un fallo que vi', JSON.stringify(f1)); | |
| 84 | +await p.route('**/proxy/report', r => r.fulfill({ status: 200, contentType: 'application/json', body: '{"ok":true}' })); | |
| 85 | +await p.click('#tel-send'); | |
| 86 | +await p.waitForTimeout(600); | |
| 87 | +const f2 = await p.evaluate(() => ({ msg: document.getElementById('tel-msg').textContent, texto: document.getElementById('tel-feedback').value })); | |
| 88 | +ok('2 · si el servidor lo acepta, lo da por enviado y vacía la caja', /enviado, gracias/.test(f2.msg) && f2.texto === '', JSON.stringify(f2)); | |
| 89 | +await p.unroute('**/proxy/report'); | |
| 90 | + | |
| 91 | +// 1 · «Guardar solo» guarda de verdad | |
| 92 | +await p.locator('#settings-panel button', { hasText: 'Usar la del proyecto' }).click(); | |
| 93 | +await p.waitForTimeout(400); | |
| 94 | +const auto = p.locator('#settings-panel label', { hasText: 'Guardar solo' }).locator('input[type=checkbox]'); | |
| 95 | +await auto.check(); | |
| 96 | +await p.click('#btn-settings'); // cerrar Ajustes | |
| 97 | +await p.fill('#prompt', 'mensaje que tiene que acabar en disco'); | |
| 98 | +await p.press('#prompt', 'Enter'); | |
| 99 | +await p.waitForTimeout(4500); // el autoguardado espera 3 s a que paren los cambios | |
| 100 | +const disco = await p.evaluate(async () => { | |
| 101 | + const root = await navigator.storage.getDirectory(); | |
| 102 | + try { | |
| 103 | + const app = await (await root.getDirectoryHandle('.elffuss')).getDirectoryHandle('code'); | |
| 104 | + const idx = JSON.parse(await (await (await app.getFileHandle('index.json')).getFile()).text()); | |
| 105 | + const conv = await app.getDirectoryHandle('conversations'); | |
| 106 | + let contiene = false; | |
| 107 | + for await (const e of conv.values()) if (e.kind === 'file' && (await (await e.getFile()).text()).includes('mensaje que tiene que acabar en disco')) contiene = true; | |
| 108 | + return { razon: idx.reason, contiene }; | |
| 109 | + } catch (e) { return { error: e.message }; } | |
| 110 | +}); | |
| 111 | +ok('1 · con «Guardar solo», el mensaje nuevo acaba en .elffuss/code/ sin pulsar Guardar', disco.razon === 'auto' && disco.contiene, JSON.stringify(disco)); | |
| 112 | + | |
| 113 | +console.log('\n errores JS:', errs[0] || 'ninguno'); | |
| 114 | +ok('sin errores de página', errs.length === 0, errs.join(' | ')); | |
| 115 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ AJUSTES QUE HACEN LO QUE DICEN'); | |
| 116 | +await b.close(); | |
| 117 | +process.exit(fails ? 1 : 0); |
modified web/js/i18n.js +16 −2
| @@ -48,7 +48,7 @@ | ||
| 48 | 48 | nExec: '▶ Ejecutar', nView: 'Ver en la Mente', |
| 49 | 49 | fallbackToast: 'Ese Gemma no cargó (memoria/GPU) — uso el ligero…', |
| 50 | 50 | setStoreTitle: 'Modelo descargado (se cachea en tu navegador)', setClear: 'Vaciar caché', setClearing: 'Vaciando…', |
| 51 | - setCached: '{gb} en caché', setNone: 'Nada cacheado todavía', | |
| 51 | + setCached: '{gb} en modelos guardados', setNone: 'Ningún modelo guardado todavía', | |
| 52 | 52 | setBrToken: 'Token (lo imprime el programa al arrancarlo)', brTokenPh: 'pega aquí el token…', |
| 53 | 53 | setFeedbackPh: 'Cuéntanos qué ha pasado o qué te gustaría que hiciera…', |
| 54 | 54 | lblModel: 'Modelo', lblApiKey: 'API key', |
| @@ -181,6 +181,13 @@ | ||
| 181 | 181 | cfgCant_running: "Ya estoy pensando: espera a que termine este ciclo.", |
| 182 | 182 | cfgCant_leader: "Otra pestaña lleva el cerebro: hazlo desde ahí.", |
| 183 | 183 | avatarLabel: "Mente de Elffuss", |
| 184 | + setTelSend: "Enviar", setTelSending: "Enviando…", | |
| 185 | + clearModelsConfirm: "Vas a borrar {size} de modelos guardados en este navegador.\n\nNo se pierde nada tuyo: solo los pesos descargados. La próxima vez habrá que bajarlos otra vez.\n\n¿Seguir?", | |
| 186 | + clearModelsShared: "Ojo: el almacén compartido de Elffuss no se pudo consultar desde aquí; puede quedar algo guardado ahí.", | |
| 187 | + clearModelsDone: "💾 Liberados {size}.", clearModelsFailed: "No se pudo vaciar: {what}.", | |
| 188 | + setSharedUnknown: " · no se pudo consultar el almacén compartido (puede haber más guardado)", | |
| 189 | + diskChipTitle: "Modelos guardados en este navegador: {size}{quota}. Pulsa para vaciarlos.", diskChipQuota: " de {quota} disponibles", | |
| 190 | + setTelFailed: "⚠️ No se pudo enviar (el servidor no lo aceptó o no hay conexión). Tu texto sigue aquí: prueba otra vez más tarde.", | |
| 184 | 191 | }, |
| 185 | 192 | en: { |
| 186 | 193 | ph: 'Type here… (@ attaches a file)', |
| @@ -224,7 +231,7 @@ | ||
| 224 | 231 | nExec: '▶ Run', nView: 'View in the Mind', |
| 225 | 232 | fallbackToast: 'That Gemma didn’t load (memory/GPU) — using the light one…', |
| 226 | 233 | setStoreTitle: 'Downloaded model (cached in your browser)', setClear: 'Clear cache', setClearing: 'Clearing…', |
| 227 | - setCached: '{gb} cached', setNone: 'Nothing cached yet', | |
| 234 | + setCached: '{gb} of stored models', setNone: 'No model stored yet', | |
| 228 | 235 | setBrToken: 'Token (printed by the program on startup)', brTokenPh: 'paste the token here…', |
| 229 | 236 | setFeedbackPh: 'Tell us what happened or what you’d like it to do…', |
| 230 | 237 | lblModel: 'Model', lblApiKey: 'API key', |
| @@ -357,6 +364,13 @@ | ||
| 357 | 364 | cfgCant_running: "I'm already thinking: wait for this cycle to end.", |
| 358 | 365 | cfgCant_leader: "Another tab runs the brain: do it from there.", |
| 359 | 366 | avatarLabel: "Elffuss Mind", |
| 367 | + setTelSend: "Send", setTelSending: "Sending…", | |
| 368 | + clearModelsConfirm: "You are about to delete {size} of models stored in this browser.\n\nNothing of yours is lost: only the downloaded weights. Next time they will be downloaded again.\n\nContinue?", | |
| 369 | + clearModelsShared: "Note: Elffuss's shared store could not be checked from here; something may remain stored there.", | |
| 370 | + clearModelsDone: "💾 Freed {size}.", clearModelsFailed: "Couldn't clear: {what}.", | |
| 371 | + setSharedUnknown: " · the shared store could not be checked (there may be more stored)", | |
| 372 | + diskChipTitle: "Models stored in this browser: {size}{quota}. Click to clear them.", diskChipQuota: " of {quota} available", | |
| 373 | + setTelFailed: "⚠️ Couldn't send it (the server didn't accept it or there is no connection). Your text is still here: try again later.", | |
| 360 | 374 | }, |
| 361 | 375 | }; |
| 362 | 376 |
modified web/js/main.js +78 −65
| @@ -11,21 +11,7 @@ | ||
| 11 | 11 | import * as terminal from './terminal.js'; |
| 12 | 12 | import * as shell from './shell.js'; |
| 13 | 13 | import { setTerminalEcho } from './tools/index.js'; |
| 14 | -import { ensureModelCache, cacheEstimate, clearModelCache } from './model-cache.js'; | |
| 15 | -// El almacén compartido vive en OTRO origen y `navigator.storage.estimate()` no | |
| 16 | -// lo ve: hay que preguntárselo a él y SUMAR. Ver model-broker.js. | |
| 17 | -import { sharedUsage, clearShared } from './runtime/model-broker.js'; | |
| 18 | - | |
| 19 | -// Los origenes donde puede haber pesos salen del REGISTRO del motor, no de una | |
| 20 | -// lista a mano: una copiada se queda vieja en cuanto un modelo cambia de host y | |
| 21 | -// el contador vuelve a mirar donde no hay nada. Import perezoso porque el motor | |
| 22 | -// puede no estar (modo ONNX); sin el, `sharedUsage` usa su defecto. | |
| 23 | -async function origenesAlmacen() { | |
| 24 | - try { | |
| 25 | - const r = await import('./engine/registro.js'); | |
| 26 | - return r.origenesAlmacen ? r.origenesAlmacen() : undefined; | |
| 27 | - } catch { return undefined; } | |
| 28 | -} | |
| 14 | +import { ensureModelCache, cacheEstimate, modelUsage, clearModels } from './model-cache.js'; | |
| 29 | 15 | import * as ceo from './ceo.js'; |
| 30 | 16 | import * as mind from './mind.js'; |
| 31 | 17 | import { buildCityAdapter, loadThoughtsAdapter } from './mind-adapter.js'; |
| @@ -76,6 +62,16 @@ | ||
| 76 | 62 | e.returnValue = ''; // Safari y navegadores viejos miran esto |
| 77 | 63 | }); |
| 78 | 64 | if (workspace.autosaveEnabled()) workspace.autosave({ enabled: true }); |
| 65 | +// «Guardar solo» guarda de verdad: cada escritura de un almacén que el espacio | |
| 66 | +// de trabajo copia a disco se le avisa con touch(). Antes nada lo llamaba y el | |
| 67 | +// autoguardado no escribía nunca, con la casilla marcada. | |
| 68 | +db.onWrite((store, key) => { | |
| 69 | + if (store !== 'kv') return; | |
| 70 | + if (key === 'conversations') workspace.touch('conversations'); | |
| 71 | + else if (key === 'skills') workspace.touch('skills'); | |
| 72 | +}); | |
| 73 | +// Las preferencias viven en localStorage: se avisa al cambiarlas. | |
| 74 | +const guardaPref = (k, v) => { try { localStorage.setItem(k, v); } catch { /* lleno o bloqueado */ } workspace.touch('prefs'); }; | |
| 79 | 75 | |
| 80 | 76 | import * as telemetry from './telemetry.js'; |
| 81 | 77 | |
| @@ -626,7 +622,7 @@ | ||
| 626 | 622 | if (id === 'rules') { |
| 627 | 623 | conv.setProvider(rules); |
| 628 | 624 | activeModel = 'rules'; |
| 629 | - localStorage.setItem('elffusscode.model', 'rules'); | |
| 625 | + guardaPref('elffusscode.model', 'rules'); | |
| 630 | 626 | $('model-dot').className = 'dot off'; |
| 631 | 627 | return true; |
| 632 | 628 | } |
| @@ -664,7 +660,7 @@ | ||
| 664 | 660 | try { if (typeof mod.contextTokens === 'function') setCtxBudget(mod.contextTokens()); } |
| 665 | 661 | catch { /* el medidor no vale un fallo de carga */ } |
| 666 | 662 | activeModel = id; |
| 667 | - localStorage.setItem('elffusscode.model', id); | |
| 663 | + guardaPref('elffusscode.model', id); | |
| 668 | 664 | $('model-dot').className = 'dot on'; |
| 669 | 665 | showModelProgress(t('modelReadyBadge'), 100); |
| 670 | 666 | setTimeout(() => showModelProgress(null), 2500); |
| @@ -884,27 +880,24 @@ | ||
| 884 | 880 | const storeMuted = el('span', 'muted', ''); storeMuted.style.fontSize = '.72rem'; |
| 885 | 881 | const clearBtn = el('button', 'prov-use', t('setClear')); |
| 886 | 882 | clearBtn.style.marginTop = '8px'; |
| 887 | - clearBtn.onclick = async () => { clearBtn.textContent = t('setClearing'); await clearModelCache(); await paintStorage(); clearBtn.textContent = t('setClear'); }; | |
| 883 | + const clearMsg = el('div', 'muted'); clearMsg.setAttribute('role', 'status'); clearMsg.style.cssText = 'font-size:.72rem;margin-top:6px'; | |
| 884 | + // La misma rutina que el chip 💾: confirma, vacía TODO lo que son modelos y | |
| 885 | + // dice cuánto se liberó (antes solo borraba una caché vieja y no decía nada). | |
| 886 | + clearBtn.onclick = async () => { | |
| 887 | + const r = await vaciarModelos(clearBtn); | |
| 888 | + if (r) clearMsg.textContent = r; | |
| 889 | + await paintStorage(); | |
| 890 | + }; | |
| 888 | 891 | const storeHead = el('div', 'prov-head'); storeHead.append(storeInfo); |
| 889 | - storeCard.append(storeHead, storeMuted, clearBtn); | |
| 892 | + storeCard.append(storeHead, storeMuted, clearBtn, clearMsg); | |
| 890 | 893 | box.appendChild(storeCard); |
| 891 | 894 | async function paintStorage() { |
| 892 | - const { usage, quota, persisted } = await cacheEstimate(); | |
| 893 | - // El modelo grande NO está en este origen: lo guarda el broker en el suyo, y | |
| 894 | - // `estimate()` solo ve el propio. Sumando los dos, el panel decía «0,82 GB» | |
| 895 | - // con 7,2 GB guardados al lado — justo sobre el modelo que más ocupa. | |
| 896 | - const compartido = await sharedUsage(await origenesAlmacen()); | |
| 897 | - const total = usage + compartido.usage; | |
| 898 | - const gb = n => (n / 1073741824).toFixed(2) + ' GB'; | |
| 899 | - storeInfo.textContent = total ? t('setCached', { gb: gb(total) }) : t('setNone'); | |
| 900 | - // Si el broker no contesta se dice, en vez de dar un total que se queda | |
| 901 | - // corto sin avisar: un número incompleto que parece completo es peor que | |
| 902 | - // uno que admite lo que le falta. | |
| 895 | + const { quota, persisted } = await cacheEstimate(); | |
| 896 | + const m = await modelUsage(); | |
| 897 | + storeInfo.textContent = m.total ? t('setCached', { gb: tamano(m.total) }) : t('setNone'); | |
| 903 | 898 | storeMuted.textContent = (persisted ? t('setPersist') : t('setNoPersist')) |
| 904 | - + (quota ? t('setLimit', { gb: gb(quota) }) : '') | |
| 905 | - + (compartido.ok | |
| 906 | - ? (compartido.usage ? ` · incluye ${gb(compartido.usage)} del almacén compartido` : '') | |
| 907 | - : ' · no se pudo consultar el almacén compartido (puede haber más guardado)'); | |
| 899 | + + (quota ? t('setLimit', { gb: tamano(quota) }) : '') | |
| 900 | + + (m.sharedOk ? '' : t('setSharedUnknown')); | |
| 908 | 901 | } |
| 909 | 902 | paintStorage(); |
| 910 | 903 | |
| @@ -970,7 +963,7 @@ | ||
| 970 | 963 | permCheckbox.checked = autoEdit; |
| 971 | 964 | permCheckbox.onchange = () => { |
| 972 | 965 | autoEdit = permCheckbox.checked; |
| 973 | - localStorage.setItem('elffusscode.autoedit', autoEdit ? '1' : '0'); | |
| 966 | + guardaPref('elffusscode.autoedit', autoEdit ? '1' : '0'); | |
| 974 | 967 | paintAuto(); |
| 975 | 968 | }; |
| 976 | 969 | |
| @@ -988,7 +981,7 @@ | ||
| 988 | 981 | goalCheckbox.checked = goalMode; |
| 989 | 982 | goalCheckbox.onchange = () => { |
| 990 | 983 | goalMode = goalCheckbox.checked; |
| 991 | - localStorage.setItem('elffusscode.goalmode', goalMode ? '1' : '0'); | |
| 984 | + guardaPref('elffusscode.goalmode', goalMode ? '1' : '0'); | |
| 992 | 985 | paintGoal(); |
| 993 | 986 | }; |
| 994 | 987 | |
| @@ -1003,21 +996,33 @@ | ||
| 1003 | 996 | `<p class="muted" style="font-size:.7rem;margin:6px 0 10px">Apagado por defecto — tu código y el contenido de tus proyectos NUNCA se incluyen, solo el mensaje de error técnico, la pila y datos del navegador.</p>` + |
| 1004 | 997 | `<label class="muted" style="font-size:.68rem">O manda algo tú directamente (un fallo que viste, algo que eches en falta…)</label>` + |
| 1005 | 998 | `<textarea id="tel-feedback" rows="2" style="width:100%;margin-top:4px;resize:vertical;background:var(--bg2);border:1px solid var(--line);border-radius:8px;color:var(--fg);padding:6px 8px;font:inherit" placeholder="${t('setFeedbackPh')}"></textarea>` + |
| 1006 | - `<button id="tel-send" class="prov-use" style="margin-top:6px">Enviar</button>` + | |
| 1007 | - `<span id="tel-msg" class="muted" style="font-size:.7rem;margin-left:8px"></span>`; | |
| 999 | + `<button id="tel-send" class="prov-use" style="margin-top:6px">${escapeHtml(t('setTelSend'))}</button>` + | |
| 1000 | + `<span id="tel-msg" class="muted" role="status" aria-live="polite" style="font-size:.7rem;margin-left:8px"></span>`; | |
| 1008 | 1001 | box.appendChild(telCard); |
| 1009 | 1002 | const telCheckbox = telCard.querySelector('#tel-enabled'); |
| 1010 | 1003 | telCheckbox.checked = telemetry.isEnabled(); |
| 1011 | 1004 | telCheckbox.onchange = () => telemetry.setEnabled(telCheckbox.checked); |
| 1005 | + // Solo dice «enviado» si el servidor lo aceptó. Antes lo decía siempre | |
| 1006 | + // (también con un 404 o sin red) y además borraba el texto: el usuario | |
| 1007 | + // creía haberlo mandado y lo había perdido. | |
| 1012 | 1008 | telCard.querySelector('#tel-send').onclick = async () => { |
| 1009 | + const btn = telCard.querySelector('#tel-send'); | |
| 1013 | 1010 | const ta = telCard.querySelector('#tel-feedback'); |
| 1014 | 1011 | const msg = telCard.querySelector('#tel-msg'); |
| 1015 | 1012 | const text = ta.value.trim(); |
| 1013 | + msg.style.color = ''; | |
| 1016 | 1014 | if (!text) { msg.textContent = t("setTelEmpty"); return; } |
| 1015 | + btn.disabled = true; btn.setAttribute('aria-busy', 'true'); | |
| 1016 | + msg.textContent = t('setTelSending'); | |
| 1017 | 1017 | const wasEnabled = telemetry.isEnabled(); |
| 1018 | 1018 | if (!wasEnabled) telemetry.setEnabled(true); // el envío manual es explícito, se permite aunque el automático esté apagado |
| 1019 | - await telemetry.sendFeedback(text); | |
| 1020 | - if (!wasEnabled) telemetry.setEnabled(false); // no activa el automático de fondo si no lo pidió | |
| 1019 | + let enviado = false; | |
| 1020 | + try { enviado = await telemetry.sendFeedback(text); } | |
| 1021 | + finally { | |
| 1022 | + if (!wasEnabled) telemetry.setEnabled(false); // no activa el automático de fondo si no lo pidió | |
| 1023 | + btn.disabled = false; btn.removeAttribute('aria-busy'); | |
| 1024 | + } | |
| 1025 | + if (!enviado) { msg.textContent = t('setTelFailed'); msg.style.color = '#ff6b8b'; return; } | |
| 1021 | 1026 | ta.value = ''; |
| 1022 | 1027 | msg.textContent = t("setTelThanks"); |
| 1023 | 1028 | setTimeout(() => { msg.textContent = ''; }, 4000); |
| @@ -1819,7 +1824,7 @@ | ||
| 1819 | 1824 | } |
| 1820 | 1825 | $('btn-autoedit').addEventListener('click', () => { |
| 1821 | 1826 | autoEdit = !autoEdit; |
| 1822 | - localStorage.setItem('elffusscode.autoedit', autoEdit ? '1' : '0'); | |
| 1827 | + guardaPref('elffusscode.autoedit', autoEdit ? '1' : '0'); | |
| 1823 | 1828 | paintAuto(); |
| 1824 | 1829 | }); |
| 1825 | 1830 | paintAuto(); |
| @@ -1838,7 +1843,7 @@ | ||
| 1838 | 1843 | } |
| 1839 | 1844 | $('btn-goal').addEventListener('click', () => { |
| 1840 | 1845 | goalMode = !goalMode; |
| 1841 | - localStorage.setItem('elffusscode.goalmode', goalMode ? '1' : '0'); | |
| 1846 | + guardaPref('elffusscode.goalmode', goalMode ? '1' : '0'); | |
| 1842 | 1847 | paintGoal(); |
| 1843 | 1848 | }); |
| 1844 | 1849 | paintGoal(); |
| @@ -2229,36 +2234,44 @@ | ||
| 2229 | 2234 | document.body.appendChild(box); |
| 2230 | 2235 | } |
| 2231 | 2236 | |
| 2237 | +// Tamaño legible: MB por debajo de 1 GB. | |
| 2238 | +function tamano(n) { return n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : Math.round(n / 1048576) + ' MB'; } | |
| 2239 | + | |
| 2240 | +// Vaciar los modelos guardados: lo usan el chip 💾 y «Vaciar caché» de Ajustes. | |
| 2241 | +// Devuelve el mensaje con lo que pasó (o null si el usuario canceló). | |
| 2242 | +async function vaciarModelos(boton) { | |
| 2243 | + const m = await modelUsage(); | |
| 2244 | + if (!confirm(t('clearModelsConfirm', { size: tamano(m.total) }) + (m.sharedOk ? '' : '\n\n' + t('clearModelsShared')))) return null; | |
| 2245 | + const antes = boton.textContent; | |
| 2246 | + boton.disabled = true; boton.setAttribute('aria-busy', 'true'); | |
| 2247 | + boton.textContent = t('setClearing'); | |
| 2248 | + let r; | |
| 2249 | + try { r = await clearModels(); } | |
| 2250 | + finally { boton.disabled = false; boton.removeAttribute('aria-busy'); boton.textContent = antes; } | |
| 2251 | + let msg = t('clearModelsDone', { size: tamano(r.liberado) }); | |
| 2252 | + if (r.fallos.length) msg += ' ' + t('clearModelsFailed', { what: r.fallos.join(' · ') }); | |
| 2253 | + if (!r.sharedOk) msg += ' ' + t('clearModelsShared'); | |
| 2254 | + $('statusbar').textContent = msg; | |
| 2255 | + return msg; | |
| 2256 | +} | |
| 2257 | + | |
| 2258 | +// Chip 💾: lo que ocupan los MODELOS (no el origen entero, que mezclaba | |
| 2259 | +// conversaciones y el proyecto de prueba) y un clic para vaciarlos. | |
| 2232 | 2260 | function mountDiskChip() { |
| 2233 | 2261 | const chip = document.getElementById('disk-chip'); |
| 2234 | 2262 | if (!chip) return; |
| 2235 | - const gb = n => n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : Math.round(n / 1048576) + ' MB'; | |
| 2236 | 2263 | async function paint() { |
| 2237 | - const { usage, quota } = await cacheEstimate(); | |
| 2238 | - const compartido = await sharedUsage(await origenesAlmacen()); | |
| 2239 | - const total = usage + compartido.usage; | |
| 2240 | - if (!total) { chip.hidden = true; return; } | |
| 2264 | + const { quota } = await cacheEstimate(); | |
| 2265 | + const m = await modelUsage(); | |
| 2266 | + if (!m.total) { chip.hidden = true; return; } | |
| 2241 | 2267 | chip.hidden = false; |
| 2242 | - chip.textContent = '💾 ' + gb(total); | |
| 2243 | - chip.title = `Modelos guardados en este navegador: ${gb(total)}` | |
| 2244 | - + (quota ? ` de ${gb(quota)} disponibles` : '') + '. Pulsa para vaciarlo.'; | |
| 2268 | + chip.textContent = '💾 ' + tamano(m.total); | |
| 2269 | + chip.title = t('diskChipTitle', { size: tamano(m.total), quota: quota ? t('diskChipQuota', { quota: tamano(quota) }) : '' }) | |
| 2270 | + + (m.sharedOk ? '' : t('setSharedUnknown')); | |
| 2245 | 2271 | } |
| 2246 | 2272 | chip.addEventListener('click', async () => { |
| 2247 | - const { usage } = await cacheEstimate(); | |
| 2248 | - const comp = await sharedUsage(await origenesAlmacen()); | |
| 2249 | - const total = usage + comp.usage; | |
| 2250 | - if (!confirm(`Vas a borrar ${gb(total)} de modelos guardados en este navegador.\n\n` | |
| 2251 | - + `No se pierde nada tuyo: solo los pesos descargados. La próxima vez habrá que bajarlos otra vez.\n\n¿Seguir?`)) return; | |
| 2252 | - chip.textContent = '💾 …'; | |
| 2253 | - // LOS DOS almacenes. Vaciar solo el de este origen dejaba intacto el modelo | |
| 2254 | - // grande —que es casi todo lo que ocupa— así que quien pulsaba para | |
| 2255 | - // recuperar espacio no lo recuperaba y no se enteraba. | |
| 2256 | - let fallo = null; | |
| 2257 | - try { await clearModelCache(); } catch (e) { fallo = e.message || String(e); } | |
| 2258 | - const r = await clearShared(); | |
| 2259 | - if (!r.ok && comp.usage) fallo = (fallo ? fallo + ' · ' : '') + 'el almacén compartido no se pudo vaciar'; | |
| 2260 | - if (fallo) alert('No se pudo vaciar del todo: ' + fallo); | |
| 2261 | - paint(); | |
| 2273 | + const msg = await vaciarModelos(chip); | |
| 2274 | + if (msg) await paint(); | |
| 2262 | 2275 | }); |
| 2263 | 2276 | paint(); |
| 2264 | 2277 | setInterval(paint, 20000); |