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