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