Elffuss BraidHub

utopia-ia/elffuss-code public

d7be1ec7f98f · 151.5 KiBRawPermalink
1// Elffuss Code: landing («abre tu carpeta») → IDE con la elfa integrada.
2import { parseToolCall } from './agent.js';
3import * as rules from './providers/rules.js';
4import * as codeTools from './tools/code.js';
5import * as db from './db.js';
6import * as settings from './settings.js';
7import { initEditor, refreshTree, openFile, gotoLine, triggerEditor, hasEditor, saveActive, activeFile, focusEditor, loadExt } from './ide.js';
8import { ACTIVITY, UI } from './icons.js';
9import { renderMarkdown } from './md.js';
10import * as skills from './skills.js';
11import * as terminal from './terminal.js';
12import * as shell from './shell.js';
13import { setTerminalEcho } from './tools/index.js';
14import { ensureModelCache, cacheEstimate, modelUsage, clearModels } from './model-cache.js';
15import * as ceo from './ceo.js';
16import * as mind from './mind.js';
17import { buildCityAdapter, loadThoughtsAdapter } from './mind-adapter.js';
18import { humanizeStreamPreview } from './humanize.js';
19import { t, applyI18n, uiLang } from './i18n.js';
20import * as bridge from './bridge.js';
21import * as conv from './conversations.js';
22import { TASK_PREFIX } from './goal.js';
23import { hardWork, gatherFolder } from './rlm.js';
24import * as workspace from './workspace.js';
25
26// Espacio de trabajo (core): qué de Code puede guardarse en tu disco.
27workspace.init({
28 app: 'code', ns: 'elffusscode', db,
29 stores: [
30 { id: 'conversations', label: 'Conversaciones', icon: '💬', kind: 'idb-key', store: 'kv', key: 'conversations',
31 files: { ext: '.json', name: c => c.title || c.id } },
32 { id: 'skills', label: 'Skills', icon: '🧩', kind: 'idb-key', store: 'kv', key: 'skills',
33 files: { ext: '.md', name: s => s.name, body: s => `---\nname: ${s.name}\ndescription: ${s.description || ''}\n---\n\n${s.content || ''}` } },
34 { id: 'prefs', label: 'Preferencias', icon: '⚙️', kind: 'ls',
35 keys: ['elffusscode.model', 'elffusscode.autoedit', 'elffusscode.goalmode', 'elffuss.acer', 'elffuss.resumen', 'elffuss.semantic', 'elffusscode.theme'] },
36 // extensiones de VS Code instaladas: solo la lista (id, versión, activa);
37 // los paquetes viven en su propia base (js/ext/store.js)
38 { id: 'extensions', label: 'Extensiones', icon: '🧱', kind: 'idb-key', store: 'kv', key: 'extensions' },
39 ],
40});
41workspace.restore().catch(() => {});
42
43// AVISAR ANTES DE SALIR si hay un turno en marcha.
44// ─────────────────────────────────────────────────────────────────────────────
45// La conversación sobrevive a recargar —se guarda en IndexedDB y se restaura al
46// arrancar—, pero el turno EN CURSO no: la respuesta solo se persiste cuando el
47// turno termina, así que refrescar a mitad de generación tira lo que llevara
48// escrito. Y volver a empezar no es gratis: hay que subir el modelo a la GPU
49// otra vez y releer la conversación entera antes de poder seguir, que con el
50// modelo grande son minutos.
51//
52// El navegador NO deja poner un texto propio —ignora lo que se devuelva y
53// enseña el suyo— así que esto solo consigue que PREGUNTE. Es poco, pero es la
54// diferencia entre perderlo sin enterarte y que te den la opción.
55//
56// Solo se avisa si de verdad hay algo vivo: un aviso que salta siempre se
57// aprende a ignorar en dos días y entonces ya no avisa de nada.
58// `hayTrabajoVivo` cubre LAS DOS cosas, no solo el turno de chat: lo más caro
59// de perder es irse a mitad de subir el modelo a la GPU, que con el grande son
60// minutos y hay que rehacerlo entero. `loadingId` es no-nulo mientras eso pasa.
61const hayTrabajoVivo = () => conv.isBusy() || loadingId !== null;
62addEventListener('beforeunload', (e) => {
63 if (!hayTrabajoVivo()) return;
64 e.preventDefault();
65 e.returnValue = ''; // Safari y navegadores viejos miran esto
66});
67if (workspace.autosaveEnabled()) workspace.autosave({ enabled: true });
68// «Guardar solo» guarda de verdad: cada escritura de un almacén que el espacio
69// de trabajo copia a disco se le avisa con touch(). Antes nada lo llamaba y el
70// autoguardado no escribía nunca, con la casilla marcada.
71db.onWrite((store, key) => {
72 if (store !== 'kv') return;
73 if (key === 'conversations') workspace.touch('conversations');
74 else if (key === 'skills') workspace.touch('skills');
75});
76// Las preferencias viven en localStorage: se avisa al cambiarlas.
77const guardaPref = (k, v) => { try { localStorage.setItem(k, v); } catch { /* lleno o bloqueado */ } workspace.touch('prefs'); };
78
79import * as telemetry from './telemetry.js';
80
81const $ = id => document.getElementById(id);
82// Atajos tal y como se pulsan en ESTA máquina: en un Mac el editor guarda con
83// ⌘S y Ctrl+S no hace nada, así que anunciar «Ctrl+S» era mandar a pulsar algo
84// que no funciona.
85const IS_MAC = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || '');
86const atajo = (k, shift = false) => IS_MAC ? '⌘' + (shift ? '⇧' : '') + k : 'Ctrl+' + (shift ? 'Shift+' : '') + k;
87// Acciones del editor que no hacen nada sin un fichero abierto: se dice en vez
88// de no hacer nada.
89const conFichero = fn => () => { if (!activeFile()) { $('statusbar').textContent = t('noFileOpen'); return; } fn(); };
90telemetry.init('elffuss-code'); // opt-in, apagado por defecto — ver Ajustes
91conv.setProvider(rules); // proveedor por defecto para cualquier conversación que se cree
92let activeModel = 'rules';
93
94// ---------- chat ----------
95// Los `paths` entre backticks del chat (README.md, .elffuss/soul/x.md…) se
96// vuelven ENLACES que abren el fichero en el editor (y en su línea si viene
97// «ruta:línea»). Son <a href="#/file/ruta:línea">: se llega con Tab, se abren
98// con Enter, y el enlace sirve para volver a ese sitio (ver abreDesdeHash).
99// Antes eran <code> con un onclick: solo ratón y sin línea.
100const RUTA_RE = /^([\w.-]+(?:\/[\w.-]+)*\.[a-z0-9]{1,10})(?::(\d+))?$/i;
101function enlaceFichero(path, line, texto) {
102 const a = document.createElement('a');
103 a.className = 'file-link';
104 a.href = '#/file/' + encodeURI(path) + (line ? ':' + line : '');
105 a.textContent = texto;
106 a.title = t('openPathTitle', { path: path + (line ? ':' + line : '') });
107 a.onclick = e => {
108 if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return; // pestaña nueva: que lo abra el navegador
109 e.preventDefault();
110 openFile(path).then(() => { if (line) gotoLine(+line); });
111 };
112 return a;
113}
114function linkifyFilePaths(root) {
115 root.querySelectorAll('code').forEach(el => {
116 if (el.closest('pre')) return;
117 const txt = el.textContent.trim();
118 const m = txt.match(RUTA_RE);
119 if (!m || /[{}()<>]/.test(txt)) return;
120 el.classList.add('file-link');
121 el.replaceChildren(enlaceFichero(m[1], m[2], txt));
122 });
123}
124// #/file/ruta[:línea] abre ese fichero: lo usan los enlaces de arriba (abrir
125// en otra pestaña) y sirve para volver al mismo sitio tras recargar.
126function abreDesdeHash() {
127 let h = location.hash;
128 try { h = decodeURI(h); } catch { /* — */ }
129 const m = h.match(/^#\/file\/(.+?)(?::(\d+))?$/);
130 if (!m || !codeTools.handle()) return;
131 openFile(m[1]).then(() => { if (m[2]) gotoLine(+m[2]); });
132}
133addEventListener('hashchange', abreDesdeHash);
134
135// Todo lo que pinta el chat entra por aquí. Lo que se escribió mientras la elfa
136// trabajaba espera AL FINAL, marcado «en cola» (⏳): lo que va llegando del turno
137// en curso se coloca ANTES de esos mensajes, para que una respuesta no se lea
138// como si contestara a un mensaje que todavía no ha empezado.
139function appendLog(node) {
140 const log = $('chat-log');
141 // Los descartados al parar también hacen de tope mientras el turno parado se
142 // suelta: su «(Parado.)» va encima de ellos, no debajo.
143 const enCola = node.classList.contains('queued') ? null : log.querySelector(':scope > .msg.user.queued, :scope > .msg.user[data-parada]');
144 if (enCola) log.insertBefore(node, enCola); else log.appendChild(node);
145}
146
147function addMsg(cls, text) {
148 const div = document.createElement('div');
149 div.className = 'msg ' + cls;
150 // las respuestas se renderizan como markdown (estilo plugin de Claude Code);
151 // lo del usuario y los errores, como texto plano
152 if (/^(assistant$|sys)/.test(cls)) {
153 div.classList.add('md');
154 // cap defensivo: no volcar miles de nodos si una respuesta trae un archivo entero
155 div.innerHTML = renderMarkdown(text.length > 8000 ? text.slice(0, 8000) + '\n… (recortado)' : text);
156 linkifyFilePaths(div);
157 } else {
158 div.textContent = text;
159 }
160 appendLog(div);
161 $('chat-log').scrollTop = $('chat-log').scrollHeight;
162 return div;
163}
164
165// estilo plugin de Claude Code: ● herramienta en negrita + detalle plegable
166function addTool(tool, arg) {
167 const div = document.createElement('div');
168 div.className = 'msg tool';
169 const dot = document.createElement('span');
170 dot.className = 'tdot';
171 const b = document.createElement('b');
172 b.textContent = tool;
173 div.append(dot, b);
174 if (arg) {
175 const a = document.createElement('span');
176 a.className = 'targ';
177 const txt = String(arg).slice(0, 60);
178 // «● code.read src/app.js»: la ruta se abre con un clic (o Enter)
179 const m = String(arg).match(RUTA_RE);
180 if (m) a.appendChild(enlaceFichero(m[1], m[2], txt)); else a.textContent = txt;
181 div.appendChild(a);
182 }
183 appendLog(div);
184 $('chat-log').scrollTop = $('chat-log').scrollHeight;
185 return div;
186}
187
188function addToolResult(result) {
189 const err = result.startsWith('ERROR');
190 const det = document.createElement('details');
191 det.className = 'msg tool-result' + (err ? ' err' : '');
192 const sum = document.createElement('summary');
193 sum.textContent = (err ? '⚠️ ' : '') + result.split('\n')[0].slice(0, 90);
194 const pre = document.createElement('pre');
195 // Los resultados de búsqueda («ruta:línea: texto») enlazan cada acierto.
196 for (const linea of result.slice(0, 1500).split('\n')) {
197 const m = linea.match(/^([\w.-]+(?:\/[\w.-]+)*\.[a-z0-9]{1,10}):(\d+):(.*)$/i);
198 if (m) pre.append(enlaceFichero(m[1], m[2], `${m[1]}:${m[2]}`), ':' + m[3] + '\n');
199 else pre.append(linea + '\n');
200 }
201 det.append(sum, pre);
202 appendLog(det);
203 $('chat-log').scrollTop = $('chat-log').scrollHeight;
204 return det;
205}
206
207const escapeHtml = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
208
209// 🎯 Modo Objetivo: tarjeta de plan (planificador → lista de tareas →
210// ejecutor). Un solo nodo por plan (mismo id), repintado in-place según
211// llegan los eventos 'plan'/'plan_update'/'plan_complete' — así se ve la
212// lista evolucionar en vivo en vez de reconstruirse entera cada vez.
213const PLAN_ICO = { pending: '⏳', 'in-progress': '🔄', done: '✅', failed: '❌', skipped: '⏭️', stopped: '⏹️' };
214const PLAN_STATUS_LABEL = { planning: t("planPlanning"), running: t("planRunning"), done: t("planDone"), failed: t("planFailed"), stopped: t("planStopped") };
215function renderPlanCard(plan) {
216 const domId = 'plan-' + plan.id;
217 let div = document.getElementById(domId);
218 if (!div) {
219 div = document.createElement('div');
220 div.id = domId;
221 div.className = 'msg plan-card';
222 appendLog(div);
223 }
224 div.innerHTML =
225 `<span class="plan-status">${escapeHtml(PLAN_STATUS_LABEL[plan.status] || plan.status)}</span>` +
226 `<div class="plan-head">🎯 Objetivo: ${escapeHtml(plan.goal)}</div>` +
227 (plan.planText ? `<div class="plan-summary">${escapeHtml(plan.planText)}</div>` : '') +
228 `<ul class="plan-tasks">` +
229 plan.tasks.map(t =>
230 `<li class="task-${t.status}"><span class="task-ico">${PLAN_ICO[t.status] || '⏳'}</span>` +
231 `<div><div class="task-title">${escapeHtml(t.title)}</div><div class="task-desc">${escapeHtml(t.description)}</div></div></li>`
232 ).join('') +
233 `</ul>`;
234 $('chat-log').scrollTop = $('chat-log').scrollHeight;
235 return div;
236}
237
238export function thinkingBubble() {
239 const div = addMsg('thinking', '');
240 const label = document.createElement('span');
241 label.textContent = t('thinking');
242 const gen = document.createElement('div');
243 gen.className = 'gen';
244 div.append(label, gen);
245 let buf = '';
246 return {
247 tick(tok) {
248 buf += tok;
249 label.textContent = t('writing', { n: buf.length }); // caracteres, no tokens
250 // si el buffer entró en un bloque de tool-call, no enseñes el JSON crudo
251 // según va llegando: una frase humana («leyendo app.js…») en su lugar.
252 const preview = humanizeStreamPreview(buf);
253 gen.classList.toggle('tool-preview', !!preview);
254 if (preview) { gen.textContent = '⟐ ' + preview; $('chat-log').scrollTop = $('chat-log').scrollHeight; }
255 else {
256 // texto normal: crece y se puede leer (antes solo los últimos 200 y lo
257 // de arriba desaparecía); se respeta tu scroll si subes a leer.
258 const pegado = gen.scrollHeight - gen.scrollTop - gen.clientHeight < 28;
259 gen.textContent = buf;
260 if (pegado) gen.scrollTop = gen.scrollHeight;
261 }
262 },
263 tool(name) { buf = ''; gen.textContent = ''; label.textContent = t('using', { name }); },
264 remove() { div.remove(); },
265 };
266}
267
268// Conversaciones (pestañas, en paralelo, con su propia cola): la lógica de
269// estado vive en conversations.js — aquí solo se pinta lo que corresponde.
270let activeThinking = null;
271
272function renderActiveLog() {
273 $('chat-log').replaceChildren();
274 const active = conv.getActive();
275 activeThinking = null;
276 if (!active) return;
277 for (const m of active.agent.history) {
278 if (m.role === 'user') {
279 if (m.content.startsWith('[resultado ')) {
280 const nl = m.content.indexOf('\n');
281 addToolResult(nl > 0 ? m.content.slice(nl + 1) : '');
282 } else if (m.content.startsWith(TASK_PREFIX)) {
283 // objetivo/tareas internas del modo Goal: no son burbujas sueltas —
284 // la tarjeta de plan las muestra todas. Se pinta justo en el punto
285 // donde se lanzó el objetivo, igual que aparece en directo.
286 if (m.content.startsWith(TASK_PREFIX + 'Objetivo: ') && active.plan) renderPlanCard(active.plan);
287 } else if (!m.content.startsWith('[…')) {
288 addMsg('user', m.content);
289 }
290 } else {
291 const call = parseToolCall(m.content);
292 if (call) addTool(call.tool, call.args?.path || call.args?.query || '');
293 else {
294 const div = addMsg('assistant', m.content);
295 if (m.propuesta) botonPropuesta(div, m.propuesta);
296 }
297 }
298 }
299 if (active.pumping) activeThinking = thinkingBubble();
300 // Lo que espera en la cola todavía no está en el historial: sin esto, al
301 // volver a la pestaña los mensajes encolados desaparecían de la vista.
302 for (const it of active.queue) if (it !== active.turno) addMsg('user queued', typeof it === 'string' ? it : it.text).title = t('queuedTitle');
303}
304
305// evento del módulo de conversaciones: 'switch' (cambiaste de pestaña o se
306// creó una), 'tabs' (se abrió/cerró una pestaña), 'pumping' (empezó/terminó
307// de procesar), 'event' (token/texto/tool/resultado/error de un turno real).
308// Las conversaciones EN SEGUNDO PLANO nunca tocan el DOM visible — solo se
309// refleja su punto de «ocupada» en la barra de pestañas.
310function onConvEvent(kind, id, payload) {
311 if (kind === 'turn') {
312 // Un mensaje encolado empieza: deja de estar «en cola» y la burbuja de
313 // «pensando» pasa debajo de él (era la del turno anterior, más arriba).
314 const active = conv.getActive();
315 if (!active || id !== active.id) return;
316 const enCola = $('chat-log').querySelector(':scope > .msg.user.queued');
317 if (enCola) {
318 enCola.classList.remove('queued');
319 enCola.removeAttribute('title');
320 if (activeThinking) { activeThinking.remove(); activeThinking = thinkingBubble(); }
321 }
322 return;
323 }
324 if (kind !== 'event') renderTabsBar();
325 // El botón es de la conversación ACTIVA: al cambiar de pestaña se repinta.
326 // Antes se quedaba como lo dejó la anterior — un ■ sobre una conversación
327 // parada, o un ▶ sobre una que seguía trabajando.
328 if (kind === 'switch') { renderActiveLog(); paintSendButton(); return; }
329 const active = conv.getActive();
330 if (!active || id !== active.id) return;
331 if (kind === 'pumping') {
332 // NO deshabilitar el botón mientras genera: se convierte en PARAR. Antes se
333 // ponía disabled=payload, y por eso no había forma de cortar un run largo.
334 paintSendButton();
335 if (payload) { if (!activeThinking) activeThinking = thinkingBubble(); }
336 else { activeThinking?.remove(); activeThinking = null; }
337 return;
338 }
339 if (kind === 'stopping') {
340 // Parar vacía la cola: lo que esperaba ya no se va a mandar, y se dice.
341 if (payload) for (const m of $('chat-log').querySelectorAll(':scope > .msg.user.queued')) {
342 m.classList.replace('queued', 'cancelled');
343 m.title = t('queuedCancelled');
344 m.dataset.parada = '1';
345 }
346 else for (const m of $('chat-log').querySelectorAll(':scope > .msg.user[data-parada]')) delete m.dataset.parada;
347 paintSendButton();
348 anunciarEnvio(payload ? t('stopping') : t('stopped'));
349 return;
350 }
351 if (kind === 'event') {
352 const ev = payload;
353 if (ev.type === 'token') activeThinking?.tick(ev.text);
354 if (ev.type === 'text') addMsg('assistant', ev.text);
355 if (ev.type === 'tool') { activeThinking?.tool(ev.call.tool); addTool(ev.call.tool, ev.call.args?.path || ev.call.args?.query || ''); }
356 if (ev.type === 'tool_result') addToolResult(ev.result);
357 if (ev.type === 'progress') activeThinking?.tool(ev.text);
358 if (ev.type === 'error') addMsg('assistant err', ev.text);
359 if (ev.type === 'aborted') addMsg('assistant muted', ev.text);
360 // 🎯 Modo Objetivo: la tarjeta de plan se crea con 'plan' y se repinta
361 // in-place en cada 'plan_update'/'plan_complete' (mismo nodo, por id).
362 if (ev.type === 'plan' || ev.type === 'plan_update' || ev.type === 'plan_complete') renderPlanCard(ev.plan);
363 }
364}
365
366function send(text, modo) {
367 const active = conv.getActive();
368 if (!active) return;
369 // Si la elfa ya está con algo, el mensaje espera su turno y se ve así (⏳).
370 const burbuja = addMsg(active.pumping || active.queue.length ? 'user queued' : 'user', text);
371 if (burbuja.classList.contains('queued')) burbuja.title = t('queuedTitle');
372 if (modo === 'hard') conv.startHardWork(active.id, text);
373 else if (goalMode) conv.startGoal(active.id, text);
374 else conv.send(active.id, text);
375}
376
377// Pestañas de conversación con semántica de pestañas: la activa entra con Tab,
378// ←/→ se mueven, Supr cierra, Shift+F10 abre su menú (Renombrar, Cerrar,
379// Cerrar otras). Antes eran <div> sin foco y la × un <b>; el punto de
380// «trabajando» se anuncia también en el nombre accesible.
381function renderTabsBar() {
382 const bar = $('conv-tabs');
383 if (!bar) return;
384 const teniaFoco = bar.contains(document.activeElement);
385 bar.replaceChildren();
386 bar.setAttribute('role', 'tablist');
387 bar.setAttribute('aria-label', t('convTabs'));
388 const active = conv.getActive();
389 const abiertas = conv.getOpenTabs();
390 for (const c of abiertas) {
391 const el = document.createElement('div');
392 const on = !!active && c.id === active.id;
393 el.className = 'tab' + (on ? ' active' : '') + (c.pumping ? ' tab-busy' : '');
394 el.dataset.id = c.id;
395 el.setAttribute('role', 'tab');
396 el.setAttribute('aria-selected', on ? 'true' : 'false');
397 el.tabIndex = on ? 0 : -1;
398 const name = document.createElement('span');
399 name.className = 'tab-name';
400 const title = conv.titleFor(c);
401 name.textContent = title;
402 name.title = title;
403 el.setAttribute('aria-label', title + (c.pumping ? ' · ' + t('convBusy') : ''));
404 const x = document.createElement('button');
405 x.type = 'button';
406 x.className = 'tab-x';
407 x.tabIndex = -1;
408 x.textContent = '×';
409 x.title = t('tabClose');
410 x.setAttribute('aria-label', t('tabCloseNamed', { title }));
411 x.onclick = e => { e.stopPropagation(); conv.closeTab(c.id); };
412 el.append(name, x);
413 el.onclick = () => conv.switchTo(c.id);
414 el.oncontextmenu = e => { e.preventDefault(); menuConversacion(c, e.clientX, e.clientY, el); };
415 el.onkeydown = e => {
416 const i = abiertas.indexOf(c);
417 if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
418 e.preventDefault();
419 const n = abiertas[(i + (e.key === 'ArrowRight' ? 1 : abiertas.length - 1)) % abiertas.length];
420 conv.switchTo(n.id);
421 $('conv-tabs').querySelector(`.tab[data-id="${n.id}"]`)?.focus();
422 } else if (e.key === 'Delete') { e.preventDefault(); conv.closeTab(c.id); $('conv-tabs').querySelector('.tab.active')?.focus(); }
423 else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) { e.preventDefault(); const r = el.getBoundingClientRect(); menuConversacion(c, r.left, r.bottom, el); }
424 };
425 bar.appendChild(el);
426 }
427 const plus = document.createElement('button');
428 plus.className = 'tab-add';
429 plus.title = t('newConv');
430 plus.setAttribute('aria-label', t('newConv'));
431 plus.textContent = '+';
432 plus.onclick = () => conv.create();
433 bar.appendChild(plus);
434 if (teniaFoco) bar.querySelector('.tab.active')?.focus();
435}
436
437// Menú de una pestaña de conversación (botón derecho / Shift+F10).
438function menuConversacion(c, x, y, volver) {
439 document.getElementById('conv-menu')?.remove();
440 const menu = document.createElement('div');
441 menu.id = 'conv-menu';
442 menu.className = 'conv-menu';
443 menu.setAttribute('role', 'menu');
444 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
445 const cerrar = () => { menu.remove(); document.removeEventListener('mousedown', fuera, true); volver?.focus?.(); };
446 const fuera = ev => { if (!menu.contains(ev.target)) cerrar(); };
447 const opciones = [
448 [t('convRename'), async () => {
449 const nuevo = prompt(t('convRenamePrompt'), conv.titleFor(c));
450 if (nuevo != null) await conv.rename(c.id, nuevo);
451 }],
452 [t('tmClose'), () => conv.closeTab(c.id)],
453 [t('tmCloseOthers'), () => { for (const o of conv.getOpenTabs()) if (o.id !== c.id) conv.closeTab(o.id); conv.switchTo(c.id); }],
454 ];
455 for (const [label, fn] of opciones) {
456 const b = document.createElement('button');
457 b.type = 'button'; b.className = 'tm-item'; b.setAttribute('role', 'menuitem'); b.textContent = label;
458 b.onclick = () => { cerrar(); fn(); };
459 menu.appendChild(b);
460 }
461 menu.addEventListener('keydown', e => {
462 const l = [...menu.querySelectorAll('[role="menuitem"]')], i = l.indexOf(document.activeElement);
463 if (e.key === 'Escape') { e.preventDefault(); cerrar(); }
464 else if (e.key === 'ArrowDown') { e.preventDefault(); l[(i + 1) % l.length].focus(); }
465 else if (e.key === 'ArrowUp') { e.preventDefault(); l[(i - 1 + l.length) % l.length].focus(); }
466 });
467 document.body.appendChild(menu);
468 setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
469 menu.querySelector('button')?.focus();
470}
471
472async function renderHistoryPanel() {
473 const panel = $('history-panel');
474 panel.replaceChildren();
475 // Un diálogo con filas que son botones: antes eran <div> y solo se usaban
476 // con el ratón. La conversación activa se marca (aria-current).
477 panel.setAttribute('role', 'dialog');
478 panel.setAttribute('aria-labelledby', 'hp-title');
479 const head = document.createElement('div');
480 head.className = 'hp-head';
481 const tit = document.createElement('span'); tit.id = 'hp-title'; tit.textContent = t('tHistory');
482 head.append(tit);
483 const xBtn = document.createElement('button');
484 xBtn.textContent = '✕';
485 xBtn.setAttribute('aria-label', t('close'));
486 xBtn.onclick = () => cierraHistorial();
487 head.appendChild(xBtn);
488 panel.appendChild(head);
489 const list = document.createElement('div');
490 list.id = 'hp-list';
491 panel.appendChild(list);
492 const all = await conv.listAll();
493 if (!all.length) {
494 const empty = document.createElement('div');
495 empty.className = 'hp-empty';
496 empty.textContent = t('histEmpty');
497 list.appendChild(empty);
498 return;
499 }
500 const activa = conv.getActive()?.id;
501 for (const c of all) {
502 const row = document.createElement('div');
503 row.className = 'hp-row';
504 const abrir = document.createElement('button');
505 abrir.type = 'button';
506 abrir.className = 'hp-open';
507 if (c.id === activa) abrir.setAttribute('aria-current', 'true');
508 const titEl = document.createElement('span');
509 titEl.className = 'hp-title';
510 titEl.textContent = c.title || t('newConv');
511 const d = new Date(c.updatedAt);
512 const date = document.createElement('span');
513 date.className = 'hp-date';
514 date.textContent = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
515 abrir.append(titEl, date);
516 abrir.onclick = async () => { await conv.open(c.id); cierraHistorial({ foco: false }); $('prompt').focus(); };
517 const del = document.createElement('button');
518 del.type = 'button';
519 del.className = 'hp-del';
520 del.title = t('histDel');
521 del.setAttribute('aria-label', t('histDelNamed', { title: c.title || t('thisConv') }));
522 del.textContent = '🗑';
523 del.onclick = async e => {
524 e.stopPropagation();
525 if (!confirm(t('confirmDel', { title: c.title || t('thisConv') }))) return;
526 await conv.remove(c.id);
527 await renderHistoryPanel();
528 ($('history-panel').querySelector('.hp-open') || $('history-panel').querySelector('.hp-head button'))?.focus();
529 };
530 row.append(abrir, del);
531 list.appendChild(row);
532 }
533}
534
535// ---------- modelos (local primero; externos = ⚙️ opt-in) ----------
536const localProviders = { litert: () => import('./providers/litert.js'), onnx: () => import('./providers/onnx.js') };
537
538async function resolveProvider(id) {
539 if (localProviders[id]) return localProviders[id]();
540 if (id.startsWith('litert:')) { // Gemma vía LiteRT-LM (build elegido)
541 const mod = await import('./providers/litert.js');
542 mod.configure(id.slice(7));
543 return mod;
544 }
545 if (id.startsWith('onnx:')) { // ONNX concreto (Qwen3.5…)
546 const mod = await import('./providers/onnx.js');
547 mod.configure(id.slice(5));
548 return mod;
549 }
550 if (id.startsWith('engine:')) { // runtime WebGPU propio (GGUF)
551 // El motor no se versiona en este repo: llega a web/js/engine/ por rsync,
552 // igual que en Claw. Si no está, el import falla y se trata como cualquier
553 // otro fallo de carga.
554 const mod = await import('./engine/provider.js');
555 mod.configure(id.slice(7));
556 // Igual que en Claw: solo el motor propio mide tok/s (`alMedir`), así que
557 // con ONNX o con un proveedor externo el chip se queda oculto en vez de
558 // mentir con un número que nadie ha medido.
559 try {
560 const vm = await import('./velocimetro.js');
561 vm.montar(mod);
562 } catch (e) { console.warn('[code] velocímetro no disponible:', e.message); }
563 return mod;
564 }
565 if (id.startsWith('ext:')) {
566 const cfg = settings.get(id.slice(4));
567 const mod = await import('./providers/api.js');
568 mod.configure(cfg);
569 return mod;
570 }
571 return null;
572}
573
574// El E4B healed (4.12 GB) NO carga aún en navegador (export prefill_decode, no
575// artisan) — descargarlo y fallar deja la GPU en estado inválido y TUMBA la
576// pestaña. Se oculta hasta el reexport artisan. Poner true para reactivarlo.
577const LITERT_READY = false;
578
579const isMobile = () => matchMedia('(max-width: 820px)').matches || matchMedia('(pointer: coarse)').matches;
580// navigator.gpu puede EXISTIR como API sin que haya un adaptador real (ciertos
581// Linux/drivers, entornos sandboxed/headless…) — comprobarlo UNA vez al
582// arrancar evita ofrecer/elegir Gemma (2-4 GB) cuando de todos modos va a
583// fallar al crear el motor (onnx.js y litert.js ya comprueban el adaptador
584// por su cuenta como defensa adicional, pero esto evita hasta OFRECERLO).
585let realGPU = !!navigator.gpu;
586const realGPUCheck = (async () => {
587 if (!navigator.gpu) return (realGPU = false);
588 try { return (realGPU = !!(await navigator.gpu.requestAdapter())); }
589 catch { return (realGPU = false); }
590})();
591// Capacidad real de la GPU: no basta con que exista navigator.gpu, hay que
592// mirar los límites del adaptador — un buffer máximo pequeño no aguanta Gemma.
593async function gpuCapacity() {
594 const mem = navigator.deviceMemory || 8; // GB (grueso, tope 8 en Chrome)
595 if (!navigator.gpu) return { gpu: false, maxBuf: 0, mem };
596 try {
597 const a = await navigator.gpu.requestAdapter();
598 if (!a) return { gpu: false, maxBuf: 0, mem };
599 return { gpu: true, maxBuf: a.limits?.maxBufferSize || 0, mem };
600 } catch { return { gpu: false, maxBuf: 0, mem }; }
601}
602
603// Auto-selección: el modelo MÁS GRANDE que entre en esta máquina. Gemma por
604// LiteRT si la GPU aguanta sus buffers; si no, un ONNX pequeño (WebGPU o wasm).
605async function pickLocalBrain() {
606 const c = await gpuCapacity();
607 if (c.gpu && !isMobile()) {
608 if (c.maxBuf >= 2 ** 31 && c.mem >= 8) return 'litert:gemma-e4b'; // ~4 GB
609 if (c.maxBuf >= 2 ** 30 && c.mem >= 6) return 'litert:gemma-e2b'; // ~2 GB
610 }
611 if (c.gpu && isMobile()) return 'litert:gemma-e2b';
612 return 'onnx'; // ONNX pequeño: Qwen3.5-0.8B por defecto (ver model-config.js)
613}
614// heurística vieja como último recurso síncrono
615const defaultBrain = () => !realGPU ? 'onnx' : (isMobile() ? 'litert:gemma-e2b' : 'litert:gemma-e4b');
616
617// El runtime propio y su modelo grande se SONDEAN, no se cablean: el motor
618// llega por rsync y el modelo son gigabytes que pueden no estar alojados.
619// Ofrecer algo que no está sería prometer un fallo que llega DESPUÉS de que el
620// usuario haya esperado, que es la peor forma de fallar.
621// Mismo patrón que el 27B: nombre y tamaño salen del REGISTRO del motor, nunca
622// de un literal aquí. Un nombre duplicado es un nombre que se queda viejo.
623// ⚠️ Con HANDLE, no «fire and forget». La lista del selector se construye tras
624// esperar las sondas de disponibilidad, así que una sonda que nadie espera deja
625// su bandera en false cuando se pinta la lista y el modelo no aparece — se sirve
626// y nadie puede elegirlo, el mismo modo de fallo que escondió a Bonsai. Pasó con
627// esta misma sonda: en una app se colaba por carrera y en la otra no aparecía.
628let MINICPM_READY = false, MINICPM_LABEL = 'MiniCPM5 2B', MINICPM_GB = 0;
629const minicpmCheck = (async () => {
630 try {
631 const reg = await import('./engine/registro.js');
632 const m = reg.MODELS && reg.MODELS['minicpm5-2b'];
633 if (m) { MINICPM_LABEL = m.label || MINICPM_LABEL; MINICPM_GB = (m.bytes || 0) / 1e9; }
634 MINICPM_READY = await reg.disponible('minicpm5-2b');
635 return MINICPM_READY;
636 } catch { return (MINICPM_READY = false); }
637})();
638
639let ENGINE_READY = false, MODEL27_READY = false;
640let MODEL27_LABEL = 'Modelo grande';
641let MODEL27_GB = 0;
642const engineCheck = (async () => {
643 try { return (ENGINE_READY = (await fetch('js/engine/provider.js', { method: 'HEAD', cache: 'no-store' })).ok); }
644 catch { return (ENGINE_READY = false); }
645})();
646// Se le pregunta AL MOTOR por sus propios ficheros. Aquí había cableada la URL
647// del 27B de un solo trozo; cuando pasó a dos fragmentos en dos hosts, esta
648// línea siguió sondeando el fichero viejo y dando 200 de milagro, porque aún
649// estaba en el servidor. El día que se borre, la opción desaparece del selector
650// y nadie ata los dos cabos. Se importa el registro (unos kilobytes) y no el
651// proveedor, que arrastra el motor entero.
652const modelo27Check = (async () => {
653 try {
654 const reg = await import('./engine/registro.js');
655 // El NOMBRE y el TAMAÑO salen del registro del motor, no de un literal aquí.
656 // Estaban a mano y al cambiar de modelo mintieron en tres cosas a la vez:
657 // decían «Qwen3.8-27B IQ1» y «~7,6 GB» cuando lo que se sirve es el ternario
658 // de Prism y son 7,2 GB. Un nombre duplicado es un nombre que se queda viejo.
659 const m27 = reg.MODELS && reg.MODELS['qwen38-27b'];
660 if (m27) { MODEL27_LABEL = m27.label || MODEL27_LABEL; MODEL27_GB = (m27.bytes || 0) / 1e9; }
661 return (MODEL27_READY = await reg.disponible('qwen38-27b'));
662 } catch { return (MODEL27_READY = false); }
663})();
664
665// Los modelos LOCALES, en un solo sitio. Los usan el desplegable y las tarjetas
666// de los ajustes: hasta ahora eran dos listas escritas a mano y la de ajustes se
667// quedó vieja — no ofrecía NI el motor propio ni el 27B, así que desde ahí era
668// imposible elegir Bonsai por mucho que el motor lo sirviera. Es justo el modo
669// de fallo que avisa el comentario de `modelo27Check`: un nombre duplicado es un
670// nombre que se queda viejo.
671function modelOptionsLocales() {
672 const opts = [];
673 if (realGPU) opts.push({ id: 'litert:gemma-e4b', label: 'Gemma-4 E4B · LiteRT-LM (~4 GB) ★' });
674 if (realGPU) opts.push({ id: 'litert:gemma-e2b', label: 'Gemma-4 E2B · LiteRT-LM (~2 GB)' });
675 // `onnx` a secas era Elffuss LM y se ha quitado. Ojo con el patrón: ESTE era
676 // el TERCER sitio donde el mismo modelo estaba declarado a mano (el registro
677 // de model-config.js, la lista del lab y esta), y quitarlo de los dos
678 // primeros lo dejaba igual de visible aquí. Es el mismo modo de fallo que el
679 // comentario de arriba avisa para Bonsai: un nombre duplicado es un nombre
680 // que se queda viejo.
681 opts.push({ id: 'onnx:qwen3.5-0.8b', label: 'Qwen3.5-0.8B · WebGPU (~600 MB)' });
682 if (realGPU && ENGINE_READY) opts.push({ id: 'engine:qwen35-0.8b', label: 'Qwen3.5-0.8B · Elffuss Engine (~800 MB)' });
683 // El 27B se guarda tras la primera descarga (repartido en dos servidores y
684 // troceado, porque el navegador corta un fichero suelto sobre 1,94 GB), así
685 // que son «gigas una vez», no «gigas cada vez». Sigue siendo lento: la espera
686 // cae entera antes de la primera palabra.
687 // MiniCPM5-2B por el motor propio. Va en «Avanzado» y sin estrella a
688 // propósito: carga y responde con texto limpio, y eso es TODO lo que está
689 // comprobado. No se ha medido contra Gemma E4B, que es el predeterminado, así
690 // que la etiqueta no promete velocidad ni calidad.
691 if (realGPU && ENGINE_READY && MINICPM_READY) opts.push({ id: 'engine:minicpm5-2b', label: `${MINICPM_LABEL} · Elffuss Engine (${MINICPM_GB.toFixed(1)} GB, se guarda)`, group: '⚠ Avanzado' });
692 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' });
693 opts.push({ id: 'rules', label: t('setModelRulesName') });
694 return opts;
695}
696
697function modelOptions() {
698 return [...modelOptionsLocales(), ...settings.enabledExternals()];
699}
700
701function rebuildSelect() {
702 const sel = $('model-select');
703 sel.replaceChildren();
704 // Los grupos avisados («⚠ Avanzado») van SIEMPRE al final. Si se crean según
705 // aparecen, basta una opción agrupada en mitad de la lista para que las
706 // siguientes queden colgando bajo el encabezado de aviso — le pasó a «Básico
707 // (sin modelo)» en Claw, que es la opción más segura que hay.
708 const grupos = new Map();
709 for (const o of modelOptions()) {
710 const opt = document.createElement('option');
711 opt.value = o.id;
712 opt.textContent = o.label;
713 if (o.group) {
714 let g = grupos.get(o.group);
715 if (!g) { g = document.createElement('optgroup'); g.label = o.group; grupos.set(o.group, g); }
716 g.appendChild(opt);
717 } else {
718 sel.appendChild(opt);
719 }
720 }
721 for (const g of grupos.values()) sel.appendChild(g);
722 sel.value = activeModel;
723}
724
725// progreso del modelo: píldora prominente visible sobre landing e IDE.
726// Es una región viva (role=status en el HTML). Con `reintentar`, un fallo deja
727// un botón para volver a intentarlo y otro para cerrar, y no se esconde solo.
728function showModelProgress(text, pct = null, { reintentar = null } = {}) {
729 const box = $('model-progress');
730 box.querySelector('.mp-acciones')?.remove();
731 if (text == null) { box.hidden = true; return; }
732 box.hidden = false;
733 $('model-progress-text').textContent = text;
734 if (reintentar) {
735 const acc = document.createElement('div'); acc.className = 'mp-acciones';
736 const r = document.createElement('button'); r.type = 'button'; r.textContent = t('retry');
737 r.onclick = () => { acc.remove(); reintentar(); };
738 const x = document.createElement('button'); x.type = 'button'; x.textContent = '✕'; x.setAttribute('aria-label', t('close'));
739 x.onclick = () => showModelProgress(null);
740 acc.append(r, x);
741 box.querySelector('.mp-body').appendChild(acc);
742 }
743 const bar = $('model-bar');
744 if (pct == null) {
745 bar.classList.add('indet'); // sin % conocido → barra animada
746 bar.style.width = '';
747 } else {
748 bar.classList.remove('indet');
749 bar.style.width = pct + '%';
750 }
751}
752
753// El punto de estado del modelo dice con palabras qué modelo es y cómo está
754// (antes era solo un color, con el título «modelo» siempre), y es un botón que
755// lleva a Ajustes → Cerebro.
756function pintaDot(estado, id) {
757 const d = $('model-dot');
758 if (!d) return;
759 d.className = 'dot ' + (estado === 'error' ? 'off' : estado);
760 const nombre = (modelOptions().find(o => o.id === id)?.label || id || '').replace(/\s*★$/, '');
761 const txt = id === 'rules' ? t('modelDotBasic') : t('modelDot', { name: nombre, state: t('modelState_' + estado) });
762 d.title = txt;
763 d.setAttribute('aria-label', txt);
764}
765
766function errorHumano(e) {
767 const m = String(e?.message || e || '');
768 if (/Failed to fetch|NetworkError|network|ERR_/i.test(m)) return t('errNet');
769 if (/adaptador WebGPU|No available adapters|webgpu|requestAdapter/i.test(m)) return t('errGpu');
770 if (/quota|QuotaExceeded/i.test(m)) return t('errQuota');
771 if (/out of memory|memory|OOM|Aborted/i.test(m)) return t('errMem');
772 return m || t('errUnknown');
773}
774
775let loadingId = null;
776// Lo pone renderSettings: repinta las tarjetas de modelo del panel abierto.
777let repintaTarjetasModelo = () => {};
778// Solo el motor propio mide tok/s: con cualquier otro cerebro el chip ⚡ se
779// oculta (montar(null)) en vez de seguir enseñando las cifras del motor.
780const apagaVelocimetro = () => import('./velocimetro.js').then(v => v.montar(null)).catch(() => {});
781
782async function changeModel(id) {
783 if (id === 'rules') {
784 conv.setProvider(rules);
785 apagaVelocimetro();
786 activeModel = 'rules';
787 guardaPref('elffusscode.model', 'rules');
788 pintaDot('off', 'rules');
789 return true;
790 }
791 if (loadingId === id || activeModel === id) return true; // un solo modelo, una sola carga
792 loadingId = id;
793 pintaDot('loading', id);
794 showModelProgress(t("stModelLoadingAI"), 4);
795 try {
796 const mod = await resolveProvider(id);
797 await mod.load(p => {
798 if (typeof p === 'string') return showModelProgress(p);
799 if (p?.status === 'progress' && p.total) {
800 const pct = Math.round(p.loaded / p.total * 100);
801 showModelProgress(t('modelLoading', { pct, loaded: (p.loaded / 1e6 | 0), total: (p.total / 1e6 | 0) }), pct);
802 }
803 });
804 conv.setProvider(mod);
805 if (!id.startsWith('engine:')) apagaVelocimetro();
806 // AHORA sí se reanuda lo que quedó a medias. Al refrescar durante un turno,
807 // el mensaje sigue en la cola —se guarda al enviarlo— pero reanudarlo antes
808 // de este punto lo habría procesado con el cerebro básico. Aquí ya hay
809 // modelo de verdad.
810 //
811 // Si un turno ya se intentó dos veces sin terminar, no se reanuda solo: lo
812 // normal es que esté tumbando la pestaña, y reintentarlo al abrir deja al
813 // usuario en un bucle del que no sale ni cerrando. Se le cuenta y decide.
814 conv.resumePending((convId, item) => {
815 const texto = String(item?.text || '').slice(0, 60);
816 addMsg('sys', `⚠️ «${texto}…» se quedó a medias dos veces y no lo reintento solo: puede estar agotando la memoria. ` +
817 `Escribe otra cosa para seguir, o vuelve a enviarlo si quieres insistir.`);
818 conv.descartarPendiente(convId);
819 });
820 // El medidor de contexto pasa a hablar del modelo QUE ESTÁ CARGADO. Quien no
821 // sepa decir su contexto deja el valor de reserva, así que esto no puede
822 // romper a un proveedor que no lo implemente.
823 try { if (typeof mod.contextTokens === 'function') setCtxBudget(mod.contextTokens()); }
824 catch { /* el medidor no vale un fallo de carga */ }
825 activeModel = id;
826 guardaPref('elffusscode.model', id);
827 pintaDot('on', id);
828 showModelProgress(t('modelReadyBadge'), 100);
829 setTimeout(() => showModelProgress(null), 2500);
830 $('statusbar').textContent = t('modelReady');
831 rebuildSelect();
832 return true;
833 } catch (e) {
834 console.error('[elffuss-code] fallo cargando', e);
835 // Un Gemma (LiteRT) que no cabe → cae al ligero (onnx, Qwen3.5-0.8B).
836 if (id.startsWith('litert') && !_fellBack) {
837 _fellBack = true;
838 sessionStorage.setItem('elffusscode.skipGemma', '1');
839 showModelProgress(t('fallbackToast'));
840 loadingId = null;
841 const okc = await changeModel('onnx');
842 _fellBack = false;
843 if (okc) return true;
844 }
845 conv.setProvider(rules);
846 apagaVelocimetro();
847 activeModel = 'rules';
848 pintaDot('error', id);
849 // En palabras de persona («sin conexión», «sin GPU», «sin espacio»…), con
850 // el detalle técnico en la consola, y un botón para reintentar.
851 showModelProgress(t('modelLoadFailed', { e: errorHumano(e) }), null, { reintentar: () => changeModel(id) });
852 $('model-bar').classList.remove('indet');
853 rebuildSelect();
854 return false;
855 } finally {
856 loadingId = null;
857 repintaTarjetasModelo(); // Ajustes abierto: la activa y el «cargando…» al día
858 }
859}
860let _fellBack = false;
861
862// El cerebro empieza a descargarse desde el PRIMER segundo, en segundo plano,
863// mientras el usuario elige la carpeta. Solo el modelo local — los externos
864// jamás se activan solos.
865// Cadena de respaldo: el modelo preferido → LFM2.5 local → básico. Si el E4B
866// healed falla (p. ej. «HF_Tokenizer_Zlib not supported» del runtime LiteRT),
867// cae solo a LFM2.5 en vez de dejar al usuario sin cerebro.
868async function preloadModel() {
869 const saved = localStorage.getItem('elffusscode.model');
870 if (saved === 'rules') return;
871 await realGPUCheck; // que defaultBrain()/modelOptions() vean el adaptador real, no solo la API
872 // Las sondas del motor y del modelo grande resuelven DESPUÉS de que se pinte
873 // el selector, así que hay que repintarlo: sin esto la opción no aparece
874 // hasta que algo más fuerce un refresco, y el usuario no la ve nunca.
875 const [hayMotor, hay27, hayMini] = await Promise.all([engineCheck, modelo27Check, minicpmCheck]);
876 if (hayMotor || hay27 || hayMini) rebuildSelect();
877 const avail = new Set(modelOptions().map(o => o.id));
878 const skipGemma = sessionStorage.getItem('elffusscode.skipGemma') === '1';
879 const def = skipGemma ? 'onnx' : await pickLocalBrain();
880 const chain = [...new Set([saved, def, 'onnx']
881 .filter(id => id && id !== 'rules' && avail.has(id)))];
882 // MÓVIL: no descargar ~1,9 GB sin permiso. defaultBrain() elige gemma-e2b en
883 // móvil, y medido el 2026-09-08 con un iPhone emulado contra producción: al
884 // abrir la página arrancaban OCHO peticiones de pesos sin que el usuario
885 // pidiera nada. Son casi dos gigas de datos de alguien que solo entró a
886 // mirar, y encima el navegador de móvil mata la pestaña bastante antes de
887 // sostener ese modelo, así que se gastaban para nada. Se avisa y se espera.
888 if (isMobile() && localStorage.getItem('elffusscode.movil.ok') !== '1') {
889 avisoMovil('~1,9 GB', () => {
890 (async () => { for (const id of chain) if (await changeModel(id)) return; })();
891 });
892 return;
893 }
894 for (const id of chain) if (await changeModel(id)) return;
895}
896
897// ---------- panel ⚙️ Ajustes: modelo (cerebro) + API keys ----------
898const el = (t, cls, txt) => { const e = document.createElement(t); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
899
900// Ajustes (y el panel de skills, que usa el mismo sitio) es un diálogo: se
901// anuncia como tal, el foco entra en él al abrirse y vuelve a quien lo abrió
902// al cerrarse (también con Escape). Antes el foco se quedaba en el engranaje.
903let volverDeAjustes = null;
904function settingsShell(title) {
905 const box = $('settings-panel');
906 const yaAbierto = !box.hidden && box.contains(document.activeElement);
907 if (box.hidden || !volverDeAjustes) volverDeAjustes = document.activeElement;
908 box.hidden = false;
909 box.replaceChildren();
910 box.setAttribute('role', 'dialog');
911 box.setAttribute('aria-labelledby', 'settings-title');
912 const close = el('button', 'panel-close'); close.innerHTML = UI.close; close.title = t("close");
913 close.setAttribute('aria-label', t('close'));
914 close.onclick = () => cierraAjustes();
915 const h = el('h3', 'panel-title', title); h.id = 'settings-title'; h.tabIndex = -1;
916 box.append(close, h);
917 if (!yaAbierto) requestAnimationFrame(() => h.focus());
918 return box;
919}
920function cierraAjustes() {
921 const box = $('settings-panel');
922 if (box.hidden) return;
923 box.hidden = true;
924 const v = volverDeAjustes; volverDeAjustes = null;
925 if (v && document.body.contains(v)) v.focus();
926}
927
928function showBridgeMsg(card, text, isErr) {
929 let el2 = card.querySelector('.br-msg');
930 if (!el2) { el2 = document.createElement('div'); el2.className = 'br-msg muted'; el2.setAttribute('role', 'status'); el2.style.cssText = 'font-size:.7rem;margin-top:6px'; card.appendChild(el2); }
931 el2.textContent = text;
932 el2.style.color = isErr ? '#ff6b8b' : '';
933}
934
935// Qué bridge descargar. Todos los Mac dicen «MacIntel» en navigator.platform,
936// también los Apple Silicon, y por eso a un Mac ARM se le ofrecía la versión
937// Intel. Se pregunta la arquitectura a userAgentData (Chrome/Edge) y, si no se
938// puede saber (Safari), se ofrecen las DOS versiones de Mac en vez de adivinar.
939async function bridgeParaEstaMaquina() {
940 const ua = navigator.userAgent;
941 let arch = '';
942 try { arch = (await navigator.userAgentData?.getHighEntropyValues?.(['architecture']))?.architecture || ''; } catch { /* sin datos */ }
943 if (/Mac/.test(ua)) {
944 if (arch === 'arm') return ['elffuss-bridge-mac-arm64'];
945 if (arch === 'x86') return ['elffuss-bridge-mac-intel'];
946 return ['elffuss-bridge-mac-arm64', 'elffuss-bridge-mac-intel'];
947 }
948 if (/Win/.test(ua)) return ['elffuss-bridge-windows.exe'];
949 if (/Linux/.test(ua)) return [arch === 'arm' || /aarch64|arm64/i.test(ua) ? 'elffuss-bridge-linux-arm64' : 'elffuss-bridge-linux'];
950 return ['elffuss-bridge-mac-arm64', 'elffuss-bridge-mac-intel'];
951}
952async function pintaDescargasBridge(card, NOMBRES) {
953 const principales = await bridgeParaEstaMaquina();
954 const host = card.querySelector('#br-dl'), otros = card.querySelector('#br-dl-other');
955 if (!host || !otros) return;
956 const enlace = (f, principal) => {
957 const a = document.createElement('a');
958 a.href = 'bridge-dl/' + f; a.setAttribute('download', '');
959 a.dataset.file = f;
960 if (principal) { a.className = 'prov-use'; a.style.cssText = 'text-decoration:none;display:inline-block;margin:0 6px 6px 0'; a.textContent = t('setBridgeDownload', { os: NOMBRES[f] }); }
961 else { a.style.cssText = 'color:var(--accent2);font-size:.72rem'; a.textContent = NOMBRES[f]; }
962 // El tamaño, para saber qué se baja (una petición HEAD, sin descargar).
963 fetch(a.href, { method: 'HEAD' }).then(r => {
964 const n = +r.headers.get('content-length');
965 if (r.ok && n) a.textContent += ` (${(n / 1048576).toFixed(1)} MB)`;
966 }).catch(() => {});
967 return a;
968 };
969 host.replaceChildren(...principales.map(f => enlace(f, true)));
970 otros.replaceChildren(...Object.keys(NOMBRES).filter(f => !principales.includes(f)).map(f => { const d = document.createElement('div'); d.appendChild(enlace(f, false)); return d; }));
971}
972
973// pequeño estallido de fuegos artificiales (canvas, un par de segundos) para
974// que se entienda de un vistazo que el bridge quedó conectado.
975function fireworks() {
976 const cv = document.createElement('canvas');
977 cv.id = 'fireworks-fx';
978 cv.width = innerWidth; cv.height = innerHeight;
979 document.body.appendChild(cv);
980 const ctx = cv.getContext('2d');
981 const colors = ['#ff4d8d', '#7c5cff', '#49e8ff', '#3fb970', '#ffd479'];
982 const bursts = Array.from({ length: 5 }, () => ({
983 x: innerWidth * (0.2 + Math.random() * 0.6), y: innerHeight * (0.2 + Math.random() * 0.4),
984 t0: performance.now() + Math.random() * 500,
985 particles: Array.from({ length: 40 }, (_, i) => { const a = (i / 40) * Math.PI * 2; const sp = 2 + Math.random() * 3; return { a, sp, color: colors[i % colors.length] }; }),
986 }));
987 const start = performance.now();
988 function frame(now) {
989 ctx.clearRect(0, 0, cv.width, cv.height);
990 let alive = false;
991 for (const b of bursts) {
992 const age = (now - b.t0) / 1000;
993 if (age < 0) { alive = true; continue; }
994 if (age > 1.4) continue;
995 alive = true;
996 for (const p of b.particles) {
997 const r = p.sp * age * 40;
998 const x = b.x + Math.cos(p.a) * r, y = b.y + Math.sin(p.a) * r + age * age * 60;
999 ctx.globalAlpha = Math.max(0, 1 - age / 1.4);
1000 ctx.fillStyle = p.color;
1001 ctx.beginPath(); ctx.arc(x, y, 2.4, 0, Math.PI * 2); ctx.fill();
1002 }
1003 }
1004 if (alive && now - start < 3000) requestAnimationFrame(frame);
1005 else cv.remove();
1006 }
1007 requestAnimationFrame(frame);
1008}
1009
1010function renderSettings() {
1011 const box = settingsShell(t("setTitle"));
1012
1013 // --- Cerebro (modelo) ---
1014 box.append(el('div', 'sk-h', t("setBrainTitle")));
1015 // De `modelOptionsLocales()`, no de una copia: así lo que se puede elegir aquí
1016 // es exactamente lo que se puede elegir en el desplegable, hoy y cuando se
1017 // añada el siguiente modelo. El texto de debajo sigue siendo a medida cuando
1018 // lo hay; si no, se saca de la propia etiqueta.
1019 const SUBS = {
1020 'litert:gemma-e4b': t("setModelE4bSub"),
1021 'litert:gemma-e2b': t("setModelE2bSub"),
1022 'onnx': t("setModelOnnxSub"),
1023 'rules': t("setModelRulesSub"),
1024 };
1025 const LOCAL = modelOptionsLocales().map((o) => {
1026 const partes = String(o.label).split(' · ');
1027 return {
1028 id: o.id,
1029 name: partes[0].trim(),
1030 sub: SUBS[o.id] || partes.slice(1).join(' · ').trim(),
1031 };
1032 });
1033 const grid = el('div', 'model-grid');
1034 grid.setAttribute('role', 'group');
1035 grid.setAttribute('aria-label', t('setBrainTitle'));
1036 // Cada tarjeta se pinta aquí y se REPINTA en su sitio (clases, aria-pressed,
1037 // aria-busy y texto): la misma tarjeta, el mismo foco. Antes elegir un modelo
1038 // rehacía el panel entero al empezar y otra vez al terminar la carga: lo que
1039 // estuvieras escribiendo en Ajustes (el feedback, el token del bridge) se
1040 // borraba y el foco caía a <body> (con Enter, al instante).
1041 const pintaTarjeta = (card, m) => {
1042 const cargando = loadingId === m.id;
1043 card.className = 'model-card' + (activeModel === m.id ? ' active' : '') + (m.disabled ? ' disabled' : '') + (cargando ? ' loading' : '');
1044 card.setAttribute('aria-pressed', activeModel === m.id ? 'true' : 'false');
1045 if (cargando) card.setAttribute('aria-busy', 'true'); else card.removeAttribute('aria-busy');
1046 card.innerHTML = `<b>${m.name}</b><span>${cargando ? escapeHtml(t('setModelLoadingCard')) : m.sub}</span>`;
1047 };
1048 const tarjetas = [];
1049 for (const m of LOCAL) {
1050 if (m.need === 'gpu' && !realGPU) continue;
1051 const card = el('button', 'model-card');
1052 card.dataset.model = m.id;
1053 if (m.disabled) card.disabled = true;
1054 pintaTarjeta(card, m);
1055 tarjetas.push([card, m]);
1056 // La tarjeta dice «cargando…» mientras carga, y la activa cambia cuando
1057 // termina (changeModel avisa: repintaTarjetasModelo).
1058 card.onclick = async () => {
1059 const p = changeModel(m.id);
1060 repintaTarjetasModelo();
1061 await p;
1062 repintaTarjetasModelo();
1063 };
1064 grid.appendChild(card);
1065 }
1066 repintaTarjetasModelo = () => { for (const [card, m] of tarjetas) if (card.isConnected) pintaTarjeta(card, m); };
1067 box.appendChild(grid);
1068
1069 // --- Espacio de trabajo: guardar conversaciones/skills en disco ---
1070 box.append(el('div', 'sk-h', '💾 ' + t('wsTitle')));
1071 const wsCard = el('div', 'prov-card');
1072 const wsState = el('div', 'muted'); wsState.style.fontSize = '.78rem';
1073 // `flex-direction:row` EXPLÍCITO. La clase `field` es una columna
1074 // (`flex-direction: column`), y el estilo de aquí ponía `display:flex` y
1075 // `flex-wrap` sin corregir la dirección: los botones quedaban apilados y
1076 // estirados a todo el ancho —tres barras de color enormes para «elige una
1077 // carpeta»— cuando son acciones pequeñas que caben en una línea. El
1078 // `align-items:center` es para que la casilla de autoguardado no se estire.
1079 const wsRow = el('div', 'field');
1080 wsRow.style.cssText = 'display:flex;flex-direction:row;align-items:center;gap:8px;flex-wrap:wrap;margin-top:8px';
1081 const wsInv = el('div'); wsInv.style.cssText = 'margin-top:10px;font-size:.78rem';
1082 wsCard.append(el('span', 'muted', t('wsDesc')), wsState, wsRow, wsInv);
1083 box.appendChild(wsCard);
1084 const wsKb = n => n > 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n > 1024 ? Math.round(n / 1024) + ' KB' : n + ' B';
1085 async function paintWs() {
1086 const st = workspace.status();
1087 wsRow.replaceChildren();
1088 wsState.textContent = !st.supported.pick ? t('wsNoSupport')
1089 : !st.folder ? t('wsNoFolder')
1090 : st.ready ? t('wsFolder', { name: st.folder }) : t('wsNeedsPerm', { name: st.folder });
1091 const mk = (label, fn) => { const b = el('button', 'prov-use', label); b.onclick = fn; wsRow.appendChild(b); };
1092 if (st.supported.pick) {
1093 if (!st.folder) {
1094 mk(t('wsPick'), async () => { try { await workspace.pick(); await paintWs(); } catch (e) { wsState.textContent = '⚠️ ' + e.message; } });
1095 // Code ya tiene una carpeta abierta: reutilizarla es un clic
1096 if (codeTools.handle()) mk(t('wsUseProject'), async () => { await workspace.adopt(codeTools.handle()); await paintWs(); });
1097 } else if (!st.ready) mk(t('wsRegrant'), async () => { try { await workspace.regrant(); await paintWs(); } catch (e) { wsState.textContent = '⚠️ ' + e.message; } });
1098 else {
1099 mk(t('wsSaveNow'), async () => { try { const r = await workspace.save(); wsState.textContent = r.ok ? t('wsSaved', { n: r.wrote.length }) : '⚠️ ' + (r.errors[0]?.error || ''); } catch (e) { wsState.textContent = '⚠️ ' + e.message; await paintWs(); } });
1100 const lbl = el('label', null); lbl.style.cssText = 'display:flex;align-items:center;gap:6px;font-size:.78rem';
1101 const chk = el('input'); chk.type = 'checkbox'; chk.checked = workspace.autosaveEnabled();
1102 chk.onchange = () => workspace.autosave({ enabled: chk.checked });
1103 lbl.append(chk, el('span', 'muted', t('wsAuto'))); wsRow.appendChild(lbl);
1104 mk(t('wsForget'), async () => { await workspace.forget(); await paintWs(); });
1105 }
1106 }
1107 mk(t('wsDownload'), async () => {
1108 const blob = await workspace.bundle();
1109 const a = document.createElement('a');
1110 a.href = URL.createObjectURL(blob);
1111 a.download = `elffuss-code-${new Date().toISOString().slice(0, 10)}.json`;
1112 a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 4000);
1113 });
1114 wsInv.replaceChildren(el('b', null, t('wsWhat')));
1115 for (const it of await workspace.inventory()) {
1116 const line = el('div'); line.style.cssText = 'display:flex;justify-content:space-between;padding:3px 0';
1117 line.append(el('span', null, `${it.icon} ${it.label}`), el('span', 'muted', it.error ? '⚠️' : `${it.count} · ${wsKb(it.bytes)}`));
1118 wsInv.appendChild(line);
1119 }
1120 }
1121 paintWs().catch(() => {});
1122
1123 // --- Almacenamiento del modelo (caché persistente) ---
1124 box.append(el('div', 'sk-h', t('setStoreTitle')));
1125 const storeCard = el('div', 'prov-card');
1126 const storeInfo = el('span', null, t('setCalc')); storeInfo.style.cssText = 'font-size:.8rem;color:var(--fg)';
1127 const storeSub = el('div', 'field'); storeSub.style.marginTop = '2px';
1128 const storeMuted = el('span', 'muted', ''); storeMuted.style.fontSize = '.72rem';
1129 const clearBtn = el('button', 'prov-use', t('setClear'));
1130 clearBtn.style.marginTop = '8px';
1131 const clearMsg = el('div', 'muted'); clearMsg.setAttribute('role', 'status'); clearMsg.style.cssText = 'font-size:.72rem;margin-top:6px';
1132 // La misma rutina que el chip 💾: confirma, vacía TODO lo que son modelos y
1133 // dice cuánto se liberó (antes solo borraba una caché vieja y no decía nada).
1134 clearBtn.onclick = async () => {
1135 const r = await vaciarModelos(clearBtn);
1136 if (r) clearMsg.textContent = r;
1137 await paintStorage();
1138 };
1139 const storeHead = el('div', 'prov-head'); storeHead.append(storeInfo);
1140 storeCard.append(storeHead, storeMuted, clearBtn, clearMsg);
1141 box.appendChild(storeCard);
1142 async function paintStorage() {
1143 const { quota, persisted } = await cacheEstimate();
1144 const m = await modelUsage();
1145 storeInfo.textContent = m.total ? t('setCached', { gb: tamano(m.total) }) : t('setNone');
1146 storeMuted.textContent = (persisted ? t('setPersist') : t('setNoPersist'))
1147 + (quota ? t('setLimit', { gb: tamano(quota) }) : '')
1148 + (m.sharedOk ? '' : t('setSharedUnknown'));
1149 }
1150 paintStorage();
1151
1152 // --- Bridge local (ejecución REAL en tu máquina: node, npm, python…) ---
1153 box.append(el('div', 'sk-h', t("setBridgeTitle")));
1154 const brCard = el('div', 'prov-card bridge-card');
1155 const OTHER = { 'elffuss-bridge-mac-arm64': 'Mac (Apple Silicon)', 'elffuss-bridge-mac-intel': 'Mac (Intel)', 'elffuss-bridge-windows.exe': 'Windows', 'elffuss-bridge-linux': 'Linux (x64)', 'elffuss-bridge-linux-arm64': 'Linux (ARM)' };
1156 // Etiquetas ASOCIADAS a sus campos (for/id) y mensajes en una región viva.
1157 brCard.innerHTML =
1158 `<div class="prov-head"><span id="br-dot" class="dot off" aria-hidden="true"></span><b>${escapeHtml(t('setBridgeName'))}</b><span id="br-status" class="muted" role="status" style="margin-left:auto;font-size:.72rem">${escapeHtml(t('setBridgeDisconnected'))}</span></div>` +
1159 `<p class="muted" style="font-size:.72rem;margin:6px 0">${t('setBridgeDesc')}</p>` +
1160 `<p class="muted" style="font-size:.7rem;margin:0 0 6px">${t('setBridgeOld')}</p>` +
1161 `<div id="br-dl"></div>` +
1162 `<details style="margin-top:6px"><summary class="muted" style="font-size:.7rem;cursor:pointer">${t('setBridgeOtherOS')}</summary><div id="br-dl-other"></div></details>` +
1163 `<p class="muted" style="font-size:.7rem;margin:6px 0 0"><a href="https://github.com/KikoCis/elffuss-code/tree/main/bridge" target="_blank" rel="noopener noreferrer" style="color:var(--accent2)">${escapeHtml(t('setBridgeSource'))} ↗</a></p>` +
1164 `<div class="field" style="margin-top:8px"><label for="br-token" class="muted" style="font-size:.68rem">${t('setBrToken')}</label><input id="br-token" type="password" autocomplete="off" placeholder="${t('brTokenPh')}"></div>` +
1165 `<div class="field" style="margin-top:6px"><label for="br-folder" class="muted" style="font-size:.68rem">${t('setBridgeFolderLabel')}</label><input id="br-folder" placeholder="${t('setBridgeFolderPh')}"></div>` +
1166 `<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:8px"><button id="br-connect" class="prov-use">${t('setBridgeConnect')}</button>` +
1167 `<button id="br-disconnect" class="prov-use" hidden>${escapeHtml(t('setBridgeDisconnect'))}</button>` +
1168 `<button id="br-forget" class="prov-use" hidden>${escapeHtml(t('setBridgeForget'))}</button></div>`;
1169 box.appendChild(brCard);
1170 pintaDescargasBridge(brCard, OTHER);
1171 brCard.querySelector('#br-folder').value = bridge.getFolder();
1172 brCard.querySelector('#br-token').value = localStorage.getItem('elffusscode.bridgeToken') || '';
1173 const paintBridge = () => {
1174 const on = bridge.isConnected();
1175 brCard.querySelector('#br-dot').className = 'dot ' + (on ? 'on' : 'off');
1176 brCard.querySelector('#br-status').textContent = on ? t("setBridgeOnStatus") : t("setBridgeDisconnected");
1177 if (on) brCard.querySelector('#br-token').value = localStorage.getItem('elffusscode.bridgeToken') || '';
1178 brCard.querySelector('#br-disconnect').hidden = !on;
1179 brCard.querySelector('#br-forget').hidden = !bridge.hasSavedToken();
1180 };
1181 paintBridge();
1182 // repinta si el bridge conecta/cae mientras Ajustes está abierto; al cerrarse
1183 // el panel se deja de escuchar
1184 const dejar = bridge.onStatusChange(() => { if (!document.body.contains(brCard)) return dejar(); paintBridge(); });
1185 brCard.querySelector('#br-connect').onclick = async () => {
1186 const btn = brCard.querySelector('#br-connect');
1187 bridge.setFolder(brCard.querySelector('#br-folder').value);
1188 const token = brCard.querySelector('#br-token').value.trim();
1189 if (!token) return showBridgeMsg(brCard, t("setBridgeNoToken"), true);
1190 btn.disabled = true; btn.textContent = t("setBridgeConnecting");
1191 try { await bridge.connect(token); paintBridge(); showBridgeMsg(brCard, t("setBridgeConnectedMsg")); fireworks(); }
1192 catch (e) { showBridgeMsg(brCard, '⚠️ ' + e.message, true); }
1193 finally { btn.disabled = false; btn.textContent = t("setBridgeConnect"); }
1194 };
1195 // Antes no había forma de desconectar (la función existía y nadie la usaba)
1196 // ni de que el navegador olvidara el token guardado.
1197 brCard.querySelector('#br-disconnect').onclick = () => { bridge.disconnect(); paintBridge(); showBridgeMsg(brCard, t('setBridgeDisconnectedMsg')); };
1198 brCard.querySelector('#br-forget').onclick = () => {
1199 bridge.forgetToken();
1200 brCard.querySelector('#br-token').value = '';
1201 paintBridge();
1202 showBridgeMsg(brCard, t('setBridgeForgotMsg'));
1203 };
1204
1205 // --- Permisos de ejecución (mismo interruptor que </> Auto de la barra) ---
1206 box.append(el('div', 'sk-h', t("setPermTitle")));
1207 const permCard = el('div', 'prov-card');
1208 permCard.innerHTML =
1209 // Lo que de verdad controla: escribir/editar ficheros. Decía «y comandos de
1210 // terminal», y la nota de debajo contaba que terminal.run no pregunta nunca.
1211 `<label style="display:flex;align-items:center;gap:8px;cursor:pointer">` +
1212 `<input type="checkbox" id="perm-autoedit"> ` +
1213 `<span>${escapeHtml(t('setPermLabel'))}</span>` +
1214 `</label>` +
1215 `<p class="muted" style="font-size:.7rem;margin:6px 0 0">${escapeHtml(t('setPermNote'))}</p>`;
1216 box.appendChild(permCard);
1217 const permCheckbox = permCard.querySelector('#perm-autoedit');
1218 permCheckbox.checked = autoEdit;
1219 permCheckbox.onchange = () => {
1220 autoEdit = permCheckbox.checked;
1221 guardaPref('elffusscode.autoedit', autoEdit ? '1' : '0');
1222 paintAuto();
1223 };
1224
1225 // --- 🎯 Modo Objetivo (planificador + ejecutor, mismo patrón que Auto) ---
1226 box.append(el('div', 'sk-h', t("setGoalTitle")));
1227 const goalCard = el('div', 'prov-card');
1228 goalCard.innerHTML =
1229 `<label style="display:flex;align-items:center;gap:8px;cursor:pointer">` +
1230 `<input type="checkbox" id="perm-goalmode"> ` +
1231 `<span>${escapeHtml(t('setGoalLabel'))}</span>` +
1232 `</label>` +
1233 `<p class="muted" style="font-size:.7rem;margin:6px 0 0">${escapeHtml(t('setGoalNote'))}</p>`;
1234 box.appendChild(goalCard);
1235 const goalCheckbox = goalCard.querySelector('#perm-goalmode');
1236 goalCheckbox.checked = goalMode;
1237 goalCheckbox.onchange = () => {
1238 goalMode = goalCheckbox.checked;
1239 guardaPref('elffusscode.goalmode', goalMode ? '1' : '0');
1240 paintGoal();
1241 };
1242
1243 // --- 📨 Errores y feedback (opt-in — apagado no sale NADA de tu máquina) ---
1244 box.append(el('div', 'sk-h', t("setTelTitle")));
1245 const telCard = el('div', 'prov-card');
1246 telCard.innerHTML =
1247 `<label style="display:flex;align-items:center;gap:8px;cursor:pointer">` +
1248 `<input type="checkbox" id="tel-enabled"> ` +
1249 `<span>${escapeHtml(t('setTelAuto'))}</span>` +
1250 `</label>` +
1251 `<p class="muted" style="font-size:.7rem;margin:6px 0 10px">${escapeHtml(t('setTelNote'))}</p>` +
1252 `<label for="tel-feedback" class="muted" style="font-size:.68rem">${escapeHtml(t('setTelManual'))}</label>` +
1253 `<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>` +
1254 `<button id="tel-send" class="prov-use" style="margin-top:6px">${escapeHtml(t('setTelSend'))}</button>` +
1255 `<span id="tel-msg" class="muted" role="status" aria-live="polite" style="font-size:.7rem;margin-left:8px"></span>`;
1256 box.appendChild(telCard);
1257 const telCheckbox = telCard.querySelector('#tel-enabled');
1258 telCheckbox.checked = telemetry.isEnabled();
1259 telCheckbox.onchange = () => telemetry.setEnabled(telCheckbox.checked);
1260 // Solo dice «enviado» si el servidor lo aceptó. Antes lo decía siempre
1261 // (también con un 404 o sin red) y además borraba el texto: el usuario
1262 // creía haberlo mandado y lo había perdido.
1263 telCard.querySelector('#tel-send').onclick = async () => {
1264 const btn = telCard.querySelector('#tel-send');
1265 const ta = telCard.querySelector('#tel-feedback');
1266 const msg = telCard.querySelector('#tel-msg');
1267 const text = ta.value.trim();
1268 msg.style.color = '';
1269 if (!text) { msg.textContent = t("setTelEmpty"); return; }
1270 btn.disabled = true; btn.setAttribute('aria-busy', 'true');
1271 msg.textContent = t('setTelSending');
1272 const wasEnabled = telemetry.isEnabled();
1273 if (!wasEnabled) telemetry.setEnabled(true); // el envío manual es explícito, se permite aunque el automático esté apagado
1274 let enviado = false;
1275 try { enviado = await telemetry.sendFeedback(text); }
1276 finally {
1277 if (!wasEnabled) telemetry.setEnabled(false); // no activa el automático de fondo si no lo pidió
1278 btn.disabled = false; btn.removeAttribute('aria-busy');
1279 }
1280 if (!enviado) { msg.textContent = t('setTelFailed'); msg.style.color = '#ff6b8b'; return; }
1281 ta.value = '';
1282 msg.textContent = t("setTelThanks");
1283 setTimeout(() => { msg.textContent = ''; }, 4000);
1284 };
1285
1286 // --- Proveedores externos (API keys) ---
1287 box.append(el('div', 'sk-h', t("setProvTitle")));
1288 for (const [id, c] of Object.entries(settings.configs())) {
1289 const card = el('div', 'prov-card' + (c.enabled ? ' on' : ''));
1290 const head = el('div', 'prov-head');
1291 const toggle = document.createElement('input'); toggle.type = 'checkbox'; toggle.checked = c.enabled;
1292 toggle.setAttribute('aria-label', t('provToggle', { name: c.label }));
1293 const title = el('b', null, c.label);
1294 const use = el('button', 'prov-use', t("setProvUse"));
1295 use.hidden = !c.enabled || activeModel === 'ext:' + id;
1296 use.onclick = () => { changeModel('ext:' + id); renderSettings(); };
1297 head.append(toggle, title, use);
1298 const fields = el('div', 'prov-fields' + (c.enabled ? '' : ' hide'));
1299 const model = document.createElement('input'); model.value = c.model || ''; model.placeholder = t('setModelPh');
1300 const key = document.createElement('input'); key.type = 'password'; key.value = c.apiKey || '';
1301 key.placeholder = c.kind === 'anthropic' ? 'sk-ant-…' : (id === 'ollama' || id === 'server' ? t('keyNeeded') : 'sk-…');
1302 fields.append(labeled(t('lblModel'), model), labeled(t('lblApiKey'), key));
1303 const save = () => {
1304 settings.update(id, { enabled: toggle.checked, model: model.value.trim(), apiKey: key.value });
1305 rebuildSelect();
1306 };
1307 toggle.onchange = () => { save(); renderSettings(); };
1308 model.onchange = key.onchange = save;
1309 card.append(head, fields);
1310 box.appendChild(card);
1311 }
1312
1313 // --- Skills ---
1314 box.append(el('div', 'sk-h', 'Skills'));
1315 const skBtn = el('button', 'primary wide', '🧩 Gestionar skills de Claude Code');
1316 skBtn.textContent = t("setManageSkillsBtn");
1317 skBtn.onclick = openSkillsPanel;
1318 box.appendChild(skBtn);
1319}
1320function labeled(label, input) {
1321 const w = el('label', 'field'); w.append(el('span', 'muted', label), input); return w;
1322}
1323
1324// ---------- arranque ----------
1325let galaxy = null;
1326async function enterIDE(handle) {
1327 const name = await codeTools.openProject(handle);
1328 shell.reset(); // el terminal arranca en la raíz del proyecto
1329 galaxy?.stop();
1330 $('landing').hidden = true;
1331 $('ide').hidden = false;
1332 $('project-name').textContent = name;
1333 $('explorer-proj').textContent = name.toUpperCase();
1334 await initEditor();
1335 await refreshTree(handle);
1336 // el sistema de conversaciones primero: renderActiveLog() REEMPLAZA todo
1337 // #chat-log con el historial replay de la conversación activa — si el
1338 // saludo se añadiera antes, desaparecería sin dejar rastro.
1339 await conv.init({ onEvent: onConvEvent });
1340 renderTabsBar();
1341 renderActiveLog();
1342 addMsg('sys', t('welcome', { name }));
1343 abreDesdeHash();
1344 // Abierto desde una notificación con la app cerrada (sw.js → ?notif=…):
1345 // la propuesta está en la Mente, que se abre ya con el proyecto cargado.
1346 try {
1347 const u = new URL(location.href);
1348 if (u.searchParams.has('notif')) {
1349 u.searchParams.delete('notif');
1350 history.replaceState(null, '', u.pathname + u.search + u.hash);
1351 mind.openMind();
1352 }
1353 } catch { /* — */ }
1354 refreshGit();
1355 preloadModel(); // por si el arranque en la landing no llegó a dispararse
1356}
1357
1358// Un fallo al abrir: en la landing si sigue a la vista, si no en la barra de
1359// estado del IDE (enterIDE ya la ha ocultado).
1360function avisaFalloApertura(e) {
1361 const msg = '⚠️ ' + t('openFolderFailed', { e: e?.message || e });
1362 if (!$('landing').hidden) { const st = $('clone-status'); st.textContent = msg; st.classList.add('err'); }
1363 else $('statusbar').textContent = msg;
1364}
1365
1366async function boot() {
1367 applyI18n(); // localiza el chrome estático (placeholder) antes de pintar nada
1368 // Caché de modelos (persistente + service worker) ANTES de descargar nada,
1369 // para que hasta la primera descarga de pesos quede cacheada y no se repita.
1370 ensureModelCache().finally(() => preloadModel());
1371 bridge.tryAutoConnect(); // reconecta en silencio si ya se conectó antes (mismo token)
1372 bridge.startAutoDetect(); // sigue sondeando en 2º plano: detecta el bridge si se arranca/reinicia más tarde
1373 // galaxia en la landing (misma técnica que Elffuss)
1374 import('./splash-gl.js').then(m => { galaxy = m.startGalaxy($('landing')); }).catch(() => {});
1375
1376 // clonar un repo público (GitHub/Bitbucket): elige carpeta destino, se
1377 // descarga ahí (fichero a fichero, sin git) y se abre como proyecto.
1378 // RESUMIBLE: el trabajo (lista de ficheros + cuáles ya se bajaron + el
1379 // handle de la carpeta) se persiste en IndexedDB — si el usuario navega
1380 // atrás, cierra la pestaña o recarga a medias, al volver se ofrece
1381 // «Reanudar» en vez de forzar a empezar de cero.
1382 const cloneUrl = $('clone-url'), cloneBtn = $('clone-btn'), cloneStatus = $('clone-status');
1383 // #clone-status es la línea de estado de la landing (role=status): ahí van
1384 // los fallos de abrir, reabrir y clonar. Antes «Reabrir» escribía en la
1385 // barra de estado del IDE, que aún está oculta, y nadie lo veía.
1386 const showCloneStatus = (text, isErr) => { cloneStatus.textContent = text; cloneStatus.classList.toggle('err', !!isErr); };
1387
1388 // Abrir una carpeta: cancelar el selector (AbortError) no es un fallo y se
1389 // calla; cualquier otro error se dice. Antes un catch pelado se lo tragaba
1390 // todo, y en un navegador sin selector de carpetas el botón no hacía nada.
1391 $('open-project').onclick = async () => {
1392 const btn = $('open-project');
1393 showCloneStatus('');
1394 let handle;
1395 try { handle = await window.showDirectoryPicker({ mode: 'readwrite' }); }
1396 catch (e) { if (e?.name !== 'AbortError') showCloneStatus('⚠️ ' + t('openFolderFailed', { e: e?.message || e }), true); return; }
1397 btn.disabled = true; btn.setAttribute('aria-busy', 'true');
1398 showCloneStatus(t('openingIde'));
1399 try { await enterIDE(handle); showCloneStatus(''); }
1400 catch (e) { avisaFalloApertura(e); }
1401 finally { btn.disabled = false; btn.removeAttribute('aria-busy'); }
1402 };
1403 // Sin File System Access (Firefox, Safari) no hay forma de abrir una carpeta
1404 // ni de elegir dónde descargar un repo: se dice en la propia landing, se
1405 // desactivan esos botones y se ofrece trabajar en el almacenamiento privado
1406 // del navegador (OPFS), que sí existe ahí.
1407 if (typeof window.showDirectoryPicker !== 'function') {
1408 for (const b of [$('open-project'), cloneBtn, cloneUrl]) b.disabled = true;
1409 showCloneStatus(t('noFsAccess'), true);
1410 if (navigator.storage?.getDirectory) {
1411 const probar = $('try-browser');
1412 probar.hidden = false;
1413 // Una carpeta PROPIA dentro del almacenamiento del navegador, no su raíz: en
1414 // la raíz viven también los pesos de los modelos (elffuss-models), y abierta
1415 // como proyecto el explorador, la paleta, la búsqueda y las herramientas del
1416 // agente los enseñaban y podían editarlos o borrarlos.
1417 probar.onclick = async () => {
1418 try { await enterIDE(await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-code', { create: true })); }
1419 catch (e) { avisaFalloApertura(e); }
1420 };
1421 }
1422 }
1423 const saveCloneJob = job => db.set('kv', 'cloneJob', job).catch(() => {});
1424 const loadCloneJob = () => db.get('kv', 'cloneJob').catch(() => null);
1425 const clearCloneJob = () => db.del('kv', 'cloneJob').catch(() => {});
1426
1427 async function runDownload(job) {
1428 cloneBtn.disabled = true;
1429 const doneSet = new Set(job.done);
1430 const clone = await import('./tools/clone.js');
1431 try {
1432 await clone.downloadFiles(job, job.handle, doneSet,
1433 p => showCloneStatus(p.text || ''),
1434 async path => {
1435 job.done.push(path);
1436 // persistir el progreso poco a poco (no en cada fichero: de sobra
1437 // para no perder más de un puñado si se interrumpe a media descarga)
1438 if (job.done.length % 5 === 0) await saveCloneJob(job);
1439 });
1440 await saveCloneJob(job);
1441 showCloneStatus(`✔ ${job.files.length} ficheros descargados` + (job.skipped ? ` (${job.skipped} omitidos por tamaño)` : ''));
1442 await clearCloneJob();
1443 await enterIDE(job.handle);
1444 } catch (e) {
1445 await saveCloneJob(job); // que lo ya bajado no se pierda aunque falle a mitad
1446 showCloneStatus('⚠️ ' + (e?.message || e) + ' — puedes reintentar, retoma donde se quedó', true);
1447 } finally { cloneBtn.disabled = false; }
1448 }
1449
1450 const runClone = async () => {
1451 const url = cloneUrl.value.trim();
1452 // La URL se valida ANTES de abrir el selector de carpeta: antes se elegía
1453 // la carpeta y solo después decía que la URL no valía. Vacía, lo dice.
1454 if (!url) { showCloneStatus(t('clonePasteUrl'), true); cloneUrl.focus(); return; }
1455 const clone = await import('./tools/clone.js');
1456 try { clone.parseRepoUrl(url); }
1457 catch { showCloneStatus('⚠️ ' + t('cloneBadUrl'), true); cloneUrl.focus(); return; }
1458 showCloneStatus('');
1459 let handle;
1460 try { handle = await window.showDirectoryPicker({ mode: 'readwrite' }); }
1461 catch (e) { if (e?.name !== 'AbortError') showCloneStatus('⚠️ ' + (e?.message || e), true); return; }
1462 showCloneStatus(t('cloneListing'));
1463 try {
1464 const info = await clone.listRepo(url);
1465 const job = { url, handle, done: [], ...info };
1466 await saveCloneJob(job);
1467 await runDownload(job);
1468 } catch (e) {
1469 showCloneStatus('⚠️ ' + (e?.message || e), true);
1470 }
1471 };
1472 cloneBtn.addEventListener('click', runClone);
1473 cloneUrl.addEventListener('keydown', e => { if (e.key === 'Enter') runClone(); });
1474
1475 // ¿había una descarga a medias de una sesión anterior? ofrece reanudarla
1476 const job = await loadCloneJob();
1477 if (job && job.handle && job.files && job.done.length < job.files.length) {
1478 const banner = $('resume-clone');
1479 banner.hidden = false;
1480 // owner/repo enlaza al repositorio público que se estaba bajando.
1481 const rc = banner.querySelector('.rc-text');
1482 const a = document.createElement('a');
1483 a.href = (job.host === 'bitbucket' ? 'https://bitbucket.org/' : 'https://github.com/') + encodeURIComponent(job.owner) + '/' + encodeURIComponent(job.repo);
1484 a.target = '_blank'; a.rel = 'noopener noreferrer';
1485 a.textContent = `${job.owner}/${job.repo}`;
1486 const [antes, despues] = t('cloneHalf', { repo: '\u0000', n: job.done.length, total: job.files.length }).split('\u0000');
1487 rc.replaceChildren(antes, a, despues);
1488 $('resume-clone-btn').onclick = async () => {
1489 banner.hidden = true;
1490 try {
1491 const q = job.handle.queryPermission ? await job.handle.queryPermission({ mode: 'readwrite' }) : 'granted';
1492 if (q !== 'granted' && await job.handle.requestPermission({ mode: 'readwrite' }) !== 'granted') throw new Error('permiso denegado para la carpeta');
1493 showCloneStatus(`Reanudando ${job.owner}/${job.repo}…`);
1494 await runDownload(job);
1495 } catch (e) { showCloneStatus('⚠️ ' + (e?.message || e), true); }
1496 };
1497 $('discard-clone-btn').onclick = async () => { await clearCloneJob(); banner.hidden = true; };
1498 } else if (job) {
1499 await clearCloneJob(); // job corrupto o ya completo: limpiar
1500 }
1501
1502 // gancho de test: ?test-opfs usa el almacenamiento del navegador como proyecto
1503 if (location.search.includes('test-opfs')) {
1504 const opfs = await navigator.storage.getDirectory();
1505 return enterIDE(opfs);
1506 }
1507
1508 // reabrir el último proyecto (un clic si el navegador exige gesto)
1509 const prev = await codeTools.restoreProject();
1510 if (prev?.ready) return enterIDE(await db.get('kv', 'project'));
1511 if (prev?.handle) {
1512 const btn = $('reopen-project');
1513 btn.hidden = false;
1514 btn.textContent = t('reopenFolder', { name: prev.name });
1515 btn.onclick = async () => {
1516 try { await codeTools.regrant(prev.handle); await enterIDE(prev.handle); }
1517 catch (e) { avisaFalloApertura(e); }
1518 };
1519 }
1520}
1521
1522// Historial del prompt del chat: ↑/↓ recuperan lo enviado (como una shell).
1523// Persistente entre recargas (localStorage, últimos 100).
1524const PROMPT_HIST_KEY = 'elffusscode.promptHistory';
1525let promptHistory = [];
1526try { promptHistory = JSON.parse(localStorage.getItem(PROMPT_HIST_KEY) || '[]'); } catch { /* corrupto */ }
1527let promptHistIdx = -1, promptDraft = '';
1528function pushPromptHistory(text) {
1529 if (promptHistory[promptHistory.length - 1] !== text) promptHistory.push(text);
1530 if (promptHistory.length > 100) promptHistory = promptHistory.slice(-100);
1531 try { localStorage.setItem(PROMPT_HIST_KEY, JSON.stringify(promptHistory)); } catch { /* lleno */ }
1532 promptHistIdx = -1; promptDraft = '';
1533}
1534$('prompt').addEventListener('keydown', e => {
1535 if (!$('menu').hidden) return; // el menú «/» ya usa ↑/↓
1536 const inp = e.target;
1537 // En un borrador de varias líneas, ↑/↓ mueven el cursor como siempre: el
1538 // historial solo salta desde la primera línea (↑) o la última (↓). Antes ↑
1539 // en un texto largo lo sustituía entero por el mensaje anterior.
1540 const antes = inp.value.slice(0, inp.selectionStart), despues = inp.value.slice(inp.selectionEnd);
1541 if (e.key === 'ArrowUp' && antes.includes('\n')) return;
1542 if (e.key === 'ArrowDown' && despues.includes('\n')) return;
1543 if (e.key === 'ArrowUp') {
1544 if (!promptHistory.length) return;
1545 if (promptHistIdx === -1) { promptDraft = inp.value; promptHistIdx = promptHistory.length; }
1546 promptHistIdx = Math.max(0, promptHistIdx - 1);
1547 inp.value = promptHistory[promptHistIdx];
1548 e.preventDefault();
1549 requestAnimationFrame(() => inp.setSelectionRange(inp.value.length, inp.value.length));
1550 } else if (e.key === 'ArrowDown') {
1551 if (promptHistIdx === -1) return;
1552 promptHistIdx++;
1553 inp.value = promptHistIdx >= promptHistory.length ? (promptHistIdx = -1, promptDraft) : promptHistory[promptHistIdx];
1554 e.preventDefault();
1555 } else if (e.key === 'Enter' && !e.isComposing && !e.shiftKey) {
1556 // envío explícito: no depender del submit-on-Enter nativo del <form>,
1557 // que algún navegador puede "tragarse" el primer Enter (autocompletar/
1558 // sugerencias) justo después de rellenar el valor por código (↑ del
1559 // historial) en vez de por tecleo real.
1560 e.preventDefault();
1561 $('composer').requestSubmit();
1562 }
1563});
1564$('composer').addEventListener('submit', e => {
1565 e.preventDefault();
1566 // Mientras el agente trabaja, el BOTÓN para en vez de enviar. Enter no: con
1567 // texto lo ENCOLA (cada conversación acepta y encola mensajes) y sale en
1568 // cuanto termine lo de ahora. Antes Enter también paraba, y el texto se
1569 // quedaba sin enviar en la caja. `submitter` es el botón solo en un clic (o
1570 // Enter/Espacio con el foco en él); con Enter en el cuadro de texto
1571 // (requestSubmit sin argumento) es null. Si ya se está parando, pulsar el
1572 // propio botón, que dice «Parando…» y está aria-disabled, no hace nada.
1573 const active = conv.getActive();
1574 const desdeBoton = e.submitter?.id === 'btn-send';
1575 if (desdeBoton && active?.parando) return;
1576 if (desdeBoton && active && active.pumping && !active.parando) { conv.stopActive(); return; }
1577 const text = $('prompt').value.trim();
1578 if (!text) return;
1579 $('prompt').value = '';
1580 pushPromptHistory(text);
1581 send(text);
1582});
1583// Reflejar en el botón si estamos generando (▶ enviar / ■ parar). Se llama desde
1584// el onChange de conversaciones cuando cambia «pumping».
1585const STOP_ICON = '<svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><rect x="2" y="2" width="10" height="10" rx="2" fill="currentColor"/></svg>';
1586function paintSendButton() {
1587 const b = document.getElementById('btn-send');
1588 if (!b) return;
1589 const active = conv.getActive();
1590 const busy = !!active?.pumping;
1591 // «Parando…»: ya se pulsó ■ y el turno aún se está soltando (un modelo lento
1592 // tarda en dejar la generación). Antes el ■ seguía igual tras el clic y
1593 // parecía que no había hecho caso. Se marca con aria-disabled y NO con
1594 // disabled: deshabilitar el botón que tiene el foco lo saca del foco, el
1595 // teclado caía a <body> y ya no volvía.
1596 const parando = busy && !!active?.parando;
1597 b.classList.toggle('sending', busy);
1598 b.classList.toggle('is-stop', busy && !parando);
1599 b.classList.toggle('is-stopping', parando);
1600 if (parando) { b.setAttribute('aria-disabled', 'true'); b.setAttribute('aria-busy', 'true'); }
1601 else { b.removeAttribute('aria-disabled'); b.removeAttribute('aria-busy'); }
1602 b.innerHTML = parando ? escapeHtml(t('stopping')) : busy ? STOP_ICON : UI.send;
1603 b.title = parando ? t('stopping') : busy ? t('stop') : t('send');
1604 b.setAttribute('aria-label', b.title);
1605}
1606// La parada se anuncia en una región viva: el botón solo lo dice en su
1607// etiqueta, y parando con Enter el foco está en el cuadro de texto, así que el
1608// cambio no se oía; el «(Parado.)» del chat tampoco, porque el chat no es una
1609// región viva. Se vacía y se escribe en otro tick para que el mismo texto dos
1610// veces seguidas se vuelva a leer, y un anuncio que llega antes de escribirse
1611// el anterior lo sustituye.
1612let anuncioPendiente = null;
1613function anunciarEnvio(texto) {
1614 const r = document.getElementById('send-status');
1615 if (!r) return;
1616 clearTimeout(anuncioPendiente);
1617 r.textContent = '';
1618 anuncioPendiente = setTimeout(() => { r.textContent = texto; }, 50);
1619}
1620$('model-select').addEventListener('change', e => changeModel(e.target.value));
1621// El foco va a la tarjeta del modelo ACTIVO (un selector con coma devolvía la
1622// primera tarjeta en el orden del documento, no la activa).
1623$('model-dot').addEventListener('click', () => {
1624 renderSettings();
1625 requestAnimationFrame(() => { const panel = $('settings-panel'); (panel.querySelector('.model-card.active') || panel.querySelector('.model-card'))?.focus(); });
1626});
1627pintaDot('off', 'rules');
1628// móvil: conmutar chat ↔ editor
1629// ☰ (solo en el móvil): cajón con el árbol de ficheros y la barra de
1630// actividad. Abrir un fichero desde ahí pasa a la vista Editor y cierra el
1631// cajón; Escape o tocar fuera lo cierran.
1632function abreCajon(abrir) {
1633 const on = abrir ?? !document.body.classList.contains('drawer-open');
1634 if (on) {
1635 document.documentElement.style.setProperty('--drawer-top', Math.round(document.querySelector('#ide header').getBoundingClientRect().bottom) + 'px');
1636 if (!$('drawer-scrim')) {
1637 const scrim = document.createElement('div');
1638 scrim.id = 'drawer-scrim';
1639 scrim.onclick = () => abreCajon(false);
1640 document.body.appendChild(scrim);
1641 }
1642 }
1643 document.body.classList.toggle('drawer-open', on);
1644 // el árbol empieza justo debajo de la fila de herramientas, mida lo que mida
1645 if (on) document.documentElement.style.setProperty('--drawer-act', Math.round($('activity').getBoundingClientRect().height) + 'px');
1646 $('btn-drawer').setAttribute('aria-expanded', on ? 'true' : 'false');
1647 if (on) ($('tree').querySelector('[tabindex="0"]') || $('act-files'))?.focus();
1648 else if (document.activeElement && ($('sidebar').contains(document.activeElement) || $('activity').contains(document.activeElement))) $('btn-drawer').focus();
1649}
1650$('btn-drawer').title = t('drawerTitle');
1651$('btn-drawer').setAttribute('aria-label', t('drawerTitle'));
1652$('btn-drawer').addEventListener('click', () => abreCajon());
1653// Elegir algo del cajón lo cierra; un fichero del árbol además enseña el editor.
1654$('tree').addEventListener('click', e => {
1655 if (!document.body.classList.contains('drawer-open')) return;
1656 if (!e.target.closest('.file')) return;
1657 document.body.classList.add('show-editor');
1658 paintFlip(true);
1659 abreCajon(false);
1660});
1661$('activity').addEventListener('click', e => {
1662 if (!document.body.classList.contains('drawer-open') || !e.target.closest('button')) return;
1663 if (e.target.closest('#act-files')) return; // en el cajón, el árbol ya se ve
1664 abreCajon(false);
1665 if (e.target.closest('#act-arch, #act-city, #act-term')) { document.body.classList.add('show-editor'); paintFlip(true); }
1666}, true);
1667
1668$('code-flip').addEventListener('click', () => {
1669 const showEditor = !document.body.classList.contains('show-editor');
1670 document.body.classList.toggle('show-editor', showEditor);
1671 paintFlip(showEditor);
1672});
1673
1674// vistas Arquitectura (grafo) y Ciudad 3D — leen el proyecto abierto y al
1675// hacer clic abren el fichero en Monaco (inspirado en CodeFlow + VibeCodeViewer)
1676$('act-arch').innerHTML = UI.graph || UI.code;
1677$('act-city').innerHTML = UI.city || UI.code;
1678let viewRenderSeq = 0;
1679async function openView(kind) {
1680 const overlay = $('view-overlay'), body = $('view-body');
1681 const seq = ++viewRenderSeq;
1682 // destruir CUALQUIER vista previa (su RAF/canvas seguía vivo al cambiar → la
1683 // nueva no cargaba bien). Ambas, no solo la del mismo tipo.
1684 try { (await import('./city.js')).disposeCity(); } catch { /* */ }
1685 try { (await import('./arch.js')).disposeArch(); } catch { /* */ }
1686 body.innerHTML = '<div class="view-loading" role="status"></div>';
1687 body.firstChild.textContent = t('viewBuilding');
1688 overlay.hidden = false;
1689 document.querySelectorAll('#activity button').forEach(b => b.classList.toggle('on', b.id === 'act-' + kind));
1690 // esperar a que el layout dé tamaño real al overlay (si no, canvas 0×0/mal aspect)
1691 await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
1692 if (seq !== viewRenderSeq) return; // el usuario cambió de vista mientras tanto
1693 try {
1694 if (kind === 'arch') { const m = await import('./arch.js'); await m.renderArchitecture(body, p => { closeView(); openFile(p); }); }
1695 else { const m = await import('./city.js'); await m.renderCity(body, p => { closeView(); openFile(p); }); }
1696 } catch (e) { body.innerHTML = '<div class="view-loading" role="status"></div>'; body.firstChild.textContent = t('viewFailed', { e: e?.message || e }); }
1697}
1698function closeView({ foco = false } = {}) {
1699 const abierta = [...document.querySelectorAll('#act-arch.on, #act-city.on')][0];
1700 $('view-overlay').hidden = true;
1701 import('./city.js').then(m => m.disposeCity()).catch(() => {});
1702 import('./arch.js').then(m => m.disposeArch()).catch(() => {});
1703 document.querySelectorAll('#activity button').forEach(b => b.classList.toggle('on', b.id === 'act-files'));
1704 if (foco) abierta?.focus();
1705}
1706$('act-arch').addEventListener('click', () => openView('arch'));
1707$('act-city').addEventListener('click', () => openView('city'));
1708$('view-close').addEventListener('click', () => closeView({ foco: true }));
1709
1710// ── Cerebro CEO autónomo + Mente de Elffuss ───────────────────────────────
1711// Cuando NO estás pidiendo nada, la elfa trabaja: revisa el proyecto y propone
1712// mejoras (en elffuss-mind/, sin tocar tu código). Clic en la elfa → abre la
1713// «Mente» (mundo trance + pensamientos paralelos + música) y activa el cerebro.
1714// «Abrir en el editor» de la Mente: abre el fichero y deja el foco en el editor
1715// (la Mente cierra sin devolverlo a la elfa).
1716mind.setOpenFile(async p => { await openFile(p); focusEditor(); });
1717mind.init({ buildCity: buildCityAdapter, loadThoughts: loadThoughtsAdapter });
1718// «Ejecutar esta propuesta»: la manda a la MISMA cola/agente del chat normal
1719// (mismas herramientas reales, mismo gate de Auto-edit) — no un auto-apply
1720// aparte sin supervisión.
1721mind.setExecuteProposal(md => { mind.closeMind(); send(t('pProposal') + md); });
1722// «perfiles»: cada uno es una línea de pensamiento paralela (foco + color de
1723// su estrella) del cerebro CEO (compartido, core/ceo.js). El usuario los
1724// edita/crea/borra desde ⚙ en la Mente.
1725const CEO_DEFAULT_PROFILES = [
1726 { id: 'arq', name: 'Arquitectura', focus: 'estructura, acoplamiento y dependencias; qué módulo conviene dividir o unificar', color: '#7c5cff' },
1727 { id: 'cal', name: 'Calidad', focus: 'bugs latentes, casos borde sin cubrir, validaciones que faltan', color: '#49e8ff' },
1728 { id: 'rend', name: 'Rendimiento', focus: 'cuellos de botella, trabajo repetido, estructuras de datos mejorables', color: '#ffb454' },
1729 { id: 'dx', name: 'Producto/DX', focus: 'legibilidad, nombres, documentación y ergonomía para quien lo usa', color: '#3fb970' },
1730];
1731// adaptador de workspace para el cerebro CEO genérico (core/ceo.js): traduce
1732// sus operaciones a las herramientas de code.js (proyecto de código único).
1733async function ceoDirHandle(dirPath) {
1734 let dir = codeTools.handle();
1735 for (const seg of dirPath.split('/').filter(Boolean)) dir = await dir.getDirectoryHandle(seg, { create: true });
1736 return dir;
1737}
1738const ceoWorkspace = {
1739 isReady: () => !!codeTools.handle(),
1740 tree: (opts) => codeTools.tree(opts),
1741 write: (opts) => codeTools.write(opts),
1742 read: (opts) => codeTools.read(opts),
1743 list: async (dirPath) => {
1744 const dir = await ceoDirHandle(dirPath);
1745 const names = [];
1746 for await (const e of dir.values()) if (e.kind === 'file') names.push(e.name);
1747 return names;
1748 },
1749 remove: async (dirPath, name) => (await ceoDirHandle(dirPath)).removeEntry(name),
1750};
1751ceo.init({
1752 namespace: 'elffusscode',
1753 workspace: ceoWorkspace,
1754 defaultProfiles: CEO_DEFAULT_PROFILES,
1755 defaultMission: 'Revisar el proyecto y proponer mejoras concretas y accionables (código, procesos, datos o docs).',
1756 // Sin modelo de verdad no hay cerebro: con el motor de reglas (modo Básico)
1757 // el CEO «pensaba» con el texto de ayuda, escribía .elffuss/soul/*.md dentro
1758 // del proyecto y anunciaba «4 mejoras» que no eran nada.
1759 provider: () => { const p = conv.getProvider(); return p && p !== rules ? p : null; },
1760 // el usuario tiene PRIORIDAD: si CUALQUIER conversación está en cola o procesándose, el cerebro espera
1761 isBusy: () => conv.isBusy(),
1762 onEvent: (ch, ev) => {
1763 mind.pushThought(ch, ev);
1764 if (ch === 'ceo' && ev.type === 'built') reportImprovements(ev);
1765 // la elfa se anima mientras el cerebro trabaja (invita a hacer clic para ver la Mente)
1766 const av = document.querySelector('#activity img');
1767 if (av) {
1768 if (ch === 'ceo' && ev.type === 'cycle') av.classList.add('working');
1769 if (ch === 'ceo' && (ev.type === 'built' || ev.type === 'paused')) av.classList.remove('working');
1770 }
1771 },
1772});
1773// Reporta las mejoras SIEMPRE en el chat (visual, entendible); la notificación
1774// del navegador solo salta si de verdad hay algo interesante y bien trabajado
1775// — nada de avisar por un ciclo flojo con una propuesta de una línea.
1776const WEAK_RE = /^(no (encontr|hay|se me ocurre)|nada que|sin cambios|todo (está|esta) bien|no aplica)/i;
1777export function isNoteworthy(ev) {
1778 const solid = (ev.proposals || []).filter(p => p.text && p.text.trim().length >= 60 && !WEAK_RE.test(p.text.trim()));
1779 return solid.length >= 2; // al menos 2 departamentos con algo sustancioso, no una ocurrencia suelta
1780}
1781// manda una propuesta (el .md completo del ciclo) a la MISMA cola/agente real
1782// del chat — usado tanto por el botón del chat como por el de la notificación.
1783function executeProposal(md) { send(t('pProposal') + md); }
1784
1785// Botón REAL para ejecutar la propuesta desde el propio chat.
1786function botonPropuesta(div, md) {
1787 const btn = document.createElement('button');
1788 btn.className = 'proposal-exec-btn';
1789 btn.textContent = t('mindExec');
1790 btn.onclick = () => { btn.disabled = true; btn.textContent = t('proposalSent'); executeProposal(md); };
1791 div.appendChild(btn);
1792}
1793
1794export function reportImprovements(ev) {
1795 const props = ev.proposals || [];
1796 if (!props.length) return;
1797 const firstLine = t => (t || '').split('\n').find(l => l.trim())?.trim().slice(0, 160) || '';
1798 const body = `💡 **Mientras estabas fuera revisé el proyecto y encontré ${props.length} mejora${props.length === 1 ? '' : 's'}:**\n\n` +
1799 props.map(p => `**${p.dept}** — ${firstLine(p.text)}`).join('\n\n') +
1800 (ev.path ? `\n\n_Guardado en \`${ev.path}\`. Dale a la elfa para verlo en la Mente, o ábrelo en el editor._` : '');
1801 const div = addMsg('assistant', body);
1802 // se guarda en el historial REAL de la conversación activa — si no, el
1803 // aviso vive solo en el DOM y desaparece al cambiar de pestaña o recargar.
1804 // Con la propuesta al lado: el botón «▶ Ejecutar» se vuelve a pintar al
1805 // repintar el chat (antes solo existía en el DOM del momento).
1806 const md = ev.md || body;
1807 const active = conv.getActive();
1808 if (active) conv.appendMessage(active.id, 'assistant', body, { propuesta: md });
1809 if (div) botonPropuesta(div, md);
1810 if (isNoteworthy(ev)) notify(`Elffuss encontró ${props.length} mejora${props.length === 1 ? '' : 's'}`, props.map(p => p.dept).join(' · '), md);
1811}
1812// SOLO notifica si el permiso YA está concedido. Nunca pide permiso aquí:
1813// fuera de un gesto de usuario, Chrome/Firefox lo bloquean en silencio —
1814// pedirlo vive únicamente en el clic de la elfa y en ⚙ de la Mente.
1815// Vía el service worker (registration.showNotification) para poder incluir
1816// un botón «▶ Ejecutar» de verdad en la propia notificación del sistema
1817// (new Notification() normal no soporta acciones); si el SW no está listo,
1818// cae a la notificación simple sin botón.
1819async function notify(title, body, md) {
1820 if (!('Notification' in window) || Notification.permission !== 'granted') return;
1821 try {
1822 if ('serviceWorker' in navigator) {
1823 const reg = await navigator.serviceWorker.ready;
1824 if (reg.showNotification) {
1825 await reg.showNotification(title, {
1826 body, icon: 'img/elffuss-code.svg',
1827 actions: [{ action: 'execute', title: t('nExec') }, { action: 'open', title: t('nView') }],
1828 data: { md },
1829 });
1830 return;
1831 }
1832 }
1833 } catch { /* cae a la notificación simple */ }
1834 try { new Notification(title, { body, icon: 'img/elffuss-code.svg' }); } catch { /* */ }
1835}
1836// clic en el botón de la notificación del sistema → lo mismo que en el chat
1837if ('serviceWorker' in navigator) {
1838 navigator.serviceWorker.addEventListener('message', e => {
1839 if (e.data?.type !== 'notif-action') return;
1840 if (e.data.action === 'execute' && e.data.md) executeProposal(e.data.md);
1841 else mind.openMind();
1842 });
1843}
1844// cualquier interacción FUERA de la Mente cuenta como actividad → pausa el CEO
1845const noteAct = e => { if (!e.target.closest?.('#mind-overlay')) ceo.noteActivity(); };
1846document.addEventListener('pointerdown', noteAct, true);
1847document.addEventListener('keydown', noteAct, true);
1848// La elfa de la barra es un BOTÓN que abre la Mente, y nada más. Antes el
1849// primer clic encendía en silencio el cerebro autónomo (que empezaba a trabajar
1850// sobre tu proyecto) y pedía permiso de notificaciones sin explicar para qué.
1851// Ahora el cerebro se enciende DENTRO de la Mente, con un botón que dice lo que
1852// hace, y las notificaciones se piden solo desde ⚙ cerebro.
1853const elfAvatar = $('act-mind');
1854if (elfAvatar) {
1855 elfAvatar.title = t('avatarTitle');
1856 elfAvatar.setAttribute('aria-label', t('avatarLabel'));
1857 elfAvatar.addEventListener('click', () => mind.openMind());
1858}
1859// restaura tu última elección (play o stop) tal cual la dejaste
1860if (ceo.wasEnabledLastSession()) ceo.enable();
1861
1862// terminal integrado: xterm.js + shell sobre los ficheros REALES del proyecto.
1863// La elfa comparte este shell (tool terminal.run) y su salida se refleja aquí.
1864$('act-term').innerHTML = UI.terminal;
1865shell.setHooks({ fsChange: () => refreshTree().catch(() => {}), openFile });
1866setTerminalEcho((cmd, out) => terminal.echoAgent(cmd, out));
1867async function toggleTerminal(force) {
1868 const show = force != null ? force : $('terminal-panel').hidden;
1869 $('terminal-panel').hidden = !show;
1870 $('act-term').classList.toggle('on', show);
1871 if (show) {
1872 pintaCapacidades();
1873 await terminal.mount($('terminal-host'));
1874 terminal.refit();
1875 }
1876}
1877// La etiqueta del terminal sigue al bridge: antes solo se pintaba al abrir el
1878// panel y se quedaba vieja si el bridge conectaba o caía con él abierto.
1879function pintaCapacidades() {
1880 const cap = shell.capabilities();
1881 $('term-caps').textContent = cap.bridge ? t("termCapsBridge") : t("termCapsNoBridge");
1882}
1883bridge.onStatusChange(() => { if (!$('terminal-panel').hidden) pintaCapacidades(); });
1884$('act-term').addEventListener('click', () => toggleTerminal());
1885$('term-close').addEventListener('click', () => toggleTerminal(false));
1886$('term-clear').addEventListener('click', () => terminal.clearScreen());
1887// Ctrl+` (o Cmd+`) alterna el terminal, como en VS Code
1888document.addEventListener('keydown', e => {
1889 if ((e.ctrlKey || e.metaKey) && e.key === '`') { e.preventDefault(); toggleTerminal(); }
1890});
1891// redimensionar arrastrando la barra superior del panel
1892(() => {
1893 const panel = $('terminal-panel'), handle = $('term-resize');
1894 let sy = 0, sh = 0;
1895 // También con el teclado: es un separador con foco, ↑/↓ cambian la altura.
1896 const ajusta = h => {
1897 h = Math.max(120, Math.min(window.innerHeight - 160, h));
1898 panel.style.height = h + 'px';
1899 handle.setAttribute('aria-valuenow', String(Math.round(h)));
1900 terminal.refit();
1901 };
1902 handle.setAttribute('role', 'separator');
1903 handle.setAttribute('aria-orientation', 'horizontal');
1904 handle.setAttribute('aria-label', t('termResizeLabel'));
1905 handle.setAttribute('aria-valuemin', '120');
1906 handle.tabIndex = 0;
1907 handle.addEventListener('keydown', e => {
1908 if (e.key === 'ArrowUp') { e.preventDefault(); ajusta(panel.offsetHeight + 24); }
1909 else if (e.key === 'ArrowDown') { e.preventDefault(); ajusta(panel.offsetHeight - 24); }
1910 });
1911 const move = e => ajusta(sh + (sy - e.clientY));
1912 const up = () => { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', up); };
1913 handle.addEventListener('mousedown', e => { sy = e.clientY; sh = panel.offsetHeight; document.addEventListener('mousemove', move); document.addEventListener('mouseup', up); e.preventDefault(); });
1914})();
1915window.addEventListener('resize', () => terminal.refit());
1916
1917// iconos VS Code (sin emojis) en cabecera, composer y flip
1918$('btn-history').innerHTML = UI.history;
1919$('btn-settings').innerHTML = UI.gear;
1920$('btn-send').innerHTML = UI.send;
1921$('btn-plus').innerHTML = UI.add;
1922$('btn-slash').innerHTML = UI.slash;
1923const paintFlip = editor => { $('code-flip').innerHTML = (editor ? UI.chat : UI.editor) + `<span>${editor ? t('flipChat') : t('flipEditor')}</span>`; };
1924paintFlip(false);
1925
1926// barra de actividad estilo VS Code
1927$('act-files').innerHTML = ACTIVITY.files;
1928$('act-search').innerHTML = ACTIVITY.search;
1929$('act-settings').innerHTML = ACTIVITY.gear;
1930$('act-files').addEventListener('click', () => {
1931 document.body.classList.toggle('hide-tree');
1932 $('act-files').classList.toggle('on');
1933});
1934// Lo que promete su título: buscar ficheros (la paleta, como Cmd/Ctrl+P). Antes
1935// escribía «busca » en el chat. Buscar DENTRO del código es «#» en la paleta.
1936$('act-search').addEventListener('click', (e) => { e.stopPropagation(); openPalette(''); });
1937$('act-settings').addEventListener('click', () => $('btn-settings').click());
1938
1939$('btn-history').addEventListener('click', () => {
1940 const panel = $('history-panel');
1941 if (!panel.hidden) return cierraHistorial();
1942 panel.hidden = false;
1943 $('btn-history').setAttribute('aria-expanded', 'true');
1944 renderHistoryPanel().then(() => (panel.querySelector('.hp-open') || panel.querySelector('.hp-head button'))?.focus());
1945});
1946function cierraHistorial({ foco = true } = {}) {
1947 const panel = $('history-panel');
1948 if (panel.hidden) return;
1949 panel.hidden = true;
1950 $('btn-history').setAttribute('aria-expanded', 'false');
1951 if (foco) $('btn-history').focus();
1952}
1953document.addEventListener('pointerdown', e => {
1954 const p = $('history-panel');
1955 if (p.hidden) return;
1956 if (p.contains(e.target) || e.target.closest('#btn-history')) return;
1957 cierraHistorial({ foco: false });
1958}, true);
1959$('btn-settings').addEventListener('click', () => {
1960 const p = $('settings-panel');
1961 if (!p.hidden) return cierraAjustes();
1962 renderSettings();
1963});
1964// clic fuera del panel (o ir a Archivo/chat) lo cierra — antes solo la X lo hacía
1965document.addEventListener('pointerdown', e => {
1966 const p = $('settings-panel');
1967 if (p.hidden) return;
1968 if (p.contains(e.target) || e.target.closest('#btn-settings, #act-settings, #model-dot')) return;
1969 p.hidden = true;
1970 volverDeAjustes = null;
1971}, true);
1972
1973// ── Escape cierra la capa de más arriba ─────────────────────────────────────
1974// Una por pulsación, y el foco vuelve a quien la abrió. Antes solo la paleta,
1975// la Mente y el menú @ hacían caso: menús de arriba, modos, historial,
1976// ajustes y la vista 3D se quedaban abiertos.
1977const CAPAS = [
1978 { abierta: () => !$('menu').hidden, cerrar: () => { $('menu').hidden = true; $('prompt').focus(); } },
1979 { abierta: () => !$('topmenu').hidden, cerrar: () => cierraMenuBarra({ foco: true }) },
1980 { abierta: () => !$('modos-menu')?.hidden, cerrar: () => cierraModos({ foco: true }) },
1981 { abierta: () => !$('history-panel').hidden, cerrar: () => cierraHistorial() },
1982 { abierta: () => !$('settings-panel').hidden, cerrar: () => cierraAjustes() },
1983 { abierta: () => !$('view-overlay').hidden, cerrar: () => closeView({ foco: true }) },
1984 { abierta: () => document.body.classList.contains('drawer-open'), cerrar: () => abreCajon(false) },
1985];
1986document.addEventListener('keydown', e => {
1987 if (e.key !== 'Escape' || e.defaultPrevented || e.isComposing) return;
1988 if (mind.isOpen() || !$('palette').hidden) return; // tienen su propio Escape
1989 if (document.querySelector('dialog[open], #tree-menu, #tab-menu, #conv-menu')) return;
1990 if (e.target.closest?.('.monaco-editor, #terminal-host')) {
1991 // El editor y el terminal usan Escape para lo suyo; solo se cierra una capa
1992 // si no hay nada que cerrar dentro de ellos.
1993 if (!CAPAS.some(c => c.abierta())) return;
1994 }
1995 for (const c of CAPAS) if (c.abierta()) { e.preventDefault(); c.cerrar(); return; }
1996});
1997
1998// ---------- composer estilo plugin: +, /, medidor de contexto, Auto ----------
1999
2000// medidor de contexto: chars del historial / presupuesto (~4 chars/token)
2001//
2002// El presupuesto se le PREGUNTA al proveedor cargado, no se escribe aquí. Era un
2003// 28.000 fijo, calculado para el LFM2.5 de serie, y enseñaba «ctx 0 / 28k» con
2004// cualquier modelo: con el motor propio a 65.536 mentía por más del doble, y al
2005// revés con uno pequeño habría dicho que cabe lo que no cabe. Un número escrito
2006// a mano en la interfaz es un número que se queda viejo — el mismo fallo que la
2007// lista de modelos de los ajustes.
2008const CTX_BUDGET_FALLBACK = 28000; // solo si el proveedor no sabe decirlo
2009let ctxBudgetTok = CTX_BUDGET_FALLBACK;
2010export function setCtxBudget(tokens) {
2011 // Se reserva sitio para el prompt de sistema y para la respuesta: el techo del
2012 // modelo NO es lo que cabe de conversación.
2013 const RESERVA = 4000;
2014 if (Number.isFinite(tokens) && tokens > RESERVA) ctxBudgetTok = tokens - RESERVA;
2015}
2016function updateCtxMeter() {
2017 if (!$('ctx-text')) return; // aún en la landing
2018 const CTX_BUDGET_TOK = ctxBudgetTok;
2019 const chars = (conv.getActive()?.agent.history || []).reduce((s, m) => s + (m.content || '').length, 0);
2020 const tok = Math.round(chars / 4);
2021 const pct = Math.min(100, Math.round(tok / CTX_BUDGET_TOK * 100));
2022 const k = n => n >= 1000 ? (n / 1000).toFixed(1).replace('.0', '') + 'k' : n;
2023 $('ctx-text').textContent = `ctx ${k(tok)} / ${k(CTX_BUDGET_TOK)}`;
2024 $('ctx-bar').style.width = pct + '%';
2025 $('ctx-bar').className = pct > 85 ? 'hot' : '';
2026 // Decía «usa 🧹 para empezar limpio», y no hay ningún 🧹: lo que empieza
2027 // limpio es «+» (nueva conversación) en la barra de pestañas del chat.
2028 $('ctx-meter').title = pct > 85
2029 ? t('ctxFull', { pct })
2030 : t('ctxUse', { tok, max: CTX_BUDGET_TOK, free: 100 - pct });
2031}
2032const _origAdd = addMsg; // refrescar el medidor cuando cambia la conversación
2033addMsg = (...a) => { const r = _origAdd(...a); updateCtxMeter(); return r; };
2034
2035// menú flotante genérico sobre el composer
2036function openMenu(items) {
2037 const menu = $('menu');
2038 menu.replaceChildren();
2039 for (const it of items) {
2040 if (it.sep) { const s = document.createElement('div'); s.className = 'sep'; s.textContent = it.sep; menu.appendChild(s); continue; }
2041 const row = document.createElement('button');
2042 row.className = 'menu-item';
2043 row.innerHTML = `<b>${it.label}</b>${it.hint ? `<span>${it.hint}</span>` : ''}`;
2044 row.onclick = () => { menu.hidden = true; it.run(); };
2045 row.onmouseenter = () => { menuSel = menuFilas().indexOf(row); pintaMenuSel(); };
2046 menu.appendChild(row);
2047 }
2048 menu.hidden = false;
2049 menuSel = menuFilas().length ? 0 : -1;
2050 pintaMenuSel();
2051}
2052
2053// Navegar el menú con el teclado. El keydown del composer se aparta cuando el
2054// menú está abierto «porque el menú ya usa ↑/↓», y era mentira: nadie escuchaba,
2055// así que con el menú abierto las flechas no movían nada y el Enter se quedaba
2056// sin enviar el mensaje y sin elegir fichero. Ahora es verdad.
2057let menuSel = -1;
2058const menuFilas = () => [...$('menu').querySelectorAll('.menu-item')];
2059function pintaMenuSel() {
2060 const filas = menuFilas();
2061 filas.forEach((f, i) => f.classList.toggle('sel', i === menuSel));
2062 if (menuSel >= 0) filas[menuSel]?.scrollIntoView({ block: 'nearest' });
2063}
2064function cierraMenu({ sueltaToken = true } = {}) {
2065 $('menu').hidden = true;
2066 menuSel = -1;
2067 if (sueltaToken) { arrobaDesde = -1; cacheFicheros = null; }
2068}
2069$('prompt').addEventListener('keydown', (e) => {
2070 if ($('menu').hidden) return;
2071 if (e.key === 'Escape') { e.preventDefault(); return cierraMenu(); }
2072 const filas = menuFilas();
2073 if (!filas.length) return;
2074 if (e.key === 'ArrowDown') { e.preventDefault(); menuSel = (menuSel + 1) % filas.length; pintaMenuSel(); }
2075 else if (e.key === 'ArrowUp') { e.preventDefault(); menuSel = (menuSel - 1 + filas.length) % filas.length; pintaMenuSel(); }
2076 else if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); filas[Math.max(0, menuSel)].click(); }
2077});
2078document.addEventListener('click', e => {
2079 if (!e.target.closest('#menu, #btn-slash, #btn-plus')) cierraMenu();
2080});
2081
2082// [/] comandos
2083$('btn-slash').addEventListener('click', () => openMenu([
2084 { sep: t('cmdsSep') },
2085 { label: '/tree', hint: t('slTree'), run: () => send(t('pTree')) },
2086 { label: '/search', hint: t('slSearch'), run: () => { $('prompt').value = t('pSearch'); $('prompt').focus(); } },
2087 { label: '/skills', hint: t('slSkills'), run: () => openSkillsPanel() },
2088 // en pantallas estrechas no hay barra de actividad ni menú View: esto sí se ve
2089 { label: '/extensions', hint: extTexto('temas, gramáticas, snippets', 'themes, grammars, snippets'), run: () => openExtensions() },
2090 { label: '/theme', hint: extTexto('tema de color', 'color theme'), run: () => openExtensions({ themes: true }) },
2091 { label: '/model', hint: t('slModel'), run: () => $('btn-settings').click() },
2092 // «/clear» abría una conversación NUEVA (no limpiaba la actual): se llama
2093 // por lo que hace.
2094 { label: '/new', hint: t('slClear'), run: () => conv.create() },
2095]));
2096// Abierto con el ratón desde + o /, el foco pasa al menú (antes se quedaba en
2097// el botón y las flechas no hacían nada); dentro, ↑/↓ recorren las opciones y
2098// Escape vuelve a la caja de texto.
2099function enfocaMenuAlAbrir() {
2100 let n = 0;
2101 const mira = () => {
2102 const primero = $('menu').hidden ? null : $('menu').querySelector('.menu-item');
2103 if (primero) return primero.focus();
2104 if (++n < 60) requestAnimationFrame(mira);
2105 };
2106 requestAnimationFrame(mira);
2107}
2108$('btn-slash').addEventListener('click', enfocaMenuAlAbrir);
2109$('btn-plus').addEventListener('click', enfocaMenuAlAbrir);
2110$('menu').addEventListener('keydown', e => {
2111 const l = [...$('menu').querySelectorAll('.menu-item')], i = l.indexOf(document.activeElement);
2112 if (i < 0) return;
2113 if (e.key === 'ArrowDown') { e.preventDefault(); l[(i + 1) % l.length].focus(); }
2114 else if (e.key === 'ArrowUp') { e.preventDefault(); l[(i - 1 + l.length) % l.length].focus(); }
2115 else if (e.key === 'Home') { e.preventDefault(); l[0].focus(); }
2116 else if (e.key === 'End') { e.preventDefault(); l.at(-1).focus(); }
2117});
2118
2119// [+] adjuntar archivo del proyecto como @ruta
2120// El menú de ficheros, en una función: lo abren el botón `+` Y escribir `@` en
2121// la conversación, que es lo natural y lo que ya prometía el título del botón
2122// («Adjuntar archivo del proyecto (@)») sin que nada lo implementara.
2123//
2124// Y FILTRA mientras escribes. Antes el menú se pintaba una vez al teclear `@` y
2125// se quedaba congelado: las letras siguientes entraban en el textarea y la lista
2126// seguía mostrando los mismos veinte ficheros. Con un árbol de verdad eso es un
2127// menú inútil, porque lo que buscas casi nunca está entre los veinte primeros.
2128let arrobaDesde = -1; // índice del `@` que se está escribiendo, o -1
2129let cacheFicheros = null; // el árbol, leído una vez por sesión de menú
2130
2131// Reconstruye las RUTAS COMPLETAS del árbol. `code.tree` indenta dos espacios
2132// por nivel y marca las carpetas con «📁 », así que la carpeta de un fichero
2133// está en su sangría, no en su línea.
2134//
2135// ⚠️ Esto hacía `l.trim()` sobre cada línea, que es exactamente tirar esa
2136// información: el menú ofrecía «obj_1_Zusammenbau.stl» cuando el fichero real
2137// es «dinos/obj_1_Zusammenbau.stl», y al insertarlo la herramienta fallaba con
2138// «no existe en este proyecto». Lo peor del fallo es que el menú te deja
2139// elegirlo: parece que la ruta está bien hasta que la lees.
2140export function rutasDelArbol(tree) {
2141 const rutas = [];
2142 const pila = [];
2143 for (const linea of String(tree || '').split('\n')) {
2144 if (!linea.trim()) continue;
2145 if (linea.startsWith('…')) continue; // el aviso de árbol recortado
2146 const sangria = linea.length - linea.replace(/^ +/, '').length;
2147 const nivel = Math.floor(sangria / 2);
2148 const texto = linea.trim();
2149 if (texto.startsWith('📁')) {
2150 pila.length = nivel; // salir de las carpetas hermanas
2151 pila.push(texto.replace(/^📁\s*/, ''));
2152 } else {
2153 rutas.push([...pila.slice(0, nivel), texto].join('/'));
2154 }
2155 }
2156 return rutas;
2157}
2158
2159async function listaProyecto() {
2160 if (cacheFicheros) return cacheFicheros;
2161 let tree = '';
2162 try { tree = await codeTools.tree({ depth: 3 }); } catch { /* sin proyecto */ }
2163 const files = rutasDelArbol(tree);
2164 const { currentFile } = codeTools.current();
2165 return (cacheFicheros = { files, currentFile });
2166}
2167
2168async function abreMenuFicheros(frag = '') {
2169 const { files, currentFile } = await listaProyecto();
2170 const q = frag.toLowerCase();
2171 // El filtro va sobre la lista COMPLETA y el recorte a 20 va DESPUÉS. Al revés
2172 // —recortar y luego filtrar, como hacía antes— un fichero en el puesto 50 del
2173 // árbol no aparece nunca, por mucho que escribas su nombre entero.
2174 const casa = (f) => !q || f.toLowerCase().includes(q);
2175 const items = [{ sep: frag ? `${t('attachSep')} · @${frag}` : t('attachSep') }];
2176 if (currentFile && casa(currentFile)) items.push({ label: '@' + currentFile, hint: t('attachOpen'), run: () => attach(currentFile) });
2177 for (const f of files.filter(f => f !== currentFile && casa(f)).slice(0, 20))
2178 items.push({ label: '@' + f, run: () => attach(f) });
2179
2180 if (items.length === 1) {
2181 // Sin coincidencias: el menú se aparta en vez de estorbar con una lista
2182 // vacía, y vuelve solo en cuanto borras una letra y el filtro encaja.
2183 if (frag) { cierraMenu({ sueltaToken: false }); return; }
2184 openMenu([{ sep: t('openProjFirst') }]);
2185 return;
2186 }
2187 openMenu(items);
2188}
2189$('btn-plus').addEventListener('click', () => { arrobaDesde = -1; cacheFicheros = null; abreMenuFicheros(); });
2190
2191// ¿Está el cursor dentro de un `@token`? Se recorre hacia atrás hasta el primer
2192// espacio: así `correo@dominio` no dispara el menú a media palabra (el carácter
2193// previo al `@` no es espacio) y `@` al principio o tras un espacio sí. El
2194// fragmento no puede contener espacios, que es justo donde termina una ruta.
2195function tokenArroba(el) {
2196 const v = el.value, cur = el.selectionStart;
2197 for (let i = cur - 1; i >= 0; i--) {
2198 if (/\s/.test(v[i])) return null;
2199 if (v[i] === '@') {
2200 const previo = i > 0 ? v[i - 1] : '';
2201 return (previo === '' || /\s/.test(previo)) ? { desde: i, frag: v.slice(i + 1, cur) } : null;
2202 }
2203 }
2204 return null;
2205}
2206
2207$('prompt').addEventListener('input', () => {
2208 const tk = tokenArroba($('prompt'));
2209 if (!tk) { if (arrobaDesde >= 0) cierraMenu(); return; }
2210 arrobaDesde = tk.desde;
2211 abreMenuFicheros(tk.frag);
2212});
2213
2214function attach(path) {
2215 const p = $('prompt');
2216 if (arrobaDesde >= 0) {
2217 // Se SUSTITUYE el `@frag` a medio escribir. Añadirlo al final, como antes,
2218 // dejaba `@src/ma @src/main.js` en cuanto el menú empezó a filtrar.
2219 const cola = p.value.slice(p.selectionStart);
2220 const sep = cola.startsWith(' ') ? '' : ' ';
2221 p.value = p.value.slice(0, arrobaDesde) + '@' + path + sep + cola;
2222 const cur = arrobaDesde + 1 + path.length + sep.length;
2223 p.focus();
2224 p.setSelectionRange(cur, cur);
2225 } else {
2226 p.value = (p.value + ' @' + path).trim() + ' ';
2227 p.focus();
2228 }
2229 arrobaDesde = -1;
2230 cacheFicheros = null;
2231}
2232
2233// </> Auto (Edit automatically): si off, pide confirmación antes de escribir
2234let autoEdit = localStorage.getItem('elffusscode.autoedit') !== '0';
2235// Los tres modos se declaran juntos y antes de pintar nada: pintaModos() los
2236// lee todos y se llama ya al pintar Auto.
2237let goalMode = localStorage.getItem('elffusscode.goalmode') === '1';
2238let hardMode = false;
2239function paintAuto() {
2240 const b = $('btn-autoedit');
2241 b.classList.toggle('on', autoEdit);
2242 b.querySelector('.ae-txt').textContent = autoEdit ? t('autoTxt') : t('reviewTxt');
2243 b.title = autoEdit ? t('autoOn') : t('autoOff');
2244 pintaModos();
2245}
2246$('btn-autoedit').addEventListener('click', () => {
2247 autoEdit = !autoEdit;
2248 guardaPref('elffusscode.autoedit', autoEdit ? '1' : '0');
2249 paintAuto();
2250});
2251paintAuto();
2252codeTools.setWriteApprover(async (path, content) => {
2253 if (autoEdit) return true;
2254 return confirm(`Elffuss quiere escribir en «${path}» (${content.split('\n').length} líneas).\n\n¿Aplicar el cambio?`);
2255});
2256
2257function cierraModos({ foco = false } = {}) {
2258 const menu = $('modos-menu');
2259 if (!menu || menu.hidden) return;
2260 menu.hidden = true;
2261 $('btn-modos')?.setAttribute('aria-expanded', 'false');
2262 if (foco) $('btn-modos')?.focus();
2263}
2264// El botón «Modos» lleva los que están encendidos (y el texto del prompt dice
2265// qué va a pasar con lo que escribas).
2266function pintaModos() {
2267 const b = $('btn-modos');
2268 if (!b) return;
2269 const activos = [];
2270 if (!autoEdit) activos.push(['Revisar', t('modeReview')]);
2271 if (goalMode) activos.push(['🎯', t('modeGoal')]);
2272 if (hardMode) activos.push(['⛏', t('modeHard')]);
2273 b.textContent = '⚙︎ ' + t('modesBtn') + (activos.length ? ' · ' + activos.map(a => a[0] === 'Revisar' ? t('reviewTxt') : a[0]).join(' ') : '') + ' ▾';
2274 b.setAttribute('aria-label', t('modesBtn') + (activos.length ? ': ' + activos.map(a => a[1]).join(', ') : ': ' + t('modesNone')));
2275 b.classList.toggle('on', activos.length > 0);
2276 $('btn-autoedit')?.setAttribute('aria-checked', autoEdit ? 'true' : 'false');
2277 $('btn-goal')?.setAttribute('aria-checked', goalMode ? 'true' : 'false');
2278 $('btn-hardwork')?.setAttribute('aria-checked', hardMode ? 'true' : 'false');
2279 $('prompt').placeholder = hardMode ? t('hwPlaceholder') : goalMode ? t('goalPlaceholder') : t('ph');
2280}
2281
2282// 🎯 Goal: el siguiente mensaje que mandes se trata como un OBJETIVO — se
2283// planifica en tareas y se ejecutan una a una (goal.js), en vez del turno de
2284// chat normal. Mismo patrón (interruptor persistente en localStorage) que
2285// </> Auto de arriba.
2286function paintGoal() {
2287 $('btn-goal').classList.toggle('on', goalMode);
2288 pintaModos();
2289}
2290$('btn-goal').addEventListener('click', () => {
2291 goalMode = !goalMode;
2292 guardaPref('elffusscode.goalmode', goalMode ? '1' : '0');
2293 paintGoal();
2294});
2295paintGoal();
2296
2297// ── Hard Work (RLM): lee el proyecto ENTERO por partes ──
2298$('btn-hardwork').addEventListener('click', () => {
2299 hardMode = !hardMode;
2300 $('btn-hardwork').classList.toggle('on', hardMode);
2301 // Al apagarlo vuelve el texto de siempre, en el idioma de la interfaz: antes
2302 // quedaba un «Pídele código a Elffuss…» fijo y en español.
2303 pintaModos();
2304});
2305
2306// Trabaja el proyecto abierto por partes: trocea, pregunta a cada parte y funde.
2307// Corre como un turno MÁS de la conversación (conversations.js → 'hard'): el ■
2308// lo para, la conversación se ve ocupada y la pregunta y la respuesta quedan en
2309// su historial, así que sobreviven a cambiar de pestaña y a recargar. Antes
2310// corría por fuera de la cola: el botón nunca pasaba a ■ y todo vivía solo en
2311// el DOM.
2312conv.setHardWorkRunner(async (c, question, onEvent, { signal }) => {
2313 const hist = c.agent.history;
2314 hist.push({ role: 'user', content: question, ts: Date.now() });
2315 const responde = texto => {
2316 hist.push({ role: 'assistant', content: texto, ts: Date.now() });
2317 onEvent({ type: 'text', text: texto });
2318 };
2319 const parado = () => onEvent({ type: 'aborted', text: '(Parado.)' });
2320 const provider = conv.getProvider();
2321 if (!provider || provider === rules) return responde(t('hwNeedBrain'));
2322 const root = codeTools.handle();
2323 if (!root) return responde(t('hwNeedProject'));
2324 // Cada sub-llamada recibe la parada (corta la generación en curso) y, si ya
2325 // se pulsó ■, la siguiente ni se lanza.
2326 const conParada = {
2327 chat: (h, sys, cb) => signal.aborted
2328 ? Promise.reject(new DOMException('Parado', 'AbortError'))
2329 : provider.chat(h, sys, cb, signal),
2330 };
2331 try {
2332 onEvent({ type: 'progress', text: t('hwReading') });
2333 const context = await gatherFolder(root, { maxBytes: 1.5e6 });
2334 if (signal.aborted) return parado();
2335 if (!context.trim()) return responde(t('hwNoFiles'));
2336 const res = await hardWork({
2337 question, context, provider: conParada,
2338 onProgress: p => {
2339 if (signal.aborted) return;
2340 if (p.phase === 'plan') onEvent({ type: 'progress', text: t('hwPhasePlan', { n: p.chunks, k: Math.round(p.chars / 1000), trim: p.truncated ? t('hwTrimmed') : '' }) });
2341 else if (p.phase === 'map') onEvent({ type: 'progress', text: t('hwPhaseMap', { i: p.i, n: p.n }) });
2342 else if (p.phase === 'reduce-group') onEvent({ type: 'progress', text: t('hwPhaseGroup', { g: p.g, n: p.n }) });
2343 else if (p.phase === 'reduce') onEvent({ type: 'progress', text: t('hwPhaseReduce') });
2344 },
2345 });
2346 if (signal.aborted) return parado();
2347 responde(res.answer + '\n\n_' + t('hwResult', { n: res.chunks, k: res.kept }) + (res.truncated ? t('hwResultTrunc') : '') + '_');
2348 } catch (e) {
2349 if (signal.aborted || e?.name === 'AbortError') return parado();
2350 const texto = t('hwFailed', { e: e?.message || String(e) });
2351 hist.push({ role: 'assistant', content: texto, ts: Date.now() });
2352 onEvent({ type: 'error', text: texto });
2353 }
2354});
2355
2356// resolver @rutas del mensaje: se leen y se adjuntan como contexto
2357const _send = send;
2358send = async (text) => {
2359 if (hardMode) return _send(text, 'hard');
2360 const refs = [...text.matchAll(/@([\w./-]+\.\w+)/g)].map(m => m[1]);
2361 if (refs.length) {
2362 let ctx = '';
2363 for (const r of [...new Set(refs)].slice(0, 4)) {
2364 try { ctx += `\n\n--- ${r} ---\n${await codeTools.read({ path: r })}`; } catch { /* ignora */ }
2365 }
2366 if (ctx) text += '\n\n[archivos adjuntos]' + ctx;
2367 }
2368 _send(text);
2369};
2370
2371// ---------- panel de skills (transparente: repo + lista + SKILL.md) ----------
2372// Mismo diálogo que Ajustes. Los fallos se dicen DENTRO del panel, en palabras
2373// de persona y con «Reintentar» (antes: «⚠️ FAILED TO FETCH» en mayúsculas, y
2374// un alert() del navegador al añadir un repo que no valía o al instalar).
2375async function openSkillsPanel() {
2376 const box = settingsShell(t('skTitle'));
2377 const wrap = document.createElement('div');
2378 wrap.className = 'skills-panel';
2379 const intro = document.createElement('p');
2380 intro.className = 'muted';
2381 intro.textContent = t('skIntro');
2382 wrap.appendChild(intro);
2383 box.appendChild(wrap);
2384
2385 // instaladas
2386 const inst = skills.installed();
2387 const instBox = document.createElement('div');
2388 instBox.append(el('div', 'sk-h', t('skInstalled', { n: inst.length })));
2389 for (const s of inst) {
2390 const row = document.createElement('div');
2391 row.className = 'sk-row';
2392 row.append(el('b', null, s.name), el('span', 'muted', s.repo || 'local'));
2393 const rm = document.createElement('button');
2394 rm.className = 'ghost'; rm.textContent = t("skRemove");
2395 rm.setAttribute('aria-label', t('skRemoveNamed', { name: s.name }));
2396 rm.onclick = async () => { await skills.remove(s.name); openSkillsPanel(); };
2397 row.appendChild(rm);
2398 instBox.appendChild(row);
2399 }
2400 if (!inst.length) instBox.append(el('p', 'muted', t('skNone')));
2401 box.appendChild(instBox);
2402
2403 // fuentes + añadir repo
2404 const srcs = await skills.sources();
2405 const srcBox = document.createElement('div');
2406 srcBox.append(el('div', 'sk-h', t('skCatalogs')));
2407 for (const s of srcs) {
2408 const row = document.createElement('div');
2409 row.className = 'sk-row';
2410 const a = document.createElement('a');
2411 a.href = `https://github.com/${s.repo}`; a.target = '_blank'; a.rel = 'noopener noreferrer';
2412 a.textContent = s.repo + ' ↗';
2413 row.append(el('b', null, s.label), a);
2414 const browse = document.createElement('button');
2415 browse.className = 'primary'; browse.textContent = t("skBrowse");
2416 browse.onclick = () => browseRepo(s.repo, box);
2417 row.appendChild(browse);
2418 if (!s.official) {
2419 const rm = document.createElement('button');
2420 rm.className = 'ghost'; rm.textContent = '🗑';
2421 rm.setAttribute('aria-label', t('skRemoveRepo', { repo: s.repo }));
2422 rm.onclick = async () => { await skills.removeSource(s.repo); openSkillsPanel(); };
2423 row.appendChild(rm);
2424 }
2425 srcBox.appendChild(row);
2426 }
2427 const addRow = document.createElement('div');
2428 addRow.className = 'sk-row';
2429 const inp = document.createElement('input');
2430 inp.placeholder = t("skAddRepoPh");
2431 inp.setAttribute('aria-label', t('skAddRepo'));
2432 const add = document.createElement('button');
2433 add.className = 'primary'; add.textContent = t("skAddRepo");
2434 const addMsg2 = el('div', 'muted sk-msg'); addMsg2.setAttribute('role', 'status');
2435 add.onclick = async () => {
2436 addMsg2.textContent = '';
2437 try { await skills.addSource(inp.value); openSkillsPanel(); }
2438 catch (e) { addMsg2.textContent = '⚠️ ' + (e?.message || e); addMsg2.classList.add('err'); inp.focus(); }
2439 };
2440 inp.addEventListener('keydown', e => { if (e.key === 'Enter') add.click(); });
2441 addRow.append(inp, add);
2442 srcBox.append(addRow, addMsg2);
2443 box.appendChild(srcBox);
2444}
2445
2446async function browseRepo(repo, box) {
2447 box.querySelector(`.sk-browse[data-repo="${CSS.escape(repo)}"]`)?.remove();
2448 const list = document.createElement('div');
2449 list.className = 'sk-browse';
2450 list.dataset.repo = repo;
2451 list.setAttribute('aria-live', 'polite');
2452 list.append(el('div', 'sk-h', t('skLoading', { repo })));
2453 box.appendChild(list);
2454 try {
2455 const found = await skills.listFromRepo(repo);
2456 list.replaceChildren(el('div', 'sk-h', t('skFound', { repo, n: found.length })));
2457 for (const sk of found.slice(0, 120)) {
2458 const row = document.createElement('div');
2459 row.className = 'sk-row';
2460 row.append(el('b', null, sk.name), el('span', 'muted', sk.dir));
2461 const btn = document.createElement('button');
2462 const on = skills.isInstalled(sk.repo, sk.path);
2463 btn.className = on ? 'ghost' : 'primary';
2464 btn.textContent = on ? t('skInstalledOne') : t('skInstall');
2465 btn.setAttribute('aria-label', (on ? t('skInstalledOne') : t('skInstall')) + ': ' + sk.name);
2466 btn.onclick = async () => {
2467 btn.textContent = '…'; btn.disabled = true;
2468 try {
2469 const entry = await skills.installFromRepo(sk);
2470 btn.textContent = t('skInstalledOne'); btn.className = 'ghost';
2471 cierraAjustes(); // cierra el panel
2472 addMsg('assistant', skills.usageMessage(entry)); // «cómo usarla» en el chat
2473 } catch (e) {
2474 btn.textContent = t('skInstall'); btn.disabled = false;
2475 row.append(el('span', 'muted sk-msg err', '⚠️ ' + (e?.message || e)));
2476 }
2477 };
2478 row.appendChild(btn);
2479 list.appendChild(row);
2480 }
2481 } catch (e) {
2482 const msg = /Failed to fetch|NetworkError|network/i.test(String(e?.message)) ? t('skNoNet', { repo }) : t('skLoadFailed', { repo, e: e?.message || e });
2483 const retry = document.createElement('button');
2484 retry.className = 'primary'; retry.textContent = t('retry');
2485 retry.onclick = () => browseRepo(repo, box);
2486 const fila = el('div', 'sk-row');
2487 fila.append(el('span', 'sk-msg err', '⚠️ ' + msg), retry);
2488 list.replaceChildren(el('div', 'sk-h', repo), fila);
2489 }
2490}
2491
2492// ---------- command palette (Cmd/Ctrl+P) ----------
2493let palItems = [], palSel = 0;
2494const COMMANDS = [
2495 { label: t('newConv'), run: () => conv.create() },
2496 { label: t('tHistory'), run: () => $('btn-history').click() },
2497 { label: t('pSearchCode'), run: () => openPalette('#') },
2498 { label: t('pManageSkills'), run: () => { closePalette(); openSkillsPanel(); } },
2499 { label: t('tActSettings'), run: () => { closePalette(); renderSettings(); } },
2500 { label: t('pToggleExplorer'), run: () => $('act-files').click() },
2501 { label: t('pToggleTerm'), hint: 'Ctrl+`', run: () => { closePalette(); toggleTerminal(); } },
2502 { label: t('pSave', { k: atajo('S') }), run: () => saveActive() },
2503 { label: t('mLab'), run: () => abrirLab() },
2504 { label: extTexto('Extensiones…', 'Extensions…'), run: () => { closePalette(); openExtensions(); } },
2505 { label: extTexto('Tema de color…', 'Color Theme…'), run: () => { closePalette(); openExtensions({ themes: true }); } },
2506];
2507// El banco de pruebas (lab.html) existía pero no había forma de llegar a él
2508// desde el IDE: solo escribiendo la URL. Se abre en otra pestaña para no
2509// dejar a medias lo que tengas aquí.
2510function abrirLab() { window.open('lab.html', '_blank', 'noopener'); }
2511
2512// La paleta es un combobox con su lista (role=listbox, opción activa en
2513// aria-activedescendant), así un lector de pantalla sigue la selección.
2514let volverDePaleta = null;
2515function openPalette(prefix = '') {
2516 if ($('palette').hidden) volverDePaleta = document.activeElement;
2517 $('palette').hidden = false;
2518 const inp = $('pal-input');
2519 inp.setAttribute('role', 'combobox');
2520 inp.setAttribute('aria-controls', 'pal-list');
2521 inp.setAttribute('aria-expanded', 'true');
2522 inp.setAttribute('aria-autocomplete', 'list');
2523 $('pal-list').setAttribute('role', 'listbox');
2524 inp.value = prefix;
2525 inp.focus();
2526 renderPalette();
2527}
2528function closePalette() {
2529 if ($('palette').hidden) return;
2530 $('palette').hidden = true;
2531 $('pal-input').setAttribute('aria-expanded', 'false');
2532 const v = volverDePaleta; volverDePaleta = null;
2533 if (v && document.body.contains(v) && document.activeElement === $('pal-input')) v.focus?.();
2534}
2535
2536function fuzzy(q, s) {
2537 q = q.toLowerCase(); s = s.toLowerCase();
2538 let i = 0, score = 0, streak = 0;
2539 for (const ch of s) {
2540 if (i < q.length && ch === q[i]) { i++; streak++; score += streak; }
2541 else streak = 0;
2542 }
2543 return i === q.length ? score + (s.endsWith(q) ? 20 : 0) : -1;
2544}
2545
2546// «#texto»: busca DENTRO de los ficheros (code.search) y lista cada resultado
2547// como fichero:línea; Enter lo abre en esa línea. Es lo que hace ahora Edit ›
2548// Buscar en el código (antes solo escribía «busca » en el chat).
2549let palSeq = 0, palBusca = null;
2550async function resultadosBusqueda(q) {
2551 const out = await codeTools.search({ query: q }).catch(e => 'ERROR: ' + e.message);
2552 const items = [];
2553 for (const linea of String(out).split('\n')) {
2554 const m = linea.match(/^(.+?):(\d+): (.*)$/);
2555 if (m) items.push({ label: m[3] || '·', hint: `${m[1]}:${m[2]}`, run: () => { closePalette(); openFile(m[1]).then(() => gotoLine(+m[2])); } });
2556 }
2557 const nota = String(out).split('\n').find(l => l.startsWith('…') || l.startsWith('Sin resultados') || l.startsWith('ERROR'));
2558 return { items, nota };
2559}
2560
2561async function renderPalette() {
2562 const raw = $('pal-input').value;
2563 const list = $('pal-list');
2564 const seq = ++palSeq;
2565 palItems = [];
2566 let nota = '';
2567
2568 if (raw.startsWith('#')) { // buscar en el código
2569 const q = raw.slice(1).trim();
2570 if (q.length < 2) nota = t('palSearchHint');
2571 else {
2572 clearTimeout(palBusca);
2573 await new Promise(r => { palBusca = setTimeout(r, 180); });
2574 if (seq !== palSeq) return; // se siguió escribiendo
2575 const r = await resultadosBusqueda(q);
2576 if (seq !== palSeq) return;
2577 palItems = r.items.slice(0, 60);
2578 nota = r.nota || '';
2579 }
2580 } else if (raw.startsWith('>')) { // comandos
2581 const q = raw.slice(1).trim().toLowerCase();
2582 // Todo comando cierra la paleta al ejecutarse: «Nueva conversación», por
2583 // ejemplo, la dejaba abierta encima.
2584 palItems = COMMANDS.filter(c => c.label.toLowerCase().includes(q)).map(c => ({ label: c.label, hint: t('palCmd'), run: () => { closePalette(); c.run(); } }));
2585 } else if (raw.startsWith('@')) { // símbolos del archivo abierto (Monaco)
2586 palItems = [{ label: t('palGotoSym'), hint: '@', run: () => { closePalette(); conFichero(() => triggerEditor('editor.action.quickOutline'))(); } }];
2587 } else { // archivos (con :línea opcional)
2588 const [pathQ, lineQ] = raw.split(':');
2589 const files = await codeTools.fileList().catch(() => []);
2590 const scored = pathQ.trim()
2591 ? files.map(f => ({ f, s: fuzzy(pathQ.trim(), f.split('/').pop()) * 2 + fuzzy(pathQ.trim(), f) })).filter(x => x.s > 0).sort((a, b) => b.s - a.s)
2592 : files.slice(0, 40).map(f => ({ f, s: 0 }));
2593 palItems = scored.slice(0, 40).map(({ f }) => ({
2594 label: f.split('/').pop(), hint: f, icon: true,
2595 run: () => { closePalette(); openFile(f); if (lineQ && +lineQ) setTimeout(() => gotoLine(+lineQ), 300); },
2596 }));
2597 }
2598 if (seq !== palSeq) return;
2599 list.replaceChildren();
2600 palSel = 0;
2601 palItems.forEach((it, i) => {
2602 const row = el('button', 'pal-item' + (i === 0 ? ' sel' : ''));
2603 row.type = 'button';
2604 row.id = 'pal-opt-' + i;
2605 row.setAttribute('role', 'option');
2606 row.setAttribute('aria-selected', i === 0 ? 'true' : 'false');
2607 row.tabIndex = -1;
2608 row.innerHTML = '<span class="pi-name"></span><span class="pi-hint"></span>';
2609 row.querySelector('.pi-name').textContent = it.label;
2610 row.querySelector('.pi-hint').textContent = it.hint || '';
2611 row.onmouseenter = () => { palSel = i; paintPalSel(); };
2612 row.onclick = () => it.run();
2613 list.appendChild(row);
2614 });
2615 if (!palItems.length) list.appendChild(el('div', 'pal-empty', nota || t('palEmpty')));
2616 else if (nota) list.appendChild(el('div', 'pal-empty', nota));
2617 paintPalSel();
2618}
2619function paintPalSel() {
2620 [...$('pal-list').querySelectorAll('.pal-item')].forEach((c, i) => { c.classList.toggle('sel', i === palSel); c.setAttribute('aria-selected', i === palSel ? 'true' : 'false'); });
2621 const opt = $('pal-list').querySelector('#pal-opt-' + palSel);
2622 if (opt) { $('pal-input').setAttribute('aria-activedescendant', opt.id); opt.scrollIntoView({ block: 'nearest' }); }
2623 else $('pal-input').removeAttribute('aria-activedescendant');
2624}
2625$('pal-input').addEventListener('input', renderPalette);
2626$('pal-input').addEventListener('keydown', e => {
2627 if (e.key === 'Escape') return closePalette();
2628 if (e.key === 'ArrowDown') { e.preventDefault(); palSel = Math.min(palSel + 1, palItems.length - 1); paintPalSel(); }
2629 if (e.key === 'ArrowUp') { e.preventDefault(); palSel = Math.max(palSel - 1, 0); paintPalSel(); }
2630 if (e.key === 'Enter') { e.preventDefault(); palItems[palSel]?.run(); }
2631});
2632document.addEventListener('keydown', e => {
2633 if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'p') { e.preventDefault(); openPalette(e.shiftKey ? '>' : ''); }
2634 if (e.key === 'Escape' && !$('palette').hidden) closePalette();
2635});
2636// Cerrar la paleta al pulsar fuera, PERO no cuando el clic viene del menú: es
2637// el menú el que la abre («Go to file»), y sin esta excepción el mismo clic la
2638// abría y la cerraba — el `onclick` del item la mostraba y acto seguido el
2639// evento seguía burbujeando hasta aquí, donde el target es el item del menú,
2640// que no está dentro de #palette. Con Cmd+P funcionaba porque es teclado y no
2641// pasa por este camino, y por eso parecía que «el atajo sí y el menú no».
2642document.addEventListener('click', e => {
2643 if (!e.target.closest('#palette, #menubar, #topmenu')) closePalette();
2644});
2645
2646// ---------- barra de menú File/Edit/View/Git ----------
2647async function menuFor(which) {
2648 if (which === 'file') return [
2649 { label: t('mNewFile'), run: () => { const p = prompt(t('promptNewPath')); if (p) codeTools.write({ path: p, content: '' }).then(() => { openFile(p); refreshTree(); }); } },
2650 { label: t('mSave'), hint: atajo('S'), run: () => saveActive() },
2651 { label: t('mOpenFolder'), run: async () => {
2652 // Cambiar de carpeta con la elfa a medias deja su trabajo sobre el
2653 // proyecto anterior: se pregunta antes.
2654 if (conv.isBusy() && !confirm(t('openFolderBusy'))) return;
2655 let handle;
2656 try { handle = await window.showDirectoryPicker({ mode: 'readwrite' }); }
2657 catch (e) { if (e?.name !== 'AbortError') $('statusbar').textContent = '⚠️ ' + t('openFolderFailed', { e: e?.message || e }); return; }
2658 try { await enterIDE(handle); } catch (e) { avisaFalloApertura(e); }
2659 } },
2660 ];
2661 if (which === 'edit') return [
2662 { label: t('mSearchCode'), hint: '#', run: () => openPalette('#') },
2663 { label: t('mGotoFile'), hint: atajo('P'), run: () => openPalette('') },
2664 { label: t('mGotoSym'), run: conFichero(() => triggerEditor('editor.action.quickOutline')) },
2665 ];
2666 if (which === 'view') return [
2667 { label: t('tFiles'), run: () => $('act-files').click() },
2668 { label: t('mTerminal'), hint: 'Ctrl+`', run: () => toggleTerminal(true) },
2669 { label: t('mArch'), run: () => openView('arch') },
2670 { label: t('tCity'), run: () => openView('city') },
2671 { label: t('mPalette'), hint: atajo('P', true), run: () => openPalette('>') },
2672 { label: 'Skills', run: () => openSkillsPanel() },
2673 { label: extTexto('Extensiones…', 'Extensions…'), run: () => openExtensions() },
2674 { label: extTexto('Tema de color…', 'Color Theme…'), run: () => openExtensions({ themes: true }) },
2675 { label: t('mLab'), hint: '↗', run: () => abrirLab() },
2676 { label: t('mAbout'), hint: '↗', run: () => window.open('https://github.com/KikoCis/elffuss-code', '_blank', 'noopener') },
2677 ];
2678 if (which === 'git') {
2679 // Rama y último commit enlazan al remoto (sin credenciales) cuando lo hay;
2680 // si no, se ven como texto desactivado. Antes parecían opciones y no hacían
2681 // nada. El commit enseña su SHA corto; el correo del autor, nunca.
2682 const g = await codeTools.gitInfo();
2683 if (!g.isRepo) return [{ label: t('gNotRepo'), disabled: true }];
2684 const abre = url => () => window.open(url, '_blank', 'noopener,noreferrer');
2685 const items = [g.web
2686 ? { label: t('gBranch', { b: g.branch }), hint: '↗', title: g.web.branch(g.branch), run: abre(g.web.branch(g.branch)) }
2687 : { label: t('gBranch', { b: g.branch }), hint: t('gNoRemote'), disabled: true }];
2688 if (g.lastCommit) {
2689 const corto = g.lastCommit.sha ? g.lastCommit.sha.slice(0, 7) + ' · ' : '';
2690 const label = t('gLast', { m: corto + g.lastCommit.msg.slice(0, 40) });
2691 items.push(g.web && g.lastCommit.sha
2692 ? { label, hint: '↗', title: g.web.commit(g.lastCommit.sha), run: abre(g.web.commit(g.lastCommit.sha)) }
2693 : { label, hint: g.lastCommit.author, disabled: true });
2694 }
2695 // Pide al agente el MENSAJE de commit: commitear de verdad no puede (el git
2696 // de aquí es de solo lectura), y la etiqueta vieja lo prometía.
2697 items.push({ label: t('gCommit'), run: () => { $('prompt').value = t('pCommit'); $('prompt').focus(); } });
2698 return items;
2699 }
2700 return [];
2701}
2702// La barra de menús se usa con el teclado como una de verdad (patrón
2703// menubar/menu): ↓, Enter o Espacio abren el menú con el foco en su primera
2704// opción; ←/→ pasan al menú de al lado; ↑/↓ recorren; Escape cierra y devuelve
2705// el foco; Tab sale. Antes ↓ no entraba en el menú y Escape no lo cerraba. Los
2706// nombres salen en el idioma de la interfaz.
2707const barraMenus = () => [...document.querySelectorAll('#menubar button')];
2708let menuBarraAbierto = null;
2709{
2710 const bar = $('menubar');
2711 bar.setAttribute('role', 'menubar');
2712 bar.setAttribute('aria-label', t('menubarLabel'));
2713 barraMenus().forEach((b, i) => {
2714 b.setAttribute('role', 'menuitem');
2715 b.setAttribute('aria-haspopup', 'menu');
2716 b.setAttribute('aria-expanded', 'false');
2717 b.textContent = t('menu_' + b.dataset.menu);
2718 b.tabIndex = i === 0 ? 0 : -1;
2719 b.addEventListener('click', () => (menuBarraAbierto === b ? cierraMenuBarra({ foco: true }) : abreMenuBarra(b)));
2720 b.addEventListener('keydown', e => {
2721 const lista = barraMenus(), j = lista.indexOf(b);
2722 const mueve = k => { const n = lista[(j + k + lista.length) % lista.length]; lista.forEach(x => { x.tabIndex = x === n ? 0 : -1; }); n.focus(); if (menuBarraAbierto) abreMenuBarra(n, { foco: true }); };
2723 if (e.key === 'ArrowRight') { e.preventDefault(); mueve(1); }
2724 else if (e.key === 'ArrowLeft') { e.preventDefault(); mueve(-1); }
2725 else if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') { e.preventDefault(); abreMenuBarra(b, { foco: true }); }
2726 });
2727 });
2728}
2729async function abreMenuBarra(b, { foco = false } = {}) {
2730 barraMenus().forEach(x => { x.classList.toggle('open', x === b); x.setAttribute('aria-expanded', x === b ? 'true' : 'false'); });
2731 menuBarraAbierto = b;
2732 openMenuAt(await menuFor(b.dataset.menu), b);
2733 if (menuBarraAbierto !== b) return; // otro menú se abrió mientras tanto
2734 if (foco) $('topmenu').querySelector('[role="menuitem"]:not([aria-disabled="true"])')?.focus();
2735}
2736function cierraMenuBarra({ foco = false } = {}) {
2737 const b = menuBarraAbierto;
2738 $('topmenu').hidden = true;
2739 barraMenus().forEach(x => { x.classList.remove('open'); x.setAttribute('aria-expanded', 'false'); });
2740 menuBarraAbierto = null;
2741 if (foco && b) b.focus();
2742}
2743function openMenuAt(items, anchor) {
2744 const menu = $('topmenu');
2745 const r = anchor.getBoundingClientRect();
2746 menu.style.left = r.left + 'px';
2747 menu.style.top = (r.bottom + 3) + 'px';
2748 menu.replaceChildren();
2749 menu.setAttribute('role', 'menu');
2750 menu.setAttribute('aria-label', anchor.textContent);
2751 for (const it of items) {
2752 const row = el('button', 'menu-item');
2753 row.type = 'button';
2754 row.setAttribute('role', 'menuitem');
2755 row.tabIndex = -1;
2756 row.innerHTML = `<b></b>${it.hint ? '<span></span>' : ''}`;
2757 row.querySelector('b').textContent = it.label;
2758 if (it.hint) row.querySelector('span').textContent = it.hint;
2759 if (it.title) row.title = it.title;
2760 if (it.disabled) { row.setAttribute('aria-disabled', 'true'); row.classList.add('disabled'); }
2761 // stopPropagation: el clic no debe seguir hasta los «clic fuera» del
2762 // documento, que cerraban al instante lo que la opción acababa de abrir
2763 // (la paleta con «Ir a archivo…» o «Buscar en el código»).
2764 row.onclick = (e) => { e.stopPropagation(); if (it.disabled) return; cierraMenuBarra(); it.run(); };
2765 menu.appendChild(row);
2766 }
2767 menu.hidden = false;
2768}
2769$('topmenu').addEventListener('keydown', e => {
2770 const filas = [...$('topmenu').querySelectorAll('[role="menuitem"]')];
2771 const i = filas.indexOf(document.activeElement);
2772 const ve = k => { e.preventDefault(); filas[(i + k + filas.length) % filas.length]?.focus(); };
2773 if (e.key === 'ArrowDown') ve(1);
2774 else if (e.key === 'ArrowUp') ve(-1);
2775 else if (e.key === 'Home') { e.preventDefault(); filas[0]?.focus(); }
2776 else if (e.key === 'End') { e.preventDefault(); filas.at(-1)?.focus(); }
2777 else if (e.key === 'Escape') { e.preventDefault(); cierraMenuBarra({ foco: true }); }
2778 else if (e.key === 'Tab') cierraMenuBarra();
2779 else if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
2780 e.preventDefault();
2781 const lista = barraMenus(), j = lista.indexOf(menuBarraAbierto);
2782 const n = lista[(j + (e.key === 'ArrowRight' ? 1 : -1) + lista.length) % lista.length];
2783 lista.forEach(x => { x.tabIndex = x === n ? 0 : -1; });
2784 abreMenuBarra(n, { foco: true });
2785 }
2786});
2787document.addEventListener('click', e => {
2788 if (!e.target.closest('#menubar, #topmenu') && !$('topmenu').hidden) cierraMenuBarra();
2789});
2790
2791// ---------- git en el header ----------
2792async function refreshGit() {
2793 const g = await codeTools.gitInfo().catch(() => ({ isRepo: false }));
2794 const chip = $('git-branch');
2795 if (g.isRepo) { chip.hidden = false; chip.innerHTML = UI.code + ' ' + g.branch; }
2796 else chip.hidden = true;
2797}
2798$('git-branch').addEventListener('click', () => document.querySelector('#menubar button[data-menu="git"]').click());
2799
2800// icono de skills en la barra de actividad
2801$('act-skills').innerHTML = UI.puzzle;
2802$('act-skills').addEventListener('click', () => openSkillsPanel());
2803
2804// Extensiones de VS Code (temas, gramáticas, snippets, lenguajes): js/ext/.
2805// Nada de eso se carga hasta que se usa; el panel y el host llegan al pulsar.
2806function extTexto(es, en) { return uiLang() === 'es' ? es : en; }
2807async function openExtensions(opts = {}) {
2808 const host = await loadExt();
2809 if (!host) { $('statusbar').textContent = t('openProjFirst'); return; }
2810 (await import('./ext/panel.js')).open(host, opts);
2811}
2812$('act-ext').innerHTML = ACTIVITY.extensions;
2813$('act-ext').title = extTexto('Extensiones (temas, gramáticas, snippets)', 'Extensions (themes, grammars, snippets)');
2814$('act-ext').addEventListener('click', () => openExtensions());
2815
2816rebuildSelect();
2817skills.initSkills();
2818boot();
2819window.elffussClaw = { conv, get agent() { return conv.getActive()?.agent; }, send, openFile, parseToolCall, skills };
2820
2821
2822// ---------- puerta de móvil y chip de disco ----------
2823// Declaradas con `function` para que se icen: preloadModel() las usa y está
2824// escrita más arriba en el fichero.
2825function avisoMovil(tam, onAccept) {
2826 // Se pinta FIJO sobre la pantalla, no dentro del layout: cuando esto corre,
2827 // #chat todavía no existe (Code construye su interfaz después), así que caía
2828 // al body y el propio layout lo tapaba — presente en el DOM y invisible para
2829 // el usuario, que es la peor variante de un aviso.
2830 const box = document.createElement('div');
2831 box.style.cssText = 'position:fixed;left:50%;bottom:16px;transform:translateX(-50%);z-index:99999;'
2832 + 'width:min(92vw,520px);padding:16px;border:1px solid #3a3a4a;border-radius:14px;'
2833 + 'background:#15161f;color:#eae8f2;box-shadow:0 18px 50px -18px rgba(0,0,0,.8);'
2834 + 'display:flex;flex-direction:column;gap:8px;font:14px/1.5 system-ui,sans-serif';
2835 const h = document.createElement('b'); h.textContent = '📱 En el móvil todavía no funciona';
2836 const p1 = document.createElement('span'); p1.style.opacity = '.75';
2837 p1.textContent = 'Elffuss Code ejecuta el modelo dentro de tu propio navegador. En el móvil eso hoy no sale bien: '
2838 + 'habría que descargar ' + tam + ' y el navegador suele cerrar la pestaña antes de terminar. '
2839 + 'Así que no te lo descargo sin preguntar.';
2840 const p2 = document.createElement('span'); p2.style.opacity = '.75';
2841 p2.textContent = 'Ábrelo en un ordenador y sí funciona: ahí es donde vive.';
2842 const fila = document.createElement('div');
2843 fila.style.cssText = 'display:flex;gap:8px;flex-wrap:wrap';
2844 const b = document.createElement('button');
2845 b.style.cssText = 'flex:1;padding:9px 12px;border-radius:9px;border:1px solid #4a4a5e;background:#22232f;color:inherit;font:inherit;cursor:pointer';
2846 b.textContent = 'Descargarlo igualmente (' + tam + ')';
2847 b.onclick = () => { try { localStorage.setItem('elffusscode.movil.ok', '1'); } catch {} box.remove(); onAccept(); };
2848 const x = document.createElement('button');
2849 x.style.cssText = 'padding:9px 12px;border-radius:9px;border:1px solid #4a4a5e;background:transparent;color:inherit;font:inherit;cursor:pointer';
2850 x.textContent = 'Entendido';
2851 x.onclick = () => box.remove();
2852 fila.append(b, x);
2853 box.append(h, p1, p2, fila);
2854 document.body.appendChild(box);
2855}
2856
2857// Tamaño legible: MB por debajo de 1 GB.
2858function tamano(n) { return n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : Math.round(n / 1048576) + ' MB'; }
2859
2860// Vaciar los modelos guardados: lo usan el chip 💾 y «Vaciar caché» de Ajustes.
2861// Devuelve el mensaje con lo que pasó (o null si el usuario canceló).
2862async function vaciarModelos(boton) {
2863 const m = await modelUsage();
2864 if (!confirm(t('clearModelsConfirm', { size: tamano(m.total) }) + (m.sharedOk ? '' : '\n\n' + t('clearModelsShared')))) return null;
2865 const antes = boton.textContent;
2866 boton.disabled = true; boton.setAttribute('aria-busy', 'true');
2867 boton.textContent = t('setClearing');
2868 let r;
2869 try { r = await clearModels(); }
2870 finally { boton.disabled = false; boton.removeAttribute('aria-busy'); boton.textContent = antes; }
2871 let msg = t('clearModelsDone', { size: tamano(r.liberado) });
2872 if (r.fallos.length) msg += ' ' + t('clearModelsFailed', { what: r.fallos.join(' · ') });
2873 if (!r.sharedOk) msg += ' ' + t('clearModelsShared');
2874 $('statusbar').textContent = msg;
2875 return msg;
2876}
2877
2878// Chip 💾: lo que ocupan los MODELOS (no el origen entero, que mezclaba
2879// conversaciones y el proyecto de prueba) y un clic para vaciarlos.
2880function mountDiskChip() {
2881 const chip = document.getElementById('disk-chip');
2882 if (!chip) return;
2883 async function paint() {
2884 const { quota } = await cacheEstimate();
2885 const m = await modelUsage();
2886 if (!m.total) { chip.hidden = true; return; }
2887 chip.hidden = false;
2888 chip.textContent = '💾 ' + tamano(m.total);
2889 chip.title = t('diskChipTitle', { size: tamano(m.total), quota: quota ? t('diskChipQuota', { quota: tamano(quota) }) : '' })
2890 + (m.sharedOk ? '' : t('setSharedUnknown'));
2891 }
2892 chip.addEventListener('click', async () => {
2893 const msg = await vaciarModelos(chip);
2894 if (msg) await paint();
2895 });
2896 paint();
2897 setInterval(paint, 20000);
2898}
2899mountDiskChip();
2900
2901// ── Compositor: menú de modos, ancho del chat y caja que crece ──────────────
2902// Los tres botones de modo siguen siendo los mismos elementos con los mismos
2903// ids: lo único que cambia es que viven dentro de un desplegable. Así el JS que
2904// ya los escuchaba no se entera de nada.
2905{
2906 const modos = $('btn-modos'), menu = $('modos-menu');
2907 if (modos && menu) {
2908 // Cada modo lleva DEBAJO lo que hace. El texto sale del `title` que ya
2909 // tenía el botón: estaba escrito y bien, pero solo lo veía quien dejara el
2910 // ratón quieto encima — o sea casi nadie, y en móvil nadie. «Auto», «Goal»
2911 // y «Hard Work» sueltos no dicen nada a quien llega nuevo.
2912 for (const b of menu.querySelectorAll('.cbtn')) {
2913 const que = b.getAttribute('title');
2914 if (!que || b.querySelector('.modo-que')) continue;
2915 const span = document.createElement('span');
2916 span.className = 'modo-que';
2917 // Cortar por el primer paréntesis dejaba «Hard Work (RLM): lee tu
2918 // proyecto…» en «Hard Work», o sea una explicación que repite el nombre
2919 // del botón y no explica nada. Lo que sobra es el PREFIJO —«Nombre
2920 // (SIGLAS):»— no lo que viene detrás, que es justo la frase útil.
2921 span.textContent = que
2922 .replace(/^[^:]{0,40}:\s*/, '') // fuera «Hard Work (RLM): »
2923 .split('.')[0] // la primera frase
2924 .replace(/\s*\([^)]*\)\s*/g, ' ') // sin incisos entre paréntesis
2925 .replace(/\s+/g, ' ')
2926 .trim()
2927 .slice(0, 120);
2928 b.appendChild(span);
2929 // Ya está a la vista: dejar el title duplicaría el texto en un tooltip.
2930 b.removeAttribute('title');
2931 }
2932 // Menú con casillas: cada modo dice si está encendido (aria-checked) y el
2933 // botón «Modos» enseña cuáles lo están, también cerrado. Antes cualquier
2934 // clic dentro cerraba el menú y desde fuera no había forma de saber que
2935 // Goal o Hard Work seguían activos (y las preguntas normales se volvían
2936 // planes sin avisar). Ahora pulsar un modo lo cambia y el menú se queda
2937 // abierto para verlo; se cierra al pulsar fuera o con Escape.
2938 modos.setAttribute('aria-haspopup', 'menu');
2939 modos.setAttribute('aria-expanded', 'false');
2940 menu.setAttribute('role', 'menu');
2941 menu.setAttribute('aria-label', t('modesLabel'));
2942 for (const b of menu.querySelectorAll('.cbtn')) b.setAttribute('role', 'menuitemcheckbox');
2943 modos.addEventListener('click', (e) => {
2944 e.stopPropagation();
2945 if (menu.hidden) { menu.hidden = false; modos.setAttribute('aria-expanded', 'true'); menu.querySelector('.cbtn')?.focus(); }
2946 else cierraModos({ foco: false });
2947 });
2948 menu.addEventListener('keydown', (e) => {
2949 const opciones = [...menu.querySelectorAll('.cbtn')], i = opciones.indexOf(document.activeElement);
2950 if (e.key === 'ArrowDown') { e.preventDefault(); opciones[(i + 1) % opciones.length]?.focus(); }
2951 else if (e.key === 'ArrowUp') { e.preventDefault(); opciones[(i - 1 + opciones.length) % opciones.length]?.focus(); }
2952 else if (e.key === 'Tab') cierraModos({ foco: false });
2953 });
2954 document.addEventListener('click', (e) => {
2955 if (!e.target.closest('#modos') && !menu.hidden) cierraModos({ foco: false });
2956 });
2957 pintaModos();
2958 }
2959
2960 // El chat a toda la ventana. Al editor se le da cero de ancho en vez de
2961 // quitarlo: volver es instantáneo y no se pierde lo que hubiera abierto.
2962 const ancho = $('btn-ancho');
2963 if (ancho) {
2964 const pinta = () => {
2965 const full = document.body.classList.contains('chat-full');
2966 ancho.textContent = full ? '⇥' : '⇔';
2967 ancho.title = full ? 'Recuperar el editor' : 'Ensanchar el chat a toda la ventana';
2968 };
2969 try { if (localStorage.getItem('elffusscode.chatfull') === '1') document.body.classList.add('chat-full'); }
2970 catch { /* sin localStorage se queda como está */ }
2971 pinta();
2972 ancho.addEventListener('click', () => {
2973 document.body.classList.toggle('chat-full');
2974 try { localStorage.setItem('elffusscode.chatfull', document.body.classList.contains('chat-full') ? '1' : '0'); }
2975 catch { /* — */ }
2976 pinta();
2977 });
2978 }
2979
2980 // La caja crece con el texto hasta el tope que pone el CSS. Se recalcula
2981 // desde cero (`auto`) antes de medir: si no, una vez crecida ya no encoge al
2982 // borrar, y acaba ocupando media pantalla vacía.
2983 const caja = $('prompt');
2984 if (caja && caja.tagName === 'TEXTAREA') {
2985 const crece = () => {
2986 caja.style.height = 'auto';
2987 caja.style.height = Math.min(caja.scrollHeight, window.innerHeight * 0.4) + 'px';
2988 };
2989 caja.addEventListener('input', crece);
2990 // Al enviar, el valor se vacía desde fuera y no salta `input`: sin esto la
2991 // caja se queda alta y vacía después de cada mensaje.
2992 new MutationObserver(crece).observe(caja, { attributes: true, attributeFilter: ['value'] });
2993 $('composer')?.addEventListener('submit', () => setTimeout(crece, 0));
2994 }
2995}
2996
2997// ── Instalable: es lo único que consigue almacenamiento persistente ─────────
2998// Medido en este proyecto: `navigator.storage.persist()` devuelve false en un
2999// perfil normal, así que Chrome puede desalojar los gigas del modelo cuando le
3000// falte disco — y lo hizo. Chrome concede la persistencia a los sitios
3001// instalados, y solo ofrece instalar si hay manifiesto Y un service worker con
3002// manejador de `fetch`. De ahí `sw.js`, que no cachea nada a propósito.
3003//
3004// El registro va tras `load` para no competir con la carga del modelo, que es
3005// lo que el usuario está esperando de verdad.
3006if ('serviceWorker' in navigator) {
3007 addEventListener('load', () => {
3008 navigator.serviceWorker.register('sw.js').then(async () => {
3009 // Se vuelve a pedir la persistencia DESPUÉS de registrar: si el usuario ya
3010 // tenía el sitio instalado de una visita anterior, aquí es donde se
3011 // concede, y sin pedirla otra vez nadie se enteraría.
3012 try {
3013 if (navigator.storage?.persist && !(await navigator.storage.persisted())) {
3014 const ok = await navigator.storage.persist();
3015 console.log('[elffuss] almacenamiento persistente: ' + (ok ? 'concedido' : 'denegado — instala la app para que el navegador no borre el modelo'));
3016 }
3017 } catch { /* el diagnóstico no vale un error */ }
3018 }).catch(e => console.warn('[elffuss] service worker no registrado: ' + e.message));
3019 });
3020}