Elffuss BraidHub

utopia-ia/elffuss-code public

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