Elffuss BraidHub

utopia-ia/elffuss-claw public

coordinated: what the UX fixes reworked reads in English on an English page

With the page in en-US these were still Spanish:
- the speed meter (chip title, panel, its accessible name). velocimetro.js
  is shared with Code, so it now takes its strings through a small hook,
  usarTraductor(t), with Spanish as the fallback; Claw installs its t() at
  boot and when mounting the meter. Values put into the panel are escaped.
- kernel toasts and messages on the reworked paths: Basic mode, preparing
  and failing to load a model (the known errors of the shared API
  provider are mapped), the low-performance brain, loading notices, the
  queue notices, Hard Work progress and summary, the memory watchdog.
- the Basic-mode reply. Its commands are Spanish, so the English help says
  so and translates each one; the "model picker" link stays.
- vault errors (saving without a name, unknown secret).
- the store labels of "What's stored" (getters, read when painted).

All new keys exist in Spanish and English. ux-ingles.mjs drives each of
these in en-US; all of them fail on the previous tree.

Integration (onto stop-fix 7147228 / main 10073b7): Hard Work's failure
message takes t('hwFailed') while keeping stop-fix 1f3af20's rule (an
AbortError from the provider is a stop, not a failure). main 66c2865 removed
the low-performance Elffuss LM option and its toast, so that line and its
weakBrain key are not added.
Changeset155e1e61a5af2d2c7cf34fa8178c3fe52d16f79c4d1639dbdd8111a9d694e8d0
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 19:14 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 17:52 +02:00
Parents968394115ecc

Browse the files at this changeset

7 files changed

