Elffuss BraidHub

utopia-ia/elffuss-code public

6fb41f3536ee · 149.5 KiBRawPermalink
1// Elffuss Code: landing («abre tu carpeta») → IDE con la elfa integrada.
2import { parseToolCall } from './agent.js';
3import * as rules from './providers/rules.js';
4import * as codeTools from './tools/code.js';
5import * as db from './db.js';
6import * as settings from './settings.js';
7import { initEditor, refreshTree, openFile, gotoLine, triggerEditor, hasEditor, saveActive, activeFile, focusEditor } 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 // Una carpeta PROPIA dentro del almacenamiento del navegador, no su raíz: en
1404 // la raíz viven también los pesos de los modelos (elffuss-models), y abierta
1405 // como proyecto el explorador, la paleta, la búsqueda y las herramientas del
1406 // agente los enseñaban y podían editarlos o borrarlos.
1407 probar.onclick = async () => {
1408 try { await enterIDE(await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-code', { create: true })); }
1409 catch (e) { avisaFalloApertura(e); }
1410 };
1411 }
1412 }
1413 const saveCloneJob = job => db.set('kv', 'cloneJob', job).catch(() => {});
1414 const loadCloneJob = () => db.get('kv', 'cloneJob').catch(() => null);
1415 const clearCloneJob = () => db.del('kv', 'cloneJob').catch(() => {});
1416
1417 async function runDownload(job) {
1418 cloneBtn.disabled = true;
1419 const doneSet = new Set(job.done);
1420 const clone = await import('./tools/clone.js');
1421 try {
1422 await clone.downloadFiles(job, job.handle, doneSet,
1423 p => showCloneStatus(p.text || ''),
1424 async path => {
1425 job.done.push(path);
1426 // persistir el progreso poco a poco (no en cada fichero: de sobra
1427 // para no perder más de un puñado si se interrumpe a media descarga)
1428 if (job.done.length % 5 === 0) await saveCloneJob(job);
1429 });
1430 await saveCloneJob(job);
1431 showCloneStatus(`✔ ${job.files.length} ficheros descargados` + (job.skipped ? ` (${job.skipped} omitidos por tamaño)` : ''));
1432 await clearCloneJob();
1433 await enterIDE(job.handle);
1434 } catch (e) {
1435 await saveCloneJob(job); // que lo ya bajado no se pierda aunque falle a mitad
1436 showCloneStatus('⚠️ ' + (e?.message || e) + ' — puedes reintentar, retoma donde se quedó', true);
1437 } finally { cloneBtn.disabled = false; }
1438 }
1439
1440 const runClone = async () => {
1441 const url = cloneUrl.value.trim();
1442 // La URL se valida ANTES de abrir el selector de carpeta: antes se elegía
1443 // la carpeta y solo después decía que la URL no valía. Vacía, lo dice.
1444 if (!url) { showCloneStatus(t('clonePasteUrl'), true); cloneUrl.focus(); return; }
1445 const clone = await import('./tools/clone.js');
1446 try { clone.parseRepoUrl(url); }
1447 catch { showCloneStatus('⚠️ ' + t('cloneBadUrl'), true); cloneUrl.focus(); return; }
1448 showCloneStatus('');
1449 let handle;
1450 try { handle = await window.showDirectoryPicker({ mode: 'readwrite' }); }
1451 catch (e) { if (e?.name !== 'AbortError') showCloneStatus('⚠️ ' + (e?.message || e), true); return; }
1452 showCloneStatus(t('cloneListing'));
1453 try {
1454 const info = await clone.listRepo(url);
1455 const job = { url, handle, done: [], ...info };
1456 await saveCloneJob(job);
1457 await runDownload(job);
1458 } catch (e) {
1459 showCloneStatus('⚠️ ' + (e?.message || e), true);
1460 }
1461 };
1462 cloneBtn.addEventListener('click', runClone);
1463 cloneUrl.addEventListener('keydown', e => { if (e.key === 'Enter') runClone(); });
1464
1465 // ¿había una descarga a medias de una sesión anterior? ofrece reanudarla
1466 const job = await loadCloneJob();
1467 if (job && job.handle && job.files && job.done.length < job.files.length) {
1468 const banner = $('resume-clone');
1469 banner.hidden = false;
1470 // owner/repo enlaza al repositorio público que se estaba bajando.
1471 const rc = banner.querySelector('.rc-text');
1472 const a = document.createElement('a');
1473 a.href = (job.host === 'bitbucket' ? 'https://bitbucket.org/' : 'https://github.com/') + encodeURIComponent(job.owner) + '/' + encodeURIComponent(job.repo);
1474 a.target = '_blank'; a.rel = 'noopener noreferrer';
1475 a.textContent = `${job.owner}/${job.repo}`;
1476 const [antes, despues] = t('cloneHalf', { repo: '\u0000', n: job.done.length, total: job.files.length }).split('\u0000');
1477 rc.replaceChildren(antes, a, despues);
1478 $('resume-clone-btn').onclick = async () => {
1479 banner.hidden = true;
1480 try {
1481 const q = job.handle.queryPermission ? await job.handle.queryPermission({ mode: 'readwrite' }) : 'granted';
1482 if (q !== 'granted' && await job.handle.requestPermission({ mode: 'readwrite' }) !== 'granted') throw new Error('permiso denegado para la carpeta');
1483 showCloneStatus(`Reanudando ${job.owner}/${job.repo}…`);
1484 await runDownload(job);
1485 } catch (e) { showCloneStatus('⚠️ ' + (e?.message || e), true); }
1486 };
1487 $('discard-clone-btn').onclick = async () => { await clearCloneJob(); banner.hidden = true; };
1488 } else if (job) {
1489 await clearCloneJob(); // job corrupto o ya completo: limpiar
1490 }
1491
1492 // gancho de test: ?test-opfs usa el almacenamiento del navegador como proyecto
1493 if (location.search.includes('test-opfs')) {
1494 const opfs = await navigator.storage.getDirectory();
1495 return enterIDE(opfs);
1496 }
1497
1498 // reabrir el último proyecto (un clic si el navegador exige gesto)
1499 const prev = await codeTools.restoreProject();
1500 if (prev?.ready) return enterIDE(await db.get('kv', 'project'));
1501 if (prev?.handle) {
1502 const btn = $('reopen-project');
1503 btn.hidden = false;
1504 btn.textContent = t('reopenFolder', { name: prev.name });
1505 btn.onclick = async () => {
1506 try { await codeTools.regrant(prev.handle); await enterIDE(prev.handle); }
1507 catch (e) { avisaFalloApertura(e); }
1508 };
1509 }
1510}
1511
1512// Historial del prompt del chat: ↑/↓ recuperan lo enviado (como una shell).
1513// Persistente entre recargas (localStorage, últimos 100).
1514const PROMPT_HIST_KEY = 'elffusscode.promptHistory';
1515let promptHistory = [];
1516try { promptHistory = JSON.parse(localStorage.getItem(PROMPT_HIST_KEY) || '[]'); } catch { /* corrupto */ }
1517let promptHistIdx = -1, promptDraft = '';
1518function pushPromptHistory(text) {
1519 if (promptHistory[promptHistory.length - 1] !== text) promptHistory.push(text);
1520 if (promptHistory.length > 100) promptHistory = promptHistory.slice(-100);
1521 try { localStorage.setItem(PROMPT_HIST_KEY, JSON.stringify(promptHistory)); } catch { /* lleno */ }
1522 promptHistIdx = -1; promptDraft = '';
1523}
1524$('prompt').addEventListener('keydown', e => {
1525 if (!$('menu').hidden) return; // el menú «/» ya usa ↑/↓
1526 const inp = e.target;
1527 // En un borrador de varias líneas, ↑/↓ mueven el cursor como siempre: el
1528 // historial solo salta desde la primera línea (↑) o la última (↓). Antes ↑
1529 // en un texto largo lo sustituía entero por el mensaje anterior.
1530 const antes = inp.value.slice(0, inp.selectionStart), despues = inp.value.slice(inp.selectionEnd);
1531 if (e.key === 'ArrowUp' && antes.includes('\n')) return;
1532 if (e.key === 'ArrowDown' && despues.includes('\n')) return;
1533 if (e.key === 'ArrowUp') {
1534 if (!promptHistory.length) return;
1535 if (promptHistIdx === -1) { promptDraft = inp.value; promptHistIdx = promptHistory.length; }
1536 promptHistIdx = Math.max(0, promptHistIdx - 1);
1537 inp.value = promptHistory[promptHistIdx];
1538 e.preventDefault();
1539 requestAnimationFrame(() => inp.setSelectionRange(inp.value.length, inp.value.length));
1540 } else if (e.key === 'ArrowDown') {
1541 if (promptHistIdx === -1) return;
1542 promptHistIdx++;
1543 inp.value = promptHistIdx >= promptHistory.length ? (promptHistIdx = -1, promptDraft) : promptHistory[promptHistIdx];
1544 e.preventDefault();
1545 } else if (e.key === 'Enter' && !e.isComposing && !e.shiftKey) {
1546 // envío explícito: no depender del submit-on-Enter nativo del <form>,
1547 // que algún navegador puede "tragarse" el primer Enter (autocompletar/
1548 // sugerencias) justo después de rellenar el valor por código (↑ del
1549 // historial) en vez de por tecleo real.
1550 e.preventDefault();
1551 $('composer').requestSubmit();
1552 }
1553});
1554$('composer').addEventListener('submit', e => {
1555 e.preventDefault();
1556 // Mientras el agente trabaja, el BOTÓN para en vez de enviar. Enter no: con
1557 // texto lo ENCOLA (cada conversación acepta y encola mensajes) y sale en
1558 // cuanto termine lo de ahora. Antes Enter también paraba, y el texto se
1559 // quedaba sin enviar en la caja. `submitter` es el botón solo en un clic (o
1560 // Enter/Espacio con el foco en él); con Enter en el cuadro de texto
1561 // (requestSubmit sin argumento) es null. Si ya se está parando, pulsar el
1562 // propio botón, que dice «Parando…» y está aria-disabled, no hace nada.
1563 const active = conv.getActive();
1564 const desdeBoton = e.submitter?.id === 'btn-send';
1565 if (desdeBoton && active?.parando) return;
1566 if (desdeBoton && active && active.pumping && !active.parando) { conv.stopActive(); return; }
1567 const text = $('prompt').value.trim();
1568 if (!text) return;
1569 $('prompt').value = '';
1570 pushPromptHistory(text);
1571 send(text);
1572});
1573// Reflejar en el botón si estamos generando (▶ enviar / ■ parar). Se llama desde
1574// el onChange de conversaciones cuando cambia «pumping».
1575const 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>';
1576function paintSendButton() {
1577 const b = document.getElementById('btn-send');
1578 if (!b) return;
1579 const active = conv.getActive();
1580 const busy = !!active?.pumping;
1581 // «Parando…»: ya se pulsó ■ y el turno aún se está soltando (un modelo lento
1582 // tarda en dejar la generación). Antes el ■ seguía igual tras el clic y
1583 // parecía que no había hecho caso. Se marca con aria-disabled y NO con
1584 // disabled: deshabilitar el botón que tiene el foco lo saca del foco, el
1585 // teclado caía a <body> y ya no volvía.
1586 const parando = busy && !!active?.parando;
1587 b.classList.toggle('sending', busy);
1588 b.classList.toggle('is-stop', busy && !parando);
1589 b.classList.toggle('is-stopping', parando);
1590 if (parando) { b.setAttribute('aria-disabled', 'true'); b.setAttribute('aria-busy', 'true'); }
1591 else { b.removeAttribute('aria-disabled'); b.removeAttribute('aria-busy'); }
1592 b.innerHTML = parando ? escapeHtml(t('stopping')) : busy ? STOP_ICON : UI.send;
1593 b.title = parando ? t('stopping') : busy ? t('stop') : t('send');
1594 b.setAttribute('aria-label', b.title);
1595}
1596// La parada se anuncia en una región viva: el botón solo lo dice en su
1597// etiqueta, y parando con Enter el foco está en el cuadro de texto, así que el
1598// cambio no se oía; el «(Parado.)» del chat tampoco, porque el chat no es una
1599// región viva. Se vacía y se escribe en otro tick para que el mismo texto dos
1600// veces seguidas se vuelva a leer, y un anuncio que llega antes de escribirse
1601// el anterior lo sustituye.
1602let anuncioPendiente = null;
1603function anunciarEnvio(texto) {
1604 const r = document.getElementById('send-status');
1605 if (!r) return;
1606 clearTimeout(anuncioPendiente);
1607 r.textContent = '';
1608 anuncioPendiente = setTimeout(() => { r.textContent = texto; }, 50);
1609}
1610$('model-select').addEventListener('change', e => changeModel(e.target.value));
1611// El foco va a la tarjeta del modelo ACTIVO (un selector con coma devolvía la
1612// primera tarjeta en el orden del documento, no la activa).
1613$('model-dot').addEventListener('click', () => {
1614 renderSettings();
1615 requestAnimationFrame(() => { const panel = $('settings-panel'); (panel.querySelector('.model-card.active') || panel.querySelector('.model-card'))?.focus(); });
1616});
1617pintaDot('off', 'rules');
1618// móvil: conmutar chat ↔ editor
1619// ☰ (solo en el móvil): cajón con el árbol de ficheros y la barra de
1620// actividad. Abrir un fichero desde ahí pasa a la vista Editor y cierra el
1621// cajón; Escape o tocar fuera lo cierran.
1622function abreCajon(abrir) {
1623 const on = abrir ?? !document.body.classList.contains('drawer-open');
1624 if (on) {
1625 document.documentElement.style.setProperty('--drawer-top', Math.round(document.querySelector('#ide header').getBoundingClientRect().bottom) + 'px');
1626 if (!$('drawer-scrim')) {
1627 const scrim = document.createElement('div');
1628 scrim.id = 'drawer-scrim';
1629 scrim.onclick = () => abreCajon(false);
1630 document.body.appendChild(scrim);
1631 }
1632 }
1633 document.body.classList.toggle('drawer-open', on);
1634 // el árbol empieza justo debajo de la fila de herramientas, mida lo que mida
1635 if (on) document.documentElement.style.setProperty('--drawer-act', Math.round($('activity').getBoundingClientRect().height) + 'px');
1636 $('btn-drawer').setAttribute('aria-expanded', on ? 'true' : 'false');
1637 if (on) ($('tree').querySelector('[tabindex="0"]') || $('act-files'))?.focus();
1638 else if (document.activeElement && ($('sidebar').contains(document.activeElement) || $('activity').contains(document.activeElement))) $('btn-drawer').focus();
1639}
1640$('btn-drawer').title = t('drawerTitle');
1641$('btn-drawer').setAttribute('aria-label', t('drawerTitle'));
1642$('btn-drawer').addEventListener('click', () => abreCajon());
1643// Elegir algo del cajón lo cierra; un fichero del árbol además enseña el editor.
1644$('tree').addEventListener('click', e => {
1645 if (!document.body.classList.contains('drawer-open')) return;
1646 if (!e.target.closest('.file')) return;
1647 document.body.classList.add('show-editor');
1648 paintFlip(true);
1649 abreCajon(false);
1650});
1651$('activity').addEventListener('click', e => {
1652 if (!document.body.classList.contains('drawer-open') || !e.target.closest('button')) return;
1653 if (e.target.closest('#act-files')) return; // en el cajón, el árbol ya se ve
1654 abreCajon(false);
1655 if (e.target.closest('#act-arch, #act-city, #act-term')) { document.body.classList.add('show-editor'); paintFlip(true); }
1656}, true);
1657
1658$('code-flip').addEventListener('click', () => {
1659 const showEditor = !document.body.classList.contains('show-editor');
1660 document.body.classList.toggle('show-editor', showEditor);
1661 paintFlip(showEditor);
1662});
1663
1664// vistas Arquitectura (grafo) y Ciudad 3D — leen el proyecto abierto y al
1665// hacer clic abren el fichero en Monaco (inspirado en CodeFlow + VibeCodeViewer)
1666$('act-arch').innerHTML = UI.graph || UI.code;
1667$('act-city').innerHTML = UI.city || UI.code;
1668let viewRenderSeq = 0;
1669async function openView(kind) {
1670 const overlay = $('view-overlay'), body = $('view-body');
1671 const seq = ++viewRenderSeq;
1672 // destruir CUALQUIER vista previa (su RAF/canvas seguía vivo al cambiar → la
1673 // nueva no cargaba bien). Ambas, no solo la del mismo tipo.
1674 try { (await import('./city.js')).disposeCity(); } catch { /* */ }
1675 try { (await import('./arch.js')).disposeArch(); } catch { /* */ }
1676 body.innerHTML = '<div class="view-loading" role="status"></div>';
1677 body.firstChild.textContent = t('viewBuilding');
1678 overlay.hidden = false;
1679 document.querySelectorAll('#activity button').forEach(b => b.classList.toggle('on', b.id === 'act-' + kind));
1680 // esperar a que el layout dé tamaño real al overlay (si no, canvas 0×0/mal aspect)
1681 await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
1682 if (seq !== viewRenderSeq) return; // el usuario cambió de vista mientras tanto
1683 try {
1684 if (kind === 'arch') { const m = await import('./arch.js'); await m.renderArchitecture(body, p => { closeView(); openFile(p); }); }
1685 else { const m = await import('./city.js'); await m.renderCity(body, p => { closeView(); openFile(p); }); }
1686 } catch (e) { body.innerHTML = '<div class="view-loading" role="status"></div>'; body.firstChild.textContent = t('viewFailed', { e: e?.message || e }); }
1687}
1688function closeView({ foco = false } = {}) {
1689 const abierta = [...document.querySelectorAll('#act-arch.on, #act-city.on')][0];
1690 $('view-overlay').hidden = true;
1691 import('./city.js').then(m => m.disposeCity()).catch(() => {});
1692 import('./arch.js').then(m => m.disposeArch()).catch(() => {});
1693 document.querySelectorAll('#activity button').forEach(b => b.classList.toggle('on', b.id === 'act-files'));
1694 if (foco) abierta?.focus();
1695}
1696$('act-arch').addEventListener('click', () => openView('arch'));
1697$('act-city').addEventListener('click', () => openView('city'));
1698$('view-close').addEventListener('click', () => closeView({ foco: true }));
1699
1700// ── Cerebro CEO autónomo + Mente de Elffuss ───────────────────────────────
1701// Cuando NO estás pidiendo nada, la elfa trabaja: revisa el proyecto y propone
1702// mejoras (en elffuss-mind/, sin tocar tu código). Clic en la elfa → abre la
1703// «Mente» (mundo trance + pensamientos paralelos + música) y activa el cerebro.
1704// «Abrir en el editor» de la Mente: abre el fichero y deja el foco en el editor
1705// (la Mente cierra sin devolverlo a la elfa).
1706mind.setOpenFile(async p => { await openFile(p); focusEditor(); });
1707mind.init({ buildCity: buildCityAdapter, loadThoughts: loadThoughtsAdapter });
1708// «Ejecutar esta propuesta»: la manda a la MISMA cola/agente del chat normal
1709// (mismas herramientas reales, mismo gate de Auto-edit) — no un auto-apply
1710// aparte sin supervisión.
1711mind.setExecuteProposal(md => { mind.closeMind(); send(t('pProposal') + md); });
1712// «perfiles»: cada uno es una línea de pensamiento paralela (foco + color de
1713// su estrella) del cerebro CEO (compartido, core/ceo.js). El usuario los
1714// edita/crea/borra desde ⚙ en la Mente.
1715const CEO_DEFAULT_PROFILES = [
1716 { id: 'arq', name: 'Arquitectura', focus: 'estructura, acoplamiento y dependencias; qué módulo conviene dividir o unificar', color: '#7c5cff' },
1717 { id: 'cal', name: 'Calidad', focus: 'bugs latentes, casos borde sin cubrir, validaciones que faltan', color: '#49e8ff' },
1718 { id: 'rend', name: 'Rendimiento', focus: 'cuellos de botella, trabajo repetido, estructuras de datos mejorables', color: '#ffb454' },
1719 { id: 'dx', name: 'Producto/DX', focus: 'legibilidad, nombres, documentación y ergonomía para quien lo usa', color: '#3fb970' },
1720];
1721// adaptador de workspace para el cerebro CEO genérico (core/ceo.js): traduce
1722// sus operaciones a las herramientas de code.js (proyecto de código único).
1723async function ceoDirHandle(dirPath) {
1724 let dir = codeTools.handle();
1725 for (const seg of dirPath.split('/').filter(Boolean)) dir = await dir.getDirectoryHandle(seg, { create: true });
1726 return dir;
1727}
1728const ceoWorkspace = {
1729 isReady: () => !!codeTools.handle(),
1730 tree: (opts) => codeTools.tree(opts),
1731 write: (opts) => codeTools.write(opts),
1732 read: (opts) => codeTools.read(opts),
1733 list: async (dirPath) => {
1734 const dir = await ceoDirHandle(dirPath);
1735 const names = [];
1736 for await (const e of dir.values()) if (e.kind === 'file') names.push(e.name);
1737 return names;
1738 },
1739 remove: async (dirPath, name) => (await ceoDirHandle(dirPath)).removeEntry(name),
1740};
1741ceo.init({
1742 namespace: 'elffusscode',
1743 workspace: ceoWorkspace,
1744 defaultProfiles: CEO_DEFAULT_PROFILES,
1745 defaultMission: 'Revisar el proyecto y proponer mejoras concretas y accionables (código, procesos, datos o docs).',
1746 // Sin modelo de verdad no hay cerebro: con el motor de reglas (modo Básico)
1747 // el CEO «pensaba» con el texto de ayuda, escribía .elffuss/soul/*.md dentro
1748 // del proyecto y anunciaba «4 mejoras» que no eran nada.
1749 provider: () => { const p = conv.getProvider(); return p && p !== rules ? p : null; },
1750 // el usuario tiene PRIORIDAD: si CUALQUIER conversación está en cola o procesándose, el cerebro espera
1751 isBusy: () => conv.isBusy(),
1752 onEvent: (ch, ev) => {
1753 mind.pushThought(ch, ev);
1754 if (ch === 'ceo' && ev.type === 'built') reportImprovements(ev);
1755 // la elfa se anima mientras el cerebro trabaja (invita a hacer clic para ver la Mente)
1756 const av = document.querySelector('#activity img');
1757 if (av) {
1758 if (ch === 'ceo' && ev.type === 'cycle') av.classList.add('working');
1759 if (ch === 'ceo' && (ev.type === 'built' || ev.type === 'paused')) av.classList.remove('working');
1760 }
1761 },
1762});
1763// Reporta las mejoras SIEMPRE en el chat (visual, entendible); la notificación
1764// del navegador solo salta si de verdad hay algo interesante y bien trabajado
1765// — nada de avisar por un ciclo flojo con una propuesta de una línea.
1766const WEAK_RE = /^(no (encontr|hay|se me ocurre)|nada que|sin cambios|todo (está|esta) bien|no aplica)/i;
1767export function isNoteworthy(ev) {
1768 const solid = (ev.proposals || []).filter(p => p.text && p.text.trim().length >= 60 && !WEAK_RE.test(p.text.trim()));
1769 return solid.length >= 2; // al menos 2 departamentos con algo sustancioso, no una ocurrencia suelta
1770}
1771// manda una propuesta (el .md completo del ciclo) a la MISMA cola/agente real
1772// del chat — usado tanto por el botón del chat como por el de la notificación.
1773function executeProposal(md) { send(t('pProposal') + md); }
1774
1775// Botón REAL para ejecutar la propuesta desde el propio chat.
1776function botonPropuesta(div, md) {
1777 const btn = document.createElement('button');
1778 btn.className = 'proposal-exec-btn';
1779 btn.textContent = t('mindExec');
1780 btn.onclick = () => { btn.disabled = true; btn.textContent = t('proposalSent'); executeProposal(md); };
1781 div.appendChild(btn);
1782}
1783
1784export function reportImprovements(ev) {
1785 const props = ev.proposals || [];
1786 if (!props.length) return;
1787 const firstLine = t => (t || '').split('\n').find(l => l.trim())?.trim().slice(0, 160) || '';
1788 const body = `💡 **Mientras estabas fuera revisé el proyecto y encontré ${props.length} mejora${props.length === 1 ? '' : 's'}:**\n\n` +
1789 props.map(p => `**${p.dept}** — ${firstLine(p.text)}`).join('\n\n') +
1790 (ev.path ? `\n\n_Guardado en \`${ev.path}\`. Dale a la elfa para verlo en la Mente, o ábrelo en el editor._` : '');
1791 const div = addMsg('assistant', body);
1792 // se guarda en el historial REAL de la conversación activa — si no, el
1793 // aviso vive solo en el DOM y desaparece al cambiar de pestaña o recargar.
1794 // Con la propuesta al lado: el botón «▶ Ejecutar» se vuelve a pintar al
1795 // repintar el chat (antes solo existía en el DOM del momento).
1796 const md = ev.md || body;
1797 const active = conv.getActive();
1798 if (active) conv.appendMessage(active.id, 'assistant', body, { propuesta: md });
1799 if (div) botonPropuesta(div, md);
1800 if (isNoteworthy(ev)) notify(`Elffuss encontró ${props.length} mejora${props.length === 1 ? '' : 's'}`, props.map(p => p.dept).join(' · '), md);
1801}
1802// SOLO notifica si el permiso YA está concedido. Nunca pide permiso aquí:
1803// fuera de un gesto de usuario, Chrome/Firefox lo bloquean en silencio —
1804// pedirlo vive únicamente en el clic de la elfa y en ⚙ de la Mente.
1805// Vía el service worker (registration.showNotification) para poder incluir
1806// un botón «▶ Ejecutar» de verdad en la propia notificación del sistema
1807// (new Notification() normal no soporta acciones); si el SW no está listo,
1808// cae a la notificación simple sin botón.
1809async function notify(title, body, md) {
1810 if (!('Notification' in window) || Notification.permission !== 'granted') return;
1811 try {
1812 if ('serviceWorker' in navigator) {
1813 const reg = await navigator.serviceWorker.ready;
1814 if (reg.showNotification) {
1815 await reg.showNotification(title, {
1816 body, icon: 'img/elffuss-code.svg',
1817 actions: [{ action: 'execute', title: t('nExec') }, { action: 'open', title: t('nView') }],
1818 data: { md },
1819 });
1820 return;
1821 }
1822 }
1823 } catch { /* cae a la notificación simple */ }
1824 try { new Notification(title, { body, icon: 'img/elffuss-code.svg' }); } catch { /* */ }
1825}
1826// clic en el botón de la notificación del sistema → lo mismo que en el chat
1827if ('serviceWorker' in navigator) {
1828 navigator.serviceWorker.addEventListener('message', e => {
1829 if (e.data?.type !== 'notif-action') return;
1830 if (e.data.action === 'execute' && e.data.md) executeProposal(e.data.md);
1831 else mind.openMind();
1832 });
1833}
1834// cualquier interacción FUERA de la Mente cuenta como actividad → pausa el CEO
1835const noteAct = e => { if (!e.target.closest?.('#mind-overlay')) ceo.noteActivity(); };
1836document.addEventListener('pointerdown', noteAct, true);
1837document.addEventListener('keydown', noteAct, true);
1838// La elfa de la barra es un BOTÓN que abre la Mente, y nada más. Antes el
1839// primer clic encendía en silencio el cerebro autónomo (que empezaba a trabajar
1840// sobre tu proyecto) y pedía permiso de notificaciones sin explicar para qué.
1841// Ahora el cerebro se enciende DENTRO de la Mente, con un botón que dice lo que
1842// hace, y las notificaciones se piden solo desde ⚙ cerebro.
1843const elfAvatar = $('act-mind');
1844if (elfAvatar) {
1845 elfAvatar.title = t('avatarTitle');
1846 elfAvatar.setAttribute('aria-label', t('avatarLabel'));
1847 elfAvatar.addEventListener('click', () => mind.openMind());
1848}
1849// restaura tu última elección (play o stop) tal cual la dejaste
1850if (ceo.wasEnabledLastSession()) ceo.enable();
1851
1852// terminal integrado: xterm.js + shell sobre los ficheros REALES del proyecto.
1853// La elfa comparte este shell (tool terminal.run) y su salida se refleja aquí.
1854$('act-term').innerHTML = UI.terminal;
1855shell.setHooks({ fsChange: () => refreshTree().catch(() => {}), openFile });
1856setTerminalEcho((cmd, out) => terminal.echoAgent(cmd, out));
1857async function toggleTerminal(force) {
1858 const show = force != null ? force : $('terminal-panel').hidden;
1859 $('terminal-panel').hidden = !show;
1860 $('act-term').classList.toggle('on', show);
1861 if (show) {
1862 pintaCapacidades();
1863 await terminal.mount($('terminal-host'));
1864 terminal.refit();
1865 }
1866}
1867// La etiqueta del terminal sigue al bridge: antes solo se pintaba al abrir el
1868// panel y se quedaba vieja si el bridge conectaba o caía con él abierto.
1869function pintaCapacidades() {
1870 const cap = shell.capabilities();
1871 $('term-caps').textContent = cap.bridge ? t("termCapsBridge") : t("termCapsNoBridge");
1872}
1873bridge.onStatusChange(() => { if (!$('terminal-panel').hidden) pintaCapacidades(); });
1874$('act-term').addEventListener('click', () => toggleTerminal());
1875$('term-close').addEventListener('click', () => toggleTerminal(false));
1876$('term-clear').addEventListener('click', () => terminal.clearScreen());
1877// Ctrl+` (o Cmd+`) alterna el terminal, como en VS Code
1878document.addEventListener('keydown', e => {
1879 if ((e.ctrlKey || e.metaKey) && e.key === '`') { e.preventDefault(); toggleTerminal(); }
1880});
1881// redimensionar arrastrando la barra superior del panel
1882(() => {
1883 const panel = $('terminal-panel'), handle = $('term-resize');
1884 let sy = 0, sh = 0;
1885 // También con el teclado: es un separador con foco, ↑/↓ cambian la altura.
1886 const ajusta = h => {
1887 h = Math.max(120, Math.min(window.innerHeight - 160, h));
1888 panel.style.height = h + 'px';
1889 handle.setAttribute('aria-valuenow', String(Math.round(h)));
1890 terminal.refit();
1891 };
1892 handle.setAttribute('role', 'separator');
1893 handle.setAttribute('aria-orientation', 'horizontal');
1894 handle.setAttribute('aria-label', t('termResizeLabel'));
1895 handle.setAttribute('aria-valuemin', '120');
1896 handle.tabIndex = 0;
1897 handle.addEventListener('keydown', e => {
1898 if (e.key === 'ArrowUp') { e.preventDefault(); ajusta(panel.offsetHeight + 24); }
1899 else if (e.key === 'ArrowDown') { e.preventDefault(); ajusta(panel.offsetHeight - 24); }
1900 });
1901 const move = e => ajusta(sh + (sy - e.clientY));
1902 const up = () => { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', up); };
1903 handle.addEventListener('mousedown', e => { sy = e.clientY; sh = panel.offsetHeight; document.addEventListener('mousemove', move); document.addEventListener('mouseup', up); e.preventDefault(); });
1904})();
1905window.addEventListener('resize', () => terminal.refit());
1906
1907// iconos VS Code (sin emojis) en cabecera, composer y flip
1908$('btn-history').innerHTML = UI.history;
1909$('btn-settings').innerHTML = UI.gear;
1910$('btn-send').innerHTML = UI.send;
1911$('btn-plus').innerHTML = UI.add;
1912$('btn-slash').innerHTML = UI.slash;
1913const paintFlip = editor => { $('code-flip').innerHTML = (editor ? UI.chat : UI.editor) + `<span>${editor ? t('flipChat') : t('flipEditor')}</span>`; };
1914paintFlip(false);
1915
1916// barra de actividad estilo VS Code
1917$('act-files').innerHTML = ACTIVITY.files;
1918$('act-search').innerHTML = ACTIVITY.search;
1919$('act-settings').innerHTML = ACTIVITY.gear;
1920$('act-files').addEventListener('click', () => {
1921 document.body.classList.toggle('hide-tree');
1922 $('act-files').classList.toggle('on');
1923});
1924// Lo que promete su título: buscar ficheros (la paleta, como Cmd/Ctrl+P). Antes
1925// escribía «busca » en el chat. Buscar DENTRO del código es «#» en la paleta.
1926$('act-search').addEventListener('click', (e) => { e.stopPropagation(); openPalette(''); });
1927$('act-settings').addEventListener('click', () => $('btn-settings').click());
1928
1929$('btn-history').addEventListener('click', () => {
1930 const panel = $('history-panel');
1931 if (!panel.hidden) return cierraHistorial();
1932 panel.hidden = false;
1933 $('btn-history').setAttribute('aria-expanded', 'true');
1934 renderHistoryPanel().then(() => (panel.querySelector('.hp-open') || panel.querySelector('.hp-head button'))?.focus());
1935});
1936function cierraHistorial({ foco = true } = {}) {
1937 const panel = $('history-panel');
1938 if (panel.hidden) return;
1939 panel.hidden = true;
1940 $('btn-history').setAttribute('aria-expanded', 'false');
1941 if (foco) $('btn-history').focus();
1942}
1943document.addEventListener('pointerdown', e => {
1944 const p = $('history-panel');
1945 if (p.hidden) return;
1946 if (p.contains(e.target) || e.target.closest('#btn-history')) return;
1947 cierraHistorial({ foco: false });
1948}, true);
1949$('btn-settings').addEventListener('click', () => {
1950 const p = $('settings-panel');
1951 if (!p.hidden) return cierraAjustes();
1952 renderSettings();
1953});
1954// clic fuera del panel (o ir a Archivo/chat) lo cierra — antes solo la X lo hacía
1955document.addEventListener('pointerdown', e => {
1956 const p = $('settings-panel');
1957 if (p.hidden) return;
1958 if (p.contains(e.target) || e.target.closest('#btn-settings, #act-settings, #model-dot')) return;
1959 p.hidden = true;
1960 volverDeAjustes = null;
1961}, true);
1962
1963// ── Escape cierra la capa de más arriba ─────────────────────────────────────
1964// Una por pulsación, y el foco vuelve a quien la abrió. Antes solo la paleta,
1965// la Mente y el menú @ hacían caso: menús de arriba, modos, historial,
1966// ajustes y la vista 3D se quedaban abiertos.
1967const CAPAS = [
1968 { abierta: () => !$('menu').hidden, cerrar: () => { $('menu').hidden = true; $('prompt').focus(); } },
1969 { abierta: () => !$('topmenu').hidden, cerrar: () => cierraMenuBarra({ foco: true }) },
1970 { abierta: () => !$('modos-menu')?.hidden, cerrar: () => cierraModos({ foco: true }) },
1971 { abierta: () => !$('history-panel').hidden, cerrar: () => cierraHistorial() },
1972 { abierta: () => !$('settings-panel').hidden, cerrar: () => cierraAjustes() },
1973 { abierta: () => !$('view-overlay').hidden, cerrar: () => closeView({ foco: true }) },
1974 { abierta: () => document.body.classList.contains('drawer-open'), cerrar: () => abreCajon(false) },
1975];
1976document.addEventListener('keydown', e => {
1977 if (e.key !== 'Escape' || e.defaultPrevented || e.isComposing) return;
1978 if (mind.isOpen() || !$('palette').hidden) return; // tienen su propio Escape
1979 if (document.querySelector('dialog[open], #tree-menu, #tab-menu, #conv-menu')) return;
1980 if (e.target.closest?.('.monaco-editor, #terminal-host')) {
1981 // El editor y el terminal usan Escape para lo suyo; solo se cierra una capa
1982 // si no hay nada que cerrar dentro de ellos.
1983 if (!CAPAS.some(c => c.abierta())) return;
1984 }
1985 for (const c of CAPAS) if (c.abierta()) { e.preventDefault(); c.cerrar(); return; }
1986});
1987
1988// ---------- composer estilo plugin: +, /, medidor de contexto, Auto ----------
1989
1990// medidor de contexto: chars del historial / presupuesto (~4 chars/token)
1991//
1992// El presupuesto se le PREGUNTA al proveedor cargado, no se escribe aquí. Era un
1993// 28.000 fijo, calculado para el LFM2.5 de serie, y enseñaba «ctx 0 / 28k» con
1994// cualquier modelo: con el motor propio a 65.536 mentía por más del doble, y al
1995// revés con uno pequeño habría dicho que cabe lo que no cabe. Un número escrito
1996// a mano en la interfaz es un número que se queda viejo — el mismo fallo que la
1997// lista de modelos de los ajustes.
1998const CTX_BUDGET_FALLBACK = 28000; // solo si el proveedor no sabe decirlo
1999let ctxBudgetTok = CTX_BUDGET_FALLBACK;
2000export function setCtxBudget(tokens) {
2001 // Se reserva sitio para el prompt de sistema y para la respuesta: el techo del
2002 // modelo NO es lo que cabe de conversación.
2003 const RESERVA = 4000;
2004 if (Number.isFinite(tokens) && tokens > RESERVA) ctxBudgetTok = tokens - RESERVA;
2005}
2006function updateCtxMeter() {
2007 if (!$('ctx-text')) return; // aún en la landing
2008 const CTX_BUDGET_TOK = ctxBudgetTok;
2009 const chars = (conv.getActive()?.agent.history || []).reduce((s, m) => s + (m.content || '').length, 0);
2010 const tok = Math.round(chars / 4);
2011 const pct = Math.min(100, Math.round(tok / CTX_BUDGET_TOK * 100));
2012 const k = n => n >= 1000 ? (n / 1000).toFixed(1).replace('.0', '') + 'k' : n;
2013 $('ctx-text').textContent = `ctx ${k(tok)} / ${k(CTX_BUDGET_TOK)}`;
2014 $('ctx-bar').style.width = pct + '%';
2015 $('ctx-bar').className = pct > 85 ? 'hot' : '';
2016 // Decía «usa 🧹 para empezar limpio», y no hay ningún 🧹: lo que empieza
2017 // limpio es «+» (nueva conversación) en la barra de pestañas del chat.
2018 $('ctx-meter').title = pct > 85
2019 ? t('ctxFull', { pct })
2020 : t('ctxUse', { tok, max: CTX_BUDGET_TOK, free: 100 - pct });
2021}
2022const _origAdd = addMsg; // refrescar el medidor cuando cambia la conversación
2023addMsg = (...a) => { const r = _origAdd(...a); updateCtxMeter(); return r; };
2024
2025// menú flotante genérico sobre el composer
2026function openMenu(items) {
2027 const menu = $('menu');
2028 menu.replaceChildren();
2029 for (const it of items) {
2030 if (it.sep) { const s = document.createElement('div'); s.className = 'sep'; s.textContent = it.sep; menu.appendChild(s); continue; }
2031 const row = document.createElement('button');
2032 row.className = 'menu-item';
2033 row.innerHTML = `<b>${it.label}</b>${it.hint ? `<span>${it.hint}</span>` : ''}`;
2034 row.onclick = () => { menu.hidden = true; it.run(); };
2035 row.onmouseenter = () => { menuSel = menuFilas().indexOf(row); pintaMenuSel(); };
2036 menu.appendChild(row);
2037 }
2038 menu.hidden = false;
2039 menuSel = menuFilas().length ? 0 : -1;
2040 pintaMenuSel();
2041}
2042
2043// Navegar el menú con el teclado. El keydown del composer se aparta cuando el
2044// menú está abierto «porque el menú ya usa ↑/↓», y era mentira: nadie escuchaba,
2045// así que con el menú abierto las flechas no movían nada y el Enter se quedaba
2046// sin enviar el mensaje y sin elegir fichero. Ahora es verdad.
2047let menuSel = -1;
2048const menuFilas = () => [...$('menu').querySelectorAll('.menu-item')];
2049function pintaMenuSel() {
2050 const filas = menuFilas();
2051 filas.forEach((f, i) => f.classList.toggle('sel', i === menuSel));
2052 if (menuSel >= 0) filas[menuSel]?.scrollIntoView({ block: 'nearest' });
2053}
2054function cierraMenu({ sueltaToken = true } = {}) {
2055 $('menu').hidden = true;
2056 menuSel = -1;
2057 if (sueltaToken) { arrobaDesde = -1; cacheFicheros = null; }
2058}
2059$('prompt').addEventListener('keydown', (e) => {
2060 if ($('menu').hidden) return;
2061 if (e.key === 'Escape') { e.preventDefault(); return cierraMenu(); }
2062 const filas = menuFilas();
2063 if (!filas.length) return;
2064 if (e.key === 'ArrowDown') { e.preventDefault(); menuSel = (menuSel + 1) % filas.length; pintaMenuSel(); }
2065 else if (e.key === 'ArrowUp') { e.preventDefault(); menuSel = (menuSel - 1 + filas.length) % filas.length; pintaMenuSel(); }
2066 else if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); filas[Math.max(0, menuSel)].click(); }
2067});
2068document.addEventListener('click', e => {
2069 if (!e.target.closest('#menu, #btn-slash, #btn-plus')) cierraMenu();
2070});
2071
2072// [/] comandos
2073$('btn-slash').addEventListener('click', () => openMenu([
2074 { sep: t('cmdsSep') },
2075 { label: '/tree', hint: t('slTree'), run: () => send(t('pTree')) },
2076 { label: '/search', hint: t('slSearch'), run: () => { $('prompt').value = t('pSearch'); $('prompt').focus(); } },
2077 { label: '/skills', hint: t('slSkills'), run: () => openSkillsPanel() },
2078 { label: '/model', hint: t('slModel'), run: () => $('btn-settings').click() },
2079 // «/clear» abría una conversación NUEVA (no limpiaba la actual): se llama
2080 // por lo que hace.
2081 { label: '/new', hint: t('slClear'), run: () => conv.create() },
2082]));
2083// Abierto con el ratón desde + o /, el foco pasa al menú (antes se quedaba en
2084// el botón y las flechas no hacían nada); dentro, ↑/↓ recorren las opciones y
2085// Escape vuelve a la caja de texto.
2086function enfocaMenuAlAbrir() {
2087 let n = 0;
2088 const mira = () => {
2089 const primero = $('menu').hidden ? null : $('menu').querySelector('.menu-item');
2090 if (primero) return primero.focus();
2091 if (++n < 60) requestAnimationFrame(mira);
2092 };
2093 requestAnimationFrame(mira);
2094}
2095$('btn-slash').addEventListener('click', enfocaMenuAlAbrir);
2096$('btn-plus').addEventListener('click', enfocaMenuAlAbrir);
2097$('menu').addEventListener('keydown', e => {
2098 const l = [...$('menu').querySelectorAll('.menu-item')], i = l.indexOf(document.activeElement);
2099 if (i < 0) return;
2100 if (e.key === 'ArrowDown') { e.preventDefault(); l[(i + 1) % l.length].focus(); }
2101 else if (e.key === 'ArrowUp') { e.preventDefault(); l[(i - 1 + l.length) % l.length].focus(); }
2102 else if (e.key === 'Home') { e.preventDefault(); l[0].focus(); }
2103 else if (e.key === 'End') { e.preventDefault(); l.at(-1).focus(); }
2104});
2105
2106// [+] adjuntar archivo del proyecto como @ruta
2107// El menú de ficheros, en una función: lo abren el botón `+` Y escribir `@` en
2108// la conversación, que es lo natural y lo que ya prometía el título del botón
2109// («Adjuntar archivo del proyecto (@)») sin que nada lo implementara.
2110//
2111// Y FILTRA mientras escribes. Antes el menú se pintaba una vez al teclear `@` y
2112// se quedaba congelado: las letras siguientes entraban en el textarea y la lista
2113// seguía mostrando los mismos veinte ficheros. Con un árbol de verdad eso es un
2114// menú inútil, porque lo que buscas casi nunca está entre los veinte primeros.
2115let arrobaDesde = -1; // índice del `@` que se está escribiendo, o -1
2116let cacheFicheros = null; // el árbol, leído una vez por sesión de menú
2117
2118// Reconstruye las RUTAS COMPLETAS del árbol. `code.tree` indenta dos espacios
2119// por nivel y marca las carpetas con «📁 », así que la carpeta de un fichero
2120// está en su sangría, no en su línea.
2121//
2122// ⚠️ Esto hacía `l.trim()` sobre cada línea, que es exactamente tirar esa
2123// información: el menú ofrecía «obj_1_Zusammenbau.stl» cuando el fichero real
2124// es «dinos/obj_1_Zusammenbau.stl», y al insertarlo la herramienta fallaba con
2125// «no existe en este proyecto». Lo peor del fallo es que el menú te deja
2126// elegirlo: parece que la ruta está bien hasta que la lees.
2127export function rutasDelArbol(tree) {
2128 const rutas = [];
2129 const pila = [];
2130 for (const linea of String(tree || '').split('\n')) {
2131 if (!linea.trim()) continue;
2132 if (linea.startsWith('…')) continue; // el aviso de árbol recortado
2133 const sangria = linea.length - linea.replace(/^ +/, '').length;
2134 const nivel = Math.floor(sangria / 2);
2135 const texto = linea.trim();
2136 if (texto.startsWith('📁')) {
2137 pila.length = nivel; // salir de las carpetas hermanas
2138 pila.push(texto.replace(/^📁\s*/, ''));
2139 } else {
2140 rutas.push([...pila.slice(0, nivel), texto].join('/'));
2141 }
2142 }
2143 return rutas;
2144}
2145
2146async function listaProyecto() {
2147 if (cacheFicheros) return cacheFicheros;
2148 let tree = '';
2149 try { tree = await codeTools.tree({ depth: 3 }); } catch { /* sin proyecto */ }
2150 const files = rutasDelArbol(tree);
2151 const { currentFile } = codeTools.current();
2152 return (cacheFicheros = { files, currentFile });
2153}
2154
2155async function abreMenuFicheros(frag = '') {
2156 const { files, currentFile } = await listaProyecto();
2157 const q = frag.toLowerCase();
2158 // El filtro va sobre la lista COMPLETA y el recorte a 20 va DESPUÉS. Al revés
2159 // —recortar y luego filtrar, como hacía antes— un fichero en el puesto 50 del
2160 // árbol no aparece nunca, por mucho que escribas su nombre entero.
2161 const casa = (f) => !q || f.toLowerCase().includes(q);
2162 const items = [{ sep: frag ? `${t('attachSep')} · @${frag}` : t('attachSep') }];
2163 if (currentFile && casa(currentFile)) items.push({ label: '@' + currentFile, hint: t('attachOpen'), run: () => attach(currentFile) });
2164 for (const f of files.filter(f => f !== currentFile && casa(f)).slice(0, 20))
2165 items.push({ label: '@' + f, run: () => attach(f) });
2166
2167 if (items.length === 1) {
2168 // Sin coincidencias: el menú se aparta en vez de estorbar con una lista
2169 // vacía, y vuelve solo en cuanto borras una letra y el filtro encaja.
2170 if (frag) { cierraMenu({ sueltaToken: false }); return; }
2171 openMenu([{ sep: t('openProjFirst') }]);
2172 return;
2173 }
2174 openMenu(items);
2175}
2176$('btn-plus').addEventListener('click', () => { arrobaDesde = -1; cacheFicheros = null; abreMenuFicheros(); });
2177
2178// ¿Está el cursor dentro de un `@token`? Se recorre hacia atrás hasta el primer
2179// espacio: así `correo@dominio` no dispara el menú a media palabra (el carácter
2180// previo al `@` no es espacio) y `@` al principio o tras un espacio sí. El
2181// fragmento no puede contener espacios, que es justo donde termina una ruta.
2182function tokenArroba(el) {
2183 const v = el.value, cur = el.selectionStart;
2184 for (let i = cur - 1; i >= 0; i--) {
2185 if (/\s/.test(v[i])) return null;
2186 if (v[i] === '@') {
2187 const previo = i > 0 ? v[i - 1] : '';
2188 return (previo === '' || /\s/.test(previo)) ? { desde: i, frag: v.slice(i + 1, cur) } : null;
2189 }
2190 }
2191 return null;
2192}
2193
2194$('prompt').addEventListener('input', () => {
2195 const tk = tokenArroba($('prompt'));
2196 if (!tk) { if (arrobaDesde >= 0) cierraMenu(); return; }
2197 arrobaDesde = tk.desde;
2198 abreMenuFicheros(tk.frag);
2199});
2200
2201function attach(path) {
2202 const p = $('prompt');
2203 if (arrobaDesde >= 0) {
2204 // Se SUSTITUYE el `@frag` a medio escribir. Añadirlo al final, como antes,
2205 // dejaba `@src/ma @src/main.js` en cuanto el menú empezó a filtrar.
2206 const cola = p.value.slice(p.selectionStart);
2207 const sep = cola.startsWith(' ') ? '' : ' ';
2208 p.value = p.value.slice(0, arrobaDesde) + '@' + path + sep + cola;
2209 const cur = arrobaDesde + 1 + path.length + sep.length;
2210 p.focus();
2211 p.setSelectionRange(cur, cur);
2212 } else {
2213 p.value = (p.value + ' @' + path).trim() + ' ';
2214 p.focus();
2215 }
2216 arrobaDesde = -1;
2217 cacheFicheros = null;
2218}
2219
2220// </> Auto (Edit automatically): si off, pide confirmación antes de escribir
2221let autoEdit = localStorage.getItem('elffusscode.autoedit') !== '0';
2222// Los tres modos se declaran juntos y antes de pintar nada: pintaModos() los
2223// lee todos y se llama ya al pintar Auto.
2224let goalMode = localStorage.getItem('elffusscode.goalmode') === '1';
2225let hardMode = false;
2226function paintAuto() {
2227 const b = $('btn-autoedit');
2228 b.classList.toggle('on', autoEdit);
2229 b.querySelector('.ae-txt').textContent = autoEdit ? t('autoTxt') : t('reviewTxt');
2230 b.title = autoEdit ? t('autoOn') : t('autoOff');
2231 pintaModos();
2232}
2233$('btn-autoedit').addEventListener('click', () => {
2234 autoEdit = !autoEdit;
2235 guardaPref('elffusscode.autoedit', autoEdit ? '1' : '0');
2236 paintAuto();
2237});
2238paintAuto();
2239codeTools.setWriteApprover(async (path, content) => {
2240 if (autoEdit) return true;
2241 return confirm(`Elffuss quiere escribir en «${path}» (${content.split('\n').length} líneas).\n\n¿Aplicar el cambio?`);
2242});
2243
2244function cierraModos({ foco = false } = {}) {
2245 const menu = $('modos-menu');
2246 if (!menu || menu.hidden) return;
2247 menu.hidden = true;
2248 $('btn-modos')?.setAttribute('aria-expanded', 'false');
2249 if (foco) $('btn-modos')?.focus();
2250}
2251// El botón «Modos» lleva los que están encendidos (y el texto del prompt dice
2252// qué va a pasar con lo que escribas).
2253function pintaModos() {
2254 const b = $('btn-modos');
2255 if (!b) return;
2256 const activos = [];
2257 if (!autoEdit) activos.push(['Revisar', t('modeReview')]);
2258 if (goalMode) activos.push(['🎯', t('modeGoal')]);
2259 if (hardMode) activos.push(['⛏', t('modeHard')]);
2260 b.textContent = '⚙︎ ' + t('modesBtn') + (activos.length ? ' · ' + activos.map(a => a[0] === 'Revisar' ? t('reviewTxt') : a[0]).join(' ') : '') + ' ▾';
2261 b.setAttribute('aria-label', t('modesBtn') + (activos.length ? ': ' + activos.map(a => a[1]).join(', ') : ': ' + t('modesNone')));
2262 b.classList.toggle('on', activos.length > 0);
2263 $('btn-autoedit')?.setAttribute('aria-checked', autoEdit ? 'true' : 'false');
2264 $('btn-goal')?.setAttribute('aria-checked', goalMode ? 'true' : 'false');
2265 $('btn-hardwork')?.setAttribute('aria-checked', hardMode ? 'true' : 'false');
2266 $('prompt').placeholder = hardMode ? t('hwPlaceholder') : goalMode ? t('goalPlaceholder') : t('ph');
2267}
2268
2269// 🎯 Goal: el siguiente mensaje que mandes se trata como un OBJETIVO — se
2270// planifica en tareas y se ejecutan una a una (goal.js), en vez del turno de
2271// chat normal. Mismo patrón (interruptor persistente en localStorage) que
2272// </> Auto de arriba.
2273function paintGoal() {
2274 $('btn-goal').classList.toggle('on', goalMode);
2275 pintaModos();
2276}
2277$('btn-goal').addEventListener('click', () => {
2278 goalMode = !goalMode;
2279 guardaPref('elffusscode.goalmode', goalMode ? '1' : '0');
2280 paintGoal();
2281});
2282paintGoal();
2283
2284// ── Hard Work (RLM): lee el proyecto ENTERO por partes ──
2285$('btn-hardwork').addEventListener('click', () => {
2286 hardMode = !hardMode;
2287 $('btn-hardwork').classList.toggle('on', hardMode);
2288 // Al apagarlo vuelve el texto de siempre, en el idioma de la interfaz: antes
2289 // quedaba un «Pídele código a Elffuss…» fijo y en español.
2290 pintaModos();
2291});
2292
2293// Trabaja el proyecto abierto por partes: trocea, pregunta a cada parte y funde.
2294// Corre como un turno MÁS de la conversación (conversations.js → 'hard'): el ■
2295// lo para, la conversación se ve ocupada y la pregunta y la respuesta quedan en
2296// su historial, así que sobreviven a cambiar de pestaña y a recargar. Antes
2297// corría por fuera de la cola: el botón nunca pasaba a ■ y todo vivía solo en
2298// el DOM.
2299conv.setHardWorkRunner(async (c, question, onEvent, { signal }) => {
2300 const hist = c.agent.history;
2301 hist.push({ role: 'user', content: question, ts: Date.now() });
2302 const responde = texto => {
2303 hist.push({ role: 'assistant', content: texto, ts: Date.now() });
2304 onEvent({ type: 'text', text: texto });
2305 };
2306 const parado = () => onEvent({ type: 'aborted', text: '(Parado.)' });
2307 const provider = conv.getProvider();
2308 if (!provider || provider === rules) return responde(t('hwNeedBrain'));
2309 const root = codeTools.handle();
2310 if (!root) return responde(t('hwNeedProject'));
2311 // Cada sub-llamada recibe la parada (corta la generación en curso) y, si ya
2312 // se pulsó ■, la siguiente ni se lanza.
2313 const conParada = {
2314 chat: (h, sys, cb) => signal.aborted
2315 ? Promise.reject(new DOMException('Parado', 'AbortError'))
2316 : provider.chat(h, sys, cb, signal),
2317 };
2318 try {
2319 onEvent({ type: 'progress', text: t('hwReading') });
2320 const context = await gatherFolder(root, { maxBytes: 1.5e6 });
2321 if (signal.aborted) return parado();
2322 if (!context.trim()) return responde(t('hwNoFiles'));
2323 const res = await hardWork({
2324 question, context, provider: conParada,
2325 onProgress: p => {
2326 if (signal.aborted) return;
2327 if (p.phase === 'plan') onEvent({ type: 'progress', text: t('hwPhasePlan', { n: p.chunks, k: Math.round(p.chars / 1000), trim: p.truncated ? t('hwTrimmed') : '' }) });
2328 else if (p.phase === 'map') onEvent({ type: 'progress', text: t('hwPhaseMap', { i: p.i, n: p.n }) });
2329 else if (p.phase === 'reduce-group') onEvent({ type: 'progress', text: t('hwPhaseGroup', { g: p.g, n: p.n }) });
2330 else if (p.phase === 'reduce') onEvent({ type: 'progress', text: t('hwPhaseReduce') });
2331 },
2332 });
2333 if (signal.aborted) return parado();
2334 responde(res.answer + '\n\n_' + t('hwResult', { n: res.chunks, k: res.kept }) + (res.truncated ? t('hwResultTrunc') : '') + '_');
2335 } catch (e) {
2336 if (signal.aborted || e?.name === 'AbortError') return parado();
2337 const texto = t('hwFailed', { e: e?.message || String(e) });
2338 hist.push({ role: 'assistant', content: texto, ts: Date.now() });
2339 onEvent({ type: 'error', text: texto });
2340 }
2341});
2342
2343// resolver @rutas del mensaje: se leen y se adjuntan como contexto
2344const _send = send;
2345send = async (text) => {
2346 if (hardMode) return _send(text, 'hard');
2347 const refs = [...text.matchAll(/@([\w./-]+\.\w+)/g)].map(m => m[1]);
2348 if (refs.length) {
2349 let ctx = '';
2350 for (const r of [...new Set(refs)].slice(0, 4)) {
2351 try { ctx += `\n\n--- ${r} ---\n${await codeTools.read({ path: r })}`; } catch { /* ignora */ }
2352 }
2353 if (ctx) text += '\n\n[archivos adjuntos]' + ctx;
2354 }
2355 _send(text);
2356};
2357
2358// ---------- panel de skills (transparente: repo + lista + SKILL.md) ----------
2359// Mismo diálogo que Ajustes. Los fallos se dicen DENTRO del panel, en palabras
2360// de persona y con «Reintentar» (antes: «⚠️ FAILED TO FETCH» en mayúsculas, y
2361// un alert() del navegador al añadir un repo que no valía o al instalar).
2362async function openSkillsPanel() {
2363 const box = settingsShell(t('skTitle'));
2364 const wrap = document.createElement('div');
2365 wrap.className = 'skills-panel';
2366 const intro = document.createElement('p');
2367 intro.className = 'muted';
2368 intro.textContent = t('skIntro');
2369 wrap.appendChild(intro);
2370 box.appendChild(wrap);
2371
2372 // instaladas
2373 const inst = skills.installed();
2374 const instBox = document.createElement('div');
2375 instBox.append(el('div', 'sk-h', t('skInstalled', { n: inst.length })));
2376 for (const s of inst) {
2377 const row = document.createElement('div');
2378 row.className = 'sk-row';
2379 row.append(el('b', null, s.name), el('span', 'muted', s.repo || 'local'));
2380 const rm = document.createElement('button');
2381 rm.className = 'ghost'; rm.textContent = t("skRemove");
2382 rm.setAttribute('aria-label', t('skRemoveNamed', { name: s.name }));
2383 rm.onclick = async () => { await skills.remove(s.name); openSkillsPanel(); };
2384 row.appendChild(rm);
2385 instBox.appendChild(row);
2386 }
2387 if (!inst.length) instBox.append(el('p', 'muted', t('skNone')));
2388 box.appendChild(instBox);
2389
2390 // fuentes + añadir repo
2391 const srcs = await skills.sources();
2392 const srcBox = document.createElement('div');
2393 srcBox.append(el('div', 'sk-h', t('skCatalogs')));
2394 for (const s of srcs) {
2395 const row = document.createElement('div');
2396 row.className = 'sk-row';
2397 const a = document.createElement('a');
2398 a.href = `https://github.com/${s.repo}`; a.target = '_blank'; a.rel = 'noopener noreferrer';
2399 a.textContent = s.repo + ' ↗';
2400 row.append(el('b', null, s.label), a);
2401 const browse = document.createElement('button');
2402 browse.className = 'primary'; browse.textContent = t("skBrowse");
2403 browse.onclick = () => browseRepo(s.repo, box);
2404 row.appendChild(browse);
2405 if (!s.official) {
2406 const rm = document.createElement('button');
2407 rm.className = 'ghost'; rm.textContent = '🗑';
2408 rm.setAttribute('aria-label', t('skRemoveRepo', { repo: s.repo }));
2409 rm.onclick = async () => { await skills.removeSource(s.repo); openSkillsPanel(); };
2410 row.appendChild(rm);
2411 }
2412 srcBox.appendChild(row);
2413 }
2414 const addRow = document.createElement('div');
2415 addRow.className = 'sk-row';
2416 const inp = document.createElement('input');
2417 inp.placeholder = t("skAddRepoPh");
2418 inp.setAttribute('aria-label', t('skAddRepo'));
2419 const add = document.createElement('button');
2420 add.className = 'primary'; add.textContent = t("skAddRepo");
2421 const addMsg2 = el('div', 'muted sk-msg'); addMsg2.setAttribute('role', 'status');
2422 add.onclick = async () => {
2423 addMsg2.textContent = '';
2424 try { await skills.addSource(inp.value); openSkillsPanel(); }
2425 catch (e) { addMsg2.textContent = '⚠️ ' + (e?.message || e); addMsg2.classList.add('err'); inp.focus(); }
2426 };
2427 inp.addEventListener('keydown', e => { if (e.key === 'Enter') add.click(); });
2428 addRow.append(inp, add);
2429 srcBox.append(addRow, addMsg2);
2430 box.appendChild(srcBox);
2431}
2432
2433async function browseRepo(repo, box) {
2434 box.querySelector(`.sk-browse[data-repo="${CSS.escape(repo)}"]`)?.remove();
2435 const list = document.createElement('div');
2436 list.className = 'sk-browse';
2437 list.dataset.repo = repo;
2438 list.setAttribute('aria-live', 'polite');
2439 list.append(el('div', 'sk-h', t('skLoading', { repo })));
2440 box.appendChild(list);
2441 try {
2442 const found = await skills.listFromRepo(repo);
2443 list.replaceChildren(el('div', 'sk-h', t('skFound', { repo, n: found.length })));
2444 for (const sk of found.slice(0, 120)) {
2445 const row = document.createElement('div');
2446 row.className = 'sk-row';
2447 row.append(el('b', null, sk.name), el('span', 'muted', sk.dir));
2448 const btn = document.createElement('button');
2449 const on = skills.isInstalled(sk.repo, sk.path);
2450 btn.className = on ? 'ghost' : 'primary';
2451 btn.textContent = on ? t('skInstalledOne') : t('skInstall');
2452 btn.setAttribute('aria-label', (on ? t('skInstalledOne') : t('skInstall')) + ': ' + sk.name);
2453 btn.onclick = async () => {
2454 btn.textContent = '…'; btn.disabled = true;
2455 try {
2456 const entry = await skills.installFromRepo(sk);
2457 btn.textContent = t('skInstalledOne'); btn.className = 'ghost';
2458 cierraAjustes(); // cierra el panel
2459 addMsg('assistant', skills.usageMessage(entry)); // «cómo usarla» en el chat
2460 } catch (e) {
2461 btn.textContent = t('skInstall'); btn.disabled = false;
2462 row.append(el('span', 'muted sk-msg err', '⚠️ ' + (e?.message || e)));
2463 }
2464 };
2465 row.appendChild(btn);
2466 list.appendChild(row);
2467 }
2468 } catch (e) {
2469 const msg = /Failed to fetch|NetworkError|network/i.test(String(e?.message)) ? t('skNoNet', { repo }) : t('skLoadFailed', { repo, e: e?.message || e });
2470 const retry = document.createElement('button');
2471 retry.className = 'primary'; retry.textContent = t('retry');
2472 retry.onclick = () => browseRepo(repo, box);
2473 const fila = el('div', 'sk-row');
2474 fila.append(el('span', 'sk-msg err', '⚠️ ' + msg), retry);
2475 list.replaceChildren(el('div', 'sk-h', repo), fila);
2476 }
2477}
2478
2479// ---------- command palette (Cmd/Ctrl+P) ----------
2480let palItems = [], palSel = 0;
2481const COMMANDS = [
2482 { label: t('newConv'), run: () => conv.create() },
2483 { label: t('tHistory'), run: () => $('btn-history').click() },
2484 { label: t('pSearchCode'), run: () => openPalette('#') },
2485 { label: t('pManageSkills'), run: () => { closePalette(); openSkillsPanel(); } },
2486 { label: t('tActSettings'), run: () => { closePalette(); renderSettings(); } },
2487 { label: t('pToggleExplorer'), run: () => $('act-files').click() },
2488 { label: t('pToggleTerm'), hint: 'Ctrl+`', run: () => { closePalette(); toggleTerminal(); } },
2489 { label: t('pSave', { k: atajo('S') }), run: () => saveActive() },
2490 { label: t('mLab'), run: () => abrirLab() },
2491];
2492// El banco de pruebas (lab.html) existía pero no había forma de llegar a él
2493// desde el IDE: solo escribiendo la URL. Se abre en otra pestaña para no
2494// dejar a medias lo que tengas aquí.
2495function abrirLab() { window.open('lab.html', '_blank', 'noopener'); }
2496
2497// La paleta es un combobox con su lista (role=listbox, opción activa en
2498// aria-activedescendant), así un lector de pantalla sigue la selección.
2499let volverDePaleta = null;
2500function openPalette(prefix = '') {
2501 if ($('palette').hidden) volverDePaleta = document.activeElement;
2502 $('palette').hidden = false;
2503 const inp = $('pal-input');
2504 inp.setAttribute('role', 'combobox');
2505 inp.setAttribute('aria-controls', 'pal-list');
2506 inp.setAttribute('aria-expanded', 'true');
2507 inp.setAttribute('aria-autocomplete', 'list');
2508 $('pal-list').setAttribute('role', 'listbox');
2509 inp.value = prefix;
2510 inp.focus();
2511 renderPalette();
2512}
2513function closePalette() {
2514 if ($('palette').hidden) return;
2515 $('palette').hidden = true;
2516 $('pal-input').setAttribute('aria-expanded', 'false');
2517 const v = volverDePaleta; volverDePaleta = null;
2518 if (v && document.body.contains(v) && document.activeElement === $('pal-input')) v.focus?.();
2519}
2520
2521function fuzzy(q, s) {
2522 q = q.toLowerCase(); s = s.toLowerCase();
2523 let i = 0, score = 0, streak = 0;
2524 for (const ch of s) {
2525 if (i < q.length && ch === q[i]) { i++; streak++; score += streak; }
2526 else streak = 0;
2527 }
2528 return i === q.length ? score + (s.endsWith(q) ? 20 : 0) : -1;
2529}
2530
2531// «#texto»: busca DENTRO de los ficheros (code.search) y lista cada resultado
2532// como fichero:línea; Enter lo abre en esa línea. Es lo que hace ahora Edit ›
2533// Buscar en el código (antes solo escribía «busca » en el chat).
2534let palSeq = 0, palBusca = null;
2535async function resultadosBusqueda(q) {
2536 const out = await codeTools.search({ query: q }).catch(e => 'ERROR: ' + e.message);
2537 const items = [];
2538 for (const linea of String(out).split('\n')) {
2539 const m = linea.match(/^(.+?):(\d+): (.*)$/);
2540 if (m) items.push({ label: m[3] || '·', hint: `${m[1]}:${m[2]}`, run: () => { closePalette(); openFile(m[1]).then(() => gotoLine(+m[2])); } });
2541 }
2542 const nota = String(out).split('\n').find(l => l.startsWith('…') || l.startsWith('Sin resultados') || l.startsWith('ERROR'));
2543 return { items, nota };
2544}
2545
2546async function renderPalette() {
2547 const raw = $('pal-input').value;
2548 const list = $('pal-list');
2549 const seq = ++palSeq;
2550 palItems = [];
2551 let nota = '';
2552
2553 if (raw.startsWith('#')) { // buscar en el código
2554 const q = raw.slice(1).trim();
2555 if (q.length < 2) nota = t('palSearchHint');
2556 else {
2557 clearTimeout(palBusca);
2558 await new Promise(r => { palBusca = setTimeout(r, 180); });
2559 if (seq !== palSeq) return; // se siguió escribiendo
2560 const r = await resultadosBusqueda(q);
2561 if (seq !== palSeq) return;
2562 palItems = r.items.slice(0, 60);
2563 nota = r.nota || '';
2564 }
2565 } else if (raw.startsWith('>')) { // comandos
2566 const q = raw.slice(1).trim().toLowerCase();
2567 // Todo comando cierra la paleta al ejecutarse: «Nueva conversación», por
2568 // ejemplo, la dejaba abierta encima.
2569 palItems = COMMANDS.filter(c => c.label.toLowerCase().includes(q)).map(c => ({ label: c.label, hint: t('palCmd'), run: () => { closePalette(); c.run(); } }));
2570 } else if (raw.startsWith('@')) { // símbolos del archivo abierto (Monaco)
2571 palItems = [{ label: t('palGotoSym'), hint: '@', run: () => { closePalette(); conFichero(() => triggerEditor('editor.action.quickOutline'))(); } }];
2572 } else { // archivos (con :línea opcional)
2573 const [pathQ, lineQ] = raw.split(':');
2574 const files = await codeTools.fileList().catch(() => []);
2575 const scored = pathQ.trim()
2576 ? 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)
2577 : files.slice(0, 40).map(f => ({ f, s: 0 }));
2578 palItems = scored.slice(0, 40).map(({ f }) => ({
2579 label: f.split('/').pop(), hint: f, icon: true,
2580 run: () => { closePalette(); openFile(f); if (lineQ && +lineQ) setTimeout(() => gotoLine(+lineQ), 300); },
2581 }));
2582 }
2583 if (seq !== palSeq) return;
2584 list.replaceChildren();
2585 palSel = 0;
2586 palItems.forEach((it, i) => {
2587 const row = el('button', 'pal-item' + (i === 0 ? ' sel' : ''));
2588 row.type = 'button';
2589 row.id = 'pal-opt-' + i;
2590 row.setAttribute('role', 'option');
2591 row.setAttribute('aria-selected', i === 0 ? 'true' : 'false');
2592 row.tabIndex = -1;
2593 row.innerHTML = '<span class="pi-name"></span><span class="pi-hint"></span>';
2594 row.querySelector('.pi-name').textContent = it.label;
2595 row.querySelector('.pi-hint').textContent = it.hint || '';
2596 row.onmouseenter = () => { palSel = i; paintPalSel(); };
2597 row.onclick = () => it.run();
2598 list.appendChild(row);
2599 });
2600 if (!palItems.length) list.appendChild(el('div', 'pal-empty', nota || t('palEmpty')));
2601 else if (nota) list.appendChild(el('div', 'pal-empty', nota));
2602 paintPalSel();
2603}
2604function paintPalSel() {
2605 [...$('pal-list').querySelectorAll('.pal-item')].forEach((c, i) => { c.classList.toggle('sel', i === palSel); c.setAttribute('aria-selected', i === palSel ? 'true' : 'false'); });
2606 const opt = $('pal-list').querySelector('#pal-opt-' + palSel);
2607 if (opt) { $('pal-input').setAttribute('aria-activedescendant', opt.id); opt.scrollIntoView({ block: 'nearest' }); }
2608 else $('pal-input').removeAttribute('aria-activedescendant');
2609}
2610$('pal-input').addEventListener('input', renderPalette);
2611$('pal-input').addEventListener('keydown', e => {
2612 if (e.key === 'Escape') return closePalette();
2613 if (e.key === 'ArrowDown') { e.preventDefault(); palSel = Math.min(palSel + 1, palItems.length - 1); paintPalSel(); }
2614 if (e.key === 'ArrowUp') { e.preventDefault(); palSel = Math.max(palSel - 1, 0); paintPalSel(); }
2615 if (e.key === 'Enter') { e.preventDefault(); palItems[palSel]?.run(); }
2616});
2617document.addEventListener('keydown', e => {
2618 if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'p') { e.preventDefault(); openPalette(e.shiftKey ? '>' : ''); }
2619 if (e.key === 'Escape' && !$('palette').hidden) closePalette();
2620});
2621// Cerrar la paleta al pulsar fuera, PERO no cuando el clic viene del menú: es
2622// el menú el que la abre («Go to file»), y sin esta excepción el mismo clic la
2623// abría y la cerraba — el `onclick` del item la mostraba y acto seguido el
2624// evento seguía burbujeando hasta aquí, donde el target es el item del menú,
2625// que no está dentro de #palette. Con Cmd+P funcionaba porque es teclado y no
2626// pasa por este camino, y por eso parecía que «el atajo sí y el menú no».
2627document.addEventListener('click', e => {
2628 if (!e.target.closest('#palette, #menubar, #topmenu')) closePalette();
2629});
2630
2631// ---------- barra de menú File/Edit/View/Git ----------
2632async function menuFor(which) {
2633 if (which === 'file') return [
2634 { label: t('mNewFile'), run: () => { const p = prompt(t('promptNewPath')); if (p) codeTools.write({ path: p, content: '' }).then(() => { openFile(p); refreshTree(); }); } },
2635 { label: t('mSave'), hint: atajo('S'), run: () => saveActive() },
2636 { label: t('mOpenFolder'), run: async () => {
2637 // Cambiar de carpeta con la elfa a medias deja su trabajo sobre el
2638 // proyecto anterior: se pregunta antes.
2639 if (conv.isBusy() && !confirm(t('openFolderBusy'))) return;
2640 let handle;
2641 try { handle = await window.showDirectoryPicker({ mode: 'readwrite' }); }
2642 catch (e) { if (e?.name !== 'AbortError') $('statusbar').textContent = '⚠️ ' + t('openFolderFailed', { e: e?.message || e }); return; }
2643 try { await enterIDE(handle); } catch (e) { avisaFalloApertura(e); }
2644 } },
2645 ];
2646 if (which === 'edit') return [
2647 { label: t('mSearchCode'), hint: '#', run: () => openPalette('#') },
2648 { label: t('mGotoFile'), hint: atajo('P'), run: () => openPalette('') },
2649 { label: t('mGotoSym'), run: conFichero(() => triggerEditor('editor.action.quickOutline')) },
2650 ];
2651 if (which === 'view') return [
2652 { label: t('tFiles'), run: () => $('act-files').click() },
2653 { label: t('mTerminal'), hint: 'Ctrl+`', run: () => toggleTerminal(true) },
2654 { label: t('mArch'), run: () => openView('arch') },
2655 { label: t('tCity'), run: () => openView('city') },
2656 { label: t('mPalette'), hint: atajo('P', true), run: () => openPalette('>') },
2657 { label: 'Skills', run: () => openSkillsPanel() },
2658 { label: t('mLab'), hint: '↗', run: () => abrirLab() },
2659 { label: t('mAbout'), hint: '↗', run: () => window.open('https://github.com/KikoCis/elffuss-code', '_blank', 'noopener') },
2660 ];
2661 if (which === 'git') {
2662 // Rama y último commit enlazan al remoto (sin credenciales) cuando lo hay;
2663 // si no, se ven como texto desactivado. Antes parecían opciones y no hacían
2664 // nada. El commit enseña su SHA corto; el correo del autor, nunca.
2665 const g = await codeTools.gitInfo();
2666 if (!g.isRepo) return [{ label: t('gNotRepo'), disabled: true }];
2667 const abre = url => () => window.open(url, '_blank', 'noopener,noreferrer');
2668 const items = [g.web
2669 ? { label: t('gBranch', { b: g.branch }), hint: '↗', title: g.web.branch(g.branch), run: abre(g.web.branch(g.branch)) }
2670 : { label: t('gBranch', { b: g.branch }), hint: t('gNoRemote'), disabled: true }];
2671 if (g.lastCommit) {
2672 const corto = g.lastCommit.sha ? g.lastCommit.sha.slice(0, 7) + ' · ' : '';
2673 const label = t('gLast', { m: corto + g.lastCommit.msg.slice(0, 40) });
2674 items.push(g.web && g.lastCommit.sha
2675 ? { label, hint: '↗', title: g.web.commit(g.lastCommit.sha), run: abre(g.web.commit(g.lastCommit.sha)) }
2676 : { label, hint: g.lastCommit.author, disabled: true });
2677 }
2678 // Pide al agente el MENSAJE de commit: commitear de verdad no puede (el git
2679 // de aquí es de solo lectura), y la etiqueta vieja lo prometía.
2680 items.push({ label: t('gCommit'), run: () => { $('prompt').value = t('pCommit'); $('prompt').focus(); } });
2681 return items;
2682 }
2683 return [];
2684}
2685// La barra de menús se usa con el teclado como una de verdad (patrón
2686// menubar/menu): ↓, Enter o Espacio abren el menú con el foco en su primera
2687// opción; ←/→ pasan al menú de al lado; ↑/↓ recorren; Escape cierra y devuelve
2688// el foco; Tab sale. Antes ↓ no entraba en el menú y Escape no lo cerraba. Los
2689// nombres salen en el idioma de la interfaz.
2690const barraMenus = () => [...document.querySelectorAll('#menubar button')];
2691let menuBarraAbierto = null;
2692{
2693 const bar = $('menubar');
2694 bar.setAttribute('role', 'menubar');
2695 bar.setAttribute('aria-label', t('menubarLabel'));
2696 barraMenus().forEach((b, i) => {
2697 b.setAttribute('role', 'menuitem');
2698 b.setAttribute('aria-haspopup', 'menu');
2699 b.setAttribute('aria-expanded', 'false');
2700 b.textContent = t('menu_' + b.dataset.menu);
2701 b.tabIndex = i === 0 ? 0 : -1;
2702 b.addEventListener('click', () => (menuBarraAbierto === b ? cierraMenuBarra({ foco: true }) : abreMenuBarra(b)));
2703 b.addEventListener('keydown', e => {
2704 const lista = barraMenus(), j = lista.indexOf(b);
2705 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 }); };
2706 if (e.key === 'ArrowRight') { e.preventDefault(); mueve(1); }
2707 else if (e.key === 'ArrowLeft') { e.preventDefault(); mueve(-1); }
2708 else if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') { e.preventDefault(); abreMenuBarra(b, { foco: true }); }
2709 });
2710 });
2711}
2712async function abreMenuBarra(b, { foco = false } = {}) {
2713 barraMenus().forEach(x => { x.classList.toggle('open', x === b); x.setAttribute('aria-expanded', x === b ? 'true' : 'false'); });
2714 menuBarraAbierto = b;
2715 openMenuAt(await menuFor(b.dataset.menu), b);
2716 if (menuBarraAbierto !== b) return; // otro menú se abrió mientras tanto
2717 if (foco) $('topmenu').querySelector('[role="menuitem"]:not([aria-disabled="true"])')?.focus();
2718}
2719function cierraMenuBarra({ foco = false } = {}) {
2720 const b = menuBarraAbierto;
2721 $('topmenu').hidden = true;
2722 barraMenus().forEach(x => { x.classList.remove('open'); x.setAttribute('aria-expanded', 'false'); });
2723 menuBarraAbierto = null;
2724 if (foco && b) b.focus();
2725}
2726function openMenuAt(items, anchor) {
2727 const menu = $('topmenu');
2728 const r = anchor.getBoundingClientRect();
2729 menu.style.left = r.left + 'px';
2730 menu.style.top = (r.bottom + 3) + 'px';
2731 menu.replaceChildren();
2732 menu.setAttribute('role', 'menu');
2733 menu.setAttribute('aria-label', anchor.textContent);
2734 for (const it of items) {
2735 const row = el('button', 'menu-item');
2736 row.type = 'button';
2737 row.setAttribute('role', 'menuitem');
2738 row.tabIndex = -1;
2739 row.innerHTML = `<b></b>${it.hint ? '<span></span>' : ''}`;
2740 row.querySelector('b').textContent = it.label;
2741 if (it.hint) row.querySelector('span').textContent = it.hint;
2742 if (it.title) row.title = it.title;
2743 if (it.disabled) { row.setAttribute('aria-disabled', 'true'); row.classList.add('disabled'); }
2744 // stopPropagation: el clic no debe seguir hasta los «clic fuera» del
2745 // documento, que cerraban al instante lo que la opción acababa de abrir
2746 // (la paleta con «Ir a archivo…» o «Buscar en el código»).
2747 row.onclick = (e) => { e.stopPropagation(); if (it.disabled) return; cierraMenuBarra(); it.run(); };
2748 menu.appendChild(row);
2749 }
2750 menu.hidden = false;
2751}
2752$('topmenu').addEventListener('keydown', e => {
2753 const filas = [...$('topmenu').querySelectorAll('[role="menuitem"]')];
2754 const i = filas.indexOf(document.activeElement);
2755 const ve = k => { e.preventDefault(); filas[(i + k + filas.length) % filas.length]?.focus(); };
2756 if (e.key === 'ArrowDown') ve(1);
2757 else if (e.key === 'ArrowUp') ve(-1);
2758 else if (e.key === 'Home') { e.preventDefault(); filas[0]?.focus(); }
2759 else if (e.key === 'End') { e.preventDefault(); filas.at(-1)?.focus(); }
2760 else if (e.key === 'Escape') { e.preventDefault(); cierraMenuBarra({ foco: true }); }
2761 else if (e.key === 'Tab') cierraMenuBarra();
2762 else if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
2763 e.preventDefault();
2764 const lista = barraMenus(), j = lista.indexOf(menuBarraAbierto);
2765 const n = lista[(j + (e.key === 'ArrowRight' ? 1 : -1) + lista.length) % lista.length];
2766 lista.forEach(x => { x.tabIndex = x === n ? 0 : -1; });
2767 abreMenuBarra(n, { foco: true });
2768 }
2769});
2770document.addEventListener('click', e => {
2771 if (!e.target.closest('#menubar, #topmenu') && !$('topmenu').hidden) cierraMenuBarra();
2772});
2773
2774// ---------- git en el header ----------
2775async function refreshGit() {
2776 const g = await codeTools.gitInfo().catch(() => ({ isRepo: false }));
2777 const chip = $('git-branch');
2778 if (g.isRepo) { chip.hidden = false; chip.innerHTML = UI.code + ' ' + g.branch; }
2779 else chip.hidden = true;
2780}
2781$('git-branch').addEventListener('click', () => document.querySelector('#menubar button[data-menu="git"]').click());
2782
2783// icono de skills en la barra de actividad
2784$('act-skills').innerHTML = UI.puzzle;
2785$('act-skills').addEventListener('click', () => openSkillsPanel());
2786
2787rebuildSelect();
2788skills.initSkills();
2789boot();
2790window.elffussClaw = { conv, get agent() { return conv.getActive()?.agent; }, send, openFile, parseToolCall, skills };
2791
2792
2793// ---------- puerta de móvil y chip de disco ----------
2794// Declaradas con `function` para que se icen: preloadModel() las usa y está
2795// escrita más arriba en el fichero.
2796function avisoMovil(tam, onAccept) {
2797 // Se pinta FIJO sobre la pantalla, no dentro del layout: cuando esto corre,
2798 // #chat todavía no existe (Code construye su interfaz después), así que caía
2799 // al body y el propio layout lo tapaba — presente en el DOM y invisible para
2800 // el usuario, que es la peor variante de un aviso.
2801 const box = document.createElement('div');
2802 box.style.cssText = 'position:fixed;left:50%;bottom:16px;transform:translateX(-50%);z-index:99999;'
2803 + 'width:min(92vw,520px);padding:16px;border:1px solid #3a3a4a;border-radius:14px;'
2804 + 'background:#15161f;color:#eae8f2;box-shadow:0 18px 50px -18px rgba(0,0,0,.8);'
2805 + 'display:flex;flex-direction:column;gap:8px;font:14px/1.5 system-ui,sans-serif';
2806 const h = document.createElement('b'); h.textContent = '📱 En el móvil todavía no funciona';
2807 const p1 = document.createElement('span'); p1.style.opacity = '.75';
2808 p1.textContent = 'Elffuss Code ejecuta el modelo dentro de tu propio navegador. En el móvil eso hoy no sale bien: '
2809 + 'habría que descargar ' + tam + ' y el navegador suele cerrar la pestaña antes de terminar. '
2810 + 'Así que no te lo descargo sin preguntar.';
2811 const p2 = document.createElement('span'); p2.style.opacity = '.75';
2812 p2.textContent = 'Ábrelo en un ordenador y sí funciona: ahí es donde vive.';
2813 const fila = document.createElement('div');
2814 fila.style.cssText = 'display:flex;gap:8px;flex-wrap:wrap';
2815 const b = document.createElement('button');
2816 b.style.cssText = 'flex:1;padding:9px 12px;border-radius:9px;border:1px solid #4a4a5e;background:#22232f;color:inherit;font:inherit;cursor:pointer';
2817 b.textContent = 'Descargarlo igualmente (' + tam + ')';
2818 b.onclick = () => { try { localStorage.setItem('elffusscode.movil.ok', '1'); } catch {} box.remove(); onAccept(); };
2819 const x = document.createElement('button');
2820 x.style.cssText = 'padding:9px 12px;border-radius:9px;border:1px solid #4a4a5e;background:transparent;color:inherit;font:inherit;cursor:pointer';
2821 x.textContent = 'Entendido';
2822 x.onclick = () => box.remove();
2823 fila.append(b, x);
2824 box.append(h, p1, p2, fila);
2825 document.body.appendChild(box);
2826}
2827
2828// Tamaño legible: MB por debajo de 1 GB.
2829function tamano(n) { return n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : Math.round(n / 1048576) + ' MB'; }
2830
2831// Vaciar los modelos guardados: lo usan el chip 💾 y «Vaciar caché» de Ajustes.
2832// Devuelve el mensaje con lo que pasó (o null si el usuario canceló).
2833async function vaciarModelos(boton) {
2834 const m = await modelUsage();
2835 if (!confirm(t('clearModelsConfirm', { size: tamano(m.total) }) + (m.sharedOk ? '' : '\n\n' + t('clearModelsShared')))) return null;
2836 const antes = boton.textContent;
2837 boton.disabled = true; boton.setAttribute('aria-busy', 'true');
2838 boton.textContent = t('setClearing');
2839 let r;
2840 try { r = await clearModels(); }
2841 finally { boton.disabled = false; boton.removeAttribute('aria-busy'); boton.textContent = antes; }
2842 let msg = t('clearModelsDone', { size: tamano(r.liberado) });
2843 if (r.fallos.length) msg += ' ' + t('clearModelsFailed', { what: r.fallos.join(' · ') });
2844 if (!r.sharedOk) msg += ' ' + t('clearModelsShared');
2845 $('statusbar').textContent = msg;
2846 return msg;
2847}
2848
2849// Chip 💾: lo que ocupan los MODELOS (no el origen entero, que mezclaba
2850// conversaciones y el proyecto de prueba) y un clic para vaciarlos.
2851function mountDiskChip() {
2852 const chip = document.getElementById('disk-chip');
2853 if (!chip) return;
2854 async function paint() {
2855 const { quota } = await cacheEstimate();
2856 const m = await modelUsage();
2857 if (!m.total) { chip.hidden = true; return; }
2858 chip.hidden = false;
2859 chip.textContent = '💾 ' + tamano(m.total);
2860 chip.title = t('diskChipTitle', { size: tamano(m.total), quota: quota ? t('diskChipQuota', { quota: tamano(quota) }) : '' })
2861 + (m.sharedOk ? '' : t('setSharedUnknown'));
2862 }
2863 chip.addEventListener('click', async () => {
2864 const msg = await vaciarModelos(chip);
2865 if (msg) await paint();
2866 });
2867 paint();
2868 setInterval(paint, 20000);
2869}
2870mountDiskChip();
2871
2872// ── Compositor: menú de modos, ancho del chat y caja que crece ──────────────
2873// Los tres botones de modo siguen siendo los mismos elementos con los mismos
2874// ids: lo único que cambia es que viven dentro de un desplegable. Así el JS que
2875// ya los escuchaba no se entera de nada.
2876{
2877 const modos = $('btn-modos'), menu = $('modos-menu');
2878 if (modos && menu) {
2879 // Cada modo lleva DEBAJO lo que hace. El texto sale del `title` que ya
2880 // tenía el botón: estaba escrito y bien, pero solo lo veía quien dejara el
2881 // ratón quieto encima — o sea casi nadie, y en móvil nadie. «Auto», «Goal»
2882 // y «Hard Work» sueltos no dicen nada a quien llega nuevo.
2883 for (const b of menu.querySelectorAll('.cbtn')) {
2884 const que = b.getAttribute('title');
2885 if (!que || b.querySelector('.modo-que')) continue;
2886 const span = document.createElement('span');
2887 span.className = 'modo-que';
2888 // Cortar por el primer paréntesis dejaba «Hard Work (RLM): lee tu
2889 // proyecto…» en «Hard Work», o sea una explicación que repite el nombre
2890 // del botón y no explica nada. Lo que sobra es el PREFIJO —«Nombre
2891 // (SIGLAS):»— no lo que viene detrás, que es justo la frase útil.
2892 span.textContent = que
2893 .replace(/^[^:]{0,40}:\s*/, '') // fuera «Hard Work (RLM): »
2894 .split('.')[0] // la primera frase
2895 .replace(/\s*\([^)]*\)\s*/g, ' ') // sin incisos entre paréntesis
2896 .replace(/\s+/g, ' ')
2897 .trim()
2898 .slice(0, 120);
2899 b.appendChild(span);
2900 // Ya está a la vista: dejar el title duplicaría el texto en un tooltip.
2901 b.removeAttribute('title');
2902 }
2903 // Menú con casillas: cada modo dice si está encendido (aria-checked) y el
2904 // botón «Modos» enseña cuáles lo están, también cerrado. Antes cualquier
2905 // clic dentro cerraba el menú y desde fuera no había forma de saber que
2906 // Goal o Hard Work seguían activos (y las preguntas normales se volvían
2907 // planes sin avisar). Ahora pulsar un modo lo cambia y el menú se queda
2908 // abierto para verlo; se cierra al pulsar fuera o con Escape.
2909 modos.setAttribute('aria-haspopup', 'menu');
2910 modos.setAttribute('aria-expanded', 'false');
2911 menu.setAttribute('role', 'menu');
2912 menu.setAttribute('aria-label', t('modesLabel'));
2913 for (const b of menu.querySelectorAll('.cbtn')) b.setAttribute('role', 'menuitemcheckbox');
2914 modos.addEventListener('click', (e) => {
2915 e.stopPropagation();
2916 if (menu.hidden) { menu.hidden = false; modos.setAttribute('aria-expanded', 'true'); menu.querySelector('.cbtn')?.focus(); }
2917 else cierraModos({ foco: false });
2918 });
2919 menu.addEventListener('keydown', (e) => {
2920 const opciones = [...menu.querySelectorAll('.cbtn')], i = opciones.indexOf(document.activeElement);
2921 if (e.key === 'ArrowDown') { e.preventDefault(); opciones[(i + 1) % opciones.length]?.focus(); }
2922 else if (e.key === 'ArrowUp') { e.preventDefault(); opciones[(i - 1 + opciones.length) % opciones.length]?.focus(); }
2923 else if (e.key === 'Tab') cierraModos({ foco: false });
2924 });
2925 document.addEventListener('click', (e) => {
2926 if (!e.target.closest('#modos') && !menu.hidden) cierraModos({ foco: false });
2927 });
2928 pintaModos();
2929 }
2930
2931 // El chat a toda la ventana. Al editor se le da cero de ancho en vez de
2932 // quitarlo: volver es instantáneo y no se pierde lo que hubiera abierto.
2933 const ancho = $('btn-ancho');
2934 if (ancho) {
2935 const pinta = () => {
2936 const full = document.body.classList.contains('chat-full');
2937 ancho.textContent = full ? '⇥' : '⇔';
2938 ancho.title = full ? 'Recuperar el editor' : 'Ensanchar el chat a toda la ventana';
2939 };
2940 try { if (localStorage.getItem('elffusscode.chatfull') === '1') document.body.classList.add('chat-full'); }
2941 catch { /* sin localStorage se queda como está */ }
2942 pinta();
2943 ancho.addEventListener('click', () => {
2944 document.body.classList.toggle('chat-full');
2945 try { localStorage.setItem('elffusscode.chatfull', document.body.classList.contains('chat-full') ? '1' : '0'); }
2946 catch { /* — */ }
2947 pinta();
2948 });
2949 }
2950
2951 // La caja crece con el texto hasta el tope que pone el CSS. Se recalcula
2952 // desde cero (`auto`) antes de medir: si no, una vez crecida ya no encoge al
2953 // borrar, y acaba ocupando media pantalla vacía.
2954 const caja = $('prompt');
2955 if (caja && caja.tagName === 'TEXTAREA') {
2956 const crece = () => {
2957 caja.style.height = 'auto';
2958 caja.style.height = Math.min(caja.scrollHeight, window.innerHeight * 0.4) + 'px';
2959 };
2960 caja.addEventListener('input', crece);
2961 // Al enviar, el valor se vacía desde fuera y no salta `input`: sin esto la
2962 // caja se queda alta y vacía después de cada mensaje.
2963 new MutationObserver(crece).observe(caja, { attributes: true, attributeFilter: ['value'] });
2964 $('composer')?.addEventListener('submit', () => setTimeout(crece, 0));
2965 }
2966}
2967
2968// ── Instalable: es lo único que consigue almacenamiento persistente ─────────
2969// Medido en este proyecto: `navigator.storage.persist()` devuelve false en un
2970// perfil normal, así que Chrome puede desalojar los gigas del modelo cuando le
2971// falte disco — y lo hizo. Chrome concede la persistencia a los sitios
2972// instalados, y solo ofrece instalar si hay manifiesto Y un service worker con
2973// manejador de `fetch`. De ahí `sw.js`, que no cachea nada a propósito.
2974//
2975// El registro va tras `load` para no competir con la carga del modelo, que es
2976// lo que el usuario está esperando de verdad.
2977if ('serviceWorker' in navigator) {
2978 addEventListener('load', () => {
2979 navigator.serviceWorker.register('sw.js').then(async () => {
2980 // Se vuelve a pedir la persistencia DESPUÉS de registrar: si el usuario ya
2981 // tenía el sitio instalado de una visita anterior, aquí es donde se
2982 // concede, y sin pedirla otra vez nadie se enteraría.
2983 try {
2984 if (navigator.storage?.persist && !(await navigator.storage.persisted())) {
2985 const ok = await navigator.storage.persist();
2986 console.log('[elffuss] almacenamiento persistente: ' + (ok ? 'concedido' : 'denegado — instala la app para que el navegador no borre el modelo'));
2987 }
2988 } catch { /* el diagnóstico no vale un error */ }
2989 }).catch(e => console.warn('[elffuss] service worker no registrado: ' + e.message));
2990 });
2991}