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