modified tests/README.md +1 −1
@@ -39,4 +39,4 @@
3939 enlaces) · `ux-mente` · `ux-borrar` (🧹 y «Borrar todo») · `ux-modelos` (💾) ·
4040 `ux-velocimetro` · `ux-movil` · `ux-copiloto` · `ux-skills` · `ux-ajustes` ·
4141 `ux-paneles` (Apps, Tareas, Permisos) · `ux-teclado` (menú «/», atajos, chips) ·
42-`ux-hardwork` · `ux-modelo` (selector) · `ux-splash`.
42+`ux-hardwork` · `ux-modelo` (selector) · `ux-splash` · `ux-ingles` (lo rehecho, en inglés).
added tests/ux-ingles.mjs +76 −0
@@ -0,0 +1,76 @@
1+// En inglés (en-US), lo que se rehízo en la auditoría de UX habla inglés:
2+// · los avisos del selector de modelo (Básico, un cerebro que no carga);
3+// · la respuesta del modo básico, con su enlace al selector de modelo;
4+// · «What's stored» en Ajustes;
5+// · el error de la bóveda al guardar sin nombre;
6+// · el velocímetro (chip, panel y su nombre accesible), con un motor de prueba.
7+// Antes todo eso salía en español con la página en inglés.
8+//
9+// BASE=http://localhost:8743 node tests/ux-ingles.mjs
10+import { navegador, contexto, pagina, ok, hasta, escribir, reposo, avisos, fin } from './ux-comun.mjs';
11+
12+const b = await navegador();
13+const ESPANOL = /\b(sin modelo|No se pudo|Estoy en modo|selector de modelo|Generadas|Conversación|Bóveda|Faltan|Velocidad|leyendo|escribiendo|Pulsa)\b/;
14+
15+const { ctx } = await contexto(b, {
16+ locale: 'en-US', grants: [],
17+ extraInit: { 'elffuss.providers': JSON.stringify({ openai: { enabled: true, baseURL: 'https://api.openai.com/v1', model: 'gpt-4o-mini', apiKey: '' } }) },
18+});
19+const { p, errores } = await pagina(ctx);
20+const elegir = id => p.evaluate(id => { const s = document.getElementById('model-select'); s.value = id; s.dispatchEvent(new Event('change')); }, id);
21+
22+// ── selector de modelo ──────────────────────────────────────────────────────
23+await elegir('rules');
24+ok('choosing Basic says so in English', await hasta(async () => (await avisos(p)).some(t => t === 'Basic mode: no model, direct commands.')),
25+ (await avisos(p)).join(' | '));
26+await hasta(() => p.evaluate(() => !document.getElementById('model-select').disabled));
27+await elegir('ext:openai'); // sin clave: no carga, y no había otro cerebro
28+ok('a brain that does not load says why in English', await hasta(async () =>
29+ (await avisos(p)).some(t => /^⚠️ Could not load OpenAI: the API key is missing \(advanced settings\)$/.test(t))), (await avisos(p)).join(' | '));
30+
31+// ── modo básico ─────────────────────────────────────────────────────────────
32+await hasta(() => p.evaluate(() => document.getElementById('model-select').value === 'rules' && !document.getElementById('model-select').disabled));
33+await escribir(p, 'hola');
34+await reposo(p);
35+const respuesta = await p.locator('#log .msg.assistant').last();
36+const texto = await respuesta.innerText();
37+ok('the Basic-mode reply is in English and says the commands are in Spanish', /I am in Basic mode/.test(texto) && /written in Spanish/.test(texto) && !/Estoy en modo/.test(texto), texto.slice(0, 160));
38+ok('…and links to the model picker', await respuesta.locator('a[href="#/modelo"]').innerText().catch(() => '') === 'model picker');
39+
40+// ── Settings › What's stored ────────────────────────────────────────────────
41+await p.click('#tabs button[data-tab="ajustes"]');
42+const tarjeta = p.locator('#panel-ajustes .card', { hasText: 'Wipe browser data' });
43+ok('“What’s stored” names the stores in English', await hasta(async () => {
44+ const t = await tarjeta.innerText().catch(() => '');
45+ return /Generated apps/.test(t) && /Conversation/.test(t) && /Vault \(encrypted\)/.test(t) && !/Apps generadas|Bóveda/.test(t);
46+}), await tarjeta.innerText().catch(() => ''));
47+
48+// ── Vault: guardar sin nombre ───────────────────────────────────────────────
49+await p.click('#tabs button[data-tab="vault"]');
50+await p.fill('#vault-master', 'test-password-1');
51+await p.press('#vault-master', 'Enter');
52+await hasta(() => p.evaluate(() => !!document.getElementById('vault-name')));
53+await p.fill('#panel-vault input[type=password]', 'secret-without-name');
54+await p.press('#panel-vault input[type=password]', 'Enter');
55+ok('saving a secret without a name says so in English', await hasta(async () => (await avisos(p)).some(t => /The name or the secret is missing/.test(t))),
56+ (await avisos(p)).join(' | '));
57+
58+// ── velocímetro ─────────────────────────────────────────────────────────────
59+await p.evaluate(async () => {
60+ const vm = await import('/js/velocimetro.js');
61+ vm.usarTraductor((await import('/js/i18n.js')).t); // lo que hace el kernel al montarlo
62+ vm.montar({
63+ alMedir: () => () => {},
64+ ultimaMedida: () => ({ prefillTokS: 300, genTokS: 20, ttftMs: 900, genTokens: 50, procesados: 400, reusados: 3, enCurso: false }),
65+ });
66+});
67+const chip = p.locator('#speed-chip');
68+ok('speed chip title in English', /^Writing at 20\.0 tok\/s · the prompt was read at 300 tok\/s · first letter after 900 ms\. Click to see the chart\.$/.test(await chip.getAttribute('title') || ''),
69+ await chip.getAttribute('title'));
70+await chip.click();
71+const panel = await p.evaluate(() => ({ text: document.getElementById('speed-panel').innerText, label: document.getElementById('speed-panel').getAttribute('aria-label') }));
72+ok('speed panel and its accessible name in English', panel.label === 'Speed of this machine' && /tok\/s reading the prompt/.test(panel.text)
73+ && /3 reused/.test(panel.text) && !ESPANOL.test(panel.text), JSON.stringify(panel).slice(0, 300));
74+
75+ok('no page errors', errores.length === 0, errores.slice(0, 3).join(' | '));
76+await fin(b, 'INGLÉS: lo rehecho en la auditoría habla inglés con la página en inglés');
modified web/js/i18n.js +73 −0
@@ -209,6 +209,45 @@
209209 modelStOff: 'Sin modelo (modo básico)', modelStLoading: 'Cargando el modelo…', modelStOn: 'Modelo listo', modelStGpu: 'Modelo listo en la GPU',
210210 modelFailedBack: 'No se pudo cargar {id}: {err}. Sigo con {prev}.',
211211 gemmaFallback: 'Ese Gemma no cargó aquí (memoria o GPU): uso Qwen3.5-0.8B, más ligero.',
212+ // Cola, carga del modelo, Hard Work, memoria del navegador (kernel.js).
213+ queuedAhead: 'En cola ({n} por delante): no se pierde ni refrescando.',
214+ queueRestored: '{n} mensaje(s) pendientes recuperados: los proceso en cuanto cargue el cerebro.',
215+ basicModeOn: 'Modo básico: sin modelo, órdenes directas.',
216+ modelPreparing: 'Preparando modelo…',
217+ modelFailed: '⚠️ No se pudo cargar {id}: {err}',
218+ errApiKeyMissing: 'falta la clave de API (config avanzada)', errProviderUnset: 'proveedor sin configurar',
219+ loadingGemma: 'Cargando Gemma (varios GB la primera vez)… mientras, el modo básico te atiende.',
220+ loadingLocal: 'Cargando el cerebro local… mientras, el modo básico te atiende.',
221+ copilotLightBrain: 'Copiloto: arranco con el cerebro ligero para no competir con el traductor. Para ventas o precisión, elige Gemma arriba (escritorio).',
222+ hwPhDraft: 'Hard Work · borrador…', hwPhCritique: 'Hard Work · autocrítica {n}', hwPhRewrite: 'Hard Work · reescribiendo {n}',
223+ hwPhDone: 'Hard Work · listo', hwPhOpening: 'Hard Work · abriendo carpeta…', hwPhPlan: 'Hard Work · {n} partes ({k}k)',
224+ hwPhPlanTrunc: ' — recorté al máximo', hwPhMap: 'Hard Work · leyendo {i}/{n}', hwPhMerge: 'Hard Work · fundiendo grupo {g}/{n}',
225+ hwPhSynth: 'Hard Work · sintetizando…',
226+ hwRead: '⛏ Hard Work (RLM): leí {folder} en {n} partes, {kept} con señal.',
227+ hwReadTrunc: ' Material recortado al máximo: acota la carpeta para abarcarlo entero.',
228+ hwFailed: 'Hard Work falló: {err}',
229+ ramFreedMsg: '⚠️ Ojo: tu ordenador va muy justo de memoria y puede ir lento o fallar si sigues. Por ahora me he parado y he liberado el modelo. Si quieres, vuelve a elegirlo en el selector de arriba.',
230+ ramFreedToast: '⚠️ Memoria muy llena: modelo local liberado automáticamente',
231+ ramWarn: '⚠️ La memoria del navegador va al {pct} %: si sigue subiendo, liberaré el modelo yo sola.',
232+ // Modo básico (providers/rules.js): sus órdenes son en español.
233+ basicHelp: 'Estoy en modo básico (sin modelo). Entiendo órdenes directas:\n• «hazme un reloj / una app de notas / una calculadora»\n• «autoriza una carpeta» · «lista los archivos» · «lee <archivo>»\n• «recuérdame dentro de N minutos <algo>» · «lista las tareas»\n• «guarda el secreto <nombre>: <valor>» · «lista los secretos»\n• «abre https://…»\nPara lenguaje libre y apps a medida, carga un modelo en el [selector de modelo](#/modelo) de arriba.',
234+ basicHi: '¡Hola! ', basicCouldNot: 'No pude: {err}',
235+ // Bóveda (tools/vault.js)
236+ vaultNeedNameSecret: 'Faltan el nombre o el secreto.', vaultNeedName: 'Falta el nombre.', vaultNoSecret: 'No existe el secreto «{name}»',
237+ // «Qué hay guardado» (manifiesto de kernel.js)
238+ stApps: 'Apps generadas', stSkills: 'Skills', stHistory: 'Conversación', stMemory: 'Memoria',
239+ stTasks: 'Tareas programadas', stVault: 'Bóveda (cifrada)', stPrefs: 'Preferencias',
240+ // Velocímetro (velocimetro.js, compartido con Code)
241+ vmTitle: 'Velocidad de esta máquina', vmCtx: 'contexto {n}',
242+ vmPrefill: 'tok/s leyendo el prompt', vmGen: 'tok/s escribiendo', vmTtft: 'hasta la primera letra',
243+ vmProcessed: 'tokens procesados', vmReused: ' · {n} reusados', vmNoTurns: 'Todavía no has hablado con el modelo.',
244+ vmAlert: 'Leer el prompt va casi tan lento como escribir, y eso no debería pasar: leer procesa cientos de posiciones a la vez y escribir solo una. Suele significar que algo está compitiendo por la GPU, o que el modelo no cabe holgado. En un equipo despejado leer va varias veces más rápido.',
245+ vmReading: 'Leyendo el prompt', vmWriting: 'Escribiendo', vmNeed2: '{what}: hacen falta 2 turnos para dibujar',
246+ vmMax: 'máx {v} tok/s', vmTurns: '{n} turnos', vmTasks: 'Tareas', vmSolved: 'se resuelven ({ok} de {n})',
247+ vmPerTask: 'por tarea, mediana', vmNoTasks: 'Sin tareas registradas todavía.',
248+ vmNote: 'Son los números de TU equipo en esta sesión, medidos por el propio motor. Cambian con la máquina, con lo que tengas abierto y con la temperatura, así que no son una cifra del producto.',
249+ vmChipWriting: 'Escribiendo a {g} tok/s · el prompt se leyó a {p} tok/s · primera letra en {t}. Pulsa para ver la gráfica.',
250+ vmChipReading: 'Leyendo el prompt a {p} tok/s. Pulsa para ver la gráfica.',
212251 optBasic: 'Básico (sin modelo)', optWeakGroup: '⚠ Avanzado · sin garantía de rendimiento', optAdvanced: '⚠ Avanzado',
213252 optSavedOnce: 'se guarda: solo se baja la primera vez', optSaved: 'se guarda', optLighter: 'más ligero, carga antes',
214253 optWeak: 'poco rendimiento', optDefault: 'por defecto', optLight: '— ligero', optText: '— texto', optSlow: '— lento', optCloud: ' · nube',
@@ -412,6 +451,40 @@
412451 modelStOff: 'No model (basic mode)', modelStLoading: 'Loading the model…', modelStOn: 'Model ready', modelStGpu: 'Model ready on the GPU',
413452 modelFailedBack: 'Could not load {id}: {err}. Staying with {prev}.',
414453 gemmaFallback: 'That Gemma did not load here (memory or GPU): using the lighter Qwen3.5-0.8B instead.',
454+ queuedAhead: 'Queued ({n} ahead): it is kept even if you reload.',
455+ queueRestored: '{n} pending message(s) recovered: I will process them as soon as the brain loads.',
456+ basicModeOn: 'Basic mode: no model, direct commands.',
457+ modelPreparing: 'Preparing the model…',
458+ modelFailed: '⚠️ Could not load {id}: {err}',
459+ errApiKeyMissing: 'the API key is missing (advanced settings)', errProviderUnset: 'the provider is not configured',
460+ loadingGemma: 'Loading Gemma (several GB the first time)… meanwhile, Basic mode is here for you.',
461+ loadingLocal: 'Loading the local brain… meanwhile, Basic mode is here for you.',
462+ copilotLightBrain: 'Copilot: starting with the light brain so it does not compete with the translator. For sales or precision, pick Gemma at the top (desktop).',
463+ hwPhDraft: 'Hard Work · draft…', hwPhCritique: 'Hard Work · self-review {n}', hwPhRewrite: 'Hard Work · rewriting {n}',
464+ hwPhDone: 'Hard Work · done', hwPhOpening: 'Hard Work · opening the folder…', hwPhPlan: 'Hard Work · {n} parts ({k}k)',
465+ hwPhPlanTrunc: ' — trimmed to the maximum', hwPhMap: 'Hard Work · reading {i}/{n}', hwPhMerge: 'Hard Work · merging group {g}/{n}',
466+ hwPhSynth: 'Hard Work · synthesising…',
467+ hwRead: '⛏ Hard Work (RLM): I read {folder} in {n} parts, {kept} with signal.',
468+ hwReadTrunc: ' Material trimmed to the maximum: narrow the folder to cover all of it.',
469+ hwFailed: 'Hard Work failed: {err}',
470+ ramFreedMsg: '⚠️ Careful: your computer is very short of memory and may slow down or fail if you go on. For now I stopped and freed the model. If you want, pick it again in the selector at the top.',
471+ ramFreedToast: '⚠️ Memory very full: local model freed automatically',
472+ ramWarn: '⚠️ Browser memory is at {pct} %: if it keeps rising, I will free the model myself.',
473+ basicHelp: 'I am in Basic mode (no model). I understand a few direct commands, written in Spanish:\n• «hazme un reloj / una app de notas / una calculadora» (make a clock / a notes app / a calculator)\n• «autoriza una carpeta» (authorize a folder) · «lista los archivos» (list the files) · «lee <archivo>» (read <file>)\n• «recuérdame dentro de N minutos <algo>» (remind me in N minutes) · «lista las tareas» (list tasks)\n• «guarda el secreto <nombre>: <valor>» (save a secret) · «lista los secretos» (list secrets)\n• «abre https://…» (open a web page)\nFor free language and custom apps, load a model in the [model picker](#/modelo) at the top.',
474+ basicHi: 'Hi! ', basicCouldNot: 'I could not: {err}',
475+ vaultNeedNameSecret: 'The name or the secret is missing.', vaultNeedName: 'The name is missing.', vaultNoSecret: 'There is no secret “{name}”',
476+ stApps: 'Generated apps', stSkills: 'Skills', stHistory: 'Conversation', stMemory: 'Memory',
477+ stTasks: 'Scheduled tasks', stVault: 'Vault (encrypted)', stPrefs: 'Preferences',
478+ vmTitle: 'Speed of this machine', vmCtx: 'context {n}',
479+ vmPrefill: 'tok/s reading the prompt', vmGen: 'tok/s writing', vmTtft: 'to the first letter',
480+ vmProcessed: 'tokens processed', vmReused: ' · {n} reused', vmNoTurns: 'You have not talked to the model yet.',
481+ vmAlert: 'Reading the prompt is almost as slow as writing, and that should not happen: reading processes hundreds of positions at once and writing only one. It usually means something else is competing for the GPU, or the model barely fits. On an idle machine reading is several times faster.',
482+ vmReading: 'Reading the prompt', vmWriting: 'Writing', vmNeed2: '{what}: 2 turns are needed to draw',
483+ vmMax: 'max {v} tok/s', vmTurns: '{n} turns', vmTasks: 'Tasks', vmSolved: 'solved ({ok} of {n})',
484+ vmPerTask: 'per task, median', vmNoTasks: 'No tasks recorded yet.',
485+ vmNote: 'These are YOUR machine’s numbers in this session, measured by the engine itself. They change with the machine, with what else is open and with temperature, so they are not a product figure.',
486+ vmChipWriting: 'Writing at {g} tok/s · the prompt was read at {p} tok/s · first letter after {t}. Click to see the chart.',
487+ vmChipReading: 'Reading the prompt at {p} tok/s. Click to see the chart.',
415488 optBasic: 'Basic (no model)', optWeakGroup: '⚠ Advanced · no performance guarantee', optAdvanced: '⚠ Advanced',
416489 optSavedOnce: 'saved: downloaded only the first time', optSaved: 'saved', optLighter: 'lighter, loads faster',
417490 optWeak: 'low performance', optDefault: 'default', optLight: '— light', optText: '— text', optSlow: '— slow', optCloud: ' · cloud',
modified web/js/kernel.js +41 −36
@@ -334,7 +334,7 @@
334334 const el = ui.addMsg('user queued', text);
335335 queue.push({ id: nuevoId(), text, el, hard });
336336 persistQueue();
337- if (queue.length > 1) ui.toast(`En cola (${queue.length - 1} por delante) — no se pierde ni refrescando.`);
337+ if (queue.length > 1) ui.toast(t('queuedAhead', { n: queue.length - 1 }));
338338 pump();
339339 }
340340
@@ -520,10 +520,10 @@
520520 const res = await deepCreate({
521521 brief: question, provider: agent.provider, rounds: 1, signal,
522522 onProgress: p => thinking.tool(
523- p.phase === 'draft' ? 'Hard Work · borrador…'
524- : p.phase === 'critique' ? `Hard Work · autocrítica ${p.round}`
525- : p.phase === 'rewrite' ? `Hard Work · reescribiendo ${p.round}`
526- : 'Hard Work · listo'),
523+ p.phase === 'draft' ? t('hwPhDraft')
524+ : p.phase === 'critique' ? t('hwPhCritique', { n: p.round })
525+ : p.phase === 'rewrite' ? t('hwPhRewrite', { n: p.round })
526+ : t('hwPhDone')),
527527 });
528528 siParado();
529529 thinking.remove();
@@ -541,7 +541,7 @@
541541 agent.history.push({ role: 'assistant', content: fallo ? '(Hard Work: no pude guardar la app: ' + fallo + ')' : '(app creada con Hard Work)', ts: Date.now() });
542542 return; // el finally resetea busy y guarda el histórico
543543 }
544- thinking.tool('Hard Work · abriendo carpeta…');
544+ thinking.tool(t('hwPhOpening'));
545545 const root = await fs.root();
546546 const context = await gatherFolder(root, { maxBytes: 1.5e6 });
547547 siParado();
@@ -549,15 +549,15 @@
549549 const res = await hardWork({
550550 question, context, provider: agent.provider, signal,
551551 onProgress: p => {
552- if (p.phase === 'plan') thinking.tool(`Hard Work · ${p.chunks} partes (${Math.round(p.chars / 1000)}k)${p.truncated ? ' — recorté al máximo' : ''}`);
553- else if (p.phase === 'map') thinking.tool(`Hard Work · leyendo ${p.i}/${p.n}`);
554- else if (p.phase === 'reduce-group') thinking.tool(`Hard Work · fundiendo grupo ${p.g}/${p.n}`);
555- else if (p.phase === 'reduce') thinking.tool('Hard Work · sintetizando…');
552+ if (p.phase === 'plan') thinking.tool(t('hwPhPlan', { n: p.chunks, k: Math.round(p.chars / 1000) }) + (p.truncated ? t('hwPhPlanTrunc') : ''));
553+ else if (p.phase === 'map') thinking.tool(t('hwPhMap', { i: p.i, n: p.n }));
554+ else if (p.phase === 'reduce-group') thinking.tool(t('hwPhMerge', { g: p.g, n: p.n }));
555+ else if (p.phase === 'reduce') thinking.tool(t('hwPhSynth'));
556556 },
557557 });
558558 siParado();
559559 thinking.remove();
560- ui.addMsg('assistant', res.answer + `\n\n_⛏ Hard Work (RLM): leí ${names[0]} en ${res.chunks} partes, ${res.kept} con señal.${res.truncated ? ' Material recortado al máximo — acota la carpeta para abarcarlo entero.' : ''}_`);
560+ ui.addMsg('assistant', res.answer + `\n\n_${t('hwRead', { folder: names[0], n: res.chunks, kept: res.kept })}${res.truncated ? t('hwReadTrunc') : ''}_`);
561561 agent.history.push({ role: 'user', content: question, ts: Date.now() });
562562 agent.history.push({ role: 'assistant', content: res.answer, ts: Date.now() });
563563 } catch (e) {
@@ -566,7 +566,7 @@
566566 // cuando el AbortError no viene de ■ sino del proveedor (el motor propio
567567 // corta el turno al descargarse): eso no es «Hard Work falló».
568568 if (signal?.aborted || e?.name === 'AbortError') avisoParado(null);
569- else ui.addMsg('assistant err', 'Hard Work falló: ' + (e?.message || String(e)));
569+ else ui.addMsg('assistant err', t('hwFailed', { err: e?.message || String(e) }));
570570 } finally {
571571 if (burbujaTurno === thinking) burbujaTurno = null;
572572 if (canceladasEnParada) avisoParado(null); // ver process()
@@ -601,7 +601,7 @@
601601 const el = ui.addMsg('user queued', it.text);
602602 queue.push({ id: it.id || nuevoId(), text: it.text, intentos: it.intentos || 0, el, hard: !!it.hard });
603603 }
604- ui.toast(`${pending.length} mensaje(s) pendientes recuperados — los proceso en cuanto cargue el cerebro.`);
604+ ui.toast(t('queueRestored', { n: pending.length }));
605605 pump();
606606 }
607607
@@ -768,8 +768,12 @@
768768 // es quien mide (`alMedir`). Con cualquier otro cerebro se monta con null y el
769769 // chip se esconde: antes se quedaba con la última cifra del motor a la vista.
770770 function montarVelocimetro(mod) {
771- import('./velocimetro.js').then(vm => vm.montar(mod?.alMedir ? mod : null)).catch(() => { /* sin velocímetro la app funciona igual */ });
771+ import('./velocimetro.js').then(vm => { vm.usarTraductor?.(t); vm.montar(mod?.alMedir ? mod : null); })
772+ .catch(() => { /* sin velocímetro la app funciona igual */ });
772773 }
774+// Sus textos van en el idioma de la página desde el principio (el módulo lo
775+// comparte Code, que pone su propio traductor).
776+import('./velocimetro.js').then(vm => vm.usarTraductor?.(t)).catch(() => { /* — */ });
773777
774778 // Ficha pública de cada cerebro local (ⓘ junto al selector). Sin ficha pública
775779 // —el 27B— no hay ⓘ: nunca se enlazan los ficheros de pesos.
@@ -783,6 +787,11 @@
783787 const etiquetaDe = id => modelOptions().find(o => o.id === id)?.label?.split(' · ')[0] || id;
784788 function pintarFicha(id) { ui.setFichaModelo(FICHAS[id] || null, etiquetaDe(id)); }
785789
790+// Errores de carga que se enseñan al usuario: los de providers/api.js (core
791+// compartido, sin i18n) llegan en español; los conocidos se traducen aquí.
792+const ERRORES_CARGA = { 'falta la clave de API (config avanzada)': 'errApiKeyMissing', 'proveedor sin configurar': 'errProviderUnset' };
793+const errorLegible = e => { const m = e?.message || String(e); return ERRORES_CARGA[m] ? t(ERRORES_CARGA[m]) : m; };
794+
786795 // `volviendo`: es la vuelta al cerebro que funcionaba tras un fallo (no se
787796 // intenta volver otra vez si también falla).
788797 async function changeModel(id, { volviendo = false } = {}) {
@@ -796,7 +805,7 @@
796805 ui.modelStatus('off');
797806 localStorage.setItem('elffuss.model', 'rules');
798807 ui.setModel('rules');
799- ui.toast('Modo básico: sin modelo, órdenes directas.');
808+ ui.toast(t('basicModeOn'));
800809 return true;
801810 }
802811 ui.modelStatus('loading');
@@ -808,7 +817,7 @@
808817 ui.modeloCargando(true); // sin cargas en paralelo: el selector espera
809818 try {
810819 const mod = await resolveProvider(id);
811- ui.modelProgress('Preparando modelo…');
820+ ui.modelProgress(t('modelPreparing'));
812821 await mod.load(p => ui.modelProgress(p));
813822 ui.modelProgress(null);
814823 agent.setProvider(mod);
@@ -838,7 +847,7 @@
838847 // funcionando te dejaba en Qwen3.5-0.8B (otra descarga de ~600 MB) en vez de
839848 // en el que tenías.
840849 if (!volviendo && previo && previo !== 'rules' && previo !== id) {
841- ui.toast(t('modelFailedBack', { id: etiquetaDe(id), err: e?.message || String(e), prev: etiquetaDe(previo) }));
850+ ui.toast(t('modelFailedBack', { id: etiquetaDe(id), err: errorLegible(e), prev: etiquetaDe(previo) }));
842851 await changeModel(previo, { volviendo: true });
843852 return false;
844853 }
@@ -857,7 +866,7 @@
857866 montarVelocimetro(null);
858867 pintarFicha(null);
859868 ui.setModel('rules');
860- ui.toast('⚠️ No se pudo cargar ' + id + ': ' + (e?.message || String(e)));
869+ ui.toast(t('modelFailed', { id: etiquetaDe(id), err: errorLegible(e) }));
861870 return false;
862871 } finally {
863872 // Pase lo que pase —éxito, fallo, o el respaldo que vuelve a entrar aquí—
@@ -1145,7 +1154,7 @@
11451154 // ligero para no competir. Pero tu elección manda: si escogiste Gemma,
11461155 // se respeta — pisarla era un error.
11471156 if (/[?&]copilot=1/.test(location.search) && !saved) {
1148- ui.toast('Copiloto: arranco con el cerebro ligero para no competir con el traductor. Para ventas/precisión, elige Gemma arriba (escritorio).');
1157+ ui.toast(t('copilotLightBrain'));
11491158 if (await changeModel('onnx:qwen3.5-0.8b')) return;
11501159 }
11511160 const available = new Set(modelOptions().map(o => o.id));
@@ -1172,9 +1181,7 @@
11721181 return;
11731182 }
11741183 const first = chain[0];
1175- ui.toast(first.startsWith('litert')
1176- ? 'Cargando Gemma (varios GB la 1ª vez)… mientras, el modo básico te atiende.'
1177- : 'Cargando el cerebro local… mientras, el modo básico te atiende.');
1184+ ui.toast(first.startsWith('litert') ? t('loadingGemma') : t('loadingLocal'));
11781185 for (const id of chain)
11791186 if (await changeModel(id)) return;
11801187 } finally {
@@ -1201,15 +1208,11 @@
12011208 ui.setModel('rules');
12021209 ui.modelStatus('off');
12031210 try { await mod?.unload?.(); } catch { /* mejor esfuerzo */ }
1204- ui.addMsg('assistant',
1205- '⚠️ Ojo: tu ordenador está muy a full de memoria — puedes experimentar caídas ' +
1206- 'o rendimiento lento si sigues usándolo. Por el momento me he parado y he ' +
1207- 'liberado el modelo. Si quieres, me arrancas de nuevo desde el selector ' +
1208- 'de arriba. ');
1209- ui.toast('⚠️ RAM muy llena: modelo local liberado automáticamente');
1211+ ui.addMsg('assistant', t('ramFreedMsg'));
1212+ ui.toast(t('ramFreedToast'));
12101213 } else if (ratio > 0.82 && !ramWarned) {
12111214 ramWarned = true;
1212- ui.toast(`⚠️ La memoria del navegador va al ${Math.round(ratio * 100)}% — si sigue subiendo, liberaré el modelo yo sola.`);
1215+ ui.toast(t('ramWarn', { pct: Math.round(ratio * 100) }));
12131216 }
12141217 }, 15000);
12151218
@@ -1237,15 +1240,17 @@
12371240 workspace.init({
12381241 app: 'claw', ns: 'elffuss', db,
12391242 stores: [
1240- { id: 'apps', label: 'Apps generadas', icon: '🎨', kind: 'idb-store', store: 'apps',
1243+ // Las etiquetas son getters: se leen al pintar «Qué hay guardado», en el idioma
1244+ // de la página (antes salían en español también en inglés).
1245+ { id: 'apps', get label() { return t('stApps'); }, icon: '🎨', kind: 'idb-store', store: 'apps',
12411246 files: { ext: '.html', name: a => a.name, body: a => a.html } },
1242- { id: 'skills', label: 'Skills', icon: '🧩', kind: 'idb-key', store: 'kv', key: 'skills',
1247+ { id: 'skills', get label() { return t('stSkills'); }, icon: '🧩', kind: 'idb-key', store: 'kv', key: 'skills',
12431248 files: { ext: '.md', name: s => s.name, body: s => `---\nname: ${s.name}\ndescription: ${s.description || ''}\n---\n\n${s.content || ''}` } },
1244- { id: 'history', label: 'Conversación', icon: '💬', kind: 'idb-key', store: 'kv', key: 'history' },
1245- { id: 'memory', label: 'Memoria', icon: '🧠', kind: 'idb-store', store: 'memory' },
1246- { id: 'tasks', label: 'Tareas programadas', icon: '⏰', kind: 'idb-store', store: 'tasks' },
1247- { id: 'vault', label: 'Bóveda (cifrada)', icon: '🔐', kind: 'idb-store', store: 'vault', sensitive: true },
1248- { id: 'prefs', label: 'Preferencias', icon: '⚙️', kind: 'ls',
1249+ { id: 'history', get label() { return t('stHistory'); }, icon: '💬', kind: 'idb-key', store: 'kv', key: 'history' },
1250+ { id: 'memory', get label() { return t('stMemory'); }, icon: '🧠', kind: 'idb-store', store: 'memory' },
1251+ { id: 'tasks', get label() { return t('stTasks'); }, icon: '⏰', kind: 'idb-store', store: 'tasks' },
1252+ { id: 'vault', get label() { return t('stVault'); }, icon: '🔐', kind: 'idb-store', store: 'vault', sensitive: true },
1253+ { id: 'prefs', get label() { return t('stPrefs'); }, icon: '⚙️', kind: 'ls',
12491254 keys: ['elffuss.model', 'elffuss.acer', 'elffuss.resumen', 'elffuss.semantic'] },
12501255 ],
12511256 });
modified web/js/providers/rules.js +10 −12
@@ -1,5 +1,7 @@
11 // «Modo básico»: cerebro determinista sin modelo — cubre las demos clave sin
22 // descargar nada. Para lenguaje libre, carga un modelo en el selector de modelo.
3+// `tr` y no `t`: dentro de chat() `t` es el texto en minúsculas.
4+import { t as tr } from '../i18n.js';
35 export const name = 'Básico (sin modelo)';
46 export async function load() {}
57
@@ -71,15 +73,11 @@
7173 const generic = desc => SHELL('Boceto',
7274 `<div style="max-width:560px;text-align:center;padding:20px"><h2>✳ Boceto de app</h2><p style="color:#8b949e">Esto es un boceto del modo básico. Pediste:</p><blockquote style="background:#161b22;border-left:3px solid #ff4d8d;padding:12px;border-radius:8px;text-align:left">${desc.replace(/</g, '&lt;')}</blockquote><p style="color:#8b949e">Carga un modelo (en el selector de modelo, arriba) y Elffuss generará esta app de verdad, a medida.</p></div>`, '');
7375
74-const HELP = `Estoy en modo básico (sin modelo). Entiendo órdenes directas:
75-• «hazme un reloj / una app de notas / una calculadora»
76-• «autoriza una carpeta» · «lista los archivos» · «lee <archivo>»
77-• «recuérdame dentro de N minutos <algo>» · «lista las tareas»
78-• «guarda el secreto <nombre>: <valor>» · «lista los secretos»
79-• «abre https://…»
80-Para lenguaje libre y apps a medida, carga un modelo en el [selector de modelo](#/modelo) de arriba.`;
81-// (El selector de modelo es el desplegable de la cabecera; 🧠 es la Mente. El
82-// enlace #/modelo lo enfoca: ver rutas.js.)
76+// La ayuda va en el idioma de la página (i18n: basicHelp). Las órdenes que
77+// entiende este motor son en español, y en inglés se dice así, con su traducción
78+// al lado. (El selector de modelo es el desplegable de la cabecera; 🧠 es la
79+// Mente. El enlace #/modelo lo enfoca: ver rutas.js.)
80+const HELP = () => tr('basicHelp');
8381
8482 export async function chat(history) {
8583 const last = history[history.length - 1];
@@ -88,7 +86,7 @@
8886 // Tras una herramienta: convertir su resultado en la respuesta…
8987 if (text.startsWith('[resultado')) {
9088 const body = text.slice(text.indexOf('\n') + 1).trim();
91- if (body.startsWith('ERROR:')) return 'No pude: ' + body.slice(6).trim();
89+ if (body.startsWith('ERROR:')) return tr('basicCouldNot', { err: body.slice(6).trim() });
9290 // …o encadenar: si lo leído era para un gráfico, generar la app ahora.
9391 if (text.startsWith('[resultado fs.read')) {
9492 const prevUser = [...history].reverse().find(m => m.role === 'user' && !m.content.startsWith('['));
@@ -188,6 +186,6 @@
188186 if (mOpen && !url) return call({ tool: 'app.open', args: { name: mOpen[1] } });
189187 if (/(lista|ver|muestra|qué|que).*apps/.test(t)) return call({ tool: 'app.list', args: {} });
190188
191- if (/^(hola|buenas|hey|hi)\b/.test(t)) return '¡Hola! ' + HELP;
192- return HELP;
189+ if (/^(hola|buenas|hey|hi)\b/.test(t)) return tr('basicHi') + HELP();
190+ return HELP();
193191 }
modified web/js/tools/vault.js +3 −3
@@ -80,7 +80,7 @@
8080 }
8181
8282 export async function setSecret({ name, secret } = {}, { desdePanel = false } = {}) {
83- if (!name || !secret) throw new Error('Faltan name o secret');
83+ if (!name || !secret) throw new Error(t('vaultNeedNameSecret'));
8484 if (!desdePanel) await requirePerm('vault', t('pdVaultSet', { name }));
8585 mustBeOpen();
8686 await db.set('vault', 's:' + name, await encrypt(secret));
@@ -92,7 +92,7 @@
9292 if (!desdePanel) await requirePerm('vault', t('pdVaultGet', { name }));
9393 mustBeOpen();
9494 const blob = await db.get('vault', 's:' + name);
95- if (!blob) throw new Error(`No existe el secreto «${name}»`);
95+ if (!blob) throw new Error(t('vaultNoSecret', { name }));
9696 armLock();
9797 return decrypt(blob);
9898 }
@@ -100,7 +100,7 @@
100100 // Borrar un secreto pide la bóveda ABIERTA, como leerlo: con ella bloqueada el
101101 // panel ni siquiera enseña la lista (ver alBloquear).
102102 export async function removeSecret({ name } = {}) {
103- if (!name) throw new Error('Falta name');
103+ if (!name) throw new Error(t('vaultNeedName'));
104104 mustBeOpen();
105105 await db.del('vault', 's:' + name);
106106 armLock();
modified web/js/velocimetro.js +51 −29
@@ -17,6 +17,35 @@
1717 // try/catch y el panel se pinta igual sin él.
1818
1919 const CLAVE = 'elffuss.velocimetro.v1';
20+
21+// Textos. Este módulo lo comparten Claw y Code y cada una tiene su i18n: la app
22+// anfitriona pasa su traductor con usarTraductor(t) (t(clave, vars) → texto, o la
23+// propia clave si no la tiene). Sin traductor, o sin la clave, va en español,
24+// como hasta ahora. Antes todo estaba escrito aquí en español y en inglés salían
25+// el título del chip, el panel y su nombre accesible en español.
26+const ES = {
27+ vmTitle: 'Velocidad de esta máquina', vmCtx: 'contexto {n}',
28+ vmPrefill: 'tok/s leyendo el prompt', vmGen: 'tok/s escribiendo', vmTtft: 'hasta la primera letra',
29+ vmProcessed: 'tokens procesados', vmReused: ' · {n} reusados', vmNoTurns: 'Todavía no has hablado con el modelo.',
30+ vmAlert: 'Leer el prompt va casi tan lento como escribir, y eso no debería pasar: leer procesa cientos de posiciones a la vez y escribir solo una. Suele significar que algo está compitiendo por la GPU, o que el modelo no cabe holgado. En un equipo despejado leer va varias veces más rápido.',
31+ vmReading: 'Leyendo el prompt', vmWriting: 'Escribiendo', vmNeed2: '{what}: hacen falta 2 turnos para dibujar',
32+ vmMax: 'máx {v} tok/s', vmTurns: '{n} turnos', vmTasks: 'Tareas', vmSolved: 'se resuelven ({ok} de {n})',
33+ vmPerTask: 'por tarea, mediana', vmNoTasks: 'Sin tareas registradas todavía.',
34+ vmNote: 'Son los números de TU equipo en esta sesión, medidos por el propio motor. Cambian con la máquina, con lo que tengas abierto y con la temperatura, así que no son una cifra del producto.',
35+ vmChipWriting: 'Escribiendo a {g} tok/s · el prompt se leyó a {p} tok/s · primera letra en {t}. Pulsa para ver la gráfica.',
36+ vmChipReading: 'Leyendo el prompt a {p} tok/s. Pulsa para ver la gráfica.',
37+};
38+let traductor = null;
39+export function usarTraductor(fn) { traductor = typeof fn === 'function' ? fn : null; }
40+function tx(clave, vars) {
41+ let s = null;
42+ try { s = traductor?.(clave, vars); } catch { /* traductor roto: español */ }
43+ if (typeof s === 'string' && s && s !== clave) return s;
44+ const base = ES[clave] ?? clave;
45+ return vars ? base.replace(/\{(\w+)\}/g, (_, k) => (vars[k] ?? '')) : base;
46+}
47+// Lo que se mete en innerHTML va escapado (el nombre del modelo, los textos).
48+const esc = v => String(v).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
2049 const MAX = 60; // turnos guardados: suficiente para ver forma
2150 let hist = []; // [{ p: prefillTokS, g: genTokS, t: ttftMs }]
2251 let tareas = []; // [{ ok: bool, ms: number }]
@@ -55,12 +84,12 @@
5584
5685 function grafica(key, color, etiqueta) {
5786 const vals = hist.map(x => x[key]).filter(v => Number.isFinite(v) && v > 0);
58- if (vals.length < 2) return `<div class="vm-vacio">${etiqueta}: hacen falta 2 turnos para dibujar</div>`;
87+ if (vals.length < 2) return `<div class="vm-vacio">${esc(tx('vmNeed2', { what: etiqueta }))}</div>`;
5988 const max = Math.max(...vals);
6089 return `<div class="vm-graf">
61- <div class="vm-graf-top"><span>${etiqueta}</span><span>máx ${uno(max)} tok/s</span></div>
62- <svg viewBox="0 0 220 38" preserveAspectRatio="none" aria-label="${etiqueta}">${linea(vals, 220, 38, color)}</svg>
63- <div class="vm-graf-pie">${vals.length} turnos</div>
90+ <div class="vm-graf-top"><span>${esc(etiqueta)}</span><span>${esc(tx('vmMax', { v: uno(max) }))}</span></div>
91+ <svg viewBox="0 0 220 38" preserveAspectRatio="none" aria-label="${esc(etiqueta)}">${linea(vals, 220, 38, color)}</svg>
92+ <div class="vm-graf-pie">${esc(tx('vmTurns', { n: vals.length }))}</div>
6493 </div>`;
6594 }
6695
@@ -86,29 +115,23 @@
86115 const ctxTxt = ctx ? (ctx >= 1024 ? `${Math.round(ctx / 1024)}k` : String(ctx)) : '';
87116
88117 panel.innerHTML = `
89- <div class="vm-tit">Velocidad de esta máquina${modelo ? ` <span class="vm-modelo">${modelo}${ctxTxt ? ` · contexto ${ctxTxt}` : ''}</span>` : ''}</div>
118+ <div class="vm-tit">${esc(tx('vmTitle'))}${modelo ? ` <span class="vm-modelo">${esc(modelo)}${ctxTxt ? ` · ${esc(tx('vmCtx', { n: ctxTxt }))}` : ''}</span>` : ''}</div>
90119 ${m ? `<div class="vm-filas">
91- <div><b>${uno(m.prefillTokS)}</b><span>tok/s leyendo el prompt</span></div>
92- <div><b>${uno(m.genTokS)}</b><span>tok/s escribiendo</span></div>
93- <div><b>${ms(m.ttftMs)}</b><span>hasta la primera letra</span></div>
94- <div><b>${m.procesados}</b><span>tokens procesados${m.reusados ? ` · ${m.reusados} reusados` : ''}</span></div>
95- </div>` : `<div class="vm-vacio">Todavía no has hablado con el modelo.</div>`}
96- ${m && m.genTokS > 0 && m.prefillTokS < m.genTokS * 1.5 ? `<div class="vm-alerta">
97- Leer el prompt va casi tan lento como escribir, y eso no deberia pasar:
98- leer procesa cientos de posiciones a la vez y escribir solo una. Suele
99- significar que algo esta compitiendo por la GPU, o que el modelo no cabe
100- holgado. En un equipo despejado leer va varias veces mas rapido.
101- </div>` : ''}
102- ${grafica('p', 'var(--accent2, #6e63c5)', 'Leyendo el prompt')}
103- ${grafica('g', 'var(--accent, #4ade80)', 'Escribiendo')}
104- <div class="vm-tit vm-tit2">Tareas</div>
120+ <div><b>${uno(m.prefillTokS)}</b><span>${esc(tx('vmPrefill'))}</span></div>
121+ <div><b>${uno(m.genTokS)}</b><span>${esc(tx('vmGen'))}</span></div>
122+ <div><b>${ms(m.ttftMs)}</b><span>${esc(tx('vmTtft'))}</span></div>
123+ <div><b>${m.procesados}</b><span>${esc(tx('vmProcessed'))}${m.reusados ? esc(tx('vmReused', { n: m.reusados })) : ''}</span></div>
124+ </div>` : `<div class="vm-vacio">${esc(tx('vmNoTurns'))}</div>`}
125+ ${m && m.genTokS > 0 && m.prefillTokS < m.genTokS * 1.5 ? `<div class="vm-alerta">${esc(tx('vmAlert'))}</div>` : ''}
126+ ${grafica('p', 'var(--accent2, #6e63c5)', tx('vmReading'))}
127+ ${grafica('g', 'var(--accent, #4ade80)', tx('vmWriting'))}
128+ <div class="vm-tit vm-tit2">${esc(tx('vmTasks'))}</div>
105129 ${hechas ? `<div class="vm-filas">
106- <div><b>${tasa}%</b><span>se resuelven (${bien} de ${hechas})</span></div>
107- <div><b>${ms(tmed)}</b><span>por tarea, mediana</span></div>
108- </div>` : `<div class="vm-vacio">Sin tareas registradas todavía.</div>`}
109- <div class="vm-nota">Son los números de TU equipo en esta sesión, medidos por el
110- propio motor. Cambian con la máquina, con lo que tengas abierto y con la
111- temperatura, así que no son una cifra del producto.</div>`;
130+ <div><b>${tasa}%</b><span>${esc(tx('vmSolved', { ok: bien, n: hechas }))}</span></div>
131+ <div><b>${ms(tmed)}</b><span>${esc(tx('vmPerTask'))}</span></div>
132+ </div>` : `<div class="vm-vacio">${esc(tx('vmNoTasks'))}</div>`}
133+ <div class="vm-nota">${esc(tx('vmNote'))}</div>`;
134+ panel.setAttribute('aria-label', tx('vmTitle'));
112135 }
113136
114137 function pintarChip(m) {
@@ -121,9 +144,8 @@
121144 const v = escribiendo ? m.genTokS : m.prefillTokS;
122145 chip.textContent = `⚡ ${uno(v)} tok/s`;
123146 chip.title = escribiendo
124- ? `Escribiendo a ${uno(m.genTokS)} tok/s · el prompt se leyó a ${uno(m.prefillTokS)} tok/s · ` +
125- `primera letra en ${ms(m.ttftMs)}. Pulsa para ver la gráfica.`
126- : `Leyendo el prompt a ${uno(m.prefillTokS)} tok/s. Pulsa para ver la gráfica.`;
147+ ? tx('vmChipWriting', { g: uno(m.genTokS), p: uno(m.prefillTokS), t: ms(m.ttftMs) })
148+ : tx('vmChipReading', { p: uno(m.prefillTokS) });
127149 }
128150
129151 /** Una tarea del agente ha terminado. `ok`: ¿se resolvió? `ms`: lo que costó. */
@@ -155,7 +177,7 @@
155177 chip.setAttribute('aria-expanded', 'false');
156178 if (panel) {
157179 panel.setAttribute('role', 'region');
158- panel.setAttribute('aria-label', 'Velocidad de esta máquina');
180+ panel.setAttribute('aria-label', tx('vmTitle'));
159181 }
160182 chip.addEventListener('click', () => abrirPanel(!!panel?.hidden));
161183 // Cerrar al pulsar fuera, como el resto de los desplegables de la cabecera.