| 1 | // UI: chat + visualizador + paneles. Todo el DOM vive aquí. |
| 2 | import * as db from './db.js'; |
| 3 | import * as perms from './permissions.js'; |
| 4 | import * as settings from './settings.js'; |
| 5 | import * as skills from './skills.js'; |
| 6 | import { fs, apps, vault, tasks, watch, memory } from './tools/index.js'; |
| 7 | import { renderMarkdown, linkify } from './md.js'; |
| 8 | import * as rutas from './rutas.js'; |
| 9 | import { t as tr, uiLang } from './i18n.js'; |
| 10 | import { humanizeStreamPreview } from './humanize.js'; // alias: dentro de tick(t) el token ya se llama t |
| 11 | import { UI } from './icons.js'; |
| 12 | import { cacheEstimate } from './model-cache.js'; |
| 13 | import * as modelos from './model-storage.js'; |
| 14 | import * as workspace from './workspace.js'; |
| 15 | import * as telemetry from './telemetry.js'; |
| 16 | |
| 17 | let onSettingsChangedCb = () => {}; |
| 18 | let onSkillInstalledCb = () => {}; |
| 19 | |
| 20 | const $ = id => document.getElementById(id); |
| 21 | |
| 22 | // ---------- chat ---------- |
| 23 | export function addMsg(cls, text) { |
| 24 | const div = document.createElement('div'); |
| 25 | div.className = 'msg ' + cls; |
| 26 | // las respuestas de Elffuss se renderizan como markdown; lo del usuario, plano |
| 27 | if (cls === 'assistant') { |
| 28 | div.classList.add('md'); |
| 29 | div.innerHTML = renderMarkdown(text); |
| 30 | } else { |
| 31 | div.textContent = text; |
| 32 | } |
| 33 | $('log').appendChild(div); |
| 34 | $('log').scrollTop = $('log').scrollHeight; |
| 35 | return div; |
| 36 | } |
| 37 | |
| 38 | // Una línea de la conversación que escucha el copiloto (viene del Translator): |
| 39 | // quién habla y qué dice, con su estilo, no como un mensaje del usuario. |
| 40 | export function addTranscripcion(quien, texto) { |
| 41 | const div = document.createElement('div'); |
| 42 | div.className = 'msg transcript'; |
| 43 | const q = document.createElement('b'); |
| 44 | q.textContent = quien + ': '; |
| 45 | div.append(q, document.createTextNode(texto)); |
| 46 | $('log').appendChild(div); |
| 47 | $('log').scrollTop = $('log').scrollHeight; |
| 48 | return div; |
| 49 | } |
| 50 | |
| 51 | function shortArgs(args = {}) { |
| 52 | const s = Object.entries(args) |
| 53 | .map(([k, v]) => `${k}=${String(v).slice(0, 40)}`).join(' · '); |
| 54 | return s ? ` (${s.slice(0, 120)})` : ''; |
| 55 | } |
| 56 | |
| 57 | // Adónde lleva cada herramienta: el «🔧 app.create …» del chat enlaza a lo que |
| 58 | // ha tocado (la app, las tareas, las skills, las carpetas). |
| 59 | function rutaDeHerramienta(call) { |
| 60 | const t = call.tool || '', a = call.args || {}; |
| 61 | if ((t === 'app.create' || t === 'app.open') && a.name) return rutas.href('apps', a.name); |
| 62 | if (t.startsWith('app.')) return rutas.href('apps'); |
| 63 | if (t === 'tasks.add' || t === 'tasks.list' || t === 'tasks.remove') return rutas.href('tareas'); |
| 64 | if (t.startsWith('fs.watch')) return rutas.href('tareas', 'automatizaciones'); |
| 65 | if ((t === 'skill.create' || t === 'skill.edit' || t === 'skill.get') && a.name) return rutas.href('skills', a.name); |
| 66 | if (t.startsWith('skill.')) return rutas.href('skills'); |
| 67 | if (t.startsWith('fs.')) return rutas.href('permisos'); |
| 68 | if (t.startsWith('vault.')) return rutas.href('vault'); |
| 69 | if (t.startsWith('memory.')) return rutas.href('memoria'); |
| 70 | return null; |
| 71 | } |
| 72 | |
| 73 | export function addTool(call) { |
| 74 | const div = addMsg('tool', `🔧 ${call.tool}${shortArgs(call.args)}`); |
| 75 | const destino = rutaDeHerramienta(call); |
| 76 | if (destino) { |
| 77 | const a = document.createElement('a'); |
| 78 | a.href = destino; |
| 79 | a.className = 'tool-link'; |
| 80 | a.textContent = '↗'; |
| 81 | a.title = tr('toolGoTo'); |
| 82 | a.setAttribute('aria-label', tr('toolGoTo')); |
| 83 | div.append(' ', a); |
| 84 | } |
| 85 | return div; |
| 86 | } |
| 87 | |
| 88 | export function addToolResult(tool, result) { |
| 89 | const err = result.startsWith('ERROR'); |
| 90 | const det = document.createElement('details'); |
| 91 | det.className = 'msg tool-result' + (err ? ' err' : ''); |
| 92 | const sum = document.createElement('summary'); |
| 93 | sum.textContent = (err ? '⚠️ ' : '✓ ') + result.split('\n')[0].slice(0, 110); |
| 94 | const pre = document.createElement('pre'); |
| 95 | // Las URL de web.fetch / web.search se pueden abrir (http y https, pestaña |
| 96 | // nueva, sin referrer); el resto sigue siendo texto plano. |
| 97 | pre.innerHTML = linkify(result.slice(0, 2000)); |
| 98 | det.append(sum, pre); |
| 99 | $('log').appendChild(det); |
| 100 | $('log').scrollTop = $('log').scrollHeight; |
| 101 | } |
| 102 | |
| 103 | // Burbuja de «pensando»: visible, con avatar, puntos animados y el texto |
| 104 | // del modelo en streaming (cola de 240 caracteres). |
| 105 | export function thinkingBubble() { |
| 106 | const div = document.createElement('div'); |
| 107 | div.className = 'msg thinking'; |
| 108 | const img = document.createElement('img'); |
| 109 | img.src = 'img/elffuss.svg'; |
| 110 | img.className = 'mini'; |
| 111 | img.alt = ''; |
| 112 | const label = document.createElement('span'); |
| 113 | label.className = 'label'; |
| 114 | label.textContent = tr('thinking'); |
| 115 | const dots = document.createElement('span'); |
| 116 | dots.className = 'dots'; |
| 117 | dots.append(...[0, 1, 2].map(() => document.createElement('i'))); |
| 118 | const gen = document.createElement('div'); |
| 119 | gen.className = 'gen'; |
| 120 | div.append(img, label, dots, gen); |
| 121 | // #log es una región viva (role=log en index.html). La burbuja se oculta a los |
| 122 | // lectores de pantalla: cambia de texto con cada token y se leería sin parar. |
| 123 | // Mientras trabaja, el log queda «ocupado» y lo que llegue se anuncia al final. |
| 124 | div.setAttribute('aria-hidden', 'true'); |
| 125 | $('log').setAttribute('aria-busy', 'true'); |
| 126 | $('log').appendChild(div); |
| 127 | $('log').scrollTop = $('log').scrollHeight; |
| 128 | // Barra del PREFILL. El prefill es la espera larga —leer el prompt antes de |
| 129 | // escribir la primera letra— y hasta ahora no se veía: con un prompt de arnés |
| 130 | // en el modelo grande son decenas de segundos de burbuja quieta, y una espera |
| 131 | // sin señal se lee como «se ha colgado». De hecho se reportó así. |
| 132 | // |
| 133 | // Va DENTRO de la burbuja que ya existe en vez de un elemento nuevo: la |
| 134 | // burbuja aparece justo cuando empieza el turno, que es exactamente cuando |
| 135 | // empieza el prefill. |
| 136 | const barra = document.createElement('div'); |
| 137 | barra.className = 'prefill'; |
| 138 | const relleno = document.createElement('i'); |
| 139 | barra.appendChild(relleno); |
| 140 | barra.hidden = true; |
| 141 | div.insertBefore(barra, gen); |
| 142 | |
| 143 | let buf = ''; |
| 144 | return { |
| 145 | // `hechos` y `total` vienen del motor por lote TERMINADO en la GPU, no |
| 146 | // encolado: la barra no llega al 100 % antes de tiempo. |
| 147 | prefill(hechos, total) { |
| 148 | if (!total) return; |
| 149 | const pct = Math.max(0, Math.min(100, Math.round((hechos / total) * 100))); |
| 150 | label.textContent = tr('reading', { p: pct }); |
| 151 | barra.hidden = false; |
| 152 | relleno.style.width = pct + '%'; |
| 153 | }, |
| 154 | tick(t) { |
| 155 | // Al escribir la primera letra el prefill ha terminado: fuera la barra, o |
| 156 | // se quedaría puesta al 100 % durante toda la respuesta. |
| 157 | if (!barra.hidden) barra.hidden = true; |
| 158 | buf += t; |
| 159 | label.textContent = tr('writing', { n: buf.length }); |
| 160 | // Si está emitiendo un tool-call (p.ej. app.create con un HTML enorme), NO |
| 161 | // volcamos el JSON/HTML crudo que parpadea: una frase humana («creando |
| 162 | // app…»). Para el texto normal, caja que CRECE y se puede leer/scrollear |
| 163 | // entera (antes se mostraban solo los últimos 240 y desaparecía lo de |
| 164 | // arriba). Se respeta tu scroll si subes a leer. |
| 165 | const preview = humanizeStreamPreview(buf); |
| 166 | if (preview) { |
| 167 | gen.classList.add('tool-preview'); |
| 168 | gen.textContent = '⟐ ' + preview; |
| 169 | } else { |
| 170 | gen.classList.remove('tool-preview'); |
| 171 | const pegado = gen.scrollHeight - gen.scrollTop - gen.clientHeight < 28; |
| 172 | gen.textContent = buf; |
| 173 | if (pegado) gen.scrollTop = gen.scrollHeight; |
| 174 | } |
| 175 | }, |
| 176 | tool(name) { |
| 177 | buf = ''; |
| 178 | gen.textContent = ''; |
| 179 | label.textContent = tr('using', { name }); |
| 180 | }, |
| 181 | // ■ pulsado y el turno aún soltando el modelo: la burbuja lo dice en vez |
| 182 | // de seguir animando como si nada. |
| 183 | stopping() { |
| 184 | label.textContent = tr('stopping'); |
| 185 | div.classList.add('stopping'); |
| 186 | }, |
| 187 | // Lo que llegó a escribir, si era texto para el usuario (no una herramienta |
| 188 | // a medias, que se enseña como «creando app…»): lo que se conserva al parar. |
| 189 | partial() { return humanizeStreamPreview(buf) ? '' : buf.trim(); }, |
| 190 | remove() { div.remove(); if (!document.querySelector('#log .msg.thinking')) $('log').removeAttribute('aria-busy'); }, |
| 191 | }; |
| 192 | } |
| 193 | |
| 194 | // Un mensaje de la cola que ■ dejó sin procesar: tachado y, para quien no lo |
| 195 | // ve, dicho con palabras (el tachado solo no llega a un lector de pantalla). |
| 196 | export function markCancelled(el) { |
| 197 | if (!el) return; |
| 198 | el.classList.remove('queued'); |
| 199 | el.classList.add('cancelled'); |
| 200 | if (el.querySelector('.sr-only')) return; |
| 201 | const s = document.createElement('span'); |
| 202 | s.className = 'sr-only'; |
| 203 | s.textContent = ' ' + tr('cancelled'); |
| 204 | el.append(s); |
| 205 | } |
| 206 | |
| 207 | // Región viva (#stop-status) para lo que no se oye de otro modo: «Parando…». |
| 208 | // Parar con el ratón o con Enter deja el foco en otro sitio, el botón solo lo |
| 209 | // dice en su etiqueta y la burbuja de «pensando» está oculta a los lectores (cambia |
| 210 | // en cada token). Lo que entra en el chat (#log) o en un aviso (#toasts) NO pasa |
| 211 | // por aquí: esas dos ya son regiones vivas, y repetirlo aquí lo leía dos veces. |
| 212 | // Se vacía y se escribe en otra tarea para que el mismo texto dos veces seguidas |
| 213 | // se vuelva a leer. |
| 214 | let anuncio = null; |
| 215 | export function announce(texto) { |
| 216 | const r = $('stop-status'); |
| 217 | if (!r) return; |
| 218 | clearTimeout(anuncio); |
| 219 | r.textContent = ''; |
| 220 | anuncio = setTimeout(() => { r.textContent = texto; }, 50); |
| 221 | } |
| 222 | |
| 223 | // Vaciar el chat a la vista, dejando el saludo (🧹). |
| 224 | export function clearLog() { |
| 225 | for (const el of [...$('log').children]) if (!el.classList.contains('sys')) el.remove(); |
| 226 | } |
| 227 | |
| 228 | // Avisos. Antes se iban a los 4,5 s pasara lo que pasara: uno de 184 caracteres |
| 229 | // (el de Hard Work) no daba tiempo a leerlo, no había forma de quitarlos ni de |
| 230 | // pararlos, y ninguno llevaba a ningún sitio. Ahora: |
| 231 | // · duran según lo que hay que leer, y se paran con el ratón o el foco encima; |
| 232 | // · se cierran con ✕; |
| 233 | // · pueden llevar UNA acción («Deshacer», «Ver tarea», «Elegir ahora»…); |
| 234 | // · #toasts es una región viva (index.html): un lector de pantalla los anuncia. |
| 235 | // `opts` admite un número (ms), como antes, o { ms, accion: { label, run } }. |
| 236 | export function toast(text, opts = {}) { |
| 237 | if (typeof opts === 'number') opts = { ms: opts }; |
| 238 | const { accion = null, ms = null } = opts || {}; |
| 239 | const t = document.createElement('div'); |
| 240 | t.className = 'toast'; |
| 241 | const txt = document.createElement('span'); |
| 242 | txt.className = 'toast-txt'; |
| 243 | txt.textContent = text; |
| 244 | t.appendChild(txt); |
| 245 | let timer = null, restante = 0, desde = 0, parado = false; |
| 246 | const quitar = () => { clearTimeout(timer); t.remove(); }; |
| 247 | if (accion?.label && typeof accion.run === 'function') { |
| 248 | const b = document.createElement('button'); |
| 249 | b.type = 'button'; |
| 250 | b.className = 'toast-accion'; |
| 251 | b.textContent = accion.label; |
| 252 | b.onclick = () => { quitar(); try { accion.run(); } catch (e) { console.warn('[elffuss] acción del aviso:', e); } }; |
| 253 | t.appendChild(b); |
| 254 | } |
| 255 | const x = document.createElement('button'); |
| 256 | x.type = 'button'; |
| 257 | x.className = 'toast-x'; |
| 258 | x.textContent = '✕'; |
| 259 | x.title = tr('close'); |
| 260 | x.setAttribute('aria-label', tr('close')); |
| 261 | x.onclick = quitar; |
| 262 | t.appendChild(x); |
| 263 | $('toasts').appendChild(t); |
| 264 | // ~50 ms por carácter, entre 4 y 12 s; con acción, unos segundos más para |
| 265 | // que dé tiempo a decidir. |
| 266 | restante = ms ?? (Math.min(12000, Math.max(4000, 1500 + String(text).length * 50)) + (accion ? 4000 : 0)); |
| 267 | const arrancar = () => { desde = Date.now(); clearTimeout(timer); timer = setTimeout(quitar, restante); }; |
| 268 | const pausar = () => { if (parado) return; parado = true; clearTimeout(timer); restante = Math.max(1500, restante - (Date.now() - desde)); }; |
| 269 | const seguir = () => { if (!parado || t.matches(':hover') || t.contains(document.activeElement)) return; parado = false; arrancar(); }; |
| 270 | t.addEventListener('mouseenter', pausar); |
| 271 | t.addEventListener('mouseleave', seguir); |
| 272 | t.addEventListener('focusin', pausar); |
| 273 | t.addEventListener('focusout', () => setTimeout(seguir, 0)); |
| 274 | arrancar(); |
| 275 | return t; |
| 276 | } |
| 277 | |
| 278 | // ---------- modal de permisos ---------- |
| 279 | // Tres cosas que fallaban, las tres con el teclado: |
| 280 | // · Escape cerraba el diálogo SIN contestar: la promesa no se resolvía nunca, |
| 281 | // el turno se quedaba colgado en «Elffuss está usando…» y todo lo que |
| 282 | // escribieras después esperaba en la cola hasta recargar —y con ella el |
| 283 | // cerebro CEO, que no arrancaba otro ciclo—. Ahora Escape (y cualquier otro |
| 284 | // cierre) es «Denegar». |
| 285 | // · Dos peticiones a la vez se pisaban los botones: la segunda reasignaba los |
| 286 | // onclick de la primera, que ya no se podía contestar. Ahora van en cola, |
| 287 | // una detrás de otra (permissions.js ya las pone en fila por ámbito; esta |
| 288 | // cola cubre además a quien llame aquí directamente). |
| 289 | // · Si la petición nacía de un Enter (p. ej. en la contraseña de la Bóveda), |
| 290 | // el diálogo se abría DENTRO de ese mismo evento, el foco caía en «Denegar» |
| 291 | // y la misma pulsación lo activaba: denegado sin haberlo visto. Ahora se |
| 292 | // abre en la tarea siguiente, cuando esa tecla ya ha terminado. |
| 293 | let colaPermisos = Promise.resolve(); |
| 294 | export function askPermission(scope, meta, detail) { |
| 295 | const turno = colaPermisos.then(() => mostrarPermiso(scope, meta, detail)); |
| 296 | colaPermisos = turno.catch(() => {}); |
| 297 | return turno; |
| 298 | } |
| 299 | |
| 300 | function mostrarPermiso(scope, meta, detail) { |
| 301 | return new Promise(resolve => { |
| 302 | const dlg = $('perm-dialog'); |
| 303 | $('perm-title').textContent = `${meta?.icon || '❓'} ${tr('permWord')}: ${meta?.label || scope}`; |
| 304 | $('perm-desc').textContent = meta?.desc || ''; |
| 305 | $('perm-detail').textContent = detail || ''; |
| 306 | const previo = document.activeElement; |
| 307 | let hecho = false, mostrado = false; |
| 308 | const done = ok => { |
| 309 | if (hecho) return; |
| 310 | hecho = true; |
| 311 | $('perm-allow').onclick = null; |
| 312 | $('perm-deny').onclick = null; |
| 313 | dlg.removeEventListener('cancel', alCancelar); |
| 314 | dlg.removeEventListener('close', alCerrar); |
| 315 | if (dlg.open) dlg.close(); |
| 316 | refreshPerms(); |
| 317 | if (previo && previo !== document.body && document.contains(previo)) { |
| 318 | try { previo.focus({ preventScroll: true }); } catch { /* — */ } |
| 319 | } |
| 320 | resolve(ok); |
| 321 | }; |
| 322 | const alCancelar = e => { e.preventDefault(); done(false); }; // Escape = Denegar |
| 323 | // Cualquier otro cierre, también. Pero solo el de ESTE diálogo: el evento |
| 324 | // «close» de la petición anterior llega en una tarea aparte, cuando esta ya |
| 325 | // ha empezado a escuchar, y sin la guarda la denegaba antes de enseñarla. |
| 326 | const alCerrar = () => { if (mostrado && !dlg.open) done(false); }; |
| 327 | $('perm-allow').onclick = () => done(true); |
| 328 | $('perm-deny').onclick = () => done(false); |
| 329 | dlg.addEventListener('cancel', alCancelar); |
| 330 | dlg.addEventListener('close', alCerrar); |
| 331 | setTimeout(() => { |
| 332 | if (hecho) return; |
| 333 | try { dlg.showModal(); mostrado = true; } catch { done(false); } |
| 334 | }, 0); |
| 335 | }); |
| 336 | } |
| 337 | |
| 338 | // ---------- visualizador ---------- |
| 339 | const isMobile = () => matchMedia('(max-width: 700px)').matches; |
| 340 | |
| 341 | // Cuándo abrió el USUARIO una app a mano (panel Apps o su dirección): el |
| 342 | // tablero del copiloto no la tapa durante un rato (ver kernel.js). |
| 343 | let aperturaManualT = 0; |
| 344 | export const aperturaManual = () => aperturaManualT; |
| 345 | |
| 346 | // `ruta`: es una app guardada (apps.create/open) y su dirección es #/apps/<nombre>. |
| 347 | // El tablero del copiloto también se pinta aquí, pero no es una app guardada. |
| 348 | export function renderApp(name, html, { ruta = false } = {}) { |
| 349 | _stage?.hide?.($('vista-empty'), false); // si estaba el escaparate de descarga, quitarlo |
| 350 | $('vista-empty').hidden = true; |
| 351 | const frame = $('appframe'); |
| 352 | frame.hidden = false; |
| 353 | frame.srcdoc = html; |
| 354 | frame.title = tr('appFrameT', { name }); |
| 355 | selectTab('vista', { reflejar: !ruta }); |
| 356 | if (ruta) rutas.reflejar('apps', name); |
| 357 | refreshApps(); |
| 358 | if (isMobile()) flipTo('viz'); // en móvil, saltar a ver la app recién creada |
| 359 | } |
| 360 | |
| 361 | // móvil: una sola columna, chat ↔ visualizador conmutables |
| 362 | export function mostrarChat() { if (isMobile()) flipTo('chat'); } |
| 363 | function flipTo(side) { |
| 364 | document.body.classList.toggle('show-viz', side === 'viz'); |
| 365 | pintarFlip(); |
| 366 | } |
| 367 | // El botón dice adónde lleva, en el idioma de la página (empezaba con «Vista» |
| 368 | // escrito en el HTML para todos los idiomas). |
| 369 | function pintarFlip() { |
| 370 | const enViz = document.body.classList.contains('show-viz'); |
| 371 | const b = $('btn-flip'); |
| 372 | b.textContent = enViz ? tr('flipChat') : tr('flipView'); |
| 373 | b.title = enViz ? tr('flipToChat') : tr('flipToView'); |
| 374 | b.setAttribute('aria-label', b.title); |
| 375 | } |
| 376 | |
| 377 | // ---------- pestañas ---------- |
| 378 | // Pestañas de verdad (tablist/tab/tabpanel, aria-selected, tabindex itinerante y |
| 379 | // flechas) y con dirección: cada una se refleja en la URL (#/apps, #/tareas…; |
| 380 | // ver rutas.js), así que se pueden enlazar, guardar y recorrer con «Atrás». |
| 381 | // `push`: un clic del usuario crea entrada de historial; lo que se abre solo |
| 382 | // (la Vista al crear una app) reemplaza la actual y no ensucia el historial. |
| 383 | export function selectTab(name, { push = false, reflejar = true } = {}) { |
| 384 | document.querySelectorAll('#tabs button').forEach(b => { |
| 385 | const on = b.dataset.tab === name; |
| 386 | b.classList.toggle('active', on); |
| 387 | b.setAttribute('aria-selected', on ? 'true' : 'false'); |
| 388 | b.tabIndex = on ? 0 : -1; |
| 389 | }); |
| 390 | document.querySelectorAll('.panel').forEach(p => |
| 391 | p.classList.toggle('active', p.id === 'panel-' + name)); |
| 392 | if (reflejar) rutas.reflejar(name, null, { push }); |
| 393 | if (name === 'apps') return refreshApps(); |
| 394 | if (name === 'tareas') return refreshTasks(); |
| 395 | if (name === 'vault') return refreshVault(); |
| 396 | if (name === 'permisos') return refreshPerms(); |
| 397 | if (name === 'ajustes') return refreshSettings(); |
| 398 | if (name === 'skills') return refreshSkillsPanel(); |
| 399 | } |
| 400 | |
| 401 | // Ir a donde dice una ruta (#/…). Lo usan el arranque, «Atrás»/«Adelante» y |
| 402 | // los enlaces del chat. La Mente no vive en ui.js: la abre quien la registre. |
| 403 | let onMenteCb = () => {}; |
| 404 | export function setOnMente(fn) { onMenteCb = fn; } |
| 405 | export async function navegar(ruta) { |
| 406 | if (!ruta) return; |
| 407 | const { seccion, detalle } = ruta; |
| 408 | const verPanel = async (tab) => { await selectTab(tab, { reflejar: false }); if (isMobile()) flipTo('viz'); }; |
| 409 | if (seccion === 'mente') return onMenteCb(detalle); |
| 410 | if (seccion === 'modelo') { |
| 411 | // No es un sitio sino una acción: se hace y la URL vuelve a decir dónde estás. |
| 412 | rutas.reflejar(tabActiva() || 'vista'); |
| 413 | enfocarSelectorModelo(); |
| 414 | return; |
| 415 | } |
| 416 | if (seccion === 'apps' && detalle) { |
| 417 | const app = (await apps.allApps()).find(a => a.name === detalle); |
| 418 | if (app) { aperturaManualT = Date.now(); await apps.open({ name: app.name }); rutas.reflejar('apps', app.name); return; } |
| 419 | toast(tr('appMissing', { name: detalle })); |
| 420 | return verPanel('apps'); |
| 421 | } |
| 422 | // La memoria vive en Ajustes; #/memoria/<id> señala un hecho por su id (el |
| 423 | // texto del hecho nunca va en la URL). |
| 424 | if (seccion === 'memoria') { await verPanel('ajustes'); resaltar('ajustes', detalle || 'memoria'); return; } |
| 425 | if (!['vista', 'apps', 'tareas', 'vault', 'skills', 'permisos', 'ajustes'].includes(seccion)) return; |
| 426 | await verPanel(seccion); |
| 427 | if (detalle) resaltar(seccion, detalle); |
| 428 | } |
| 429 | |
| 430 | // Señala un elemento dentro del panel (una tarea, una skill, la sección |
| 431 | // «Acerca de»…): lo trae a la vista, lo marca y le da el foco. |
| 432 | function resaltar(seccion, detalle) { |
| 433 | const panel = $('panel-' + seccion); |
| 434 | const sel = `[data-ruta="${CSS.escape(detalle)}"]`; |
| 435 | const tryIt = (n = 0) => { |
| 436 | const el = panel?.querySelector(sel); |
| 437 | if (!el) { if (n < 20) setTimeout(() => tryIt(n + 1), 50); return; } |
| 438 | panel.querySelectorAll('.resaltado').forEach(e => e.classList.remove('resaltado')); |
| 439 | el.classList.add('resaltado'); |
| 440 | el.querySelector('details')?.setAttribute('open', ''); // p. ej. el texto de una skill |
| 441 | if (!el.hasAttribute('tabindex') && !/^(BUTTON|A|INPUT|DETAILS|SUMMARY)$/.test(el.tagName)) el.tabIndex = -1; |
| 442 | el.scrollIntoView({ block: 'nearest' }); |
| 443 | try { el.focus({ preventScroll: true }); } catch { /* — */ } |
| 444 | }; |
| 445 | tryIt(); |
| 446 | } |
| 447 | |
| 448 | // El selector de modelo es un <select>: se enfoca y, donde se puede, se |
| 449 | // despliega. Es a donde llevan los «elige un modelo arriba» del chat. |
| 450 | export function enfocarSelectorModelo() { |
| 451 | const sel = $('model-select'); |
| 452 | if (!sel) return; |
| 453 | sel.focus(); // está en la cabecera: a la vista en los dos lados del móvil |
| 454 | try { sel.showPicker?.(); } catch { /* sin gesto de usuario no se despliega: queda enfocado */ } |
| 455 | } |
| 456 | |
| 457 | // Skills en su propia pestaña (visible y descubrible) |
| 458 | export function refreshSkillsPanel() { |
| 459 | const panel = $('panel-skills'); |
| 460 | panel.replaceChildren(el('h3', null, tr('skillsTitle'))); |
| 461 | panel.appendChild(el('p', 'muted', tr('skillsDesc'))); |
| 462 | renderSkills(panel); |
| 463 | } |
| 464 | |
| 465 | function card(...children) { |
| 466 | const c = document.createElement('div'); |
| 467 | c.className = 'card'; |
| 468 | c.append(...children); |
| 469 | return c; |
| 470 | } |
| 471 | const el = (tag, cls, text) => { |
| 472 | const e = document.createElement(tag); |
| 473 | if (cls) e.className = cls; |
| 474 | if (text != null) e.textContent = text; |
| 475 | return e; |
| 476 | }; |
| 477 | const btn = (label, cls, onClick) => { |
| 478 | const b = el('button', cls, label); |
| 479 | b.onclick = onClick; |
| 480 | return b; |
| 481 | }; |
| 482 | |
| 483 | // ---------- panel apps ---------- |
| 484 | export async function refreshApps() { |
| 485 | const list = await apps.allApps(); |
| 486 | const panel = $('panel-apps'); |
| 487 | panel.replaceChildren(el('h3', null, tr('appsTitle'))); |
| 488 | if (!list.length) { |
| 489 | panel.appendChild(el('p', 'muted', tr('appsEmpty'))); |
| 490 | return; |
| 491 | } |
| 492 | for (const app of list) { |
| 493 | panel.appendChild(card( |
| 494 | el('b', null, app.name), |
| 495 | el('span', 'muted', new Date(app.created).toLocaleString(uiLang())), |
| 496 | // Por apps.open(): así la app abierta es ESTA también para el modelo |
| 497 | // (CONTEXTO AHORA), no solo en pantalla. |
| 498 | btn(tr('open'), 'primary', () => { aperturaManualT = Date.now(); apps.open({ name: app.name }).catch(e => toast('⚠️ ' + e.message)); }), |
| 499 | botonBorrarApp(app), |
| 500 | )); |
| 501 | } |
| 502 | } |
| 503 | // 🗑 con nombre propio y «Deshacer» (borraba al instante, sin vuelta atrás). Si |
| 504 | // era la app abierta, el visor se vacía (ver apps.setOnRemoved en init). |
| 505 | function botonBorrarApp(app) { |
| 506 | const b = btn('🗑', 'ghost', async () => { |
| 507 | await apps.removeApp({ name: app.name }); |
| 508 | refreshApps(); |
| 509 | toast(tr('appRemoved', { name: app.name }), { accion: { label: tr('undo'), run: async () => { |
| 510 | try { await apps.restoreApp(app); refreshApps(); } catch (e) { toast('⚠️ ' + e.message); } |
| 511 | } } }); |
| 512 | }); |
| 513 | b.title = tr('appDelL', { name: app.name }); |
| 514 | b.setAttribute('aria-label', tr('appDelL', { name: app.name })); |
| 515 | return b; |
| 516 | } |
| 517 | // El visor deja de enseñar una app borrada. |
| 518 | function vaciarVisor() { |
| 519 | const f = $('appframe'); |
| 520 | f.hidden = true; |
| 521 | f.srcdoc = ''; |
| 522 | f.title = tr('appFrameEmpty'); |
| 523 | $('vista-empty').hidden = false; |
| 524 | if (/^#\/apps\//.test(location.hash)) rutas.reflejar('apps'); |
| 525 | } |
| 526 | |
| 527 | // ---------- panel tareas ---------- |
| 528 | export async function refreshTasks() { |
| 529 | const [list, watches] = await Promise.all([ |
| 530 | db.all('tasks').then(l => l.sort((a, b) => a.when - b.when)), |
| 531 | watch.allWatches().catch(() => []), |
| 532 | ]); |
| 533 | const panel = $('panel-tareas'); |
| 534 | panel.replaceChildren(el('h3', null, tr('tasksTitle'))); |
| 535 | if (!list.length) panel.appendChild(el('p', 'muted', tr('tasksEmpty'))); |
| 536 | for (const t of list) { |
| 537 | const estado = el('span', null, t.done ? '✅' : '⏳'); |
| 538 | estado.title = t.done ? tr('taskDone') : tr('taskPending'); |
| 539 | estado.setAttribute('aria-label', estado.title); |
| 540 | const id = el('code', null, t.id); // el id que nombran los avisos del chat |
| 541 | id.title = tr('taskId'); |
| 542 | const fila = [estado, el('b', null, t.prompt), el('span', 'muted', new Date(t.when).toLocaleString(uiLang())), id]; |
| 543 | if (!t.done) { |
| 544 | const ya = btn(tr('taskRunNow'), 'ghost', async () => { |
| 545 | ya.disabled = true; |
| 546 | const hecha = await tasks.marcarHecha(t.id); |
| 547 | if (hecha) onRunTaskCb(hecha); |
| 548 | refreshTasks(); |
| 549 | }); |
| 550 | ya.setAttribute('aria-label', tr('taskRunNowL', { prompt: t.prompt })); |
| 551 | fila.push(ya); |
| 552 | } |
| 553 | const borrar = btn('🗑', 'ghost', async () => { await tasks.removeTask({ id: t.id }); toast(tr('taskDeleted', { id: t.id })); refreshTasks(); }); |
| 554 | borrar.title = tr('taskDelL', { prompt: t.prompt }); |
| 555 | borrar.setAttribute('aria-label', tr('taskDelL', { prompt: t.prompt })); |
| 556 | fila.push(borrar); |
| 557 | const c = card(...fila); |
| 558 | c.dataset.ruta = t.id; // #/tareas/<id> |
| 559 | panel.appendChild(c); |
| 560 | } |
| 561 | // Automatizaciones de carpetas (fs.watch): antes no tenían interfaz; solo se |
| 562 | // podían ver o quitar pidiéndoselo al chat. |
| 563 | const sec = el('section', 'automatizaciones'); |
| 564 | sec.dataset.ruta = 'automatizaciones'; // #/tareas/automatizaciones |
| 565 | sec.appendChild(el('h3', null, tr('watchTitle'))); |
| 566 | if (!watches.length) sec.appendChild(el('p', 'muted', tr('watchEmpty'))); |
| 567 | for (const w of watches) { |
| 568 | const x = btn('✕', 'ghost', async () => { await watch.removeWatch({ id: w.id }); toast(tr('watchRemoved', { id: w.id })); refreshTasks(); }); |
| 569 | x.title = tr('watchDelL', { from: w.from, to: w.to }); |
| 570 | x.setAttribute('aria-label', x.title); |
| 571 | const c = card(el('span', null, '👁'), el('b', null, `${w.from} → ${w.to}`), |
| 572 | el('span', 'muted', `${w.pattern || '*'} · ${tr('watchSeen', { n: Object.keys(w.seen || {}).length })}`), el('code', null, w.id), x); |
| 573 | c.dataset.ruta = w.id; |
| 574 | sec.appendChild(c); |
| 575 | } |
| 576 | panel.appendChild(sec); |
| 577 | } |
| 578 | // El kernel manda a la cola una tarea lanzada a mano («Ejecutar ahora»). |
| 579 | let onRunTaskCb = () => {}; |
| 580 | export function setOnRunTask(fn) { onRunTaskCb = fn; } |
| 581 | // Algo ha cambiado en tareas o automatizaciones (una tarea se lanzó, una |
| 582 | // automatización procesó un fichero): si el panel está abierto, se repinta. Se |
| 583 | // quedaba con ⏳ después de que la tarea se hubiera lanzado. |
| 584 | export function tareasCambiaron() { if (tabActiva() === 'tareas') refreshTasks(); } |
| 585 | |
| 586 | // ---------- panel vault ---------- |
| 587 | // Lo que haces aquí lo haces tú: no pasa por el permiso «Bóveda», que es el del |
| 588 | // agente (ver tools/vault.js, `desdePanel`). Y el panel se repinta cuando la |
| 589 | // bóveda se cierra sola: antes seguía ofreciendo «Bloquear ahora» y un secreto |
| 590 | // revelado se quedaba en claro. |
| 591 | const VAULT_REVELADO_MS = 30000; // un secreto a la vista se vuelve a tapar solo |
| 592 | let vaultOyente = null, vaultRepintado = Promise.resolve(); |
| 593 | const tabActiva = () => document.querySelector('#tabs button.active')?.dataset.tab; |
| 594 | export async function refreshVault() { |
| 595 | vaultOyente ||= vault.alBloquear(motivo => { |
| 596 | if (tabActiva() === 'vault') vaultRepintado = refreshVault(); |
| 597 | if (motivo === 'auto') toast(tr('vaultAutoLocked')); |
| 598 | }); |
| 599 | const panel = $('panel-vault'); |
| 600 | panel.replaceChildren(el('h3', null, tr('vaultTitle'))); |
| 601 | const setup = await vault.isSetup(); |
| 602 | |
| 603 | if (!vault.isUnlocked()) { |
| 604 | panel.appendChild(el('p', 'muted', setup ? tr('vaultLocked') : tr('vaultUnset'))); |
| 605 | // Un <form>: Enter envía como el botón, sin un keydown a mano. |
| 606 | const form = el('form', 'row'); |
| 607 | const input = el('input'); |
| 608 | input.type = 'password'; |
| 609 | input.id = 'vault-master'; |
| 610 | input.autocomplete = setup ? 'current-password' : 'new-password'; |
| 611 | input.placeholder = tr('vaultMasterPh'); |
| 612 | input.setAttribute('aria-label', tr('vaultMasterPh')); |
| 613 | const go = el('button', 'primary', setup ? tr('vaultUnlock') : tr('vaultCreate')); |
| 614 | go.type = 'submit'; |
| 615 | form.addEventListener('submit', async e => { |
| 616 | e.preventDefault(); |
| 617 | if (!input.value) { input.focus(); return; } |
| 618 | go.disabled = true; |
| 619 | try { |
| 620 | await vault.unlock(input.value, { desdePanel: true }); |
| 621 | toast(setup ? tr('vaultUnlockedT') : tr('vaultCreatedT')); |
| 622 | await refreshVault(); |
| 623 | panel.querySelector('#vault-name')?.focus(); |
| 624 | } catch (err) { |
| 625 | go.disabled = false; |
| 626 | toast('⚠️ ' + (/incorrecta/.test(err.message) ? tr('vaultWrongPw') : err.message)); |
| 627 | input.select(); |
| 628 | } |
| 629 | }); |
| 630 | form.append(input, go); |
| 631 | panel.appendChild(form); |
| 632 | return; |
| 633 | } |
| 634 | |
| 635 | const estado = el('div', 'row between'); |
| 636 | // Al bloquear el panel se repinta (y el botón desaparece): el foco va a la |
| 637 | // contraseña, que es lo siguiente que se usa; antes caía a <body>. |
| 638 | estado.append(el('span', 'muted', tr('vaultOpenState')), |
| 639 | btn(tr('vaultLockNow'), 'ghost', async () => { |
| 640 | vault.lock(); // el oyente de alBloquear repinta el panel… |
| 641 | toast(tr('vaultLockedNow')); |
| 642 | await vaultRepintado; // …y se espera a ese repintado, sin pintar dos veces |
| 643 | $('panel-vault').querySelector('#vault-master')?.focus(); |
| 644 | })); |
| 645 | panel.appendChild(estado); |
| 646 | |
| 647 | const form = el('form', 'row'); |
| 648 | const name = el('input'); |
| 649 | name.id = 'vault-name'; |
| 650 | name.placeholder = tr('vaultNamePh'); |
| 651 | name.setAttribute('aria-label', tr('vaultNameL')); |
| 652 | const secret = el('input'); |
| 653 | secret.type = 'password'; |
| 654 | secret.autocomplete = 'off'; |
| 655 | secret.placeholder = tr('vaultSecretPh'); |
| 656 | secret.setAttribute('aria-label', tr('vaultSecretL')); |
| 657 | const add = el('button', 'primary', tr('save')); |
| 658 | add.type = 'submit'; |
| 659 | form.addEventListener('submit', async e => { |
| 660 | e.preventDefault(); |
| 661 | try { |
| 662 | await vault.setSecret({ name: name.value.trim(), secret: secret.value }, { desdePanel: true }); |
| 663 | toast(tr('vaultSavedT', { name: name.value.trim() })); |
| 664 | name.value = secret.value = ''; |
| 665 | await refreshVault(); |
| 666 | panel.querySelector('#vault-name')?.focus(); |
| 667 | } catch (err) { toast('⚠️ ' + err.message); } |
| 668 | }); |
| 669 | form.append(name, secret, add); |
| 670 | panel.appendChild(form); |
| 671 | |
| 672 | for (const n of await vault.secretNames()) { |
| 673 | const val = el('code', null, '••••••'); |
| 674 | let tapar = null; |
| 675 | const ver = btn('👁', 'ghost', async () => { |
| 676 | if (ver.getAttribute('aria-pressed') === 'true') { ocultar(); return; } |
| 677 | try { |
| 678 | val.textContent = await vault.getSecret({ name: n }, { desdePanel: true }); |
| 679 | ver.setAttribute('aria-pressed', 'true'); |
| 680 | ver.title = tr('vaultHide', { name: n }); |
| 681 | clearTimeout(tapar); |
| 682 | tapar = setTimeout(ocultar, VAULT_REVELADO_MS); |
| 683 | } catch (err) { toast('⚠️ ' + err.message); refreshVault(); } |
| 684 | }); |
| 685 | const ocultar = () => { |
| 686 | clearTimeout(tapar); |
| 687 | val.textContent = '••••••'; |
| 688 | ver.setAttribute('aria-pressed', 'false'); |
| 689 | ver.title = tr('vaultShow', { name: n }); |
| 690 | }; |
| 691 | ver.setAttribute('aria-pressed', 'false'); |
| 692 | ver.title = tr('vaultShow', { name: n }); |
| 693 | ver.setAttribute('aria-label', tr('vaultShowL', { name: n })); |
| 694 | const borrar = btn('🗑', 'ghost', async () => { |
| 695 | if (!window.confirm(tr('vaultDelConfirm', { name: n }))) return; |
| 696 | try { await vault.removeSecret({ name: n }); toast(tr('vaultDeleted', { name: n })); } |
| 697 | catch (err) { toast('⚠️ ' + err.message); } |
| 698 | refreshVault(); |
| 699 | }); |
| 700 | borrar.title = tr('vaultDel', { name: n }); |
| 701 | borrar.setAttribute('aria-label', tr('vaultDel', { name: n })); |
| 702 | panel.appendChild(card(el('b', null, n), val, ver, borrar)); |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | // ---------- panel permisos ---------- |
| 707 | export async function refreshPerms() { |
| 708 | const panel = $('panel-permisos'); |
| 709 | panel.replaceChildren(el('h3', null, tr('permsTitle'))); |
| 710 | const g = perms.grants(); |
| 711 | if (!g.length) |
| 712 | panel.appendChild(el('p', 'muted', tr('permsEmpty'))); |
| 713 | for (const scope of g) { |
| 714 | const meta = perms.SCOPES[scope] || {}; |
| 715 | panel.appendChild(card( |
| 716 | el('b', null, `${meta.icon || ''} ${meta.label || scope}`), |
| 717 | el('span', 'muted', meta.desc || ''), |
| 718 | btn(tr('revoke'), 'ghost', () => { perms.revoke(scope); refreshPerms(); }), |
| 719 | )); |
| 720 | } |
| 721 | const folders = await fs.folders(); |
| 722 | if (folders.length) { |
| 723 | panel.appendChild(el('h3', null, tr('foldersTitle'))); |
| 724 | // Dónde escribe la Mente: en la primera carpeta (ceo-adapter.js). |
| 725 | panel.appendChild(el('p', 'muted', tr('folderSoulNote', { name: folders[0] }))); |
| 726 | for (const f of folders) { |
| 727 | const quitar = btn(tr('remove'), 'ghost', () => quitarCarpeta(f, folders)); |
| 728 | quitar.setAttribute('aria-label', tr('folderRemoveL', { name: f })); |
| 729 | const c = card(el('b', null, '📁 ' + f), quitar); |
| 730 | c.dataset.ruta = f; // #/permisos/<carpeta> |
| 731 | panel.appendChild(c); |
| 732 | } |
| 733 | } |
| 734 | } |
| 735 | // Quitar una carpeta pide confirmación y dice qué arrastra: las automatizaciones |
| 736 | // que la usan (que si no seguían sondeándola y fallando en silencio) y, si es la |
| 737 | // primera, que la Mente pasará a escribir en la siguiente. |
| 738 | async function quitarCarpeta(f, folders) { |
| 739 | const dependientes = (await watch.allWatches().catch(() => [])).filter(w => w.from === f || w.to === f); |
| 740 | let txt = tr('folderRemoveConfirm', { name: f }); |
| 741 | if (dependientes.length) txt += '\n\n' + tr('folderRemoveWatches', { list: dependientes.map(w => `${w.from} → ${w.to}`).join(', ') }); |
| 742 | if (folders[0] === f) txt += '\n\n' + (folders[1] ? tr('folderRemoveSoulNext', { next: folders[1] }) : tr('folderRemoveSoulNone')); |
| 743 | if (!window.confirm(txt)) return; |
| 744 | for (const w of dependientes) await watch.removeWatch({ id: w.id }).catch(() => {}); |
| 745 | await db.del('fs', f); |
| 746 | toast(tr('folderRemoved', { name: f }) + (dependientes.length ? ' · ' + tr('folderRemovedWatches', { n: dependientes.length }) : '')); |
| 747 | refreshPerms(); |
| 748 | } |
| 749 | |
| 750 | // ---------- progreso y estado del modelo ---------- |
| 751 | // Escaparate de descarga: mientras baja el modelo y NO hay app abierta, mostramos |
| 752 | // la galaxia + carrusel de mini-UIs en el panel Vista (en móvil evita la caja |
| 753 | // flotante que se solapaba con el compositor). Con app abierta → caja flotante. |
| 754 | let _stage = null; |
| 755 | async function _loadStage() { if (!_stage) _stage = await import('./loading-stage.js'); return _stage; } |
| 756 | function _pct(p) { |
| 757 | if (typeof p === 'string') return p; |
| 758 | if (p && p.status === 'progress' && p.total) return Math.round(p.loaded / p.total * 100); |
| 759 | return p; |
| 760 | } |
| 761 | // El escaparate se monta en la Vista SOLO si ya la estás mirando. Antes cada |
| 762 | // cambio de cerebro —también uno remoto, que ni descarga— te llevaba a la Vista |
| 763 | // (estando en Ajustes, saltabas a la Vista) y en el móvil te sacaba del chat. |
| 764 | async function _showStage(p) { |
| 765 | const st = await _loadStage(); |
| 766 | if (!st.isMounted()) await st.show($('panel-vista'), $('vista-empty')); |
| 767 | st.setProgress(_pct(p)); |
| 768 | } |
| 769 | const mirandoLaVista = () => tabActiva() === 'vista' && (!isMobile() || document.body.classList.contains('show-viz')); |
| 770 | |
| 771 | export function modelProgress(p) { |
| 772 | const box = $('model-progress'); |
| 773 | const appHidden = $('appframe').hidden !== false; // ¿aún no hay app abierta? |
| 774 | if (p == null) { // carga terminada |
| 775 | box.hidden = true; |
| 776 | _stage?.hide?.($('vista-empty'), appHidden); |
| 777 | return; |
| 778 | } |
| 779 | if (appHidden && (mirandoLaVista() || _stage?.isMounted?.())) { box.hidden = true; _showStage(p); return; } |
| 780 | |
| 781 | box.hidden = false; |
| 782 | // La barra es una barra de progreso de verdad para un lector de pantalla. |
| 783 | const track = box.querySelector('.track'); |
| 784 | const anunciar = pct => { |
| 785 | if (pct == null) track.removeAttribute('aria-valuenow'); |
| 786 | else track.setAttribute('aria-valuenow', String(pct)); |
| 787 | track.setAttribute('aria-valuetext', $('model-progress-text').textContent || ''); |
| 788 | }; |
| 789 | if (typeof p === 'string') { |
| 790 | $('model-progress-text').textContent = p; |
| 791 | // Sacar el % del texto, igual que hace el escaparate (loading-stage.js). |
| 792 | // Los proveedores informan con cadenas del tipo «… · 42 %», y este camino |
| 793 | // —la caja flotante, o sea con la app abierta— las daba TODAS por |
| 794 | // desconocidas: la barra se quedaba animada de principio a fin aunque el |
| 795 | // porcentaje viniera dentro. Con un modelo de gigabytes eso es la |
| 796 | // diferencia entre ver que avanza y creer que se ha colgado. |
| 797 | const m = p.match(/(\d+)\s*%/); |
| 798 | if (m) { |
| 799 | $('model-bar').classList.remove('indet'); |
| 800 | $('model-bar').style.width = Math.min(100, +m[1]) + '%'; |
| 801 | anunciar(Math.min(100, +m[1])); |
| 802 | } else { |
| 803 | $('model-bar').classList.add('indet'); // sin % conocido → barra animada |
| 804 | $('model-bar').style.width = ''; |
| 805 | anunciar(null); |
| 806 | } |
| 807 | return; |
| 808 | } |
| 809 | if (p.status === 'progress' && p.total) { |
| 810 | const pct = Math.round(p.loaded / p.total * 100); |
| 811 | $('model-bar').classList.remove('indet'); |
| 812 | $('model-bar').style.width = pct + '%'; |
| 813 | $('model-progress-text').textContent = |
| 814 | `Descargando modelo · ${pct}% · ${(p.loaded / 1e6 | 0)}/${(p.total / 1e6 | 0)} MB`; |
| 815 | anunciar(pct); |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | // Mientras carga un cerebro el selector se desactiva: elegir otro a la vez |
| 820 | // arrancaba una segunda carga en paralelo. Un control desactivado pierde el |
| 821 | // foco (cae a <body>), así que se recuerda y, al terminar, el foco vuelve al |
| 822 | // selector si nadie lo ha llevado a otra parte mientras tanto. |
| 823 | let selectorTeniaFoco = false; |
| 824 | export function modeloCargando(on) { |
| 825 | const sel = $('model-select'); |
| 826 | if (on) selectorTeniaFoco = selectorTeniaFoco || document.activeElement === sel; |
| 827 | sel.disabled = !!on; |
| 828 | if (on) sel.setAttribute('aria-busy', 'true'); else sel.removeAttribute('aria-busy'); |
| 829 | if (!on && selectorTeniaFoco) { |
| 830 | selectorTeniaFoco = false; |
| 831 | if (!document.activeElement || document.activeElement === document.body) { |
| 832 | try { sel.focus({ preventScroll: true }); } catch { /* — */ } |
| 833 | } |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | // ⓘ junto al selector: la ficha del modelo cargado en Hugging Face (un |
| 838 | // <option> no puede llevar enlace). Sin ficha pública, no hay ⓘ. Nunca se |
| 839 | // enlazan los ficheros de pesos. |
| 840 | let fichaModelo = null; |
| 841 | export function setFichaModelo(url, nombre = '') { |
| 842 | fichaModelo = url ? { url, nombre } : null; |
| 843 | const a = $('model-card'); |
| 844 | if (!a) return; |
| 845 | a.hidden = !url; |
| 846 | if (url) { |
| 847 | a.href = url; |
| 848 | a.title = tr('modelCardL', { name: nombre }); |
| 849 | a.setAttribute('aria-label', a.title); |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | export function modelStatus(state) { // 'off' | 'loading' | 'on' | 'gpu' |
| 854 | const d = $('model-status'); |
| 855 | d.className = 'dot ' + state; |
| 856 | // El punto solo era color (y un title en español): ahora dice el estado. |
| 857 | const txt = tr({ off: 'modelStOff', loading: 'modelStLoading', on: 'modelStOn', gpu: 'modelStGpu' }[state] || 'modelStOff'); |
| 858 | d.title = txt; |
| 859 | d.setAttribute('aria-label', txt); |
| 860 | } |
| 861 | |
| 862 | // ---------- selector de modelo (dinámico) ---------- |
| 863 | export function rebuildModelSelect(options, current) { |
| 864 | const sel = $('model-select'); |
| 865 | sel.replaceChildren(); |
| 866 | // Los grupos van SIEMPRE al final, pase lo que pase con el orden de la lista. |
| 867 | // Se creaban según aparecían, y bastó meter un cerebro agrupado en mitad de la |
| 868 | // lista para que «Básico (sin modelo)» —la opción más segura que hay— quedara |
| 869 | // colgando por debajo del encabezado «⚠ Avanzado», como si fuera uno de ellos. |
| 870 | const groups = new Map(); // label de optgroup → <optgroup> |
| 871 | for (const o of options) { |
| 872 | const opt = document.createElement('option'); |
| 873 | opt.value = o.id; |
| 874 | opt.textContent = etiquetaModelo(o.label); |
| 875 | if (o.group) { // cerebros «Avanzado · poco rendimiento» agrupados y avisados |
| 876 | let g = groups.get(o.group); |
| 877 | if (!g) { g = document.createElement('optgroup'); g.label = etiquetaModelo(o.group); groups.set(o.group, g); } |
| 878 | g.appendChild(opt); |
| 879 | } else { |
| 880 | sel.appendChild(opt); |
| 881 | } |
| 882 | } |
| 883 | for (const g of groups.values()) sel.appendChild(g); |
| 884 | if (current && options.some(o => o.id === current)) sel.value = current; |
| 885 | } |
| 886 | |
| 887 | export function setModel(id) { $('model-select').value = id; } |
| 888 | |
| 889 | // Las etiquetas del selector se escriben en español (kernel.js). Fuera del |
| 890 | // español se traducen sus coletillas —«por defecto», «ligero», «Básico (sin |
| 891 | // modelo)»…—, que era lo que quedaba en español en todos los idiomas; los |
| 892 | // nombres de modelo y los tamaños se quedan como están. |
| 893 | const COLETILLAS = [ |
| 894 | ['Básico (sin modelo)', 'optBasic'], |
| 895 | ['⚠ Avanzado · sin garantía de rendimiento', 'optWeakGroup'], |
| 896 | ['⚠ Avanzado', 'optAdvanced'], |
| 897 | ['se guarda: solo se baja la primera vez', 'optSavedOnce'], |
| 898 | ['se guarda', 'optSaved'], |
| 899 | ['más ligero, carga antes', 'optLighter'], |
| 900 | ['poco rendimiento', 'optWeak'], |
| 901 | ['por defecto', 'optDefault'], |
| 902 | ['— ligero', 'optLight'], |
| 903 | ['— texto', 'optText'], |
| 904 | ['— lento', 'optSlow'], |
| 905 | [' · nube', 'optCloud'], |
| 906 | ]; |
| 907 | function etiquetaModelo(label) { |
| 908 | if (uiLang() === 'es') return label; |
| 909 | let out = String(label); |
| 910 | for (const [es, k] of COLETILLAS) if (out.includes(es)) out = out.split(es).join(tr(k)); |
| 911 | return out; |
| 912 | } |
| 913 | |
| 914 | |
| 915 | // Consumo en vivo: qué está gastando Elffuss ahora mismo y cómo soltarlo. |
| 916 | // Se refresca solo mientras el panel está abierto. |
| 917 | function usageCard() { |
| 918 | const card = el('div', 'card col'); |
| 919 | card.appendChild(el('b', null, '📊 ' + tr('useTitle'))); |
| 920 | const ram = el('div', 'row between'), disk = el('div', 'row between'), brain = el('div', 'row between'); |
| 921 | const mk = (row, label) => { row.appendChild(el('span', 'muted', label)); const v = el('span', null, '…'); row.appendChild(v); card.appendChild(row); return v; }; |
| 922 | const vRam = mk(ram, tr('useRam')), vDisk = mk(disk, tr('useDisk')), vBrain = mk(brain, tr('useBrain')); |
| 923 | const gb = n => n >= 1073741824 ? (n / 1073741824).toFixed(2) + ' GB' : Math.round(n / 1048576) + ' MB'; |
| 924 | const freeBtn = btn(tr('useFree'), 'ghost', () => { onFreeModelCb(); toast(tr('useFreed')); setTimeout(paint, 400); }); |
| 925 | card.appendChild(freeBtn); |
| 926 | let timer = null; |
| 927 | async function paint() { |
| 928 | const m = performance.memory; |
| 929 | vRam.textContent = m?.jsHeapSizeLimit |
| 930 | ? `${gb(m.usedJSHeapSize)} / ${gb(m.jsHeapSizeLimit)} (${Math.round(m.usedJSHeapSize / m.jsHeapSizeLimit * 100)}%)` |
| 931 | : tr('useNoRam'); |
| 932 | // Este origen (estimate) más el almacén compartido, medido por model-storage.js |
| 933 | // como el chip y «Vaciar caché»: el modelo grande vive en los brokers de sus |
| 934 | // hosts y estimate() no lo ve. Sin camino al compartido no hay «?». |
| 935 | const [{ usage, quota, persisted }, m2] = await Promise.all([cacheEstimate(), modelos.medir()]); |
| 936 | const comp = { usage: m2.compartido, ok: m2.compartidoOk || !m2.hayCompartido }; |
| 937 | vDisk.textContent = `${gb(usage + comp.usage)}${quota ? ' / ' + gb(quota) : ''} ${persisted ? '· ✓' : '· ⚠'}` + (comp.ok ? '' : ' · ?'); |
| 938 | const sel = $('model-select'); |
| 939 | vBrain.textContent = sel ? (sel.options[sel.selectedIndex]?.textContent || '—').slice(0, 34) : '—'; |
| 940 | if (fichaModelo) { // la ficha del modelo, también aquí |
| 941 | const a = document.createElement('a'); |
| 942 | a.href = fichaModelo.url; a.target = '_blank'; a.rel = 'noopener noreferrer'; |
| 943 | a.textContent = ' ⓘ'; |
| 944 | a.title = tr('modelCardL', { name: fichaModelo.nombre }); |
| 945 | a.setAttribute('aria-label', a.title); |
| 946 | vBrain.appendChild(a); |
| 947 | } |
| 948 | freeBtn.style.display = (sel && sel.value !== 'rules') ? '' : 'none'; |
| 949 | // refrescar solo mientras se está viendo |
| 950 | clearTimeout(timer); |
| 951 | if (document.querySelector('#tabs button.active')?.dataset.tab === 'ajustes') timer = setTimeout(paint, 4000); |
| 952 | } |
| 953 | paint(); |
| 954 | return card; |
| 955 | } |
| 956 | let onFreeModelCb = () => {}; |
| 957 | export function setOnFreeModel(fn) { onFreeModelCb = fn; } |
| 958 | let onWipeCb = async () => { await workspace.wipe({ confirm: 'BORRAR' }); location.reload(); }; |
| 959 | export function setOnWipe(fn) { onWipeCb = fn; } |
| 960 | |
| 961 | // ---------- espacio de trabajo (carpeta en disco, inventario, limpieza) ---------- |
| 962 | const kb = n => n > 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n > 1024 ? Math.round(n / 1024) + ' KB' : n + ' B'; |
| 963 | |
| 964 | function workspaceCard() { |
| 965 | const card = el('div', 'card col'); |
| 966 | card.appendChild(el('b', null, '💾 ' + tr('wsTitle'))); |
| 967 | card.appendChild(el('span', 'muted', tr('wsDesc'))); |
| 968 | |
| 969 | const state = el('div', 'muted'); |
| 970 | const row = el('div', 'row'); |
| 971 | const inv = el('div', 'col'); |
| 972 | card.append(state, row, inv); |
| 973 | |
| 974 | const paint = async () => { |
| 975 | const st = workspace.status(); |
| 976 | row.replaceChildren(); |
| 977 | state.textContent = !st.supported.pick ? tr('wsNoSupport') |
| 978 | : !st.folder ? tr('wsNoFolder') |
| 979 | : st.ready ? tr('wsFolder', { name: st.folder }) + (st.lastSaveAt ? ' · ' + tr('wsSavedAt', { time: new Date(st.lastSaveAt).toLocaleTimeString() }) : '') |
| 980 | : tr('wsNeedsPerm', { name: st.folder }); |
| 981 | |
| 982 | if (st.supported.pick) { |
| 983 | if (!st.folder) row.appendChild(btn(tr('wsPick'), 'primary', async () => { |
| 984 | try { await workspace.pick(); toast(tr('wsPicked')); await paint(); } catch (e) { toast('⚠️ ' + e.message); } |
| 985 | })); |
| 986 | else if (!st.ready) row.appendChild(btn(tr('wsRegrant'), 'primary', async () => { |
| 987 | try { await workspace.regrant(); toast(tr('wsPicked')); await paint(); } catch (e) { toast('⚠️ ' + e.message); } |
| 988 | })); |
| 989 | else { |
| 990 | row.appendChild(btn(tr('wsSaveNow'), 'primary', async () => { |
| 991 | try { const r = await workspace.save({ reason: 'manual' }); toast(r.ok ? tr('wsSaved', { n: r.wrote.length }) : '⚠️ ' + (r.errors[0]?.error || '')); await paint(); } |
| 992 | catch (e) { toast('⚠️ ' + (e.message === 'needs-regrant' ? tr('wsNeedsPerm', { name: st.folder }) : e.message)); await paint(); } |
| 993 | })); |
| 994 | const auto = el('label', 'row'); |
| 995 | const chk = el('input'); chk.type = 'checkbox'; chk.checked = workspace.autosaveEnabled(); |
| 996 | chk.onchange = () => { workspace.autosave({ enabled: chk.checked }); toast(chk.checked ? tr('wsAutoOn') : tr('wsAutoOff')); }; |
| 997 | auto.append(chk, el('span', 'muted', tr('wsAuto'))); |
| 998 | row.appendChild(auto); |
| 999 | row.appendChild(btn(tr('wsForget'), 'ghost', async () => { await workspace.forget(); await paint(); })); |
| 1000 | } |
| 1001 | } |
| 1002 | // copia descargable: funciona en TODOS los navegadores (Safari/Firefox incluidos) |
| 1003 | row.appendChild(btn(tr('wsDownload'), 'ghost', async () => { |
| 1004 | const blob = await workspace.bundle(); |
| 1005 | const a = document.createElement('a'); |
| 1006 | a.href = URL.createObjectURL(blob); |
| 1007 | a.download = `elffuss-claw-${new Date().toISOString().slice(0, 10)}.json`; |
| 1008 | a.click(); |
| 1009 | setTimeout(() => URL.revokeObjectURL(a.href), 4000); |
| 1010 | })); |
| 1011 | |
| 1012 | // inventario: «ver qué hay» en cada almacén |
| 1013 | inv.replaceChildren(el('b', null, tr('wsWhat'))); |
| 1014 | for (const it of await workspace.inventory()) { |
| 1015 | const line = el('div', 'row between'); |
| 1016 | line.appendChild(el('span', null, `${it.icon} ${it.label}`)); |
| 1017 | line.appendChild(el('span', 'muted', it.error ? '⚠️' : `${it.count} · ${kb(it.bytes)}${it.sensitive ? ' 🔒' : ''}`)); |
| 1018 | inv.appendChild(line); |
| 1019 | } |
| 1020 | const danger = el('div', 'row'); |
| 1021 | const wipe = btn(tr('wsWipe'), 'ghost', async () => { |
| 1022 | if (!window.confirm(tr('wsWipeConfirm'))) return; |
| 1023 | wipe.disabled = true; |
| 1024 | // Lo hace el kernel: para el turno en marcha, borra y RECARGA. Borrar solo |
| 1025 | // el IndexedDB dejaba la conversación en pantalla y en memoria, y el |
| 1026 | // siguiente mensaje la volvía a guardar entera; skills, bóveda abierta y |
| 1027 | // app actual también seguían vivas hasta recargar. |
| 1028 | try { await onWipeCb(); } |
| 1029 | catch (e) { wipe.disabled = false; toast('⚠️ ' + (e?.message || e)); } |
| 1030 | }); |
| 1031 | danger.appendChild(wipe); |
| 1032 | inv.appendChild(danger); |
| 1033 | }; |
| 1034 | paint().catch(() => { state.textContent = '—'; }); |
| 1035 | return card; |
| 1036 | } |
| 1037 | |
| 1038 | // ---------- panel ajustes (config avanzada de proveedores) ---------- |
| 1039 | export function refreshSettings() { |
| 1040 | const panel = $('panel-ajustes'); |
| 1041 | panel.replaceChildren(); |
| 1042 | // Lo que se consulta a menudo va PRIMERO: qué está gastando y cómo limpiarlo. |
| 1043 | // Los proveedores externos son configuración avanzada y bajan al final. |
| 1044 | panel.appendChild(usageCard()); |
| 1045 | panel.appendChild(workspaceCard()); |
| 1046 | panel.appendChild(memoriaCard()); |
| 1047 | // Los modelos EXTERNOS (no locales) van al final, en su propia sección |
| 1048 | // plegada: son la excepción, no la norma — Elffuss corre en tu máquina. |
| 1049 | const ext = document.createElement('details'); |
| 1050 | ext.className = 'card col ext-block'; |
| 1051 | const extSum = document.createElement('summary'); |
| 1052 | extSum.textContent = tr('extTitle'); |
| 1053 | ext.appendChild(extSum); |
| 1054 | ext.appendChild(el('p', 'muted', tr('extDesc'))); |
| 1055 | |
| 1056 | const cfgs = settings.configs(); |
| 1057 | for (const [id, c] of Object.entries(cfgs)) { |
| 1058 | const wrap = el('div', 'card col'); |
| 1059 | const head = el('div', 'row between'); |
| 1060 | // La casilla con nombre: era una casilla suelta sin etiqueta. |
| 1061 | const toggle = el('input'); |
| 1062 | toggle.type = 'checkbox'; |
| 1063 | toggle.id = 'prov-' + id; |
| 1064 | toggle.checked = c.enabled; |
| 1065 | const title = el('label', 'prov-name', c.label); |
| 1066 | title.htmlFor = toggle.id; |
| 1067 | toggle.setAttribute('aria-label', tr('provEnableL', { label: c.label })); |
| 1068 | head.append(title, toggle); |
| 1069 | wrap.appendChild(head); |
| 1070 | wrap.appendChild(el('span', 'muted', c.help || '')); |
| 1071 | |
| 1072 | const model = el('input'); |
| 1073 | model.placeholder = tr('modelPh'); |
| 1074 | model.value = c.model || ''; |
| 1075 | const base = el('input'); |
| 1076 | base.placeholder = tr('endpointPh'); |
| 1077 | base.value = c.baseURL || ''; |
| 1078 | const key = el('input'); |
| 1079 | key.type = 'password'; |
| 1080 | key.placeholder = c.kind === 'anthropic' ? 'sk-ant-…' : (id === 'ollama' || id === 'server' ? tr('keyNeeded') : 'sk-…'); |
| 1081 | key.value = c.apiKey || ''; |
| 1082 | |
| 1083 | wrap.append(labeled(tr('lblModel'), model), labeled(tr('lblEndpoint'), base)); |
| 1084 | if (id !== 'ollama' && id !== 'server') wrap.append(labeled(tr('lblApiKey'), key)); |
| 1085 | |
| 1086 | const save = () => { |
| 1087 | settings.update(id, { |
| 1088 | enabled: toggle.checked, |
| 1089 | model: model.value.trim(), |
| 1090 | baseURL: base.value.trim(), |
| 1091 | apiKey: key.value, |
| 1092 | }); |
| 1093 | onSettingsChangedCb(); |
| 1094 | }; |
| 1095 | // «Elígelo en el selector de modelo», con un botón que lleva a él (antes |
| 1096 | // decía «en el selector 🧠», y 🧠 abre la Mente). |
| 1097 | toggle.onchange = () => { |
| 1098 | save(); |
| 1099 | if (toggle.checked) toast(tr('provOn', { label: c.label }), { accion: { label: tr('pickModel'), run: enfocarSelectorModelo } }); |
| 1100 | else toast(tr('provOff', { label: c.label })); |
| 1101 | }; |
| 1102 | wrap.appendChild(btn(tr('save'), 'primary', () => { save(); toast(tr('saved')); })); |
| 1103 | ext.appendChild(wrap); |
| 1104 | } |
| 1105 | |
| 1106 | // --- Almacenamiento del modelo (caché persistente) --- |
| 1107 | const store = el('div', 'card col'); |
| 1108 | store.appendChild(el('b', null, tr('storeTitle'))); |
| 1109 | const info = el('span', 'muted', tr('storeCalc')); |
| 1110 | store.appendChild(info); |
| 1111 | // Lo mismo que el chip 💾 (model-storage.js): cuenta solo pesos, y vacía los de |
| 1112 | // este origen y los del almacén compartido de CADA broker con modelos (antes |
| 1113 | // el modelo grande, guardado en los brokers de sus hosts, no se tocaba). |
| 1114 | const clearBtn = btn(tr('storeClear'), 'ghost', async () => { |
| 1115 | clearBtn.disabled = true; |
| 1116 | clearBtn.setAttribute('aria-busy', 'true'); |
| 1117 | info.textContent = tr('storeClearing'); |
| 1118 | try { avisarLiberado(await modelos.vaciar()); } |
| 1119 | catch (e) { toast(tr('diskFail', { err: e?.message || e })); } |
| 1120 | clearBtn.disabled = false; |
| 1121 | clearBtn.removeAttribute('aria-busy'); |
| 1122 | await paintStore(); |
| 1123 | }); |
| 1124 | store.appendChild(clearBtn); |
| 1125 | panel.appendChild(store); |
| 1126 | async function paintStore() { |
| 1127 | contarCompartido(); // Ajustes abierto: el chip ya puede preguntar al compartido |
| 1128 | const [{ total, compartido, compartidoOk, hayCompartido }, { quota, persisted }] = await Promise.all([modelos.medir(), cacheEstimate()]); |
| 1129 | const gb = n => (n / 1073741824).toFixed(2) + ' GB'; |
| 1130 | info.textContent = (total >= UMBRAL_CHIP ? tr('storeCached', { gb: gb(total) }) : tr('storeNone')) |
| 1131 | + (persisted ? tr('storePersist') : tr('storeNoPersist')) |
| 1132 | + (quota ? tr('storeLimit', { gb: gb(quota) }) : '') |
| 1133 | + (!hayCompartido ? '' : !compartidoOk ? tr('storeSharedUnknown') : compartido ? tr('storeShared', { gb: gb(compartido) }) : ''); |
| 1134 | } |
| 1135 | paintStore(); |
| 1136 | |
| 1137 | // --- 📨 Errores y feedback (opt-in — apagado no sale NADA de tu máquina) --- |
| 1138 | const telCard = el('div', 'card col'); |
| 1139 | telCard.innerHTML = |
| 1140 | `<b>${tr('telTitle')}</b>` + |
| 1141 | `<label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-top:6px">` + |
| 1142 | `<input type="checkbox" id="tel-enabled"> ` + |
| 1143 | `<span>${tr('telAuto')}</span>` + |
| 1144 | `</label>` + |
| 1145 | `<span class="muted">${tr('telPrivacy')}</span>` + |
| 1146 | `<label class="muted" for="tel-feedback" style="font-size:.8em;margin-top:4px">${tr('telManual')}</label>` + |
| 1147 | `<textarea id="tel-feedback" rows="2" style="width:100%;resize:vertical" placeholder="${tr('telPh')}"></textarea>`; |
| 1148 | // Dice si LLEGÓ: antes daba las gracias y vaciaba el texto aunque el envío |
| 1149 | // fallara. Si falla, el texto se queda y se ofrece el sitio público de |
| 1150 | // incidencias, que además deja un enlace para seguirlo. |
| 1151 | const telSendBtn = btn(tr('send'), 'primary', async () => { |
| 1152 | const ta = telCard.querySelector('#tel-feedback'); |
| 1153 | const text = ta.value.trim(); |
| 1154 | if (!text) { toast(tr('writeSomething')); ta.focus(); return; } |
| 1155 | telSendBtn.disabled = true; |
| 1156 | const wasEnabled = telemetry.isEnabled(); |
| 1157 | if (!wasEnabled) telemetry.setEnabled(true); // envío manual es explícito, se permite aunque el automático esté apagado |
| 1158 | let llego = false; |
| 1159 | try { llego = await telemetry.sendFeedback(text); } |
| 1160 | finally { |
| 1161 | if (!wasEnabled) telemetry.setEnabled(false); // no activa el automático de fondo si no lo pidió |
| 1162 | telSendBtn.disabled = false; |
| 1163 | } |
| 1164 | if (llego) { ta.value = ''; toast(tr('sentThanks')); } |
| 1165 | else toast(tr('sendFailed'), { accion: { label: tr('openIssues'), run: () => window.open(ISSUES_URL, '_blank', 'noopener,noreferrer') } }); |
| 1166 | }); |
| 1167 | telCard.appendChild(telSendBtn); |
| 1168 | const alt = el('span', 'muted', tr('telIssues') + ' '); |
| 1169 | alt.appendChild(enlaceFuera(ISSUES_URL, 'git.elffuss.com/elffuss/claw/issues ↗')); |
| 1170 | telCard.appendChild(alt); |
| 1171 | panel.appendChild(telCard); |
| 1172 | panel.appendChild(ext); // externos: lo último de todo |
| 1173 | telCard.querySelector('#tel-enabled').checked = telemetry.isEnabled(); |
| 1174 | telCard.querySelector('#tel-enabled').onchange = e => telemetry.setEnabled(e.target.checked); |
| 1175 | |
| 1176 | panel.appendChild(acercaDe()); |
| 1177 | panel.appendChild(el('p', 'muted', tr('skillsTabHint'))); |
| 1178 | } |
| 1179 | |
| 1180 | // ---------- memoria ---------- |
| 1181 | // Lo que Elffuss recuerda de ti (memory.save) se veía solo como un número en |
| 1182 | // «Qué hay guardado» o pidiéndoselo al chat. Aquí se ve y se olvida hecho a hecho. |
| 1183 | function memoriaCard() { |
| 1184 | const c = el('div', 'card col'); |
| 1185 | c.dataset.ruta = 'memoria'; // #/memoria |
| 1186 | pintarMemoria(c); |
| 1187 | return c; |
| 1188 | } |
| 1189 | async function pintarMemoria(c) { |
| 1190 | const hechos = (await db.all('memory').catch(() => [])).sort((a, b) => a.at - b.at); |
| 1191 | c.replaceChildren(el('b', null, tr('memTitle')), el('span', 'muted', tr('memDesc'))); |
| 1192 | if (!hechos.length) c.appendChild(el('span', 'muted', tr('memEmpty'))); |
| 1193 | for (const f of hechos) { |
| 1194 | const fila = el('div', 'row between'); |
| 1195 | fila.dataset.ruta = f.id; // #/memoria/<id> |
| 1196 | const x = btn('✕', 'ghost', async () => { |
| 1197 | await memory.forget({ id: f.id }); |
| 1198 | pintarMemoria(c); |
| 1199 | toast(tr('memForgotten'), { accion: { label: tr('undo'), run: async () => { await db.set('memory', f.id, f); pintarMemoria(c); } } }); |
| 1200 | }); |
| 1201 | x.title = tr('memForgetL', { fact: String(f.fact).slice(0, 60) }); |
| 1202 | x.setAttribute('aria-label', x.title); |
| 1203 | fila.append(el('span', null, f.fact), x); |
| 1204 | c.appendChild(fila); |
| 1205 | } |
| 1206 | } |
| 1207 | |
| 1208 | // ---------- acerca de ---------- |
| 1209 | // Dónde está el código, dónde se cuentan los fallos y con qué licencia. No |
| 1210 | // estaba en ninguna parte de la interfaz. |
| 1211 | const REPO_URL = 'https://github.com/KikoCis/elffuss-claw'; |
| 1212 | const COMUNIDAD_URL = 'https://git.elffuss.com/elffuss/claw'; |
| 1213 | const ISSUES_URL = COMUNIDAD_URL + '/issues'; |
| 1214 | function enlaceFuera(href, texto) { |
| 1215 | const a = document.createElement('a'); |
| 1216 | a.href = href; a.target = '_blank'; a.rel = 'noopener noreferrer'; |
| 1217 | a.textContent = texto; |
| 1218 | return a; |
| 1219 | } |
| 1220 | // El sello del build: un commit limpio enlaza a GitHub; «-dirty» (desplegado con |
| 1221 | // cambios sin commitear, ver deploy.sh) no, porque ese commit no es lo que se |
| 1222 | // sirve; en desarrollo no hay sello. |
| 1223 | export function enlaceBuild(sello) { |
| 1224 | const s = String(sello || '').trim(); |
| 1225 | if (/^[0-9a-f]{7,40}$/.test(s)) return enlaceFuera(`${REPO_URL}/commit/${s}`, s); |
| 1226 | if (/^[0-9a-f]{7,40}-dirty$/.test(s)) { const x = el('span', null, s); x.title = tr('buildDirty'); return x; } |
| 1227 | return el('span', null, tr('buildDev')); |
| 1228 | } |
| 1229 | function acercaDe() { |
| 1230 | const c = el('div', 'card col'); |
| 1231 | c.dataset.ruta = 'acerca'; // #/ajustes/acerca |
| 1232 | c.appendChild(el('b', null, tr('aboutTitle'))); |
| 1233 | const l1 = el('span', 'muted', tr('aboutCode') + ' '); |
| 1234 | l1.append(enlaceFuera(REPO_URL, 'github.com/KikoCis/elffuss-claw ↗'), ' · ' + tr('aboutCommunity') + ' ', |
| 1235 | enlaceFuera(COMUNIDAD_URL, 'git.elffuss.com/elffuss/claw ↗'), ' · ', enlaceFuera(ISSUES_URL, tr('aboutIssues') + ' ↗')); |
| 1236 | const l2 = el('span', 'muted', tr('aboutLicense') + ' · ' + tr('aboutBuild') + ' '); |
| 1237 | l2.appendChild(enlaceBuild($('build')?.dataset.sello || $('build')?.textContent)); |
| 1238 | c.append(l1, l2); |
| 1239 | return c; |
| 1240 | } |
| 1241 | |
| 1242 | // Dos secciones que se repintan solas: lo instalado (con su contador) y las |
| 1243 | // fuentes. Antes «Quitar» y «Añadir repo» llamaban a refreshSettings() —el panel |
| 1244 | // de AJUSTES— y aquí no cambiaba nada hasta cambiar de pestaña; «Instalar» no |
| 1245 | // tocaba el contador; «Explorar» añadía la lista al final del panel, una copia |
| 1246 | // más por clic. |
| 1247 | async function renderSkills(panel) { |
| 1248 | const instaladas = el('section', 'skills-instaladas'); |
| 1249 | const fuentes = el('section', 'skills-fuentes'); |
| 1250 | panel.append(instaladas, fuentes); |
| 1251 | pintarInstaladas(instaladas); |
| 1252 | await pintarFuentes(fuentes, instaladas); |
| 1253 | } |
| 1254 | |
| 1255 | // La skill instalada desde un repo enlaza a su SKILL.md; todas dejan ver lo |
| 1256 | // que se inyecta al modelo (el panel lo prometía y no había forma de verlo). |
| 1257 | const enlaceSkillMd = (repo, path, branch = 'HEAD') => { |
| 1258 | const a = document.createElement('a'); |
| 1259 | a.href = `https://github.com/${repo}/blob/${encodeURIComponent(branch)}/${path.split('/').map(encodeURIComponent).join('/')}`; |
| 1260 | a.target = '_blank'; a.rel = 'noopener noreferrer'; |
| 1261 | a.className = 'repo-link'; |
| 1262 | a.textContent = 'SKILL.md ↗'; |
| 1263 | return a; |
| 1264 | }; |
| 1265 | function pintarInstaladas(box) { |
| 1266 | const inst = skills.installed(); |
| 1267 | box.replaceChildren(el('div', 'muted', tr('installedN', { n: inst.length }))); |
| 1268 | for (const s of inst) { |
| 1269 | const c = el('div', 'card col'); |
| 1270 | c.dataset.ruta = s.name; // #/skills/<nombre> |
| 1271 | const fila = el('div', 'row between'); |
| 1272 | const desdeRepo = s.repo && s.path && !String(s.path).startsWith('local/'); |
| 1273 | const origen = desdeRepo ? enlaceSkillMd(s.repo, s.path) : el('span', 'muted', s.repo || 'local'); |
| 1274 | const quitar = btn(tr('remove'), 'ghost', async () => { |
| 1275 | await skills.remove(s.name); |
| 1276 | pintarInstaladas(box); |
| 1277 | toast(tr('skillRemoved', { name: s.name }), { accion: { label: tr('undo'), run: async () => { |
| 1278 | try { await skills.install(s); pintarInstaladas(box); } catch (e) { toast('⚠️ ' + e.message); } |
| 1279 | } } }); |
| 1280 | }); |
| 1281 | quitar.setAttribute('aria-label', tr('skillRemoveL', { name: s.name })); |
| 1282 | fila.append(el('b', null, s.name), el('span', 'muted', desdeRepo ? s.repo : ''), origen, quitar); |
| 1283 | const ver = document.createElement('details'); |
| 1284 | const sum = document.createElement('summary'); |
| 1285 | sum.textContent = tr('skillSeeText'); |
| 1286 | const pre = el('pre', 'skill-text', [s.description, s.content].filter(Boolean).join('\n\n')); |
| 1287 | ver.append(sum, pre); |
| 1288 | c.append(fila, ver); |
| 1289 | box.appendChild(c); |
| 1290 | } |
| 1291 | } |
| 1292 | |
| 1293 | async function pintarFuentes(box, instaladas) { |
| 1294 | const srcs = await skills.sources(); |
| 1295 | box.replaceChildren(); |
| 1296 | for (const src of srcs) { |
| 1297 | const c = el('div', 'card col'); |
| 1298 | c.dataset.ruta = 'repo:' + src.repo; |
| 1299 | const fila = el('div', 'row between'); |
| 1300 | const link = document.createElement('a'); |
| 1301 | link.href = 'https://github.com/' + src.repo; |
| 1302 | link.target = '_blank'; link.rel = 'noopener noreferrer'; |
| 1303 | link.className = 'repo-link'; |
| 1304 | link.textContent = src.repo + ' ↗'; |
| 1305 | const lista = el('div', 'repo-skills'); |
| 1306 | lista.id = 'repo-' + src.repo.replace(/[^\w-]/g, '-'); |
| 1307 | lista.hidden = true; |
| 1308 | lista.setAttribute('aria-live', 'polite'); |
| 1309 | const explorar = btn(tr('browse'), 'primary', () => explorarRepo(src.repo, lista, explorar, instaladas)); |
| 1310 | explorar.setAttribute('aria-expanded', 'false'); |
| 1311 | explorar.setAttribute('aria-controls', lista.id); |
| 1312 | fila.append(el('b', null, src.label), link, explorar); |
| 1313 | if (!src.official) { // las que añadiste tú se pueden quitar |
| 1314 | const x = btn('✕', 'ghost', async () => { |
| 1315 | await skills.removeSource(src.repo); |
| 1316 | toast(tr('repoRemoved', { repo: src.repo })); |
| 1317 | await pintarFuentes(box, instaladas); |
| 1318 | }); |
| 1319 | x.title = tr('repoRemoveL', { repo: src.repo }); |
| 1320 | x.setAttribute('aria-label', tr('repoRemoveL', { repo: src.repo })); |
| 1321 | fila.appendChild(x); |
| 1322 | } |
| 1323 | c.append(fila, lista); |
| 1324 | box.appendChild(c); |
| 1325 | } |
| 1326 | const form = el('form', 'row'); |
| 1327 | const inp = el('input'); inp.placeholder = tr('repoPh'); |
| 1328 | inp.setAttribute('aria-label', tr('repoPh')); |
| 1329 | const add = el('button', 'primary', tr('addRepo')); |
| 1330 | add.type = 'submit'; |
| 1331 | form.addEventListener('submit', async e => { |
| 1332 | e.preventDefault(); |
| 1333 | try { |
| 1334 | const repo = await skills.addSource(inp.value); |
| 1335 | inp.value = ''; |
| 1336 | toast(tr('repoAdded', { repo })); |
| 1337 | await pintarFuentes(box, instaladas); |
| 1338 | box.querySelector(`[data-ruta="${CSS.escape('repo:' + repo)}"] button`)?.focus(); |
| 1339 | } catch (err) { toast('⚠️ ' + err.message); } |
| 1340 | }); |
| 1341 | form.append(inp, add); |
| 1342 | box.appendChild(form); |
| 1343 | } |
| 1344 | |
| 1345 | // La lista de un repo va DENTRO de su tarjeta y el botón la abre y la cierra. |
| 1346 | async function explorarRepo(repo, lista, boton, instaladas) { |
| 1347 | if (!lista.hidden) { |
| 1348 | lista.hidden = true; |
| 1349 | boton.textContent = tr('browse'); |
| 1350 | boton.setAttribute('aria-expanded', 'false'); |
| 1351 | return; |
| 1352 | } |
| 1353 | lista.hidden = false; |
| 1354 | boton.setAttribute('aria-expanded', 'true'); |
| 1355 | boton.textContent = tr('hideList'); |
| 1356 | if (lista.dataset.cargada) return; |
| 1357 | boton.disabled = true; |
| 1358 | lista.setAttribute('aria-busy', 'true'); |
| 1359 | lista.replaceChildren(el('div', 'muted', tr('loadingRepo', { repo }))); |
| 1360 | try { |
| 1361 | const found = await skills.listFromRepo(repo); |
| 1362 | lista.replaceChildren(el('div', 'muted', tr('repoSkills', { repo, n: found.length }))); |
| 1363 | for (const sk of found.slice(0, 120)) { |
| 1364 | const c = el('div', 'card'); |
| 1365 | const on = skills.isInstalled(sk.repo, sk.path); |
| 1366 | const b = btn(on ? tr('installedOk') : tr('install'), on ? 'ghost' : 'primary', async () => { |
| 1367 | b.disabled = true; |
| 1368 | b.textContent = '…'; |
| 1369 | try { |
| 1370 | const entry = await skills.installFromRepo(sk); |
| 1371 | b.textContent = tr('installedOk'); |
| 1372 | b.className = 'ghost'; |
| 1373 | pintarInstaladas(instaladas); |
| 1374 | onSkillInstalledCb(entry); // → mensaje «cómo usarla» en el chat |
| 1375 | } catch (e) { b.disabled = false; b.textContent = tr('install'); toast('⚠️ ' + e.message); } |
| 1376 | }); |
| 1377 | b.disabled = on; |
| 1378 | b.setAttribute('aria-label', (on ? tr('installedOk') : tr('install')) + ': ' + sk.name); |
| 1379 | c.append(el('b', null, sk.name), el('span', 'muted', sk.dir), enlaceSkillMd(sk.repo, sk.path, sk.branch || 'HEAD'), b); |
| 1380 | lista.appendChild(c); |
| 1381 | } |
| 1382 | lista.dataset.cargada = '1'; |
| 1383 | } catch (e) { |
| 1384 | lista.replaceChildren(el('div', 'muted', '⚠️ ' + e.message)); |
| 1385 | } finally { |
| 1386 | boton.disabled = false; |
| 1387 | lista.removeAttribute('aria-busy'); |
| 1388 | } |
| 1389 | } |
| 1390 | |
| 1391 | function labeled(label, input) { |
| 1392 | const row = el('label', 'field'); |
| 1393 | row.append(el('span', 'muted', label), input); |
| 1394 | return row; |
| 1395 | } |
| 1396 | |
| 1397 | // ---------- botón enviar ↔ parar ---------- |
| 1398 | // Mientras Elffuss trabaja, #send es ■ y PARA (mismo icono, título y aria que |
| 1399 | // en Elffuss Code). Va como type="button" a propósito: así un clic en él —con |
| 1400 | // ratón, dedo o teclado— solo para, y Enter en la caja ya no pasa por el botón |
| 1401 | // (sin botón de enviar, el formulario se envía directamente) y sigue mandando |
| 1402 | // a la cola lo que escribas, que es como funciona la cola de Claw. |
| 1403 | 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>'; |
| 1404 | let working = false, parando = false; |
| 1405 | export function setWorking(on) { |
| 1406 | working = !!on; |
| 1407 | parando = false; |
| 1408 | const b = $('send'); |
| 1409 | if (!b) return; |
| 1410 | b.type = working ? 'button' : 'submit'; |
| 1411 | b.classList.toggle('is-stop', working); |
| 1412 | b.classList.remove('is-stopping'); |
| 1413 | b.removeAttribute('aria-busy'); |
| 1414 | b.removeAttribute('aria-disabled'); |
| 1415 | b.innerHTML = working ? STOP_ICON : UI.send; |
| 1416 | b.title = working ? tr('stop') : tr('send'); |
| 1417 | b.setAttribute('aria-label', b.title); |
| 1418 | } |
| 1419 | |
| 1420 | // «Parando…»: ya se pulsó ■ y el turno aún está soltando el modelo (un cerebro |
| 1421 | // que no suelta al momento, una herramienta, Hard Work leyendo la carpeta…). |
| 1422 | // Antes el ■ seguía igual tras el clic —rojo, «Parar», pulsable— y parecía que |
| 1423 | // no había hecho caso. Mientras dura, los clics no hacen nada. Se marca con |
| 1424 | // aria-disabled y NO con disabled: deshabilitar el botón que tiene el foco lo |
| 1425 | // saca del foco y el teclado cae a <body> (lo mismo que en Elffuss Code). |
| 1426 | // Vuelve a ➤ (o a ■ si arranca el siguiente de la cola) con setWorking(). |
| 1427 | export function setStopping() { |
| 1428 | const b = $('send'); |
| 1429 | if (!b || !working) return; |
| 1430 | parando = true; |
| 1431 | b.classList.add('is-stopping'); |
| 1432 | b.setAttribute('aria-busy', 'true'); |
| 1433 | b.setAttribute('aria-disabled', 'true'); |
| 1434 | b.textContent = tr('stopping'); |
| 1435 | b.title = tr('stopping'); |
| 1436 | b.setAttribute('aria-label', b.title); |
| 1437 | } |
| 1438 | |
| 1439 | // ---------- arranque ---------- |
| 1440 | export function init({ onSend, onStop = () => {}, onModelChange, onSettingsChanged, onPickFolder = () => onSend(tr('pFolder')) }) { |
| 1441 | perms.setAsker(askPermission); |
| 1442 | apps.setRenderer((name, html) => renderApp(name, html, { ruta: true })); |
| 1443 | apps.setOnRemoved(vaciarVisor); |
| 1444 | if ($('appframe').hidden) $('appframe').title = tr('appFrameEmpty'); |
| 1445 | onSettingsChangedCb = onSettingsChanged || (() => {}); |
| 1446 | // al instalar una skill: mensaje «cómo usarla» en el chat + volver al chat en móvil |
| 1447 | onSkillInstalledCb = entry => { |
| 1448 | addMsg('assistant', skills.usageMessage(entry)); // addMsg renderiza markdown en 'assistant' |
| 1449 | if (isMobile()) flipTo('chat'); |
| 1450 | }; |
| 1451 | |
| 1452 | // Historial del prompt: ↑/↓ recuperan lo enviado (como una shell). Persistente. |
| 1453 | const HKEY = 'elffuss.promptHistory'; |
| 1454 | let hist = []; try { hist = JSON.parse(localStorage.getItem(HKEY) || '[]'); } catch { /* corrupto */ } |
| 1455 | let hIdx = -1, draft = ''; |
| 1456 | $('prompt').addEventListener('keydown', e => { |
| 1457 | if (!$('cmd-menu').hidden) return; // el menú «/» ya usa ↑/↓ |
| 1458 | const inp = e.target; |
| 1459 | if (e.key === 'ArrowUp') { |
| 1460 | if (!hist.length) return; |
| 1461 | if (hIdx === -1) { draft = inp.value; hIdx = hist.length; } |
| 1462 | hIdx = Math.max(0, hIdx - 1); inp.value = hist[hIdx]; e.preventDefault(); |
| 1463 | requestAnimationFrame(() => inp.setSelectionRange(inp.value.length, inp.value.length)); |
| 1464 | } else if (e.key === 'ArrowDown') { |
| 1465 | if (hIdx === -1) return; |
| 1466 | hIdx++; inp.value = hIdx >= hist.length ? (hIdx = -1, draft) : hist[hIdx]; e.preventDefault(); |
| 1467 | } |
| 1468 | }); |
| 1469 | $('send').addEventListener('click', e => { |
| 1470 | if (!working) return; // en reposo es el submit de siempre |
| 1471 | e.preventDefault(); |
| 1472 | if (parando) return; // ya se está parando: otro clic no hace nada |
| 1473 | onStop(); |
| 1474 | }); |
| 1475 | $('composer').addEventListener('submit', e => { |
| 1476 | e.preventDefault(); |
| 1477 | // Mientras trabaja, aquí solo se llega con Enter (el ■ no envía): con texto |
| 1478 | // va a la cola como siempre, y sin texto no hace nada —un segundo Enter |
| 1479 | // dado por inercia no debe tirar el trabajo en curso—. Parar es el ■. |
| 1480 | const text = $('prompt').value.trim(); |
| 1481 | if (!text || text === '/') return; // un «/» suelto es abrir el menú, no un mensaje |
| 1482 | $('prompt').value = ''; |
| 1483 | if (hist[hist.length - 1] !== text) hist.push(text); |
| 1484 | if (hist.length > 100) hist = hist.slice(-100); |
| 1485 | try { localStorage.setItem(HKEY, JSON.stringify(hist)); } catch { /* lleno */ } |
| 1486 | hIdx = -1; draft = ''; |
| 1487 | onSend(text, { desdeCaja: true }); // solo lo escrito en la caja puede ir por Hard Work |
| 1488 | }); |
| 1489 | // Chips: botones (antes <span> sin foco). «Autoriza una carpeta» abre el |
| 1490 | // selector de carpetas EN el clic: pasándoselo al modelo, el selector nativo |
| 1491 | // llegaba después de su turno y el navegador ya no lo dejaba abrir. |
| 1492 | $('chips').addEventListener('click', e => { |
| 1493 | const c = e.target.closest('.chip'); |
| 1494 | if (!c) return; |
| 1495 | if (c.dataset.accion === 'carpeta') onPickFolder(); |
| 1496 | else onSend(c.textContent.trim()); |
| 1497 | }); |
| 1498 | document.querySelectorAll('#tabs button').forEach(b => |
| 1499 | b.addEventListener('click', () => selectTab(b.dataset.tab, { push: true }))); |
| 1500 | // Flechas, Inicio y Fin entre pestañas (patrón de tablist): solo la activa |
| 1501 | // está en el orden de tabulación, y moverse con flechas la activa. |
| 1502 | $('tabs').addEventListener('keydown', e => { |
| 1503 | const tabs = [...document.querySelectorAll('#tabs [role="tab"]')]; |
| 1504 | const i = tabs.indexOf(document.activeElement); |
| 1505 | if (i < 0) return; |
| 1506 | const j = e.key === 'ArrowRight' ? (i + 1) % tabs.length |
| 1507 | : e.key === 'ArrowLeft' ? (i - 1 + tabs.length) % tabs.length |
| 1508 | : e.key === 'Home' ? 0 : e.key === 'End' ? tabs.length - 1 : -1; |
| 1509 | if (j < 0) return; |
| 1510 | e.preventDefault(); |
| 1511 | tabs[j].focus(); |
| 1512 | selectTab(tabs[j].dataset.tab); |
| 1513 | }); |
| 1514 | $('btn-perms').addEventListener('click', () => { selectTab('permisos', { push: true }); if (isMobile()) flipTo('viz'); }); |
| 1515 | $('model-select').addEventListener('change', e => onModelChange(e.target.value)); |
| 1516 | // El selector tenía por nombre un icono: ahora se llama «Cerebro (modelo de IA)». |
| 1517 | $('model-select').setAttribute('aria-label', tr('modelSelectL')); |
| 1518 | modelStatus($('model-status').className.replace('dot', '').trim() || 'off'); |
| 1519 | $('btn-flip').addEventListener('click', () => |
| 1520 | flipTo(document.body.classList.contains('show-viz') ? 'chat' : 'viz')); |
| 1521 | pintarFlip(); |
| 1522 | // En el teléfono el botón flota por encima de los chips y del compositor: su |
| 1523 | // alto real (cambia con el idioma y el teclado) va a --alto-pie. |
| 1524 | const altoPie = () => document.documentElement.style.setProperty('--alto-pie', |
| 1525 | (($('composer')?.offsetHeight || 0) + ($('chips')?.offsetHeight || 0)) + 'px'); |
| 1526 | try { const ro = new ResizeObserver(altoPie); ro.observe($('composer')); ro.observe($('chips')); } catch { /* sin ResizeObserver: queda el valor por defecto */ } |
| 1527 | altoPie(); |
| 1528 | |
| 1529 | // el sello del build enlaza al commit cuando es un commit limpio |
| 1530 | { const b = $('build'); if (b) { const sello = b.textContent.trim(); b.dataset.sello = sello; b.replaceChildren(enlaceBuild(sello)); } } |
| 1531 | |
| 1532 | // iconos vectoriales (sin emojis) |
| 1533 | $('model-ico').innerHTML = UI.code; |
| 1534 | $('btn-clear').innerHTML = UI.newChat || UI.clear; |
| 1535 | setWorking(working); // icono, título y aria del botón enviar/parar |
| 1536 | $('btn-slash').innerHTML = UI.slash; |
| 1537 | |
| 1538 | // menú de comandos (/) en el chat, estilo plugin de Claude Code. |
| 1539 | // Un menú de verdad: role=menu, ↑/↓/Inicio/Fin, Enter, Escape, y el foco |
| 1540 | // vuelve a donde toca. Escribiendo «/» filtra por prefijo («/sk» → /skills) y |
| 1541 | // Enter ejecuta el marcado; un «/» suelto nunca se manda al modelo. Después |
| 1542 | // de ejecutar, la caja queda limpia y con el foco. |
| 1543 | const verPanel = tab => { selectTab(tab, { push: true }); if (isMobile()) flipTo('viz'); }; |
| 1544 | const cmds = [ |
| 1545 | { label: '/reloj', hint: tr('cmClock'), run: () => onSend(tr('pClock')) }, |
| 1546 | { label: '/carpeta', hint: tr('cmFolder'), run: () => onPickFolder() }, // el selector nativo se abre en el gesto |
| 1547 | { label: '/skills', hint: tr('cmSkills'), run: () => verPanel('skills') }, |
| 1548 | { label: '/modelo', hint: tr('cmModel'), run: () => enfocarSelectorModelo(), foco: false }, |
| 1549 | { label: '/ajustes', hint: tr('cmSettings'), run: () => verPanel('ajustes') }, |
| 1550 | { label: '/tareas', hint: tr('cmTasks'), run: () => verPanel('tareas') }, |
| 1551 | { label: '/vault', hint: tr('cmVault'), run: () => verPanel('vault') }, |
| 1552 | { label: '/limpiar', hint: tr('cmClear'), run: () => $('btn-clear').click() }, |
| 1553 | { label: '/atajos', hint: tr('cmKeys'), run: () => mostrarAtajos(), foco: false }, |
| 1554 | ]; |
| 1555 | const cmdMenu = $('cmd-menu'); |
| 1556 | const slash = $('btn-slash'); |
| 1557 | const caja = $('prompt'); |
| 1558 | cmdMenu.setAttribute('role', 'menu'); |
| 1559 | cmdMenu.setAttribute('aria-label', tr('cmdMenuL')); |
| 1560 | slash.setAttribute('aria-haspopup', 'menu'); |
| 1561 | slash.setAttribute('aria-controls', 'cmd-menu'); |
| 1562 | slash.setAttribute('aria-expanded', 'false'); |
| 1563 | slash.title = tr('cmdMenuL'); |
| 1564 | slash.setAttribute('aria-label', tr('cmdMenuL')); |
| 1565 | const sinTilde = x => x.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase(); |
| 1566 | let visibles = [], activo = -1; |
| 1567 | const filas = () => [...cmdMenu.querySelectorAll('.cmd-item')]; |
| 1568 | const marcar = i => { |
| 1569 | const fs = filas(); |
| 1570 | activo = fs.length ? (i + fs.length) % fs.length : -1; |
| 1571 | fs.forEach((f, j) => f.classList.toggle('activo', j === activo)); |
| 1572 | if (activo >= 0) { caja.setAttribute('aria-activedescendant', fs[activo].id); fs[activo].scrollIntoView({ block: 'nearest' }); } |
| 1573 | else caja.removeAttribute('aria-activedescendant'); |
| 1574 | }; |
| 1575 | const pintarMenu = (filtro = '/') => { |
| 1576 | const f = sinTilde(filtro); |
| 1577 | visibles = cmds.filter(c => sinTilde(c.label).startsWith(f)); |
| 1578 | cmdMenu.replaceChildren(); |
| 1579 | visibles.forEach((c, i) => { |
| 1580 | const row = document.createElement('button'); |
| 1581 | row.type = 'button'; |
| 1582 | row.className = 'cmd-item'; |
| 1583 | row.id = 'cmd-' + i; |
| 1584 | row.setAttribute('role', 'menuitem'); |
| 1585 | row.tabIndex = -1; |
| 1586 | const b = document.createElement('b'); b.textContent = c.label; |
| 1587 | const h = document.createElement('span'); h.textContent = c.hint; |
| 1588 | row.append(b, h); |
| 1589 | row.onclick = () => ejecutar(c); |
| 1590 | cmdMenu.appendChild(row); |
| 1591 | }); |
| 1592 | if (!visibles.length) cmdMenu.appendChild(el('div', 'cmd-vacio', tr('cmNone'))); |
| 1593 | marcar(0); |
| 1594 | }; |
| 1595 | const abrirMenu = (filtro = '/') => { |
| 1596 | pintarMenu(filtro); |
| 1597 | cmdMenu.hidden = false; |
| 1598 | slash.setAttribute('aria-expanded', 'true'); |
| 1599 | }; |
| 1600 | const cerrarMenu = ({ foco = null } = {}) => { |
| 1601 | if (cmdMenu.hidden) return; |
| 1602 | cmdMenu.hidden = true; |
| 1603 | slash.setAttribute('aria-expanded', 'false'); |
| 1604 | caja.removeAttribute('aria-activedescendant'); |
| 1605 | activo = -1; |
| 1606 | foco?.focus(); |
| 1607 | }; |
| 1608 | const ejecutar = c => { |
| 1609 | cerrarMenu(); |
| 1610 | if (caja.value.trim().startsWith('/')) caja.value = ''; |
| 1611 | c.run(); |
| 1612 | if (c.foco !== false) caja.focus(); |
| 1613 | }; |
| 1614 | slash.addEventListener('click', () => { |
| 1615 | if (!cmdMenu.hidden) { cerrarMenu({ foco: slash }); return; } |
| 1616 | abrirMenu('/'); |
| 1617 | filas()[0]?.focus(); |
| 1618 | }); |
| 1619 | // Dentro del menú (abierto con el botón): flechas, Inicio/Fin, Escape. |
| 1620 | cmdMenu.addEventListener('keydown', e => { |
| 1621 | const fs = filas(); |
| 1622 | const i = fs.indexOf(document.activeElement); |
| 1623 | if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Home' || e.key === 'End') { |
| 1624 | e.preventDefault(); |
| 1625 | const j = e.key === 'Home' ? 0 : e.key === 'End' ? fs.length - 1 : i + (e.key === 'ArrowDown' ? 1 : -1); |
| 1626 | marcar(j); fs[activo]?.focus(); |
| 1627 | } else if (e.key === 'Escape') { |
| 1628 | e.preventDefault(); e.stopPropagation(); |
| 1629 | cerrarMenu({ foco: slash }); |
| 1630 | } else if (e.key === 'Tab') { |
| 1631 | cerrarMenu(); |
| 1632 | } |
| 1633 | }); |
| 1634 | // Escribiendo «/…» en la caja: filtra, ↑/↓ marcan, Enter ejecuta, Escape cierra. |
| 1635 | caja.addEventListener('input', () => { |
| 1636 | const v = caja.value; |
| 1637 | if (/^\/\S*$/.test(v)) abrirMenu(v); |
| 1638 | else cerrarMenu(); |
| 1639 | }); |
| 1640 | caja.addEventListener('keydown', e => { |
| 1641 | if (cmdMenu.hidden) return; |
| 1642 | if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); marcar(activo + (e.key === 'ArrowDown' ? 1 : -1)); } |
| 1643 | else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrarMenu(); } |
| 1644 | else if (e.key === 'Enter' && activo >= 0 && visibles[activo]) { e.preventDefault(); ejecutar(visibles[activo]); } |
| 1645 | }); |
| 1646 | document.addEventListener('click', e => { if (!e.target.closest('#cmd-menu, #btn-slash, #prompt')) cerrarMenu(); }); |
| 1647 | |
| 1648 | // Atajos globales fuera de un campo de texto: «/» va a la caja con el menú |
| 1649 | // abierto y «?» enseña la lista de atajos. |
| 1650 | document.addEventListener('keydown', e => { |
| 1651 | if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return; |
| 1652 | const t = e.target; |
| 1653 | if (t?.closest?.('input, textarea, select, [contenteditable], dialog, #mind-overlay')) return; |
| 1654 | if (e.key === '/') { e.preventDefault(); if (isMobile()) flipTo('chat'); caja.focus(); caja.value = '/'; abrirMenu('/'); } |
| 1655 | else if (e.key === '?') { e.preventDefault(); mostrarAtajos(); } |
| 1656 | }); |
| 1657 | } |
| 1658 | |
| 1659 | // La lista de atajos (antes no había ayuda de teclado en ninguna parte). |
| 1660 | function mostrarAtajos() { |
| 1661 | let d = $('atajos'); |
| 1662 | if (!d) { |
| 1663 | d = document.createElement('dialog'); |
| 1664 | d.id = 'atajos'; |
| 1665 | d.setAttribute('aria-labelledby', 'atajos-t'); |
| 1666 | const h = el('h3', null, tr('keysTitle')); |
| 1667 | h.id = 'atajos-t'; |
| 1668 | const dl = document.createElement('dl'); |
| 1669 | dl.className = 'atajos'; |
| 1670 | for (const [k, v] of [['Enter', 'keyEnter'], ['↑ / ↓', 'keyHist'], ['/', 'keySlash'], ['Esc', 'keyEsc'], ['?', 'keyHelp']]) { |
| 1671 | const dt = el('dt'); dt.appendChild(el('kbd', null, k)); |
| 1672 | dl.append(dt, el('dd', null, tr(v))); |
| 1673 | } |
| 1674 | const cerrar = btn(tr('close'), 'primary', () => d.close()); |
| 1675 | const fila = el('div', 'row right'); fila.appendChild(cerrar); |
| 1676 | d.append(h, dl, fila); |
| 1677 | document.body.appendChild(d); |
| 1678 | } |
| 1679 | if (!d.open) d.showModal(); |
| 1680 | } |
| 1681 | |
| 1682 | |
| 1683 | // ---------- indicador de disco, SIEMPRE a la vista ---------- |
| 1684 | // El dato ya existía, pero dentro del panel de Ajustes: o sea escondido. Nadie |
| 1685 | // sabía cuánto ocupaban los modelos en su navegador ni que se podían borrar. |
| 1686 | // Aquí va en la cabecera, pequeño y permanente, y solo aparece si hay MODELOS |
| 1687 | // guardados (model-storage.js): antes contaba el origen entero —tus apps y tu |
| 1688 | // conversación incluidas— y con solo eso decía «💾 0 MB … pulsa para vaciarlo». |
| 1689 | const _gbDisk = n => n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : Math.round(n / 1048576) + ' MB'; |
| 1690 | const UMBRAL_CHIP = 1048576; // menos de 1 MB de pesos no es un modelo: no se enseña |
| 1691 | |
| 1692 | function avisarLiberado(r) { |
| 1693 | toast(tr('diskFreed', { size: _gbDisk(r?.liberado || 0) }) + (r?.hayCompartido && !r.compartidoOk ? ' ' + tr('diskSharedFail') : '')); |
| 1694 | } |
| 1695 | |
| 1696 | // El chip mide SOLO este origen hasta que haya motivo para preguntar al almacén |
| 1697 | // compartido: abrir el chip o Ajustes, o cargar un modelo local en esta sesión |
| 1698 | // (kernel.js). Preguntar incrusta la página del broker (models.elffuss.com y cada |
| 1699 | // host del registro del motor), y eso pasaba en cada carga y cada minuto, también |
| 1700 | // en Básico sin nada descargado. Lo que vive solo en el compartido aparece en |
| 1701 | // cuanto se da uno de esos motivos. |
| 1702 | let preguntarCompartido = false, repintarChip = () => {}; |
| 1703 | export function contarCompartido() { |
| 1704 | if (preguntarCompartido) return; |
| 1705 | preguntarCompartido = true; |
| 1706 | repintarChip(); |
| 1707 | } |
| 1708 | export function mountDiskChip() { |
| 1709 | const chip = document.getElementById('disk-chip'); |
| 1710 | if (!chip) return; |
| 1711 | repintarChip = () => paint(); |
| 1712 | async function paint() { |
| 1713 | if (chip.disabled) return; |
| 1714 | const { total } = await modelos.medir({ compartido: preguntarCompartido }); |
| 1715 | if (total < UMBRAL_CHIP) { chip.hidden = true; return; } |
| 1716 | chip.hidden = false; |
| 1717 | chip.textContent = '💾 ' + _gbDisk(total); |
| 1718 | const txt = tr('diskChipT', { size: _gbDisk(total) }); |
| 1719 | chip.title = txt; |
| 1720 | chip.setAttribute('aria-label', txt); |
| 1721 | } |
| 1722 | chip.addEventListener('click', async () => { |
| 1723 | preguntarCompartido = true; |
| 1724 | const { total, hayCompartido } = await modelos.medir(); |
| 1725 | // El aviso solo menciona el almacén compartido si de verdad se va a vaciar. |
| 1726 | if (!confirm(tr(hayCompartido ? 'diskConfirm' : 'diskConfirmLocal', { size: _gbDisk(total) }))) return; |
| 1727 | chip.disabled = true; |
| 1728 | chip.setAttribute('aria-busy', 'true'); |
| 1729 | chip.textContent = '💾 …'; |
| 1730 | try { avisarLiberado(await modelos.vaciar()); } |
| 1731 | catch (e) { toast(tr('diskFail', { err: e?.message || e })); } |
| 1732 | chip.disabled = false; |
| 1733 | chip.removeAttribute('aria-busy'); |
| 1734 | paint(); |
| 1735 | }); |
| 1736 | paint(); |
| 1737 | // Cada minuto y solo con la pestaña a la vista: contar es fichero a fichero. |
| 1738 | setInterval(() => { if (document.visibilityState === 'visible') paint(); }, 60000); |
| 1739 | } |
| 1740 | |
| 1741 | // ---------- puerta de móvil ---------- |
| 1742 | // Antes, abrir esto en un móvil arrancaba SOLO la descarga del cerebro: medio |
| 1743 | // giga de datos de alguien que no había pedido nada, y encima con muchas |
| 1744 | // papeletas de no llegar a funcionar (el navegador de móvil cierra la pestaña |
| 1745 | // bastante antes de sostener un modelo entero). Ahora se avisa y se espera. |
| 1746 | // |
| 1747 | // `onAccept()` devuelve si el cerebro cargó. Si no, la tarjeta se queda con el |
| 1748 | // error y un «Reintentar» (antes desaparecía al pulsar y un fallo solo dejaba un |
| 1749 | // aviso pasajero). Quién es un teléfono lo decide el kernel (esTelefono). |
| 1750 | export function mobileGate(sizeText, onAccept) { |
| 1751 | const box = el('div', 'card col mobile-gate'); |
| 1752 | box.style.cssText = 'margin:14px 0;padding:14px;gap:8px'; |
| 1753 | box.setAttribute('role', 'region'); |
| 1754 | box.setAttribute('aria-label', tr('mobTitle')); |
| 1755 | box.appendChild(el('b', null, tr('mobTitle'))); |
| 1756 | box.appendChild(el('span', 'muted', tr('mobDesc', { size: sizeText }))); |
| 1757 | box.appendChild(el('span', 'muted', tr('mobDesktop'))); |
| 1758 | const estado = el('span', 'muted'); |
| 1759 | estado.setAttribute('role', 'status'); |
| 1760 | const boton = btn(tr('mobAnyway', { size: sizeText }), 'ghost', async () => { |
| 1761 | try { localStorage.setItem('elffuss.movil.ok', '1'); } catch { /* — */ } |
| 1762 | boton.disabled = true; |
| 1763 | estado.textContent = tr('mobLoading'); |
| 1764 | let cargo = false; |
| 1765 | try { cargo = await onAccept(); } catch { cargo = false; } |
| 1766 | if (cargo) { box.remove(); return; } |
| 1767 | estado.textContent = tr('mobFailed'); |
| 1768 | boton.textContent = tr('mobRetry'); |
| 1769 | boton.disabled = false; |
| 1770 | }); |
| 1771 | box.append(estado, boton); |
| 1772 | (document.getElementById('log') || document.body).appendChild(box); |
| 1773 | } |