| 1 | // Elffuss Code: landing («abre tu carpeta») → IDE con la elfa integrada. |
| 2 | import { parseToolCall } from './agent.js'; |
| 3 | import * as rules from './providers/rules.js'; |
| 4 | import * as codeTools from './tools/code.js'; |
| 5 | import * as db from './db.js'; |
| 6 | import * as settings from './settings.js'; |
| 7 | import { initEditor, refreshTree, openFile, gotoLine, triggerEditor, hasEditor } from './ide.js'; |
| 8 | import { ACTIVITY, UI } from './icons.js'; |
| 9 | import { renderMarkdown } from './md.js'; |
| 10 | import * as skills from './skills.js'; |
| 11 | import * as terminal from './terminal.js'; |
| 12 | import * as shell from './shell.js'; |
| 13 | import { setTerminalEcho } from './tools/index.js'; |
| 14 | import { ensureModelCache, cacheEstimate, clearModelCache } from './model-cache.js'; |
| 15 | // El almacén compartido vive en OTRO origen y `navigator.storage.estimate()` no |
| 16 | // lo ve: hay que preguntárselo a él y SUMAR. Ver model-broker.js. |
| 17 | import { sharedUsage, clearShared } from './runtime/model-broker.js'; |
| 18 | |
| 19 | // Los origenes donde puede haber pesos salen del REGISTRO del motor, no de una |
| 20 | // lista a mano: una copiada se queda vieja en cuanto un modelo cambia de host y |
| 21 | // el contador vuelve a mirar donde no hay nada. Import perezoso porque el motor |
| 22 | // puede no estar (modo ONNX); sin el, `sharedUsage` usa su defecto. |
| 23 | async function origenesAlmacen() { |
| 24 | try { |
| 25 | const r = await import('./engine/registro.js'); |
| 26 | return r.origenesAlmacen ? r.origenesAlmacen() : undefined; |
| 27 | } catch { return undefined; } |
| 28 | } |
| 29 | import * as ceo from './ceo.js'; |
| 30 | import * as mind from './mind.js'; |
| 31 | import { buildCityAdapter, loadThoughtsAdapter } from './mind-adapter.js'; |
| 32 | import { humanizeStreamPreview } from './humanize.js'; |
| 33 | import { t, applyI18n } from './i18n.js'; |
| 34 | import * as bridge from './bridge.js'; |
| 35 | import * as conv from './conversations.js'; |
| 36 | import { TASK_PREFIX } from './goal.js'; |
| 37 | import { hardWork, gatherFolder } from './rlm.js'; |
| 38 | import * as workspace from './workspace.js'; |
| 39 | |
| 40 | // Espacio de trabajo (core): qué de Code puede guardarse en tu disco. |
| 41 | workspace.init({ |
| 42 | app: 'code', ns: 'elffusscode', db, |
| 43 | stores: [ |
| 44 | { id: 'conversations', label: 'Conversaciones', icon: '💬', kind: 'idb-key', store: 'kv', key: 'conversations', |
| 45 | files: { ext: '.json', name: c => c.title || c.id } }, |
| 46 | { id: 'skills', label: 'Skills', icon: '🧩', kind: 'idb-key', store: 'kv', key: 'skills', |
| 47 | files: { ext: '.md', name: s => s.name, body: s => `---\nname: ${s.name}\ndescription: ${s.description || ''}\n---\n\n${s.content || ''}` } }, |
| 48 | { id: 'prefs', label: 'Preferencias', icon: '⚙️', kind: 'ls', |
| 49 | keys: ['elffusscode.model', 'elffusscode.autoedit', 'elffusscode.goalmode', 'elffuss.acer', 'elffuss.resumen', 'elffuss.semantic'] }, |
| 50 | ], |
| 51 | }); |
| 52 | workspace.restore().catch(() => {}); |
| 53 | |
| 54 | // AVISAR ANTES DE SALIR si hay un turno en marcha. |
| 55 | // ───────────────────────────────────────────────────────────────────────────── |
| 56 | // La conversación sobrevive a recargar —se guarda en IndexedDB y se restaura al |
| 57 | // arrancar—, pero el turno EN CURSO no: la respuesta solo se persiste cuando el |
| 58 | // turno termina, así que refrescar a mitad de generación tira lo que llevara |
| 59 | // escrito. Y volver a empezar no es gratis: hay que subir el modelo a la GPU |
| 60 | // otra vez y releer la conversación entera antes de poder seguir, que con el |
| 61 | // modelo grande son minutos. |
| 62 | // |
| 63 | // El navegador NO deja poner un texto propio —ignora lo que se devuelva y |
| 64 | // enseña el suyo— así que esto solo consigue que PREGUNTE. Es poco, pero es la |
| 65 | // diferencia entre perderlo sin enterarte y que te den la opción. |
| 66 | // |
| 67 | // Solo se avisa si de verdad hay algo vivo: un aviso que salta siempre se |
| 68 | // aprende a ignorar en dos días y entonces ya no avisa de nada. |
| 69 | // `hayTrabajoVivo` cubre LAS DOS cosas, no solo el turno de chat: lo más caro |
| 70 | // de perder es irse a mitad de subir el modelo a la GPU, que con el grande son |
| 71 | // minutos y hay que rehacerlo entero. `loadingId` es no-nulo mientras eso pasa. |
| 72 | const hayTrabajoVivo = () => conv.isBusy() || loadingId !== null; |
| 73 | addEventListener('beforeunload', (e) => { |
| 74 | if (!hayTrabajoVivo()) return; |
| 75 | e.preventDefault(); |
| 76 | e.returnValue = ''; // Safari y navegadores viejos miran esto |
| 77 | }); |
| 78 | if (workspace.autosaveEnabled()) workspace.autosave({ enabled: true }); |
| 79 | |
| 80 | import * as telemetry from './telemetry.js'; |
| 81 | |
| 82 | const $ = id => document.getElementById(id); |
| 83 | telemetry.init('elffuss-code'); // opt-in, apagado por defecto — ver Ajustes |
| 84 | conv.setProvider(rules); // proveedor por defecto para cualquier conversación que se cree |
| 85 | let activeModel = 'rules'; |
| 86 | |
| 87 | // ---------- chat ---------- |
| 88 | // Los `paths` entre backticks del chat (README.md, .elffuss/soul/x.md…) se |
| 89 | // vuelven clicables → abren el fichero en el editor directamente, sin tener |
| 90 | // que ir a buscarlos a mano. |
| 91 | function linkifyFilePaths(root) { |
| 92 | root.querySelectorAll('code').forEach(el => { |
| 93 | const t = el.textContent.trim(); |
| 94 | if (!/^[\w.-]+(\/[\w.-]+)*\.[a-z0-9]{1,10}$/i.test(t) || /[{}()<>]/.test(t)) return; |
| 95 | el.classList.add('file-link'); |
| 96 | el.title = 'abrir ' + t; |
| 97 | el.onclick = () => openFile(t); |
| 98 | }); |
| 99 | } |
| 100 | |
| 101 | function addMsg(cls, text) { |
| 102 | const div = document.createElement('div'); |
| 103 | div.className = 'msg ' + cls; |
| 104 | // las respuestas se renderizan como markdown (estilo plugin de Claude Code); |
| 105 | // lo del usuario y los errores, como texto plano |
| 106 | if (/^(assistant$|sys)/.test(cls)) { |
| 107 | div.classList.add('md'); |
| 108 | // cap defensivo: no volcar miles de nodos si una respuesta trae un archivo entero |
| 109 | div.innerHTML = renderMarkdown(text.length > 8000 ? text.slice(0, 8000) + '\n… (recortado)' : text); |
| 110 | linkifyFilePaths(div); |
| 111 | } else { |
| 112 | div.textContent = text; |
| 113 | } |
| 114 | $('chat-log').appendChild(div); |
| 115 | $('chat-log').scrollTop = $('chat-log').scrollHeight; |
| 116 | return div; |
| 117 | } |
| 118 | |
| 119 | // estilo plugin de Claude Code: ● herramienta en negrita + detalle plegable |
| 120 | function addTool(tool, arg) { |
| 121 | const div = document.createElement('div'); |
| 122 | div.className = 'msg tool'; |
| 123 | const dot = document.createElement('span'); |
| 124 | dot.className = 'tdot'; |
| 125 | const b = document.createElement('b'); |
| 126 | b.textContent = tool; |
| 127 | div.append(dot, b); |
| 128 | if (arg) { |
| 129 | const a = document.createElement('span'); |
| 130 | a.className = 'targ'; |
| 131 | a.textContent = String(arg).slice(0, 60); |
| 132 | div.appendChild(a); |
| 133 | } |
| 134 | $('chat-log').appendChild(div); |
| 135 | $('chat-log').scrollTop = $('chat-log').scrollHeight; |
| 136 | return div; |
| 137 | } |
| 138 | |
| 139 | function addToolResult(result) { |
| 140 | const err = result.startsWith('ERROR'); |
| 141 | const det = document.createElement('details'); |
| 142 | det.className = 'msg tool-result' + (err ? ' err' : ''); |
| 143 | const sum = document.createElement('summary'); |
| 144 | sum.textContent = (err ? '⚠️ ' : '') + result.split('\n')[0].slice(0, 90); |
| 145 | const pre = document.createElement('pre'); |
| 146 | pre.textContent = result.slice(0, 1500); |
| 147 | det.append(sum, pre); |
| 148 | $('chat-log').appendChild(det); |
| 149 | $('chat-log').scrollTop = $('chat-log').scrollHeight; |
| 150 | return det; |
| 151 | } |
| 152 | |
| 153 | const escapeHtml = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); |
| 154 | |
| 155 | // 🎯 Modo Objetivo: tarjeta de plan (planificador → lista de tareas → |
| 156 | // ejecutor). Un solo nodo por plan (mismo id), repintado in-place según |
| 157 | // llegan los eventos 'plan'/'plan_update'/'plan_complete' — así se ve la |
| 158 | // lista evolucionar en vivo en vez de reconstruirse entera cada vez. |
| 159 | const PLAN_ICO = { pending: '⏳', 'in-progress': '🔄', done: '✅', failed: '❌', skipped: '⏭️', stopped: '⏹️' }; |
| 160 | const PLAN_STATUS_LABEL = { planning: t("planPlanning"), running: t("planRunning"), done: t("planDone"), failed: t("planFailed"), stopped: t("planStopped") }; |
| 161 | function renderPlanCard(plan) { |
| 162 | const domId = 'plan-' + plan.id; |
| 163 | let div = document.getElementById(domId); |
| 164 | if (!div) { |
| 165 | div = document.createElement('div'); |
| 166 | div.id = domId; |
| 167 | div.className = 'msg plan-card'; |
| 168 | $('chat-log').appendChild(div); |
| 169 | } |
| 170 | div.innerHTML = |
| 171 | `<span class="plan-status">${escapeHtml(PLAN_STATUS_LABEL[plan.status] || plan.status)}</span>` + |
| 172 | `<div class="plan-head">🎯 Objetivo: ${escapeHtml(plan.goal)}</div>` + |
| 173 | (plan.planText ? `<div class="plan-summary">${escapeHtml(plan.planText)}</div>` : '') + |
| 174 | `<ul class="plan-tasks">` + |
| 175 | plan.tasks.map(t => |
| 176 | `<li class="task-${t.status}"><span class="task-ico">${PLAN_ICO[t.status] || '⏳'}</span>` + |
| 177 | `<div><div class="task-title">${escapeHtml(t.title)}</div><div class="task-desc">${escapeHtml(t.description)}</div></div></li>` |
| 178 | ).join('') + |
| 179 | `</ul>`; |
| 180 | $('chat-log').scrollTop = $('chat-log').scrollHeight; |
| 181 | return div; |
| 182 | } |
| 183 | |
| 184 | export function thinkingBubble() { |
| 185 | const div = addMsg('thinking', ''); |
| 186 | const label = document.createElement('span'); |
| 187 | label.textContent = t('thinking'); |
| 188 | const gen = document.createElement('div'); |
| 189 | gen.className = 'gen'; |
| 190 | div.append(label, gen); |
| 191 | let buf = ''; |
| 192 | return { |
| 193 | tick(tok) { |
| 194 | buf += tok; |
| 195 | label.textContent = t('writing', { n: buf.length }); // caracteres, no tokens |
| 196 | // si el buffer entró en un bloque de tool-call, no enseñes el JSON crudo |
| 197 | // según va llegando: una frase humana («leyendo app.js…») en su lugar. |
| 198 | const preview = humanizeStreamPreview(buf); |
| 199 | gen.classList.toggle('tool-preview', !!preview); |
| 200 | if (preview) { gen.textContent = '⟐ ' + preview; $('chat-log').scrollTop = $('chat-log').scrollHeight; } |
| 201 | else { |
| 202 | // texto normal: crece y se puede leer (antes solo los últimos 200 y lo |
| 203 | // de arriba desaparecía); se respeta tu scroll si subes a leer. |
| 204 | const pegado = gen.scrollHeight - gen.scrollTop - gen.clientHeight < 28; |
| 205 | gen.textContent = buf; |
| 206 | if (pegado) gen.scrollTop = gen.scrollHeight; |
| 207 | } |
| 208 | }, |
| 209 | tool(name) { buf = ''; gen.textContent = ''; label.textContent = t('using', { name }); }, |
| 210 | remove() { div.remove(); }, |
| 211 | }; |
| 212 | } |
| 213 | |
| 214 | // Conversaciones (pestañas, en paralelo, con su propia cola): la lógica de |
| 215 | // estado vive en conversations.js — aquí solo se pinta lo que corresponde. |
| 216 | let activeThinking = null; |
| 217 | |
| 218 | function renderActiveLog() { |
| 219 | $('chat-log').replaceChildren(); |
| 220 | const active = conv.getActive(); |
| 221 | activeThinking = null; |
| 222 | if (!active) return; |
| 223 | for (const m of active.agent.history) { |
| 224 | if (m.role === 'user') { |
| 225 | if (m.content.startsWith('[resultado ')) { |
| 226 | const nl = m.content.indexOf('\n'); |
| 227 | addToolResult(nl > 0 ? m.content.slice(nl + 1) : ''); |
| 228 | } else if (m.content.startsWith(TASK_PREFIX)) { |
| 229 | // objetivo/tareas internas del modo Goal: no son burbujas sueltas — |
| 230 | // la tarjeta de plan las muestra todas. Se pinta justo en el punto |
| 231 | // donde se lanzó el objetivo, igual que aparece en directo. |
| 232 | if (m.content.startsWith(TASK_PREFIX + 'Objetivo: ') && active.plan) renderPlanCard(active.plan); |
| 233 | } else if (!m.content.startsWith('[…')) { |
| 234 | addMsg('user', m.content); |
| 235 | } |
| 236 | } else { |
| 237 | const call = parseToolCall(m.content); |
| 238 | if (call) addTool(call.tool, call.args?.path || call.args?.query || ''); |
| 239 | else addMsg('assistant', m.content); |
| 240 | } |
| 241 | } |
| 242 | if (active.pumping) activeThinking = thinkingBubble(); |
| 243 | } |
| 244 | |
| 245 | // evento del módulo de conversaciones: 'switch' (cambiaste de pestaña o se |
| 246 | // creó una), 'tabs' (se abrió/cerró una pestaña), 'pumping' (empezó/terminó |
| 247 | // de procesar), 'event' (token/texto/tool/resultado/error de un turno real). |
| 248 | // Las conversaciones EN SEGUNDO PLANO nunca tocan el DOM visible — solo se |
| 249 | // refleja su punto de «ocupada» en la barra de pestañas. |
| 250 | function onConvEvent(kind, id, payload) { |
| 251 | if (kind !== 'event') renderTabsBar(); |
| 252 | // El botón es de la conversación ACTIVA: al cambiar de pestaña se repinta. |
| 253 | // Antes se quedaba como lo dejó la anterior — un ■ sobre una conversación |
| 254 | // parada, o un ▶ sobre una que seguía trabajando. |
| 255 | if (kind === 'switch') { renderActiveLog(); paintSendButton(); return; } |
| 256 | const active = conv.getActive(); |
| 257 | if (!active || id !== active.id) return; |
| 258 | if (kind === 'pumping') { |
| 259 | // NO deshabilitar el botón mientras genera: se convierte en PARAR. Antes se |
| 260 | // ponía disabled=payload, y por eso no había forma de cortar un run largo. |
| 261 | paintSendButton(); |
| 262 | if (payload) { if (!activeThinking) activeThinking = thinkingBubble(); } |
| 263 | else { activeThinking?.remove(); activeThinking = null; } |
| 264 | return; |
| 265 | } |
| 266 | if (kind === 'stopping') { paintSendButton(); return; } |
| 267 | if (kind === 'event') { |
| 268 | const ev = payload; |
| 269 | if (ev.type === 'token') activeThinking?.tick(ev.text); |
| 270 | if (ev.type === 'text') addMsg('assistant', ev.text); |
| 271 | if (ev.type === 'tool') { activeThinking?.tool(ev.call.tool); addTool(ev.call.tool, ev.call.args?.path || ev.call.args?.query || ''); } |
| 272 | if (ev.type === 'tool_result') addToolResult(ev.result); |
| 273 | if (ev.type === 'error') addMsg('assistant err', ev.text); |
| 274 | if (ev.type === 'aborted') addMsg('assistant muted', ev.text); |
| 275 | // 🎯 Modo Objetivo: la tarjeta de plan se crea con 'plan' y se repinta |
| 276 | // in-place en cada 'plan_update'/'plan_complete' (mismo nodo, por id). |
| 277 | if (ev.type === 'plan' || ev.type === 'plan_update' || ev.type === 'plan_complete') renderPlanCard(ev.plan); |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | function send(text) { |
| 282 | const active = conv.getActive(); |
| 283 | if (!active) return; |
| 284 | addMsg('user', text); |
| 285 | if (goalMode) conv.startGoal(active.id, text); |
| 286 | else conv.send(active.id, text); |
| 287 | } |
| 288 | |
| 289 | function renderTabsBar() { |
| 290 | const bar = $('conv-tabs'); |
| 291 | if (!bar) return; |
| 292 | bar.replaceChildren(); |
| 293 | const active = conv.getActive(); |
| 294 | for (const c of conv.getOpenTabs()) { |
| 295 | const el = document.createElement('div'); |
| 296 | el.className = 'tab' + (active && c.id === active.id ? ' active' : '') + (c.pumping ? ' tab-busy' : ''); |
| 297 | el.dataset.id = c.id; |
| 298 | const name = document.createElement('span'); |
| 299 | name.className = 'tab-name'; |
| 300 | const title = conv.titleFor(c); |
| 301 | name.textContent = title; |
| 302 | name.title = title; |
| 303 | const x = document.createElement('b'); |
| 304 | x.textContent = '×'; |
| 305 | x.title = t('tabClose'); |
| 306 | x.onclick = e => { e.stopPropagation(); conv.closeTab(c.id); }; |
| 307 | el.append(name, x); |
| 308 | el.onclick = () => conv.switchTo(c.id); |
| 309 | bar.appendChild(el); |
| 310 | } |
| 311 | const plus = document.createElement('button'); |
| 312 | plus.className = 'tab-add'; |
| 313 | plus.title = t('newConv'); |
| 314 | plus.textContent = '+'; |
| 315 | plus.onclick = () => conv.create(); |
| 316 | bar.appendChild(plus); |
| 317 | } |
| 318 | |
| 319 | async function renderHistoryPanel() { |
| 320 | const panel = $('history-panel'); |
| 321 | panel.replaceChildren(); |
| 322 | const head = document.createElement('div'); |
| 323 | head.className = 'hp-head'; |
| 324 | head.append(document.createTextNode(t('tHistory'))); |
| 325 | const xBtn = document.createElement('button'); |
| 326 | xBtn.textContent = '✕'; |
| 327 | xBtn.onclick = () => { panel.hidden = true; }; |
| 328 | head.appendChild(xBtn); |
| 329 | panel.appendChild(head); |
| 330 | const list = document.createElement('div'); |
| 331 | list.id = 'hp-list'; |
| 332 | panel.appendChild(list); |
| 333 | const all = await conv.listAll(); |
| 334 | if (!all.length) { |
| 335 | const empty = document.createElement('div'); |
| 336 | empty.className = 'hp-empty'; |
| 337 | empty.textContent = t('histEmpty'); |
| 338 | list.appendChild(empty); |
| 339 | return; |
| 340 | } |
| 341 | for (const c of all) { |
| 342 | const row = document.createElement('div'); |
| 343 | row.className = 'hp-row'; |
| 344 | const titEl = document.createElement('div'); |
| 345 | titEl.className = 'hp-title'; |
| 346 | titEl.textContent = c.title || t('newConv'); |
| 347 | const d = new Date(c.updatedAt); |
| 348 | const date = document.createElement('div'); |
| 349 | date.className = 'hp-date'; |
| 350 | date.textContent = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); |
| 351 | const del = document.createElement('button'); |
| 352 | del.className = 'hp-del'; |
| 353 | del.title = t('histDel'); |
| 354 | del.textContent = '🗑'; |
| 355 | del.onclick = async e => { |
| 356 | e.stopPropagation(); |
| 357 | if (!confirm(t('confirmDel', { title: c.title || t('thisConv') }))) return; |
| 358 | await conv.remove(c.id); |
| 359 | renderHistoryPanel(); |
| 360 | }; |
| 361 | row.append(titEl, date, del); |
| 362 | row.onclick = async () => { await conv.open(c.id); panel.hidden = true; }; |
| 363 | list.appendChild(row); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // ---------- modelos (local primero; externos = ⚙️ opt-in) ---------- |
| 368 | const localProviders = { litert: () => import('./providers/litert.js'), onnx: () => import('./providers/onnx.js') }; |
| 369 | |
| 370 | async function resolveProvider(id) { |
| 371 | if (localProviders[id]) return localProviders[id](); |
| 372 | if (id.startsWith('litert:')) { // Gemma vía LiteRT-LM (build elegido) |
| 373 | const mod = await import('./providers/litert.js'); |
| 374 | mod.configure(id.slice(7)); |
| 375 | return mod; |
| 376 | } |
| 377 | if (id.startsWith('onnx:')) { // ONNX concreto (Qwen3.5…) |
| 378 | const mod = await import('./providers/onnx.js'); |
| 379 | mod.configure(id.slice(5)); |
| 380 | return mod; |
| 381 | } |
| 382 | if (id.startsWith('engine:')) { // runtime WebGPU propio (GGUF) |
| 383 | // El motor no se versiona en este repo: llega a web/js/engine/ por rsync, |
| 384 | // igual que en Claw. Si no está, el import falla y se trata como cualquier |
| 385 | // otro fallo de carga. |
| 386 | const mod = await import('./engine/provider.js'); |
| 387 | mod.configure(id.slice(7)); |
| 388 | // Igual que en Claw: solo el motor propio mide tok/s (`alMedir`), así que |
| 389 | // con ONNX o con un proveedor externo el chip se queda oculto en vez de |
| 390 | // mentir con un número que nadie ha medido. |
| 391 | try { |
| 392 | const vm = await import('./velocimetro.js'); |
| 393 | vm.montar(mod); |
| 394 | } catch (e) { console.warn('[code] velocímetro no disponible:', e.message); } |
| 395 | return mod; |
| 396 | } |
| 397 | if (id.startsWith('ext:')) { |
| 398 | const cfg = settings.get(id.slice(4)); |
| 399 | const mod = await import('./providers/api.js'); |
| 400 | mod.configure(cfg); |
| 401 | return mod; |
| 402 | } |
| 403 | return null; |
| 404 | } |
| 405 | |
| 406 | // El E4B healed (4.12 GB) NO carga aún en navegador (export prefill_decode, no |
| 407 | // artisan) — descargarlo y fallar deja la GPU en estado inválido y TUMBA la |
| 408 | // pestaña. Se oculta hasta el reexport artisan. Poner true para reactivarlo. |
| 409 | const LITERT_READY = false; |
| 410 | |
| 411 | const isMobile = () => matchMedia('(max-width: 820px)').matches || matchMedia('(pointer: coarse)').matches; |
| 412 | // navigator.gpu puede EXISTIR como API sin que haya un adaptador real (ciertos |
| 413 | // Linux/drivers, entornos sandboxed/headless…) — comprobarlo UNA vez al |
| 414 | // arrancar evita ofrecer/elegir Gemma (2-4 GB) cuando de todos modos va a |
| 415 | // fallar al crear el motor (onnx.js y litert.js ya comprueban el adaptador |
| 416 | // por su cuenta como defensa adicional, pero esto evita hasta OFRECERLO). |
| 417 | let realGPU = !!navigator.gpu; |
| 418 | const realGPUCheck = (async () => { |
| 419 | if (!navigator.gpu) return (realGPU = false); |
| 420 | try { return (realGPU = !!(await navigator.gpu.requestAdapter())); } |
| 421 | catch { return (realGPU = false); } |
| 422 | })(); |
| 423 | // Capacidad real de la GPU: no basta con que exista navigator.gpu, hay que |
| 424 | // mirar los límites del adaptador — un buffer máximo pequeño no aguanta Gemma. |
| 425 | async function gpuCapacity() { |
| 426 | const mem = navigator.deviceMemory || 8; // GB (grueso, tope 8 en Chrome) |
| 427 | if (!navigator.gpu) return { gpu: false, maxBuf: 0, mem }; |
| 428 | try { |
| 429 | const a = await navigator.gpu.requestAdapter(); |
| 430 | if (!a) return { gpu: false, maxBuf: 0, mem }; |
| 431 | return { gpu: true, maxBuf: a.limits?.maxBufferSize || 0, mem }; |
| 432 | } catch { return { gpu: false, maxBuf: 0, mem }; } |
| 433 | } |
| 434 | |
| 435 | // Auto-selección: el modelo MÁS GRANDE que entre en esta máquina. Gemma por |
| 436 | // LiteRT si la GPU aguanta sus buffers; si no, un ONNX pequeño (WebGPU o wasm). |
| 437 | async function pickLocalBrain() { |
| 438 | const c = await gpuCapacity(); |
| 439 | if (c.gpu && !isMobile()) { |
| 440 | if (c.maxBuf >= 2 ** 31 && c.mem >= 8) return 'litert:gemma-e4b'; // ~4 GB |
| 441 | if (c.maxBuf >= 2 ** 30 && c.mem >= 6) return 'litert:gemma-e2b'; // ~2 GB |
| 442 | } |
| 443 | if (c.gpu && isMobile()) return 'litert:gemma-e2b'; |
| 444 | return 'onnx'; // ONNX pequeño: Qwen3.5-0.8B por defecto (ver model-config.js) |
| 445 | } |
| 446 | // heurística vieja como último recurso síncrono |
| 447 | const defaultBrain = () => !realGPU ? 'onnx' : (isMobile() ? 'litert:gemma-e2b' : 'litert:gemma-e4b'); |
| 448 | |
| 449 | // El runtime propio y su modelo grande se SONDEAN, no se cablean: el motor |
| 450 | // llega por rsync y el modelo son gigabytes que pueden no estar alojados. |
| 451 | // Ofrecer algo que no está sería prometer un fallo que llega DESPUÉS de que el |
| 452 | // usuario haya esperado, que es la peor forma de fallar. |
| 453 | // Mismo patrón que el 27B: nombre y tamaño salen del REGISTRO del motor, nunca |
| 454 | // de un literal aquí. Un nombre duplicado es un nombre que se queda viejo. |
| 455 | // ⚠️ Con HANDLE, no «fire and forget». La lista del selector se construye tras |
| 456 | // esperar las sondas de disponibilidad, así que una sonda que nadie espera deja |
| 457 | // su bandera en false cuando se pinta la lista y el modelo no aparece — se sirve |
| 458 | // y nadie puede elegirlo, el mismo modo de fallo que escondió a Bonsai. Pasó con |
| 459 | // esta misma sonda: en una app se colaba por carrera y en la otra no aparecía. |
| 460 | let MINICPM_READY = false, MINICPM_LABEL = 'MiniCPM5 2B', MINICPM_GB = 0; |
| 461 | const minicpmCheck = (async () => { |
| 462 | try { |
| 463 | const reg = await import('./engine/registro.js'); |
| 464 | const m = reg.MODELS && reg.MODELS['minicpm5-2b']; |
| 465 | if (m) { MINICPM_LABEL = m.label || MINICPM_LABEL; MINICPM_GB = (m.bytes || 0) / 1e9; } |
| 466 | MINICPM_READY = await reg.disponible('minicpm5-2b'); |
| 467 | return MINICPM_READY; |
| 468 | } catch { return (MINICPM_READY = false); } |
| 469 | })(); |
| 470 | |
| 471 | let ENGINE_READY = false, MODEL27_READY = false; |
| 472 | let MODEL27_LABEL = 'Modelo grande'; |
| 473 | let MODEL27_GB = 0; |
| 474 | const engineCheck = (async () => { |
| 475 | try { return (ENGINE_READY = (await fetch('js/engine/provider.js', { method: 'HEAD', cache: 'no-store' })).ok); } |
| 476 | catch { return (ENGINE_READY = false); } |
| 477 | })(); |
| 478 | // Se le pregunta AL MOTOR por sus propios ficheros. Aquí había cableada la URL |
| 479 | // del 27B de un solo trozo; cuando pasó a dos fragmentos en dos hosts, esta |
| 480 | // línea siguió sondeando el fichero viejo y dando 200 de milagro, porque aún |
| 481 | // estaba en el servidor. El día que se borre, la opción desaparece del selector |
| 482 | // y nadie ata los dos cabos. Se importa el registro (unos kilobytes) y no el |
| 483 | // proveedor, que arrastra el motor entero. |
| 484 | const modelo27Check = (async () => { |
| 485 | try { |
| 486 | const reg = await import('./engine/registro.js'); |
| 487 | // El NOMBRE y el TAMAÑO salen del registro del motor, no de un literal aquí. |
| 488 | // Estaban a mano y al cambiar de modelo mintieron en tres cosas a la vez: |
| 489 | // decían «Qwen3.8-27B IQ1» y «~7,6 GB» cuando lo que se sirve es el ternario |
| 490 | // de Prism y son 7,2 GB. Un nombre duplicado es un nombre que se queda viejo. |
| 491 | const m27 = reg.MODELS && reg.MODELS['qwen38-27b']; |
| 492 | if (m27) { MODEL27_LABEL = m27.label || MODEL27_LABEL; MODEL27_GB = (m27.bytes || 0) / 1e9; } |
| 493 | return (MODEL27_READY = await reg.disponible('qwen38-27b')); |
| 494 | } catch { return (MODEL27_READY = false); } |
| 495 | })(); |
| 496 | |
| 497 | // Los modelos LOCALES, en un solo sitio. Los usan el desplegable y las tarjetas |
| 498 | // de los ajustes: hasta ahora eran dos listas escritas a mano y la de ajustes se |
| 499 | // quedó vieja — no ofrecía NI el motor propio ni el 27B, así que desde ahí era |
| 500 | // imposible elegir Bonsai por mucho que el motor lo sirviera. Es justo el modo |
| 501 | // de fallo que avisa el comentario de `modelo27Check`: un nombre duplicado es un |
| 502 | // nombre que se queda viejo. |
| 503 | function modelOptionsLocales() { |
| 504 | const opts = []; |
| 505 | if (realGPU) opts.push({ id: 'litert:gemma-e4b', label: 'Gemma-4 E4B · LiteRT-LM (~4 GB) ★' }); |
| 506 | if (realGPU) opts.push({ id: 'litert:gemma-e2b', label: 'Gemma-4 E2B · LiteRT-LM (~2 GB)' }); |
| 507 | // `onnx` a secas era Elffuss LM y se ha quitado. Ojo con el patrón: ESTE era |
| 508 | // el TERCER sitio donde el mismo modelo estaba declarado a mano (el registro |
| 509 | // de model-config.js, la lista del lab y esta), y quitarlo de los dos |
| 510 | // primeros lo dejaba igual de visible aquí. Es el mismo modo de fallo que el |
| 511 | // comentario de arriba avisa para Bonsai: un nombre duplicado es un nombre |
| 512 | // que se queda viejo. |
| 513 | opts.push({ id: 'onnx:qwen3.5-0.8b', label: 'Qwen3.5-0.8B · WebGPU (~600 MB)' }); |
| 514 | if (realGPU && ENGINE_READY) opts.push({ id: 'engine:qwen35-0.8b', label: 'Qwen3.5-0.8B · Elffuss Engine (~800 MB)' }); |
| 515 | // El 27B se guarda tras la primera descarga (repartido en dos servidores y |
| 516 | // troceado, porque el navegador corta un fichero suelto sobre 1,94 GB), así |
| 517 | // que son «gigas una vez», no «gigas cada vez». Sigue siendo lento: la espera |
| 518 | // cae entera antes de la primera palabra. |
| 519 | // MiniCPM5-2B por el motor propio. Va en «Avanzado» y sin estrella a |
| 520 | // propósito: carga y responde con texto limpio, y eso es TODO lo que está |
| 521 | // comprobado. No se ha medido contra Gemma E4B, que es el predeterminado, así |
| 522 | // que la etiqueta no promete velocidad ni calidad. |
| 523 | if (realGPU && ENGINE_READY && MINICPM_READY) opts.push({ id: 'engine:minicpm5-2b', label: `${MINICPM_LABEL} · Elffuss Engine (${MINICPM_GB.toFixed(1)} GB, se guarda)`, group: '⚠ Avanzado' }); |
| 524 | if (realGPU && ENGINE_READY && MODEL27_READY) opts.push({ id: 'engine:qwen38-27b', label: `${MODEL27_LABEL} · Elffuss Engine (${MODEL27_GB.toFixed(1)} GB, se guarda: solo se baja la primera vez) — lento`, group: '⚠ Avanzado' }); |
| 525 | opts.push({ id: 'rules', label: t('setModelRulesName') }); |
| 526 | return opts; |
| 527 | } |
| 528 | |
| 529 | function modelOptions() { |
| 530 | return [...modelOptionsLocales(), ...settings.enabledExternals()]; |
| 531 | } |
| 532 | |
| 533 | function rebuildSelect() { |
| 534 | const sel = $('model-select'); |
| 535 | sel.replaceChildren(); |
| 536 | // Los grupos avisados («⚠ Avanzado») van SIEMPRE al final. Si se crean según |
| 537 | // aparecen, basta una opción agrupada en mitad de la lista para que las |
| 538 | // siguientes queden colgando bajo el encabezado de aviso — le pasó a «Básico |
| 539 | // (sin modelo)» en Claw, que es la opción más segura que hay. |
| 540 | const grupos = new Map(); |
| 541 | for (const o of modelOptions()) { |
| 542 | const opt = document.createElement('option'); |
| 543 | opt.value = o.id; |
| 544 | opt.textContent = o.label; |
| 545 | if (o.group) { |
| 546 | let g = grupos.get(o.group); |
| 547 | if (!g) { g = document.createElement('optgroup'); g.label = o.group; grupos.set(o.group, g); } |
| 548 | g.appendChild(opt); |
| 549 | } else { |
| 550 | sel.appendChild(opt); |
| 551 | } |
| 552 | } |
| 553 | for (const g of grupos.values()) sel.appendChild(g); |
| 554 | sel.value = activeModel; |
| 555 | } |
| 556 | |
| 557 | // progreso del modelo: píldora prominente visible sobre landing e IDE |
| 558 | function showModelProgress(text, pct = null) { |
| 559 | const box = $('model-progress'); |
| 560 | if (text == null) { box.hidden = true; return; } |
| 561 | box.hidden = false; |
| 562 | $('model-progress-text').textContent = text; |
| 563 | const bar = $('model-bar'); |
| 564 | if (pct == null) { |
| 565 | bar.classList.add('indet'); // sin % conocido → barra animada |
| 566 | bar.style.width = ''; |
| 567 | } else { |
| 568 | bar.classList.remove('indet'); |
| 569 | bar.style.width = pct + '%'; |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | let loadingId = null; |
| 574 | async function changeModel(id) { |
| 575 | if (id === 'rules') { |
| 576 | conv.setProvider(rules); |
| 577 | activeModel = 'rules'; |
| 578 | localStorage.setItem('elffusscode.model', 'rules'); |
| 579 | $('model-dot').className = 'dot off'; |
| 580 | return true; |
| 581 | } |
| 582 | if (loadingId === id || activeModel === id) return true; // un solo modelo, una sola carga |
| 583 | loadingId = id; |
| 584 | $('model-dot').className = 'dot loading'; |
| 585 | showModelProgress(t("stModelLoadingAI"), 4); |
| 586 | try { |
| 587 | const mod = await resolveProvider(id); |
| 588 | await mod.load(p => { |
| 589 | if (typeof p === 'string') return showModelProgress(p); |
| 590 | if (p?.status === 'progress' && p.total) { |
| 591 | const pct = Math.round(p.loaded / p.total * 100); |
| 592 | showModelProgress(t('modelLoading', { pct, loaded: (p.loaded / 1e6 | 0), total: (p.total / 1e6 | 0) }), pct); |
| 593 | } |
| 594 | }); |
| 595 | conv.setProvider(mod); |
| 596 | // AHORA sí se reanuda lo que quedó a medias. Al refrescar durante un turno, |
| 597 | // el mensaje sigue en la cola —se guarda al enviarlo— pero reanudarlo antes |
| 598 | // de este punto lo habría procesado con el cerebro básico. Aquí ya hay |
| 599 | // modelo de verdad. |
| 600 | // |
| 601 | // Si un turno ya se intentó dos veces sin terminar, no se reanuda solo: lo |
| 602 | // normal es que esté tumbando la pestaña, y reintentarlo al abrir deja al |
| 603 | // usuario en un bucle del que no sale ni cerrando. Se le cuenta y decide. |
| 604 | conv.resumePending((convId, item) => { |
| 605 | const texto = String(item?.text || '').slice(0, 60); |
| 606 | addMsg('sys', `⚠️ «${texto}…» se quedó a medias dos veces y no lo reintento solo: puede estar agotando la memoria. ` + |
| 607 | `Escribe otra cosa para seguir, o vuelve a enviarlo si quieres insistir.`); |
| 608 | conv.descartarPendiente(convId); |
| 609 | }); |
| 610 | // El medidor de contexto pasa a hablar del modelo QUE ESTÁ CARGADO. Quien no |
| 611 | // sepa decir su contexto deja el valor de reserva, así que esto no puede |
| 612 | // romper a un proveedor que no lo implemente. |
| 613 | try { if (typeof mod.contextTokens === 'function') setCtxBudget(mod.contextTokens()); } |
| 614 | catch { /* el medidor no vale un fallo de carga */ } |
| 615 | activeModel = id; |
| 616 | localStorage.setItem('elffusscode.model', id); |
| 617 | $('model-dot').className = 'dot on'; |
| 618 | showModelProgress(t('modelReadyBadge'), 100); |
| 619 | setTimeout(() => showModelProgress(null), 2500); |
| 620 | $('statusbar').textContent = t('modelReady'); |
| 621 | rebuildSelect(); |
| 622 | return true; |
| 623 | } catch (e) { |
| 624 | console.error('[elffuss-code] fallo cargando', e); |
| 625 | // Un Gemma (LiteRT) que no cabe → cae al ligero (onnx, Qwen3.5-0.8B). |
| 626 | if (id.startsWith('litert') && !_fellBack) { |
| 627 | _fellBack = true; |
| 628 | sessionStorage.setItem('elffusscode.skipGemma', '1'); |
| 629 | showModelProgress(t('fallbackToast')); |
| 630 | loadingId = null; |
| 631 | const okc = await changeModel('onnx'); |
| 632 | _fellBack = false; |
| 633 | if (okc) return true; |
| 634 | } |
| 635 | conv.setProvider(rules); |
| 636 | activeModel = 'rules'; |
| 637 | $('model-dot').className = 'dot off'; |
| 638 | showModelProgress('⚠️ No pude cargar el modelo: ' + (e?.message || e)); |
| 639 | setTimeout(() => showModelProgress(null), 6000); |
| 640 | rebuildSelect(); |
| 641 | return false; |
| 642 | } finally { |
| 643 | loadingId = null; |
| 644 | } |
| 645 | } |
| 646 | let _fellBack = false; |
| 647 | |
| 648 | // El cerebro empieza a descargarse desde el PRIMER segundo, en segundo plano, |
| 649 | // mientras el usuario elige la carpeta. Solo el modelo local — los externos |
| 650 | // jamás se activan solos. |
| 651 | // Cadena de respaldo: el modelo preferido → LFM2.5 local → básico. Si el E4B |
| 652 | // healed falla (p. ej. «HF_Tokenizer_Zlib not supported» del runtime LiteRT), |
| 653 | // cae solo a LFM2.5 en vez de dejar al usuario sin cerebro. |
| 654 | async function preloadModel() { |
| 655 | const saved = localStorage.getItem('elffusscode.model'); |
| 656 | if (saved === 'rules') return; |
| 657 | await realGPUCheck; // que defaultBrain()/modelOptions() vean el adaptador real, no solo la API |
| 658 | // Las sondas del motor y del modelo grande resuelven DESPUÉS de que se pinte |
| 659 | // el selector, así que hay que repintarlo: sin esto la opción no aparece |
| 660 | // hasta que algo más fuerce un refresco, y el usuario no la ve nunca. |
| 661 | const [hayMotor, hay27, hayMini] = await Promise.all([engineCheck, modelo27Check, minicpmCheck]); |
| 662 | if (hayMotor || hay27 || hayMini) rebuildSelect(); |
| 663 | const avail = new Set(modelOptions().map(o => o.id)); |
| 664 | const skipGemma = sessionStorage.getItem('elffusscode.skipGemma') === '1'; |
| 665 | const def = skipGemma ? 'onnx' : await pickLocalBrain(); |
| 666 | const chain = [...new Set([saved, def, 'onnx'] |
| 667 | .filter(id => id && id !== 'rules' && avail.has(id)))]; |
| 668 | // MÓVIL: no descargar ~1,9 GB sin permiso. defaultBrain() elige gemma-e2b en |
| 669 | // móvil, y medido el 2026-09-08 con un iPhone emulado contra producción: al |
| 670 | // abrir la página arrancaban OCHO peticiones de pesos sin que el usuario |
| 671 | // pidiera nada. Son casi dos gigas de datos de alguien que solo entró a |
| 672 | // mirar, y encima el navegador de móvil mata la pestaña bastante antes de |
| 673 | // sostener ese modelo, así que se gastaban para nada. Se avisa y se espera. |
| 674 | if (isMobile() && localStorage.getItem('elffusscode.movil.ok') !== '1') { |
| 675 | avisoMovil('~1,9 GB', () => { |
| 676 | (async () => { for (const id of chain) if (await changeModel(id)) return; })(); |
| 677 | }); |
| 678 | return; |
| 679 | } |
| 680 | for (const id of chain) if (await changeModel(id)) return; |
| 681 | } |
| 682 | |
| 683 | // ---------- panel ⚙️ Ajustes: modelo (cerebro) + API keys ---------- |
| 684 | const el = (t, cls, txt) => { const e = document.createElement(t); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; }; |
| 685 | |
| 686 | function settingsShell(title) { |
| 687 | const box = $('settings-panel'); |
| 688 | box.hidden = false; |
| 689 | box.replaceChildren(); |
| 690 | const close = el('button', 'panel-close'); close.innerHTML = UI.close; close.title = t("close"); |
| 691 | close.onclick = () => { box.hidden = true; }; |
| 692 | box.append(close, el('h3', 'panel-title', title)); |
| 693 | return box; |
| 694 | } |
| 695 | |
| 696 | function showBridgeMsg(card, text, isErr) { |
| 697 | let el2 = card.querySelector('.br-msg'); |
| 698 | if (!el2) { el2 = document.createElement('div'); el2.className = 'br-msg muted'; el2.style.cssText = 'font-size:.7rem;margin-top:6px'; card.appendChild(el2); } |
| 699 | el2.textContent = text; |
| 700 | el2.style.color = isErr ? '#ff6b8b' : ''; |
| 701 | } |
| 702 | |
| 703 | // pequeño estallido de fuegos artificiales (canvas, un par de segundos) para |
| 704 | // que se entienda de un vistazo que el bridge quedó conectado. |
| 705 | function fireworks() { |
| 706 | const cv = document.createElement('canvas'); |
| 707 | cv.id = 'fireworks-fx'; |
| 708 | cv.width = innerWidth; cv.height = innerHeight; |
| 709 | document.body.appendChild(cv); |
| 710 | const ctx = cv.getContext('2d'); |
| 711 | const colors = ['#ff4d8d', '#7c5cff', '#49e8ff', '#3fb970', '#ffd479']; |
| 712 | const bursts = Array.from({ length: 5 }, () => ({ |
| 713 | x: innerWidth * (0.2 + Math.random() * 0.6), y: innerHeight * (0.2 + Math.random() * 0.4), |
| 714 | t0: performance.now() + Math.random() * 500, |
| 715 | particles: Array.from({ length: 40 }, (_, i) => { const a = (i / 40) * Math.PI * 2; const sp = 2 + Math.random() * 3; return { a, sp, color: colors[i % colors.length] }; }), |
| 716 | })); |
| 717 | const start = performance.now(); |
| 718 | function frame(now) { |
| 719 | ctx.clearRect(0, 0, cv.width, cv.height); |
| 720 | let alive = false; |
| 721 | for (const b of bursts) { |
| 722 | const age = (now - b.t0) / 1000; |
| 723 | if (age < 0) { alive = true; continue; } |
| 724 | if (age > 1.4) continue; |
| 725 | alive = true; |
| 726 | for (const p of b.particles) { |
| 727 | const r = p.sp * age * 40; |
| 728 | const x = b.x + Math.cos(p.a) * r, y = b.y + Math.sin(p.a) * r + age * age * 60; |
| 729 | ctx.globalAlpha = Math.max(0, 1 - age / 1.4); |
| 730 | ctx.fillStyle = p.color; |
| 731 | ctx.beginPath(); ctx.arc(x, y, 2.4, 0, Math.PI * 2); ctx.fill(); |
| 732 | } |
| 733 | } |
| 734 | if (alive && now - start < 3000) requestAnimationFrame(frame); |
| 735 | else cv.remove(); |
| 736 | } |
| 737 | requestAnimationFrame(frame); |
| 738 | } |
| 739 | |
| 740 | function renderSettings() { |
| 741 | const box = settingsShell(t("setTitle")); |
| 742 | |
| 743 | // --- Cerebro (modelo) --- |
| 744 | box.append(el('div', 'sk-h', t("setBrainTitle"))); |
| 745 | // De `modelOptionsLocales()`, no de una copia: así lo que se puede elegir aquí |
| 746 | // es exactamente lo que se puede elegir en el desplegable, hoy y cuando se |
| 747 | // añada el siguiente modelo. El texto de debajo sigue siendo a medida cuando |
| 748 | // lo hay; si no, se saca de la propia etiqueta. |
| 749 | const SUBS = { |
| 750 | 'litert:gemma-e4b': t("setModelE4bSub"), |
| 751 | 'litert:gemma-e2b': t("setModelE2bSub"), |
| 752 | 'onnx': t("setModelOnnxSub"), |
| 753 | 'rules': t("setModelRulesSub"), |
| 754 | }; |
| 755 | const LOCAL = modelOptionsLocales().map((o) => { |
| 756 | const partes = String(o.label).split(' · '); |
| 757 | return { |
| 758 | id: o.id, |
| 759 | name: partes[0].trim(), |
| 760 | sub: SUBS[o.id] || partes.slice(1).join(' · ').trim(), |
| 761 | }; |
| 762 | }); |
| 763 | const grid = el('div', 'model-grid'); |
| 764 | for (const m of LOCAL) { |
| 765 | if (m.need === 'gpu' && !realGPU) continue; |
| 766 | const card = el('button', 'model-card' + (activeModel === m.id ? ' active' : '') + (m.disabled ? ' disabled' : '')); |
| 767 | if (m.disabled) card.disabled = true; |
| 768 | card.innerHTML = `<b>${m.name}</b><span>${m.sub}</span>`; |
| 769 | card.onclick = () => { changeModel(m.id); renderSettings(); }; |
| 770 | grid.appendChild(card); |
| 771 | } |
| 772 | box.appendChild(grid); |
| 773 | |
| 774 | // --- Espacio de trabajo: guardar conversaciones/skills en disco --- |
| 775 | box.append(el('div', 'sk-h', '💾 ' + t('wsTitle'))); |
| 776 | const wsCard = el('div', 'prov-card'); |
| 777 | const wsState = el('div', 'muted'); wsState.style.fontSize = '.78rem'; |
| 778 | // `flex-direction:row` EXPLÍCITO. La clase `field` es una columna |
| 779 | // (`flex-direction: column`), y el estilo de aquí ponía `display:flex` y |
| 780 | // `flex-wrap` sin corregir la dirección: los botones quedaban apilados y |
| 781 | // estirados a todo el ancho —tres barras de color enormes para «elige una |
| 782 | // carpeta»— cuando son acciones pequeñas que caben en una línea. El |
| 783 | // `align-items:center` es para que la casilla de autoguardado no se estire. |
| 784 | const wsRow = el('div', 'field'); |
| 785 | wsRow.style.cssText = 'display:flex;flex-direction:row;align-items:center;gap:8px;flex-wrap:wrap;margin-top:8px'; |
| 786 | const wsInv = el('div'); wsInv.style.cssText = 'margin-top:10px;font-size:.78rem'; |
| 787 | wsCard.append(el('span', 'muted', t('wsDesc')), wsState, wsRow, wsInv); |
| 788 | box.appendChild(wsCard); |
| 789 | const wsKb = n => n > 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n > 1024 ? Math.round(n / 1024) + ' KB' : n + ' B'; |
| 790 | async function paintWs() { |
| 791 | const st = workspace.status(); |
| 792 | wsRow.replaceChildren(); |
| 793 | wsState.textContent = !st.supported.pick ? t('wsNoSupport') |
| 794 | : !st.folder ? t('wsNoFolder') |
| 795 | : st.ready ? t('wsFolder', { name: st.folder }) : t('wsNeedsPerm', { name: st.folder }); |
| 796 | const mk = (label, fn) => { const b = el('button', 'prov-use', label); b.onclick = fn; wsRow.appendChild(b); }; |
| 797 | if (st.supported.pick) { |
| 798 | if (!st.folder) { |
| 799 | mk(t('wsPick'), async () => { try { await workspace.pick(); await paintWs(); } catch (e) { wsState.textContent = '⚠️ ' + e.message; } }); |
| 800 | // Code ya tiene una carpeta abierta: reutilizarla es un clic |
| 801 | if (codeTools.handle()) mk(t('wsUseProject'), async () => { await workspace.adopt(codeTools.handle()); await paintWs(); }); |
| 802 | } else if (!st.ready) mk(t('wsRegrant'), async () => { try { await workspace.regrant(); await paintWs(); } catch (e) { wsState.textContent = '⚠️ ' + e.message; } }); |
| 803 | else { |
| 804 | mk(t('wsSaveNow'), async () => { try { const r = await workspace.save(); wsState.textContent = r.ok ? t('wsSaved', { n: r.wrote.length }) : '⚠️ ' + (r.errors[0]?.error || ''); } catch (e) { wsState.textContent = '⚠️ ' + e.message; await paintWs(); } }); |
| 805 | const lbl = el('label', null); lbl.style.cssText = 'display:flex;align-items:center;gap:6px;font-size:.78rem'; |
| 806 | const chk = el('input'); chk.type = 'checkbox'; chk.checked = workspace.autosaveEnabled(); |
| 807 | chk.onchange = () => workspace.autosave({ enabled: chk.checked }); |
| 808 | lbl.append(chk, el('span', 'muted', t('wsAuto'))); wsRow.appendChild(lbl); |
| 809 | mk(t('wsForget'), async () => { await workspace.forget(); await paintWs(); }); |
| 810 | } |
| 811 | } |
| 812 | mk(t('wsDownload'), async () => { |
| 813 | const blob = await workspace.bundle(); |
| 814 | const a = document.createElement('a'); |
| 815 | a.href = URL.createObjectURL(blob); |
| 816 | a.download = `elffuss-code-${new Date().toISOString().slice(0, 10)}.json`; |
| 817 | a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 4000); |
| 818 | }); |
| 819 | wsInv.replaceChildren(el('b', null, t('wsWhat'))); |
| 820 | for (const it of await workspace.inventory()) { |
| 821 | const line = el('div'); line.style.cssText = 'display:flex;justify-content:space-between;padding:3px 0'; |
| 822 | line.append(el('span', null, `${it.icon} ${it.label}`), el('span', 'muted', it.error ? '⚠️' : `${it.count} · ${wsKb(it.bytes)}`)); |
| 823 | wsInv.appendChild(line); |
| 824 | } |
| 825 | } |
| 826 | paintWs().catch(() => {}); |
| 827 | |
| 828 | // --- Almacenamiento del modelo (caché persistente) --- |
| 829 | box.append(el('div', 'sk-h', t('setStoreTitle'))); |
| 830 | const storeCard = el('div', 'prov-card'); |
| 831 | const storeInfo = el('span', null, t('setCalc')); storeInfo.style.cssText = 'font-size:.8rem;color:var(--fg)'; |
| 832 | const storeSub = el('div', 'field'); storeSub.style.marginTop = '2px'; |
| 833 | const storeMuted = el('span', 'muted', ''); storeMuted.style.fontSize = '.72rem'; |
| 834 | const clearBtn = el('button', 'prov-use', t('setClear')); |
| 835 | clearBtn.style.marginTop = '8px'; |
| 836 | clearBtn.onclick = async () => { clearBtn.textContent = t('setClearing'); await clearModelCache(); await paintStorage(); clearBtn.textContent = t('setClear'); }; |
| 837 | const storeHead = el('div', 'prov-head'); storeHead.append(storeInfo); |
| 838 | storeCard.append(storeHead, storeMuted, clearBtn); |
| 839 | box.appendChild(storeCard); |
| 840 | async function paintStorage() { |
| 841 | const { usage, quota, persisted } = await cacheEstimate(); |
| 842 | // El modelo grande NO está en este origen: lo guarda el broker en el suyo, y |
| 843 | // `estimate()` solo ve el propio. Sumando los dos, el panel decía «0,82 GB» |
| 844 | // con 7,2 GB guardados al lado — justo sobre el modelo que más ocupa. |
| 845 | const compartido = await sharedUsage(await origenesAlmacen()); |
| 846 | const total = usage + compartido.usage; |
| 847 | const gb = n => (n / 1073741824).toFixed(2) + ' GB'; |
| 848 | storeInfo.textContent = total ? t('setCached', { gb: gb(total) }) : t('setNone'); |
| 849 | // Si el broker no contesta se dice, en vez de dar un total que se queda |
| 850 | // corto sin avisar: un número incompleto que parece completo es peor que |
| 851 | // uno que admite lo que le falta. |
| 852 | storeMuted.textContent = (persisted ? t('setPersist') : t('setNoPersist')) |
| 853 | + (quota ? t('setLimit', { gb: gb(quota) }) : '') |
| 854 | + (compartido.ok |
| 855 | ? (compartido.usage ? ` · incluye ${gb(compartido.usage)} del almacén compartido` : '') |
| 856 | : ' · no se pudo consultar el almacén compartido (puede haber más guardado)'); |
| 857 | } |
| 858 | paintStorage(); |
| 859 | |
| 860 | // --- Bridge local (ejecución REAL en tu máquina: node, npm, python…) --- |
| 861 | box.append(el('div', 'sk-h', t("setBridgeTitle"))); |
| 862 | const brCard = el('div', 'prov-card bridge-card'); |
| 863 | const guessOS = () => { |
| 864 | const ua = navigator.userAgent; |
| 865 | if (/Mac/.test(ua)) return /Intel/.test(navigator.platform) && !/arm/i.test(ua) ? 'elffuss-bridge-mac-intel' : 'elffuss-bridge-mac-arm64'; |
| 866 | if (/Win/.test(ua)) return 'elffuss-bridge-windows.exe'; |
| 867 | if (/Linux/.test(ua)) return /aarch64|arm64/i.test(ua) ? 'elffuss-bridge-linux-arm64' : 'elffuss-bridge-linux'; |
| 868 | return 'elffuss-bridge-mac-arm64'; |
| 869 | }; |
| 870 | const OTHER = { 'elffuss-bridge-mac-arm64': 'Mac (Apple Silicon)', 'elffuss-bridge-mac-intel': 'Mac (Intel)', 'elffuss-bridge-windows.exe': 'Windows', 'elffuss-bridge-linux': 'Linux (x64)', 'elffuss-bridge-linux-arm64': 'Linux (ARM)' }; |
| 871 | const primary = guessOS(); |
| 872 | brCard.innerHTML = |
| 873 | `<div class="prov-head"><span id="br-dot" class="dot off"></span><b>Bridge local</b><span id="br-status" class="muted" style="margin-left:auto;font-size:.72rem">desconectado</span></div>` + |
| 874 | `<p class="muted" style="font-size:.72rem;margin:6px 0">${t('setBridgeDesc')}</p>` + |
| 875 | `<p class="muted" style="font-size:.7rem;margin:0 0 6px">${t('setBridgeOld')}</p>` + |
| 876 | `<a class="prov-use" style="text-decoration:none;display:inline-block" href="bridge-dl/${primary}" download>${t('setBridgeDownload',{os:OTHER[primary]})}</a>` + |
| 877 | `<details style="margin-top:6px"><summary class="muted" style="font-size:.7rem;cursor:pointer">${t('setBridgeOtherOS')}</summary>` + |
| 878 | Object.entries(OTHER).filter(([f]) => f !== primary).map(([f, label]) => `<div><a href="bridge-dl/${f}" download style="color:var(--accent2);font-size:.72rem">${label}</a></div>`).join('') + |
| 879 | `</details>` + |
| 880 | `<div class="field" style="margin-top:8px"><label class="muted" style="font-size:.68rem">${t('setBrToken')}</label><input id="br-token" placeholder="${t('brTokenPh')}"></div>` + |
| 881 | `<div class="field" style="margin-top:6px"><label class="muted" style="font-size:.68rem">${t('setBridgeFolderLabel')}</label><input id="br-folder" placeholder="${t('setBridgeFolderPh')}"></div>` + |
| 882 | `<button id="br-connect" class="prov-use" style="margin-top:8px">${t('setBridgeConnect')}</button>`; |
| 883 | box.appendChild(brCard); |
| 884 | brCard.querySelector('#br-folder').value = bridge.getFolder(); |
| 885 | brCard.querySelector('#br-token').value = localStorage.getItem('elffusscode.bridgeToken') || ''; |
| 886 | const paintBridge = () => { |
| 887 | // el panel puede haberse cerrado entre sondeos de fondo — si ya no está |
| 888 | // en el DOM, nos desuscribimos en vez de tocar nodos huérfanos. |
| 889 | if (!document.body.contains(brCard)) { bridge.onStatusChange(() => {}); return; } |
| 890 | const on = bridge.isConnected(); |
| 891 | brCard.querySelector('#br-dot').className = 'dot ' + (on ? 'on' : 'off'); |
| 892 | brCard.querySelector('#br-status').textContent = on ? t("setBridgeOnStatus") : t("setBridgeDisconnected"); |
| 893 | if (on) brCard.querySelector('#br-token').value = localStorage.getItem('elffusscode.bridgeToken') || ''; |
| 894 | }; |
| 895 | paintBridge(); |
| 896 | bridge.onStatusChange(paintBridge); // repinta solo si el bridge conecta/cae mientras Ajustes está abierto |
| 897 | brCard.querySelector('#br-connect').onclick = async () => { |
| 898 | const btn = brCard.querySelector('#br-connect'); |
| 899 | bridge.setFolder(brCard.querySelector('#br-folder').value); |
| 900 | const token = brCard.querySelector('#br-token').value.trim(); |
| 901 | if (!token) return showBridgeMsg(brCard, t("setBridgeNoToken"), true); |
| 902 | btn.disabled = true; btn.textContent = t("setBridgeConnecting"); |
| 903 | try { await bridge.connect(token); paintBridge(); showBridgeMsg(brCard, t("setBridgeConnectedMsg")); fireworks(); } |
| 904 | catch (e) { showBridgeMsg(brCard, '⚠️ ' + e.message, true); } |
| 905 | finally { btn.disabled = false; btn.textContent = t("setBridgeConnect"); } |
| 906 | }; |
| 907 | |
| 908 | // --- Permisos de ejecución (mismo interruptor que </> Auto de la barra) --- |
| 909 | box.append(el('div', 'sk-h', t("setPermTitle"))); |
| 910 | const permCard = el('div', 'prov-card'); |
| 911 | permCard.innerHTML = |
| 912 | `<label style="display:flex;align-items:center;gap:8px;cursor:pointer">` + |
| 913 | `<input type="checkbox" id="perm-autoedit"> ` + |
| 914 | `<span>Ejecutar todo automáticamente (escribir/editar ficheros y comandos de terminal), sin pedir confirmación</span>` + |
| 915 | `</label>` + |
| 916 | `<p class="muted" style="font-size:.7rem;margin:6px 0 0">terminal.run ya se ejecuta siempre sin preguntar. Esto controla solo la escritura de ficheros (code.write/code.edit) — desmárcalo si prefieres revisar cada cambio antes de aplicarlo.</p>`; |
| 917 | box.appendChild(permCard); |
| 918 | const permCheckbox = permCard.querySelector('#perm-autoedit'); |
| 919 | permCheckbox.checked = autoEdit; |
| 920 | permCheckbox.onchange = () => { |
| 921 | autoEdit = permCheckbox.checked; |
| 922 | localStorage.setItem('elffusscode.autoedit', autoEdit ? '1' : '0'); |
| 923 | paintAuto(); |
| 924 | }; |
| 925 | |
| 926 | // --- 🎯 Modo Objetivo (planificador + ejecutor, mismo patrón que Auto) --- |
| 927 | box.append(el('div', 'sk-h', t("setGoalTitle"))); |
| 928 | const goalCard = el('div', 'prov-card'); |
| 929 | goalCard.innerHTML = |
| 930 | `<label style="display:flex;align-items:center;gap:8px;cursor:pointer">` + |
| 931 | `<input type="checkbox" id="perm-goalmode"> ` + |
| 932 | `<span>Tratar el próximo mensaje como un objetivo: lo descompone en tareas y las ejecuta una a una</span>` + |
| 933 | `</label>` + |
| 934 | `<p class="muted" style="font-size:.7rem;margin:6px 0 0">Igual que el botón 🎯 Goal de la barra — un planificador crea la lista de tareas y un ejecutor las va cumpliendo, marcando cada una como hecha o fallida (si una falla, las siguientes se saltan en vez de seguir a ciegas).</p>`; |
| 935 | box.appendChild(goalCard); |
| 936 | const goalCheckbox = goalCard.querySelector('#perm-goalmode'); |
| 937 | goalCheckbox.checked = goalMode; |
| 938 | goalCheckbox.onchange = () => { |
| 939 | goalMode = goalCheckbox.checked; |
| 940 | localStorage.setItem('elffusscode.goalmode', goalMode ? '1' : '0'); |
| 941 | paintGoal(); |
| 942 | }; |
| 943 | |
| 944 | // --- 📨 Errores y feedback (opt-in — apagado no sale NADA de tu máquina) --- |
| 945 | box.append(el('div', 'sk-h', t("setTelTitle"))); |
| 946 | const telCard = el('div', 'prov-card'); |
| 947 | telCard.innerHTML = |
| 948 | `<label style="display:flex;align-items:center;gap:8px;cursor:pointer">` + |
| 949 | `<input type="checkbox" id="tel-enabled"> ` + |
| 950 | `<span>Enviar automáticamente los errores técnicos que ocurran, para poder arreglarlos</span>` + |
| 951 | `</label>` + |
| 952 | `<p class="muted" style="font-size:.7rem;margin:6px 0 10px">Apagado por defecto — tu código y el contenido de tus proyectos NUNCA se incluyen, solo el mensaje de error técnico, la pila y datos del navegador.</p>` + |
| 953 | `<label class="muted" style="font-size:.68rem">O manda algo tú directamente (un fallo que viste, algo que eches en falta…)</label>` + |
| 954 | `<textarea id="tel-feedback" rows="2" style="width:100%;margin-top:4px;resize:vertical;background:var(--bg2);border:1px solid var(--line);border-radius:8px;color:var(--fg);padding:6px 8px;font:inherit" placeholder="${t('setFeedbackPh')}"></textarea>` + |
| 955 | `<button id="tel-send" class="prov-use" style="margin-top:6px">Enviar</button>` + |
| 956 | `<span id="tel-msg" class="muted" style="font-size:.7rem;margin-left:8px"></span>`; |
| 957 | box.appendChild(telCard); |
| 958 | const telCheckbox = telCard.querySelector('#tel-enabled'); |
| 959 | telCheckbox.checked = telemetry.isEnabled(); |
| 960 | telCheckbox.onchange = () => telemetry.setEnabled(telCheckbox.checked); |
| 961 | telCard.querySelector('#tel-send').onclick = async () => { |
| 962 | const ta = telCard.querySelector('#tel-feedback'); |
| 963 | const msg = telCard.querySelector('#tel-msg'); |
| 964 | const text = ta.value.trim(); |
| 965 | if (!text) { msg.textContent = t("setTelEmpty"); return; } |
| 966 | const wasEnabled = telemetry.isEnabled(); |
| 967 | if (!wasEnabled) telemetry.setEnabled(true); // el envío manual es explícito, se permite aunque el automático esté apagado |
| 968 | await telemetry.sendFeedback(text); |
| 969 | if (!wasEnabled) telemetry.setEnabled(false); // no activa el automático de fondo si no lo pidió |
| 970 | ta.value = ''; |
| 971 | msg.textContent = t("setTelThanks"); |
| 972 | setTimeout(() => { msg.textContent = ''; }, 4000); |
| 973 | }; |
| 974 | |
| 975 | // --- Proveedores externos (API keys) --- |
| 976 | box.append(el('div', 'sk-h', t("setProvTitle"))); |
| 977 | for (const [id, c] of Object.entries(settings.configs())) { |
| 978 | const card = el('div', 'prov-card' + (c.enabled ? ' on' : '')); |
| 979 | const head = el('div', 'prov-head'); |
| 980 | const toggle = document.createElement('input'); toggle.type = 'checkbox'; toggle.checked = c.enabled; |
| 981 | const title = el('b', null, c.label); |
| 982 | const use = el('button', 'prov-use', t("setProvUse")); |
| 983 | use.hidden = !c.enabled || activeModel === 'ext:' + id; |
| 984 | use.onclick = () => { changeModel('ext:' + id); renderSettings(); }; |
| 985 | head.append(toggle, title, use); |
| 986 | const fields = el('div', 'prov-fields' + (c.enabled ? '' : ' hide')); |
| 987 | const model = document.createElement('input'); model.value = c.model || ''; model.placeholder = t('setModelPh'); |
| 988 | const key = document.createElement('input'); key.type = 'password'; key.value = c.apiKey || ''; |
| 989 | key.placeholder = c.kind === 'anthropic' ? 'sk-ant-…' : (id === 'ollama' || id === 'server' ? t('keyNeeded') : 'sk-…'); |
| 990 | fields.append(labeled(t('lblModel'), model), labeled(t('lblApiKey'), key)); |
| 991 | const save = () => { |
| 992 | settings.update(id, { enabled: toggle.checked, model: model.value.trim(), apiKey: key.value }); |
| 993 | rebuildSelect(); |
| 994 | }; |
| 995 | toggle.onchange = () => { save(); renderSettings(); }; |
| 996 | model.onchange = key.onchange = save; |
| 997 | card.append(head, fields); |
| 998 | box.appendChild(card); |
| 999 | } |
| 1000 | |
| 1001 | // --- Skills --- |
| 1002 | box.append(el('div', 'sk-h', 'Skills')); |
| 1003 | const skBtn = el('button', 'primary wide', '🧩 Gestionar skills de Claude Code'); |
| 1004 | skBtn.textContent = t("setManageSkillsBtn"); |
| 1005 | skBtn.onclick = openSkillsPanel; |
| 1006 | box.appendChild(skBtn); |
| 1007 | } |
| 1008 | function labeled(label, input) { |
| 1009 | const w = el('label', 'field'); w.append(el('span', 'muted', label), input); return w; |
| 1010 | } |
| 1011 | |
| 1012 | // ---------- arranque ---------- |
| 1013 | let galaxy = null; |
| 1014 | async function enterIDE(handle) { |
| 1015 | const name = await codeTools.openProject(handle); |
| 1016 | shell.reset(); // el terminal arranca en la raíz del proyecto |
| 1017 | galaxy?.stop(); |
| 1018 | $('landing').hidden = true; |
| 1019 | $('ide').hidden = false; |
| 1020 | $('project-name').textContent = name; |
| 1021 | $('explorer-proj').textContent = name.toUpperCase(); |
| 1022 | await initEditor(); |
| 1023 | await refreshTree(handle); |
| 1024 | // el sistema de conversaciones primero: renderActiveLog() REEMPLAZA todo |
| 1025 | // #chat-log con el historial replay de la conversación activa — si el |
| 1026 | // saludo se añadiera antes, desaparecería sin dejar rastro. |
| 1027 | await conv.init({ onEvent: onConvEvent }); |
| 1028 | renderTabsBar(); |
| 1029 | renderActiveLog(); |
| 1030 | addMsg('sys', t('welcome', { name })); |
| 1031 | refreshGit(); |
| 1032 | preloadModel(); // por si el arranque en la landing no llegó a dispararse |
| 1033 | } |
| 1034 | |
| 1035 | async function boot() { |
| 1036 | applyI18n(); // localiza el chrome estático (placeholder) antes de pintar nada |
| 1037 | // Caché de modelos (persistente + service worker) ANTES de descargar nada, |
| 1038 | // para que hasta la primera descarga de pesos quede cacheada y no se repita. |
| 1039 | ensureModelCache().finally(() => preloadModel()); |
| 1040 | bridge.tryAutoConnect(); // reconecta en silencio si ya se conectó antes (mismo token) |
| 1041 | bridge.startAutoDetect(); // sigue sondeando en 2º plano: detecta el bridge si se arranca/reinicia más tarde |
| 1042 | // galaxia en la landing (misma técnica que Elffuss) |
| 1043 | import('./splash-gl.js').then(m => { galaxy = m.startGalaxy($('landing')); }).catch(() => {}); |
| 1044 | |
| 1045 | $('open-project').onclick = async () => { |
| 1046 | try { await enterIDE(await window.showDirectoryPicker({ mode: 'readwrite' })); } |
| 1047 | catch { /* cancelado */ } |
| 1048 | }; |
| 1049 | |
| 1050 | // clonar un repo público (GitHub/Bitbucket): elige carpeta destino, se |
| 1051 | // descarga ahí (fichero a fichero, sin git) y se abre como proyecto. |
| 1052 | // RESUMIBLE: el trabajo (lista de ficheros + cuáles ya se bajaron + el |
| 1053 | // handle de la carpeta) se persiste en IndexedDB — si el usuario navega |
| 1054 | // atrás, cierra la pestaña o recarga a medias, al volver se ofrece |
| 1055 | // «Reanudar» en vez de forzar a empezar de cero. |
| 1056 | const cloneUrl = $('clone-url'), cloneBtn = $('clone-btn'), cloneStatus = $('clone-status'); |
| 1057 | const showCloneStatus = (text, isErr) => { cloneStatus.textContent = text; cloneStatus.hidden = !text; cloneStatus.classList.toggle('err', !!isErr); }; |
| 1058 | const saveCloneJob = job => db.set('kv', 'cloneJob', job).catch(() => {}); |
| 1059 | const loadCloneJob = () => db.get('kv', 'cloneJob').catch(() => null); |
| 1060 | const clearCloneJob = () => db.del('kv', 'cloneJob').catch(() => {}); |
| 1061 | |
| 1062 | async function runDownload(job) { |
| 1063 | cloneBtn.disabled = true; |
| 1064 | const doneSet = new Set(job.done); |
| 1065 | const clone = await import('./tools/clone.js'); |
| 1066 | try { |
| 1067 | await clone.downloadFiles(job, job.handle, doneSet, |
| 1068 | p => showCloneStatus(p.text || ''), |
| 1069 | async path => { |
| 1070 | job.done.push(path); |
| 1071 | // persistir el progreso poco a poco (no en cada fichero: de sobra |
| 1072 | // para no perder más de un puñado si se interrumpe a media descarga) |
| 1073 | if (job.done.length % 5 === 0) await saveCloneJob(job); |
| 1074 | }); |
| 1075 | await saveCloneJob(job); |
| 1076 | showCloneStatus(`✔ ${job.files.length} ficheros descargados` + (job.skipped ? ` (${job.skipped} omitidos por tamaño)` : '')); |
| 1077 | await clearCloneJob(); |
| 1078 | await enterIDE(job.handle); |
| 1079 | } catch (e) { |
| 1080 | await saveCloneJob(job); // que lo ya bajado no se pierda aunque falle a mitad |
| 1081 | showCloneStatus('⚠️ ' + (e?.message || e) + ' — puedes reintentar, retoma donde se quedó', true); |
| 1082 | } finally { cloneBtn.disabled = false; } |
| 1083 | } |
| 1084 | |
| 1085 | const runClone = async () => { |
| 1086 | const url = cloneUrl.value.trim(); |
| 1087 | if (!url) return; |
| 1088 | let handle; |
| 1089 | try { handle = await window.showDirectoryPicker({ mode: 'readwrite' }); } |
| 1090 | catch { return; } // cancelado, sin error |
| 1091 | showCloneStatus('Listando el repo…'); |
| 1092 | try { |
| 1093 | const clone = await import('./tools/clone.js'); |
| 1094 | const info = await clone.listRepo(url); |
| 1095 | const job = { url, handle, done: [], ...info }; |
| 1096 | await saveCloneJob(job); |
| 1097 | await runDownload(job); |
| 1098 | } catch (e) { |
| 1099 | showCloneStatus('⚠️ ' + (e?.message || e), true); |
| 1100 | } |
| 1101 | }; |
| 1102 | cloneBtn.addEventListener('click', runClone); |
| 1103 | cloneUrl.addEventListener('keydown', e => { if (e.key === 'Enter') runClone(); }); |
| 1104 | |
| 1105 | // ¿había una descarga a medias de una sesión anterior? ofrece reanudarla |
| 1106 | const job = await loadCloneJob(); |
| 1107 | if (job && job.handle && job.files && job.done.length < job.files.length) { |
| 1108 | const banner = $('resume-clone'); |
| 1109 | banner.hidden = false; |
| 1110 | banner.querySelector('.rc-text').textContent = `Descarga a medias de ${job.owner}/${job.repo} (${job.done.length}/${job.files.length} ficheros)`; |
| 1111 | $('resume-clone-btn').onclick = async () => { |
| 1112 | banner.hidden = true; |
| 1113 | try { |
| 1114 | const q = job.handle.queryPermission ? await job.handle.queryPermission({ mode: 'readwrite' }) : 'granted'; |
| 1115 | if (q !== 'granted' && await job.handle.requestPermission({ mode: 'readwrite' }) !== 'granted') throw new Error('permiso denegado para la carpeta'); |
| 1116 | showCloneStatus(`Reanudando ${job.owner}/${job.repo}…`); |
| 1117 | await runDownload(job); |
| 1118 | } catch (e) { showCloneStatus('⚠️ ' + (e?.message || e), true); } |
| 1119 | }; |
| 1120 | $('discard-clone-btn').onclick = async () => { await clearCloneJob(); banner.hidden = true; }; |
| 1121 | } else if (job) { |
| 1122 | await clearCloneJob(); // job corrupto o ya completo: limpiar |
| 1123 | } |
| 1124 | |
| 1125 | // gancho de test: ?test-opfs usa el almacenamiento del navegador como proyecto |
| 1126 | if (location.search.includes('test-opfs')) { |
| 1127 | const opfs = await navigator.storage.getDirectory(); |
| 1128 | return enterIDE(opfs); |
| 1129 | } |
| 1130 | |
| 1131 | // reabrir el último proyecto (un clic si el navegador exige gesto) |
| 1132 | const prev = await codeTools.restoreProject(); |
| 1133 | if (prev?.ready) return enterIDE(await db.get('kv', 'project')); |
| 1134 | if (prev?.handle) { |
| 1135 | const btn = $('reopen-project'); |
| 1136 | btn.hidden = false; |
| 1137 | btn.textContent = `Reabrir «${prev.name}»`; |
| 1138 | btn.onclick = async () => { |
| 1139 | try { await codeTools.regrant(prev.handle); await enterIDE(prev.handle); } |
| 1140 | catch (e) { $('statusbar').textContent = '⚠️ ' + e.message; } |
| 1141 | }; |
| 1142 | } |
| 1143 | } |
| 1144 | |
| 1145 | // Historial del prompt del chat: ↑/↓ recuperan lo enviado (como una shell). |
| 1146 | // Persistente entre recargas (localStorage, últimos 100). |
| 1147 | const PROMPT_HIST_KEY = 'elffusscode.promptHistory'; |
| 1148 | let promptHistory = []; |
| 1149 | try { promptHistory = JSON.parse(localStorage.getItem(PROMPT_HIST_KEY) || '[]'); } catch { /* corrupto */ } |
| 1150 | let promptHistIdx = -1, promptDraft = ''; |
| 1151 | function pushPromptHistory(text) { |
| 1152 | if (promptHistory[promptHistory.length - 1] !== text) promptHistory.push(text); |
| 1153 | if (promptHistory.length > 100) promptHistory = promptHistory.slice(-100); |
| 1154 | try { localStorage.setItem(PROMPT_HIST_KEY, JSON.stringify(promptHistory)); } catch { /* lleno */ } |
| 1155 | promptHistIdx = -1; promptDraft = ''; |
| 1156 | } |
| 1157 | $('prompt').addEventListener('keydown', e => { |
| 1158 | if (!$('menu').hidden) return; // el menú «/» ya usa ↑/↓ |
| 1159 | const inp = e.target; |
| 1160 | if (e.key === 'ArrowUp') { |
| 1161 | if (!promptHistory.length) return; |
| 1162 | if (promptHistIdx === -1) { promptDraft = inp.value; promptHistIdx = promptHistory.length; } |
| 1163 | promptHistIdx = Math.max(0, promptHistIdx - 1); |
| 1164 | inp.value = promptHistory[promptHistIdx]; |
| 1165 | e.preventDefault(); |
| 1166 | requestAnimationFrame(() => inp.setSelectionRange(inp.value.length, inp.value.length)); |
| 1167 | } else if (e.key === 'ArrowDown') { |
| 1168 | if (promptHistIdx === -1) return; |
| 1169 | promptHistIdx++; |
| 1170 | inp.value = promptHistIdx >= promptHistory.length ? (promptHistIdx = -1, promptDraft) : promptHistory[promptHistIdx]; |
| 1171 | e.preventDefault(); |
| 1172 | } else if (e.key === 'Enter' && !e.isComposing && !e.shiftKey) { |
| 1173 | // envío explícito: no depender del submit-on-Enter nativo del <form>, |
| 1174 | // que algún navegador puede "tragarse" el primer Enter (autocompletar/ |
| 1175 | // sugerencias) justo después de rellenar el valor por código (↑ del |
| 1176 | // historial) en vez de por tecleo real. |
| 1177 | e.preventDefault(); |
| 1178 | $('composer').requestSubmit(); |
| 1179 | } |
| 1180 | }); |
| 1181 | $('composer').addEventListener('submit', e => { |
| 1182 | e.preventDefault(); |
| 1183 | // Mientras el agente trabaja, el mismo botón PARA en vez de enviar. Si ya se |
| 1184 | // está parando, lo que se escriba va a la cola y sale en cuanto termine. |
| 1185 | const active = conv.getActive(); |
| 1186 | if (active && active.pumping && !active.parando) { conv.stopActive(); return; } |
| 1187 | const text = $('prompt').value.trim(); |
| 1188 | if (!text) return; |
| 1189 | $('prompt').value = ''; |
| 1190 | pushPromptHistory(text); |
| 1191 | send(text); |
| 1192 | }); |
| 1193 | // Reflejar en el botón si estamos generando (▶ enviar / ■ parar). Se llama desde |
| 1194 | // el onChange de conversaciones cuando cambia «pumping». |
| 1195 | 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>'; |
| 1196 | function paintSendButton() { |
| 1197 | const b = document.getElementById('btn-send'); |
| 1198 | if (!b) return; |
| 1199 | const active = conv.getActive(); |
| 1200 | const busy = !!active?.pumping; |
| 1201 | // «Parando…»: ya se pulsó ■ y el turno aún se está soltando (un modelo lento |
| 1202 | // tarda en dejar la generación). Deshabilitado y con aria-busy: antes el ■ |
| 1203 | // seguía igual tras el clic y parecía que no había hecho caso. |
| 1204 | const parando = busy && !!active?.parando; |
| 1205 | b.classList.toggle('sending', busy); |
| 1206 | b.classList.toggle('is-stop', busy && !parando); |
| 1207 | b.classList.toggle('is-stopping', parando); |
| 1208 | b.disabled = parando; |
| 1209 | if (parando) b.setAttribute('aria-busy', 'true'); else b.removeAttribute('aria-busy'); |
| 1210 | b.innerHTML = parando ? escapeHtml(t('stopping')) : busy ? STOP_ICON : UI.send; |
| 1211 | b.title = parando ? t('stopping') : busy ? 'Parar' : 'Enviar'; |
| 1212 | b.setAttribute('aria-label', b.title); |
| 1213 | } |
| 1214 | $('model-select').addEventListener('change', e => changeModel(e.target.value)); |
| 1215 | // móvil: conmutar chat ↔ editor |
| 1216 | $('code-flip').addEventListener('click', () => { |
| 1217 | const showEditor = !document.body.classList.contains('show-editor'); |
| 1218 | document.body.classList.toggle('show-editor', showEditor); |
| 1219 | paintFlip(showEditor); |
| 1220 | }); |
| 1221 | |
| 1222 | // vistas Arquitectura (grafo) y Ciudad 3D — leen el proyecto abierto y al |
| 1223 | // hacer clic abren el fichero en Monaco (inspirado en CodeFlow + VibeCodeViewer) |
| 1224 | $('act-arch').innerHTML = UI.graph || UI.code; |
| 1225 | $('act-city').innerHTML = UI.city || UI.code; |
| 1226 | let viewRenderSeq = 0; |
| 1227 | async function openView(kind) { |
| 1228 | const overlay = $('view-overlay'), body = $('view-body'); |
| 1229 | const seq = ++viewRenderSeq; |
| 1230 | // destruir CUALQUIER vista previa (su RAF/canvas seguía vivo al cambiar → la |
| 1231 | // nueva no cargaba bien). Ambas, no solo la del mismo tipo. |
| 1232 | try { (await import('./city.js')).disposeCity(); } catch { /* */ } |
| 1233 | try { (await import('./arch.js')).disposeArch(); } catch { /* */ } |
| 1234 | body.innerHTML = '<div class="view-loading">Construyendo…</div>'; |
| 1235 | overlay.hidden = false; |
| 1236 | document.querySelectorAll('#activity button').forEach(b => b.classList.toggle('on', b.id === 'act-' + kind)); |
| 1237 | // esperar a que el layout dé tamaño real al overlay (si no, canvas 0×0/mal aspect) |
| 1238 | await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))); |
| 1239 | if (seq !== viewRenderSeq) return; // el usuario cambió de vista mientras tanto |
| 1240 | try { |
| 1241 | if (kind === 'arch') { const m = await import('./arch.js'); await m.renderArchitecture(body, p => { closeView(); openFile(p); }); } |
| 1242 | else { const m = await import('./city.js'); await m.renderCity(body, p => { closeView(); openFile(p); }); } |
| 1243 | } catch (e) { body.innerHTML = '<div class="view-loading">No pude construir la vista: ' + (e?.message || e) + '</div>'; } |
| 1244 | } |
| 1245 | function closeView() { |
| 1246 | $('view-overlay').hidden = true; |
| 1247 | import('./city.js').then(m => m.disposeCity()).catch(() => {}); |
| 1248 | import('./arch.js').then(m => m.disposeArch()).catch(() => {}); |
| 1249 | document.querySelectorAll('#activity button').forEach(b => b.classList.toggle('on', b.id === 'act-files')); |
| 1250 | } |
| 1251 | $('act-arch').addEventListener('click', () => openView('arch')); |
| 1252 | $('act-city').addEventListener('click', () => openView('city')); |
| 1253 | $('view-close').addEventListener('click', closeView); |
| 1254 | |
| 1255 | // ── Cerebro CEO autónomo + Mente de Elffuss ─────────────────────────────── |
| 1256 | // Cuando NO estás pidiendo nada, la elfa trabaja: revisa el proyecto y propone |
| 1257 | // mejoras (en elffuss-mind/, sin tocar tu código). Clic en la elfa → abre la |
| 1258 | // «Mente» (mundo trance + pensamientos paralelos + música) y activa el cerebro. |
| 1259 | mind.setOpenFile(openFile); |
| 1260 | mind.init({ buildCity: buildCityAdapter, loadThoughts: loadThoughtsAdapter }); |
| 1261 | // «Ejecutar esta propuesta»: la manda a la MISMA cola/agente del chat normal |
| 1262 | // (mismas herramientas reales, mismo gate de Auto-edit) — no un auto-apply |
| 1263 | // aparte sin supervisión. |
| 1264 | mind.setExecuteProposal(md => { mind.closeMind(); send(t('pProposal') + md); }); |
| 1265 | // «perfiles»: cada uno es una línea de pensamiento paralela (foco + color de |
| 1266 | // su estrella) del cerebro CEO (compartido, core/ceo.js). El usuario los |
| 1267 | // edita/crea/borra desde ⚙ en la Mente. |
| 1268 | const CEO_DEFAULT_PROFILES = [ |
| 1269 | { id: 'arq', name: 'Arquitectura', focus: 'estructura, acoplamiento y dependencias; qué módulo conviene dividir o unificar', color: '#7c5cff' }, |
| 1270 | { id: 'cal', name: 'Calidad', focus: 'bugs latentes, casos borde sin cubrir, validaciones que faltan', color: '#49e8ff' }, |
| 1271 | { id: 'rend', name: 'Rendimiento', focus: 'cuellos de botella, trabajo repetido, estructuras de datos mejorables', color: '#ffb454' }, |
| 1272 | { id: 'dx', name: 'Producto/DX', focus: 'legibilidad, nombres, documentación y ergonomía para quien lo usa', color: '#3fb970' }, |
| 1273 | ]; |
| 1274 | // adaptador de workspace para el cerebro CEO genérico (core/ceo.js): traduce |
| 1275 | // sus operaciones a las herramientas de code.js (proyecto de código único). |
| 1276 | async function ceoDirHandle(dirPath) { |
| 1277 | let dir = codeTools.handle(); |
| 1278 | for (const seg of dirPath.split('/').filter(Boolean)) dir = await dir.getDirectoryHandle(seg, { create: true }); |
| 1279 | return dir; |
| 1280 | } |
| 1281 | const ceoWorkspace = { |
| 1282 | isReady: () => !!codeTools.handle(), |
| 1283 | tree: (opts) => codeTools.tree(opts), |
| 1284 | write: (opts) => codeTools.write(opts), |
| 1285 | read: (opts) => codeTools.read(opts), |
| 1286 | list: async (dirPath) => { |
| 1287 | const dir = await ceoDirHandle(dirPath); |
| 1288 | const names = []; |
| 1289 | for await (const e of dir.values()) if (e.kind === 'file') names.push(e.name); |
| 1290 | return names; |
| 1291 | }, |
| 1292 | remove: async (dirPath, name) => (await ceoDirHandle(dirPath)).removeEntry(name), |
| 1293 | }; |
| 1294 | ceo.init({ |
| 1295 | namespace: 'elffusscode', |
| 1296 | workspace: ceoWorkspace, |
| 1297 | defaultProfiles: CEO_DEFAULT_PROFILES, |
| 1298 | defaultMission: 'Revisar el proyecto y proponer mejoras concretas y accionables (código, procesos, datos o docs).', |
| 1299 | provider: () => conv.getProvider(), |
| 1300 | // el usuario tiene PRIORIDAD: si CUALQUIER conversación está en cola o procesándose, el cerebro espera |
| 1301 | isBusy: () => conv.isBusy(), |
| 1302 | onEvent: (ch, ev) => { |
| 1303 | mind.pushThought(ch, ev); |
| 1304 | if (ch === 'ceo' && ev.type === 'built') reportImprovements(ev); |
| 1305 | // la elfa se anima mientras el cerebro trabaja (invita a hacer clic para ver la Mente) |
| 1306 | const av = document.querySelector('#activity img'); |
| 1307 | if (av) { |
| 1308 | if (ch === 'ceo' && ev.type === 'cycle') av.classList.add('working'); |
| 1309 | if (ch === 'ceo' && (ev.type === 'built' || ev.type === 'paused')) av.classList.remove('working'); |
| 1310 | } |
| 1311 | }, |
| 1312 | }); |
| 1313 | // Reporta las mejoras SIEMPRE en el chat (visual, entendible); la notificación |
| 1314 | // del navegador solo salta si de verdad hay algo interesante y bien trabajado |
| 1315 | // — nada de avisar por un ciclo flojo con una propuesta de una línea. |
| 1316 | const WEAK_RE = /^(no (encontr|hay|se me ocurre)|nada que|sin cambios|todo (está|esta) bien|no aplica)/i; |
| 1317 | export function isNoteworthy(ev) { |
| 1318 | const solid = (ev.proposals || []).filter(p => p.text && p.text.trim().length >= 60 && !WEAK_RE.test(p.text.trim())); |
| 1319 | return solid.length >= 2; // al menos 2 departamentos con algo sustancioso, no una ocurrencia suelta |
| 1320 | } |
| 1321 | // manda una propuesta (el .md completo del ciclo) a la MISMA cola/agente real |
| 1322 | // del chat — usado tanto por el botón del chat como por el de la notificación. |
| 1323 | function executeProposal(md) { send(t('pProposal') + md); } |
| 1324 | |
| 1325 | export function reportImprovements(ev) { |
| 1326 | const props = ev.proposals || []; |
| 1327 | if (!props.length) return; |
| 1328 | const firstLine = t => (t || '').split('\n').find(l => l.trim())?.trim().slice(0, 160) || ''; |
| 1329 | const body = `💡 **Mientras estabas fuera revisé el proyecto y encontré ${props.length} mejora${props.length === 1 ? '' : 's'}:**\n\n` + |
| 1330 | props.map(p => `**${p.dept}** — ${firstLine(p.text)}`).join('\n\n') + |
| 1331 | (ev.path ? `\n\n_Guardado en \`${ev.path}\`. Dale a la elfa para verlo en la Mente, o ábrelo en el editor._` : ''); |
| 1332 | const div = addMsg('assistant', body); |
| 1333 | // se guarda en el historial REAL de la conversación activa — si no, el |
| 1334 | // aviso vive solo en el DOM y desaparece al cambiar de pestaña o recargar |
| 1335 | const active = conv.getActive(); |
| 1336 | if (active) conv.appendMessage(active.id, 'assistant', body); |
| 1337 | // botón REAL para ejecutar la propuesta desde el propio chat (antes solo |
| 1338 | // se podía desde el panel de la Mente, había que ir a buscarlo) |
| 1339 | const md = ev.md || body; |
| 1340 | if (div) { |
| 1341 | const btn = document.createElement('button'); |
| 1342 | btn.className = 'proposal-exec-btn'; |
| 1343 | btn.textContent = '▶ Ejecutar esta propuesta'; |
| 1344 | btn.onclick = () => { btn.disabled = true; btn.textContent = '▶ enviado a la cola…'; executeProposal(md); }; |
| 1345 | div.appendChild(btn); |
| 1346 | } |
| 1347 | if (isNoteworthy(ev)) notify(`Elffuss encontró ${props.length} mejora${props.length === 1 ? '' : 's'}`, props.map(p => p.dept).join(' · '), md); |
| 1348 | } |
| 1349 | // SOLO notifica si el permiso YA está concedido. Nunca pide permiso aquí: |
| 1350 | // fuera de un gesto de usuario, Chrome/Firefox lo bloquean en silencio — |
| 1351 | // pedirlo vive únicamente en el clic de la elfa y en ⚙ de la Mente. |
| 1352 | // Vía el service worker (registration.showNotification) para poder incluir |
| 1353 | // un botón «▶ Ejecutar» de verdad en la propia notificación del sistema |
| 1354 | // (new Notification() normal no soporta acciones); si el SW no está listo, |
| 1355 | // cae a la notificación simple sin botón. |
| 1356 | async function notify(title, body, md) { |
| 1357 | if (!('Notification' in window) || Notification.permission !== 'granted') return; |
| 1358 | try { |
| 1359 | if ('serviceWorker' in navigator) { |
| 1360 | const reg = await navigator.serviceWorker.ready; |
| 1361 | if (reg.showNotification) { |
| 1362 | await reg.showNotification(title, { |
| 1363 | body, icon: 'img/elffuss-code.svg', |
| 1364 | actions: [{ action: 'execute', title: t('nExec') }, { action: 'open', title: t('nView') }], |
| 1365 | data: { md }, |
| 1366 | }); |
| 1367 | return; |
| 1368 | } |
| 1369 | } |
| 1370 | } catch { /* cae a la notificación simple */ } |
| 1371 | try { new Notification(title, { body, icon: 'img/elffuss-code.svg' }); } catch { /* */ } |
| 1372 | } |
| 1373 | // clic en el botón de la notificación del sistema → lo mismo que en el chat |
| 1374 | if ('serviceWorker' in navigator) { |
| 1375 | navigator.serviceWorker.addEventListener('message', e => { |
| 1376 | if (e.data?.type !== 'notif-action') return; |
| 1377 | if (e.data.action === 'execute' && e.data.md) executeProposal(e.data.md); |
| 1378 | else mind.openMind(); |
| 1379 | }); |
| 1380 | } |
| 1381 | // cualquier interacción FUERA de la Mente cuenta como actividad → pausa el CEO |
| 1382 | const noteAct = e => { if (!e.target.closest?.('#mind-overlay')) ceo.noteActivity(); }; |
| 1383 | document.addEventListener('pointerdown', noteAct, true); |
| 1384 | document.addEventListener('keydown', noteAct, true); |
| 1385 | const elfAvatar = document.querySelector('#activity img'); |
| 1386 | if (elfAvatar) { |
| 1387 | elfAvatar.style.cursor = 'pointer'; |
| 1388 | elfAvatar.title = t('avatarTitle'); |
| 1389 | elfAvatar.addEventListener('click', () => { |
| 1390 | // auto-activa SOLO la primera vez (nunca decidiste play/stop); si lo |
| 1391 | // pausaste a propósito, abrir la Mente NO debe reactivarlo por sorpresa. |
| 1392 | if (!ceo.isEnabled() && !ceo.hasDecided()) ceo.enable(); |
| 1393 | try { if ('Notification' in window && Notification.permission === 'default') Notification.requestPermission(); } catch { /* */ } |
| 1394 | mind.openMind(); |
| 1395 | }); |
| 1396 | } |
| 1397 | // restaura tu última elección (play o stop) tal cual la dejaste |
| 1398 | if (ceo.wasEnabledLastSession()) ceo.enable(); |
| 1399 | |
| 1400 | // terminal integrado: xterm.js + shell sobre los ficheros REALES del proyecto. |
| 1401 | // La elfa comparte este shell (tool terminal.run) y su salida se refleja aquí. |
| 1402 | $('act-term').innerHTML = UI.terminal; |
| 1403 | shell.setHooks({ fsChange: () => refreshTree().catch(() => {}), openFile }); |
| 1404 | setTerminalEcho((cmd, out) => terminal.echoAgent(cmd, out)); |
| 1405 | async function toggleTerminal(force) { |
| 1406 | const show = force != null ? force : $('terminal-panel').hidden; |
| 1407 | $('terminal-panel').hidden = !show; |
| 1408 | $('act-term').classList.toggle('on', show); |
| 1409 | if (show) { |
| 1410 | const cap = shell.capabilities(); |
| 1411 | $('term-caps').textContent = cap.bridge ? t("termCapsBridge") : t("termCapsNoBridge"); |
| 1412 | await terminal.mount($('terminal-host')); |
| 1413 | terminal.refit(); |
| 1414 | } |
| 1415 | } |
| 1416 | $('act-term').addEventListener('click', () => toggleTerminal()); |
| 1417 | $('term-close').addEventListener('click', () => toggleTerminal(false)); |
| 1418 | $('term-clear').addEventListener('click', () => terminal.clearScreen()); |
| 1419 | // Ctrl+` (o Cmd+`) alterna el terminal, como en VS Code |
| 1420 | document.addEventListener('keydown', e => { |
| 1421 | if ((e.ctrlKey || e.metaKey) && e.key === '`') { e.preventDefault(); toggleTerminal(); } |
| 1422 | }); |
| 1423 | // redimensionar arrastrando la barra superior del panel |
| 1424 | (() => { |
| 1425 | const panel = $('terminal-panel'), handle = $('term-resize'); |
| 1426 | let sy = 0, sh = 0; |
| 1427 | const move = e => { const h = Math.max(120, Math.min(window.innerHeight - 160, sh + (sy - e.clientY))); panel.style.height = h + 'px'; terminal.refit(); }; |
| 1428 | const up = () => { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', up); }; |
| 1429 | handle.addEventListener('mousedown', e => { sy = e.clientY; sh = panel.offsetHeight; document.addEventListener('mousemove', move); document.addEventListener('mouseup', up); e.preventDefault(); }); |
| 1430 | })(); |
| 1431 | window.addEventListener('resize', () => terminal.refit()); |
| 1432 | |
| 1433 | // iconos VS Code (sin emojis) en cabecera, composer y flip |
| 1434 | $('btn-history').innerHTML = UI.history; |
| 1435 | $('btn-settings').innerHTML = UI.gear; |
| 1436 | $('btn-send').innerHTML = UI.send; |
| 1437 | $('btn-plus').innerHTML = UI.add; |
| 1438 | $('btn-slash').innerHTML = UI.slash; |
| 1439 | const paintFlip = editor => { $('code-flip').innerHTML = (editor ? UI.chat : UI.editor) + `<span>${editor ? 'Chat' : 'Editor'}</span>`; }; |
| 1440 | paintFlip(false); |
| 1441 | |
| 1442 | // barra de actividad estilo VS Code |
| 1443 | $('act-files').innerHTML = ACTIVITY.files; |
| 1444 | $('act-search').innerHTML = ACTIVITY.search; |
| 1445 | $('act-settings').innerHTML = ACTIVITY.gear; |
| 1446 | $('act-files').addEventListener('click', () => { |
| 1447 | document.body.classList.toggle('hide-tree'); |
| 1448 | $('act-files').classList.toggle('on'); |
| 1449 | }); |
| 1450 | $('act-search').addEventListener('click', () => { |
| 1451 | $('prompt').value = 'busca '; |
| 1452 | $('prompt').focus(); |
| 1453 | }); |
| 1454 | $('act-settings').addEventListener('click', () => $('btn-settings').click()); |
| 1455 | |
| 1456 | $('btn-history').addEventListener('click', () => { |
| 1457 | const panel = $('history-panel'); |
| 1458 | panel.hidden = !panel.hidden; |
| 1459 | if (!panel.hidden) renderHistoryPanel(); |
| 1460 | }); |
| 1461 | document.addEventListener('pointerdown', e => { |
| 1462 | const p = $('history-panel'); |
| 1463 | if (p.hidden) return; |
| 1464 | if (p.contains(e.target) || e.target.closest('#btn-history')) return; |
| 1465 | p.hidden = true; |
| 1466 | }, true); |
| 1467 | $('btn-settings').addEventListener('click', () => { |
| 1468 | const p = $('settings-panel'); |
| 1469 | p.hidden = !p.hidden; |
| 1470 | if (!p.hidden) renderSettings(); |
| 1471 | }); |
| 1472 | // clic fuera del panel (o ir a Archivo/chat) lo cierra — antes solo la X lo hacía |
| 1473 | document.addEventListener('pointerdown', e => { |
| 1474 | const p = $('settings-panel'); |
| 1475 | if (p.hidden) return; |
| 1476 | if (p.contains(e.target) || e.target.closest('#btn-settings, #act-settings')) return; |
| 1477 | p.hidden = true; |
| 1478 | }, true); |
| 1479 | |
| 1480 | // ---------- composer estilo plugin: +, /, medidor de contexto, Auto ---------- |
| 1481 | |
| 1482 | // medidor de contexto: chars del historial / presupuesto (~4 chars/token) |
| 1483 | // |
| 1484 | // El presupuesto se le PREGUNTA al proveedor cargado, no se escribe aquí. Era un |
| 1485 | // 28.000 fijo, calculado para el LFM2.5 de serie, y enseñaba «ctx 0 / 28k» con |
| 1486 | // cualquier modelo: con el motor propio a 65.536 mentía por más del doble, y al |
| 1487 | // revés con uno pequeño habría dicho que cabe lo que no cabe. Un número escrito |
| 1488 | // a mano en la interfaz es un número que se queda viejo — el mismo fallo que la |
| 1489 | // lista de modelos de los ajustes. |
| 1490 | const CTX_BUDGET_FALLBACK = 28000; // solo si el proveedor no sabe decirlo |
| 1491 | let ctxBudgetTok = CTX_BUDGET_FALLBACK; |
| 1492 | export function setCtxBudget(tokens) { |
| 1493 | // Se reserva sitio para el prompt de sistema y para la respuesta: el techo del |
| 1494 | // modelo NO es lo que cabe de conversación. |
| 1495 | const RESERVA = 4000; |
| 1496 | if (Number.isFinite(tokens) && tokens > RESERVA) ctxBudgetTok = tokens - RESERVA; |
| 1497 | } |
| 1498 | function updateCtxMeter() { |
| 1499 | if (!$('ctx-text')) return; // aún en la landing |
| 1500 | const CTX_BUDGET_TOK = ctxBudgetTok; |
| 1501 | const chars = (conv.getActive()?.agent.history || []).reduce((s, m) => s + (m.content || '').length, 0); |
| 1502 | const tok = Math.round(chars / 4); |
| 1503 | const pct = Math.min(100, Math.round(tok / CTX_BUDGET_TOK * 100)); |
| 1504 | const k = n => n >= 1000 ? (n / 1000).toFixed(1).replace('.0', '') + 'k' : n; |
| 1505 | $('ctx-text').textContent = `ctx ${k(tok)} / ${k(CTX_BUDGET_TOK)}`; |
| 1506 | $('ctx-bar').style.width = pct + '%'; |
| 1507 | $('ctx-bar').className = pct > 85 ? 'hot' : ''; |
| 1508 | $('ctx-meter').title = pct > 85 |
| 1509 | ? `Contexto casi lleno (${pct}%). Los mensajes viejos se comprimen solos; usa 🧹 para empezar limpio.` |
| 1510 | : `Contexto: ${tok} de ~${CTX_BUDGET_TOK} tokens (${100 - pct}% libre)`; |
| 1511 | } |
| 1512 | const _origAdd = addMsg; // refrescar el medidor cuando cambia la conversación |
| 1513 | addMsg = (...a) => { const r = _origAdd(...a); updateCtxMeter(); return r; }; |
| 1514 | |
| 1515 | // menú flotante genérico sobre el composer |
| 1516 | function openMenu(items) { |
| 1517 | const menu = $('menu'); |
| 1518 | menu.replaceChildren(); |
| 1519 | for (const it of items) { |
| 1520 | if (it.sep) { const s = document.createElement('div'); s.className = 'sep'; s.textContent = it.sep; menu.appendChild(s); continue; } |
| 1521 | const row = document.createElement('button'); |
| 1522 | row.className = 'menu-item'; |
| 1523 | row.innerHTML = `<b>${it.label}</b>${it.hint ? `<span>${it.hint}</span>` : ''}`; |
| 1524 | row.onclick = () => { menu.hidden = true; it.run(); }; |
| 1525 | row.onmouseenter = () => { menuSel = menuFilas().indexOf(row); pintaMenuSel(); }; |
| 1526 | menu.appendChild(row); |
| 1527 | } |
| 1528 | menu.hidden = false; |
| 1529 | menuSel = menuFilas().length ? 0 : -1; |
| 1530 | pintaMenuSel(); |
| 1531 | } |
| 1532 | |
| 1533 | // Navegar el menú con el teclado. El keydown del composer se aparta cuando el |
| 1534 | // menú está abierto «porque el menú ya usa ↑/↓», y era mentira: nadie escuchaba, |
| 1535 | // así que con el menú abierto las flechas no movían nada y el Enter se quedaba |
| 1536 | // sin enviar el mensaje y sin elegir fichero. Ahora es verdad. |
| 1537 | let menuSel = -1; |
| 1538 | const menuFilas = () => [...$('menu').querySelectorAll('.menu-item')]; |
| 1539 | function pintaMenuSel() { |
| 1540 | const filas = menuFilas(); |
| 1541 | filas.forEach((f, i) => f.classList.toggle('sel', i === menuSel)); |
| 1542 | if (menuSel >= 0) filas[menuSel]?.scrollIntoView({ block: 'nearest' }); |
| 1543 | } |
| 1544 | function cierraMenu({ sueltaToken = true } = {}) { |
| 1545 | $('menu').hidden = true; |
| 1546 | menuSel = -1; |
| 1547 | if (sueltaToken) { arrobaDesde = -1; cacheFicheros = null; } |
| 1548 | } |
| 1549 | $('prompt').addEventListener('keydown', (e) => { |
| 1550 | if ($('menu').hidden) return; |
| 1551 | if (e.key === 'Escape') { e.preventDefault(); return cierraMenu(); } |
| 1552 | const filas = menuFilas(); |
| 1553 | if (!filas.length) return; |
| 1554 | if (e.key === 'ArrowDown') { e.preventDefault(); menuSel = (menuSel + 1) % filas.length; pintaMenuSel(); } |
| 1555 | else if (e.key === 'ArrowUp') { e.preventDefault(); menuSel = (menuSel - 1 + filas.length) % filas.length; pintaMenuSel(); } |
| 1556 | else if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); filas[Math.max(0, menuSel)].click(); } |
| 1557 | }); |
| 1558 | document.addEventListener('click', e => { |
| 1559 | if (!e.target.closest('#menu, #btn-slash, #btn-plus')) cierraMenu(); |
| 1560 | }); |
| 1561 | |
| 1562 | // [/] comandos |
| 1563 | $('btn-slash').addEventListener('click', () => openMenu([ |
| 1564 | { sep: t('cmdsSep') }, |
| 1565 | { label: '/tree', hint: t('slTree'), run: () => send(t('pTree')) }, |
| 1566 | { label: '/search', hint: t('slSearch'), run: () => { $('prompt').value = t('pSearch'); $('prompt').focus(); } }, |
| 1567 | { label: '/skills', hint: t('slSkills'), run: () => openSkillsPanel() }, |
| 1568 | { label: '/model', hint: t('slModel'), run: () => $('btn-settings').click() }, |
| 1569 | { label: '/clear', hint: t('slClear'), run: () => conv.create() }, |
| 1570 | ])); |
| 1571 | |
| 1572 | // [+] adjuntar archivo del proyecto como @ruta |
| 1573 | // El menú de ficheros, en una función: lo abren el botón `+` Y escribir `@` en |
| 1574 | // la conversación, que es lo natural y lo que ya prometía el título del botón |
| 1575 | // («Adjuntar archivo del proyecto (@)») sin que nada lo implementara. |
| 1576 | // |
| 1577 | // Y FILTRA mientras escribes. Antes el menú se pintaba una vez al teclear `@` y |
| 1578 | // se quedaba congelado: las letras siguientes entraban en el textarea y la lista |
| 1579 | // seguía mostrando los mismos veinte ficheros. Con un árbol de verdad eso es un |
| 1580 | // menú inútil, porque lo que buscas casi nunca está entre los veinte primeros. |
| 1581 | let arrobaDesde = -1; // índice del `@` que se está escribiendo, o -1 |
| 1582 | let cacheFicheros = null; // el árbol, leído una vez por sesión de menú |
| 1583 | |
| 1584 | // Reconstruye las RUTAS COMPLETAS del árbol. `code.tree` indenta dos espacios |
| 1585 | // por nivel y marca las carpetas con «📁 », así que la carpeta de un fichero |
| 1586 | // está en su sangría, no en su línea. |
| 1587 | // |
| 1588 | // ⚠️ Esto hacía `l.trim()` sobre cada línea, que es exactamente tirar esa |
| 1589 | // información: el menú ofrecía «obj_1_Zusammenbau.stl» cuando el fichero real |
| 1590 | // es «dinos/obj_1_Zusammenbau.stl», y al insertarlo la herramienta fallaba con |
| 1591 | // «no existe en este proyecto». Lo peor del fallo es que el menú te deja |
| 1592 | // elegirlo: parece que la ruta está bien hasta que la lees. |
| 1593 | export function rutasDelArbol(tree) { |
| 1594 | const rutas = []; |
| 1595 | const pila = []; |
| 1596 | for (const linea of String(tree || '').split('\n')) { |
| 1597 | if (!linea.trim()) continue; |
| 1598 | if (linea.startsWith('…')) continue; // el aviso de árbol recortado |
| 1599 | const sangria = linea.length - linea.replace(/^ +/, '').length; |
| 1600 | const nivel = Math.floor(sangria / 2); |
| 1601 | const texto = linea.trim(); |
| 1602 | if (texto.startsWith('📁')) { |
| 1603 | pila.length = nivel; // salir de las carpetas hermanas |
| 1604 | pila.push(texto.replace(/^📁\s*/, '')); |
| 1605 | } else { |
| 1606 | rutas.push([...pila.slice(0, nivel), texto].join('/')); |
| 1607 | } |
| 1608 | } |
| 1609 | return rutas; |
| 1610 | } |
| 1611 | |
| 1612 | async function listaProyecto() { |
| 1613 | if (cacheFicheros) return cacheFicheros; |
| 1614 | let tree = ''; |
| 1615 | try { tree = await codeTools.tree({ depth: 3 }); } catch { /* sin proyecto */ } |
| 1616 | const files = rutasDelArbol(tree); |
| 1617 | const { currentFile } = codeTools.current(); |
| 1618 | return (cacheFicheros = { files, currentFile }); |
| 1619 | } |
| 1620 | |
| 1621 | async function abreMenuFicheros(frag = '') { |
| 1622 | const { files, currentFile } = await listaProyecto(); |
| 1623 | const q = frag.toLowerCase(); |
| 1624 | // El filtro va sobre la lista COMPLETA y el recorte a 20 va DESPUÉS. Al revés |
| 1625 | // —recortar y luego filtrar, como hacía antes— un fichero en el puesto 50 del |
| 1626 | // árbol no aparece nunca, por mucho que escribas su nombre entero. |
| 1627 | const casa = (f) => !q || f.toLowerCase().includes(q); |
| 1628 | const items = [{ sep: frag ? `${t('attachSep')} · @${frag}` : t('attachSep') }]; |
| 1629 | if (currentFile && casa(currentFile)) items.push({ label: '@' + currentFile, hint: t('attachOpen'), run: () => attach(currentFile) }); |
| 1630 | for (const f of files.filter(f => f !== currentFile && casa(f)).slice(0, 20)) |
| 1631 | items.push({ label: '@' + f, run: () => attach(f) }); |
| 1632 | |
| 1633 | if (items.length === 1) { |
| 1634 | // Sin coincidencias: el menú se aparta en vez de estorbar con una lista |
| 1635 | // vacía, y vuelve solo en cuanto borras una letra y el filtro encaja. |
| 1636 | if (frag) { cierraMenu({ sueltaToken: false }); return; } |
| 1637 | openMenu([{ sep: t('openProjFirst') }]); |
| 1638 | return; |
| 1639 | } |
| 1640 | openMenu(items); |
| 1641 | } |
| 1642 | $('btn-plus').addEventListener('click', () => { arrobaDesde = -1; cacheFicheros = null; abreMenuFicheros(); }); |
| 1643 | |
| 1644 | // ¿Está el cursor dentro de un `@token`? Se recorre hacia atrás hasta el primer |
| 1645 | // espacio: así `correo@dominio` no dispara el menú a media palabra (el carácter |
| 1646 | // previo al `@` no es espacio) y `@` al principio o tras un espacio sí. El |
| 1647 | // fragmento no puede contener espacios, que es justo donde termina una ruta. |
| 1648 | function tokenArroba(el) { |
| 1649 | const v = el.value, cur = el.selectionStart; |
| 1650 | for (let i = cur - 1; i >= 0; i--) { |
| 1651 | if (/\s/.test(v[i])) return null; |
| 1652 | if (v[i] === '@') { |
| 1653 | const previo = i > 0 ? v[i - 1] : ''; |
| 1654 | return (previo === '' || /\s/.test(previo)) ? { desde: i, frag: v.slice(i + 1, cur) } : null; |
| 1655 | } |
| 1656 | } |
| 1657 | return null; |
| 1658 | } |
| 1659 | |
| 1660 | $('prompt').addEventListener('input', () => { |
| 1661 | const tk = tokenArroba($('prompt')); |
| 1662 | if (!tk) { if (arrobaDesde >= 0) cierraMenu(); return; } |
| 1663 | arrobaDesde = tk.desde; |
| 1664 | abreMenuFicheros(tk.frag); |
| 1665 | }); |
| 1666 | |
| 1667 | function attach(path) { |
| 1668 | const p = $('prompt'); |
| 1669 | if (arrobaDesde >= 0) { |
| 1670 | // Se SUSTITUYE el `@frag` a medio escribir. Añadirlo al final, como antes, |
| 1671 | // dejaba `@src/ma @src/main.js` en cuanto el menú empezó a filtrar. |
| 1672 | const cola = p.value.slice(p.selectionStart); |
| 1673 | const sep = cola.startsWith(' ') ? '' : ' '; |
| 1674 | p.value = p.value.slice(0, arrobaDesde) + '@' + path + sep + cola; |
| 1675 | const cur = arrobaDesde + 1 + path.length + sep.length; |
| 1676 | p.focus(); |
| 1677 | p.setSelectionRange(cur, cur); |
| 1678 | } else { |
| 1679 | p.value = (p.value + ' @' + path).trim() + ' '; |
| 1680 | p.focus(); |
| 1681 | } |
| 1682 | arrobaDesde = -1; |
| 1683 | cacheFicheros = null; |
| 1684 | } |
| 1685 | |
| 1686 | // </> Auto (Edit automatically): si off, pide confirmación antes de escribir |
| 1687 | let autoEdit = localStorage.getItem('elffusscode.autoedit') !== '0'; |
| 1688 | function paintAuto() { |
| 1689 | const b = $('btn-autoedit'); |
| 1690 | b.classList.toggle('on', autoEdit); |
| 1691 | b.querySelector('.ae-txt').textContent = autoEdit ? t('autoTxt') : t('reviewTxt'); |
| 1692 | b.title = autoEdit ? t('autoOn') : t('autoOff'); |
| 1693 | } |
| 1694 | $('btn-autoedit').addEventListener('click', () => { |
| 1695 | autoEdit = !autoEdit; |
| 1696 | localStorage.setItem('elffusscode.autoedit', autoEdit ? '1' : '0'); |
| 1697 | paintAuto(); |
| 1698 | }); |
| 1699 | paintAuto(); |
| 1700 | codeTools.setWriteApprover(async (path, content) => { |
| 1701 | if (autoEdit) return true; |
| 1702 | return confirm(`Elffuss quiere escribir en «${path}» (${content.split('\n').length} líneas).\n\n¿Aplicar el cambio?`); |
| 1703 | }); |
| 1704 | |
| 1705 | // 🎯 Goal: el siguiente mensaje que mandes se trata como un OBJETIVO — se |
| 1706 | // planifica en tareas y se ejecutan una a una (goal.js), en vez del turno de |
| 1707 | // chat normal. Mismo patrón (interruptor persistente en localStorage) que |
| 1708 | // </> Auto de arriba. |
| 1709 | let goalMode = localStorage.getItem('elffusscode.goalmode') === '1'; |
| 1710 | function paintGoal() { |
| 1711 | $('btn-goal').classList.toggle('on', goalMode); |
| 1712 | } |
| 1713 | $('btn-goal').addEventListener('click', () => { |
| 1714 | goalMode = !goalMode; |
| 1715 | localStorage.setItem('elffusscode.goalmode', goalMode ? '1' : '0'); |
| 1716 | paintGoal(); |
| 1717 | }); |
| 1718 | paintGoal(); |
| 1719 | |
| 1720 | // ── Hard Work (RLM): lee el proyecto ENTERO por partes ── |
| 1721 | let hardMode = false; |
| 1722 | $('btn-hardwork').addEventListener('click', () => { |
| 1723 | hardMode = !hardMode; |
| 1724 | $('btn-hardwork').classList.toggle('on', hardMode); |
| 1725 | $('prompt').placeholder = hardMode ? t("hwPlaceholder") : 'Pídele código a Elffuss…'; |
| 1726 | }); |
| 1727 | |
| 1728 | // Trabaja el proyecto abierto por partes: trocea, pregunta a cada parte y funde. |
| 1729 | async function runHardWork(question) { |
| 1730 | const active = conv.getActive(); |
| 1731 | if (!active) return; |
| 1732 | addMsg('user', question); |
| 1733 | const thinking = thinkingBubble(); |
| 1734 | const fail = msg => { thinking.remove(); addMsg('assistant', msg); }; |
| 1735 | try { |
| 1736 | const provider = conv.getProvider(); |
| 1737 | if (!provider || provider === rules) return fail(t("hwNeedBrain")); |
| 1738 | const root = codeTools.handle(); |
| 1739 | if (!root) return fail(t("hwNeedProject")); |
| 1740 | thinking.tool(t("hwReading")); |
| 1741 | const context = await gatherFolder(root, { maxBytes: 1.5e6 }); |
| 1742 | if (!context.trim()) return fail(t("hwNoFiles")); |
| 1743 | const res = await hardWork({ |
| 1744 | question, context, provider, |
| 1745 | onProgress: p => { |
| 1746 | if (p.phase === 'plan') thinking.tool(`Hard Work · ${p.chunks} partes (${Math.round(p.chars / 1000)}k)${p.truncated ? t("hwTrimmed") : ''}`); |
| 1747 | else if (p.phase === 'map') thinking.tool(`Hard Work · leyendo ${p.i}/${p.n}`); |
| 1748 | else if (p.phase === 'reduce-group') thinking.tool(`Hard Work · fundiendo ${p.g}/${p.n}`); |
| 1749 | else if (p.phase === 'reduce') thinking.tool(t("hwPhaseReduce")); |
| 1750 | }, |
| 1751 | }); |
| 1752 | thinking.remove(); |
| 1753 | addMsg('assistant', res.answer + `\n\n_⛏ Hard Work (RLM): ${res.chunks} partes, ${res.kept} con señal.${res.truncated ? t("hwResultTrunc") : ''}_`); |
| 1754 | } catch (e) { |
| 1755 | thinking.remove(); |
| 1756 | addMsg('assistant err', 'Hard Work falló: ' + (e?.message || String(e))); |
| 1757 | } |
| 1758 | } |
| 1759 | |
| 1760 | // resolver @rutas del mensaje: se leen y se adjuntan como contexto |
| 1761 | const _send = send; |
| 1762 | send = async (text) => { |
| 1763 | if (hardMode) return runHardWork(text); |
| 1764 | const refs = [...text.matchAll(/@([\w./-]+\.\w+)/g)].map(m => m[1]); |
| 1765 | if (refs.length) { |
| 1766 | let ctx = ''; |
| 1767 | for (const r of [...new Set(refs)].slice(0, 4)) { |
| 1768 | try { ctx += `\n\n--- ${r} ---\n${await codeTools.read({ path: r })}`; } catch { /* ignora */ } |
| 1769 | } |
| 1770 | if (ctx) text += '\n\n[archivos adjuntos]' + ctx; |
| 1771 | } |
| 1772 | _send(text); |
| 1773 | }; |
| 1774 | |
| 1775 | // ---------- panel de skills (transparente: repo + lista + SKILL.md) ---------- |
| 1776 | async function openSkillsPanel() { |
| 1777 | const box = $('settings-panel'); |
| 1778 | box.hidden = false; |
| 1779 | box.replaceChildren(); |
| 1780 | const close = document.createElement('button'); |
| 1781 | close.id = 'settings-close'; close.textContent = '✕'; close.onclick = () => { box.hidden = true; }; |
| 1782 | box.appendChild(close); |
| 1783 | |
| 1784 | const wrap = document.createElement('div'); |
| 1785 | wrap.className = 'skills-panel'; |
| 1786 | wrap.innerHTML = `<h3>🧩 Skills de Claude Code</h3> |
| 1787 | <p class="muted">Instala instrucciones especializadas (formato SKILL.md) desde repos públicos. |
| 1788 | Todo se guarda en tu navegador. Se ve el repo y lo que se inyecta.</p>`; |
| 1789 | box.appendChild(wrap); |
| 1790 | |
| 1791 | // instaladas |
| 1792 | const inst = skills.installed(); |
| 1793 | const instBox = document.createElement('div'); |
| 1794 | instBox.innerHTML = `<div class="sk-h">Instaladas (${inst.length})</div>`; |
| 1795 | for (const s of inst) { |
| 1796 | const row = document.createElement('div'); |
| 1797 | row.className = 'sk-row'; |
| 1798 | row.innerHTML = `<b>${s.name}</b><span class="muted">${s.repo || 'local'}</span>`; |
| 1799 | const rm = document.createElement('button'); |
| 1800 | rm.className = 'ghost'; rm.textContent = t("skRemove"); |
| 1801 | rm.onclick = async () => { await skills.remove(s.name); openSkillsPanel(); }; |
| 1802 | row.appendChild(rm); |
| 1803 | instBox.appendChild(row); |
| 1804 | } |
| 1805 | if (!inst.length) instBox.innerHTML += '<p class="muted">Ninguna todavía.</p>'; |
| 1806 | box.appendChild(instBox); |
| 1807 | |
| 1808 | // fuentes + añadir repo |
| 1809 | const srcs = await skills.sources(); |
| 1810 | const srcBox = document.createElement('div'); |
| 1811 | srcBox.innerHTML = `<div class="sk-h">Catálogos (repos)</div>`; |
| 1812 | for (const s of srcs) { |
| 1813 | const row = document.createElement('div'); |
| 1814 | row.className = 'sk-row'; |
| 1815 | row.innerHTML = `<b>${s.label}</b><a href="https://github.com/${s.repo}" target="_blank" rel="noopener">${s.repo} ↗</a>`; |
| 1816 | const browse = document.createElement('button'); |
| 1817 | browse.className = 'primary'; browse.textContent = t("skBrowse"); |
| 1818 | browse.onclick = () => browseRepo(s.repo, box); |
| 1819 | row.appendChild(browse); |
| 1820 | if (!s.official) { |
| 1821 | const rm = document.createElement('button'); |
| 1822 | rm.className = 'ghost'; rm.textContent = '🗑'; |
| 1823 | rm.onclick = async () => { await skills.removeSource(s.repo); openSkillsPanel(); }; |
| 1824 | row.appendChild(rm); |
| 1825 | } |
| 1826 | srcBox.appendChild(row); |
| 1827 | } |
| 1828 | const addRow = document.createElement('div'); |
| 1829 | addRow.className = 'sk-row'; |
| 1830 | const inp = document.createElement('input'); |
| 1831 | inp.placeholder = t("skAddRepoPh"); |
| 1832 | const add = document.createElement('button'); |
| 1833 | add.className = 'primary'; add.textContent = t("skAddRepo"); |
| 1834 | add.onclick = async () => { |
| 1835 | try { await skills.addSource(inp.value); openSkillsPanel(); } |
| 1836 | catch (e) { alert(e.message); } |
| 1837 | }; |
| 1838 | addRow.append(inp, add); |
| 1839 | srcBox.appendChild(addRow); |
| 1840 | box.appendChild(srcBox); |
| 1841 | } |
| 1842 | |
| 1843 | async function browseRepo(repo, box) { |
| 1844 | const list = document.createElement('div'); |
| 1845 | list.innerHTML = `<div class="sk-h">Cargando ${repo}…</div>`; |
| 1846 | box.appendChild(list); |
| 1847 | try { |
| 1848 | const found = await skills.listFromRepo(repo); |
| 1849 | list.innerHTML = `<div class="sk-h">${repo} — ${found.length} skills</div>`; |
| 1850 | for (const sk of found.slice(0, 120)) { |
| 1851 | const row = document.createElement('div'); |
| 1852 | row.className = 'sk-row'; |
| 1853 | row.innerHTML = `<b>${sk.name}</b><span class="muted">${sk.dir}</span>`; |
| 1854 | const btn = document.createElement('button'); |
| 1855 | const on = skills.isInstalled(sk.repo, sk.path); |
| 1856 | btn.className = on ? 'ghost' : 'primary'; |
| 1857 | btn.textContent = on ? 'Instalada ✓' : 'Instalar'; |
| 1858 | btn.onclick = async () => { |
| 1859 | btn.textContent = '…'; |
| 1860 | try { |
| 1861 | const entry = await skills.installFromRepo(sk); |
| 1862 | btn.textContent = 'Instalada ✓'; btn.className = 'ghost'; |
| 1863 | $('settings-panel').hidden = true; // cierra el panel |
| 1864 | addMsg('assistant', skills.usageMessage(entry)); // «cómo usarla» en el chat |
| 1865 | } catch (e) { btn.textContent = 'Instalar'; alert(e.message); } |
| 1866 | }; |
| 1867 | row.appendChild(btn); |
| 1868 | list.appendChild(row); |
| 1869 | } |
| 1870 | } catch (e) { |
| 1871 | list.innerHTML = `<div class="sk-h">⚠️ ${e.message}</div>`; |
| 1872 | } |
| 1873 | } |
| 1874 | |
| 1875 | // ---------- command palette (Cmd/Ctrl+P) ---------- |
| 1876 | let palItems = [], palSel = 0; |
| 1877 | const COMMANDS = [ |
| 1878 | { label: t('newConv'), run: () => conv.create() }, |
| 1879 | { label: t('tHistory'), run: () => $('btn-history').click() }, |
| 1880 | { label: t('pSearchCode'), run: () => { closePalette(); $('prompt').value = t('pSearch'); $('prompt').focus(); } }, |
| 1881 | { label: t('pManageSkills'), run: () => { closePalette(); openSkillsPanel(); } }, |
| 1882 | { label: t('tActSettings'), run: () => { closePalette(); renderSettings(); } }, |
| 1883 | { label: t('pToggleExplorer'), run: () => $('act-files').click() }, |
| 1884 | { label: t('pToggleTerm'), hint: 'Ctrl+`', run: () => { closePalette(); toggleTerminal(); } }, |
| 1885 | { label: t('pSave'), run: () => triggerEditor('') || (hasEditor() && triggerEditor('workbench.action.files.save')) }, |
| 1886 | ]; |
| 1887 | |
| 1888 | function openPalette(prefix = '') { |
| 1889 | $('palette').hidden = false; |
| 1890 | const inp = $('pal-input'); |
| 1891 | inp.value = prefix; |
| 1892 | inp.focus(); |
| 1893 | renderPalette(); |
| 1894 | } |
| 1895 | function closePalette() { $('palette').hidden = true; } |
| 1896 | |
| 1897 | function fuzzy(q, s) { |
| 1898 | q = q.toLowerCase(); s = s.toLowerCase(); |
| 1899 | let i = 0, score = 0, streak = 0; |
| 1900 | for (const ch of s) { |
| 1901 | if (i < q.length && ch === q[i]) { i++; streak++; score += streak; } |
| 1902 | else streak = 0; |
| 1903 | } |
| 1904 | return i === q.length ? score + (s.endsWith(q) ? 20 : 0) : -1; |
| 1905 | } |
| 1906 | |
| 1907 | async function renderPalette() { |
| 1908 | const raw = $('pal-input').value; |
| 1909 | const list = $('pal-list'); |
| 1910 | list.replaceChildren(); |
| 1911 | palItems = []; |
| 1912 | |
| 1913 | if (raw.startsWith('>')) { // comandos |
| 1914 | const q = raw.slice(1).trim().toLowerCase(); |
| 1915 | palItems = COMMANDS.filter(c => c.label.toLowerCase().includes(q)).map(c => ({ label: c.label, hint: t('palCmd'), run: c.run })); |
| 1916 | } else if (raw.startsWith('@')) { // símbolos del archivo abierto (Monaco) |
| 1917 | palItems = [{ label: t('palGotoSym'), hint: '@', run: () => { closePalette(); triggerEditor('editor.action.quickOutline'); } }]; |
| 1918 | } else { // archivos (con :línea opcional) |
| 1919 | const [pathQ, lineQ] = raw.split(':'); |
| 1920 | const files = await codeTools.fileList().catch(() => []); |
| 1921 | const scored = pathQ.trim() |
| 1922 | ? files.map(f => ({ f, s: fuzzy(pathQ.trim(), f.split('/').pop()) * 2 + fuzzy(pathQ.trim(), f) })).filter(x => x.s > 0).sort((a, b) => b.s - a.s) |
| 1923 | : files.slice(0, 40).map(f => ({ f, s: 0 })); |
| 1924 | palItems = scored.slice(0, 40).map(({ f }) => ({ |
| 1925 | label: f.split('/').pop(), hint: f, icon: true, |
| 1926 | run: () => { closePalette(); openFile(f); if (lineQ && +lineQ) setTimeout(() => gotoLine(+lineQ), 300); }, |
| 1927 | })); |
| 1928 | } |
| 1929 | palSel = 0; |
| 1930 | palItems.forEach((it, i) => { |
| 1931 | const row = el('button', 'pal-item' + (i === 0 ? ' sel' : '')); |
| 1932 | row.innerHTML = `<span class="pi-name">${it.label}</span><span class="pi-hint">${it.hint || ''}</span>`; |
| 1933 | row.onmouseenter = () => { palSel = i; paintPalSel(); }; |
| 1934 | row.onclick = () => it.run(); |
| 1935 | list.appendChild(row); |
| 1936 | }); |
| 1937 | if (!palItems.length) list.appendChild(el('div', 'pal-empty', t('palEmpty'))); |
| 1938 | } |
| 1939 | function paintPalSel() { |
| 1940 | [...$('pal-list').children].forEach((c, i) => c.classList.toggle('sel', i === palSel)); |
| 1941 | $('pal-list').children[palSel]?.scrollIntoView({ block: 'nearest' }); |
| 1942 | } |
| 1943 | $('pal-input').addEventListener('input', renderPalette); |
| 1944 | $('pal-input').addEventListener('keydown', e => { |
| 1945 | if (e.key === 'Escape') return closePalette(); |
| 1946 | if (e.key === 'ArrowDown') { e.preventDefault(); palSel = Math.min(palSel + 1, palItems.length - 1); paintPalSel(); } |
| 1947 | if (e.key === 'ArrowUp') { e.preventDefault(); palSel = Math.max(palSel - 1, 0); paintPalSel(); } |
| 1948 | if (e.key === 'Enter') { e.preventDefault(); palItems[palSel]?.run(); } |
| 1949 | }); |
| 1950 | document.addEventListener('keydown', e => { |
| 1951 | if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'p') { e.preventDefault(); openPalette(e.shiftKey ? '>' : ''); } |
| 1952 | if (e.key === 'Escape' && !$('palette').hidden) closePalette(); |
| 1953 | }); |
| 1954 | // Cerrar la paleta al pulsar fuera, PERO no cuando el clic viene del menú: es |
| 1955 | // el menú el que la abre («Go to file»), y sin esta excepción el mismo clic la |
| 1956 | // abría y la cerraba — el `onclick` del item la mostraba y acto seguido el |
| 1957 | // evento seguía burbujeando hasta aquí, donde el target es el item del menú, |
| 1958 | // que no está dentro de #palette. Con Cmd+P funcionaba porque es teclado y no |
| 1959 | // pasa por este camino, y por eso parecía que «el atajo sí y el menú no». |
| 1960 | document.addEventListener('click', e => { |
| 1961 | if (!e.target.closest('#palette, #menubar, #topmenu')) closePalette(); |
| 1962 | }); |
| 1963 | |
| 1964 | // ---------- barra de menú File/Edit/View/Git ---------- |
| 1965 | async function menuFor(which) { |
| 1966 | if (which === 'file') return [ |
| 1967 | { label: t('mNewFile'), run: () => { const p = prompt(t('promptNewPath')); if (p) codeTools.write({ path: p, content: '' }).then(() => { openFile(p); refreshTree(); }); } }, |
| 1968 | { label: t('mSave'), hint: 'Ctrl+S', run: () => triggerEditor('workbench.action.files.save') }, |
| 1969 | { label: t('mOpenFolder'), run: async () => { try { await enterIDE(await window.showDirectoryPicker({ mode: 'readwrite' })); } catch {} } }, |
| 1970 | ]; |
| 1971 | if (which === 'edit') return [ |
| 1972 | { label: t('mSearchCode'), run: () => { $('prompt').value = t('pSearch'); $('prompt').focus(); } }, |
| 1973 | { label: t('mGotoFile'), hint: 'Cmd+P', run: () => openPalette('') }, |
| 1974 | { label: t('mGotoSym'), run: () => triggerEditor('editor.action.quickOutline') }, |
| 1975 | ]; |
| 1976 | if (which === 'view') return [ |
| 1977 | { label: t('tFiles'), run: () => $('act-files').click() }, |
| 1978 | { label: t('mTerminal'), hint: 'Ctrl+`', run: () => toggleTerminal(true) }, |
| 1979 | { label: t('mArch'), run: () => openView('arch') }, |
| 1980 | { label: t('tCity'), run: () => openView('city') }, |
| 1981 | { label: 'Command Palette', hint: 'Cmd+Shift+P', run: () => openPalette('>') }, |
| 1982 | { label: 'Skills', run: () => openSkillsPanel() }, |
| 1983 | { label: t('mAbout'), hint: '↗', run: () => window.open('https://github.com/KikoCis/elffuss-code', '_blank', 'noopener') }, |
| 1984 | ]; |
| 1985 | if (which === 'git') { |
| 1986 | const g = await codeTools.gitInfo(); |
| 1987 | if (!g.isRepo) return [{ label: t('gNotRepo'), hint: '', run: () => {} }]; |
| 1988 | const items = [{ label: t('gBranch', { b: g.branch }), hint: 'git', run: () => {} }]; |
| 1989 | if (g.lastCommit) items.push({ label: t('gLast', { m: g.lastCommit.msg.slice(0, 40) }), hint: g.lastCommit.author, run: () => {} }); |
| 1990 | items.push({ label: t('gCommit'), run: () => { $('prompt').value = t('pCommit'); $('prompt').focus(); } }); |
| 1991 | return items; |
| 1992 | } |
| 1993 | return []; |
| 1994 | } |
| 1995 | document.querySelectorAll('#menubar button').forEach(b => { |
| 1996 | b.addEventListener('click', async () => { |
| 1997 | document.querySelectorAll('#menubar button').forEach(x => x.classList.toggle('open', x === b)); |
| 1998 | openMenuAt(await menuFor(b.dataset.menu), b); |
| 1999 | }); |
| 2000 | }); |
| 2001 | function openMenuAt(items, anchor) { |
| 2002 | const menu = $('topmenu'); |
| 2003 | const r = anchor.getBoundingClientRect(); |
| 2004 | menu.style.left = r.left + 'px'; |
| 2005 | menu.style.top = (r.bottom + 3) + 'px'; |
| 2006 | menu.replaceChildren(); |
| 2007 | for (const it of items) { |
| 2008 | const row = el('button', 'menu-item'); |
| 2009 | row.innerHTML = `<b>${it.label}</b>${it.hint ? `<span>${it.hint}</span>` : ''}`; |
| 2010 | row.onclick = () => { menu.hidden = true; it.run(); }; |
| 2011 | menu.appendChild(row); |
| 2012 | } |
| 2013 | menu.hidden = false; |
| 2014 | } |
| 2015 | document.addEventListener('click', e => { |
| 2016 | if (!e.target.closest('#menubar, #topmenu')) { |
| 2017 | document.querySelectorAll('#menubar button').forEach(x => x.classList.remove('open')); |
| 2018 | $('topmenu').hidden = true; |
| 2019 | } |
| 2020 | }); |
| 2021 | |
| 2022 | // ---------- git en el header ---------- |
| 2023 | async function refreshGit() { |
| 2024 | const g = await codeTools.gitInfo().catch(() => ({ isRepo: false })); |
| 2025 | const chip = $('git-branch'); |
| 2026 | if (g.isRepo) { chip.hidden = false; chip.innerHTML = UI.code + ' ' + g.branch; } |
| 2027 | else chip.hidden = true; |
| 2028 | } |
| 2029 | $('git-branch').addEventListener('click', () => document.querySelector('#menubar button[data-menu="git"]').click()); |
| 2030 | |
| 2031 | // icono de skills en la barra de actividad |
| 2032 | $('act-skills').innerHTML = UI.puzzle; |
| 2033 | $('act-skills').addEventListener('click', () => openSkillsPanel()); |
| 2034 | |
| 2035 | rebuildSelect(); |
| 2036 | skills.initSkills(); |
| 2037 | boot(); |
| 2038 | window.elffussClaw = { conv, get agent() { return conv.getActive()?.agent; }, send, openFile, parseToolCall, skills }; |
| 2039 | |
| 2040 | |
| 2041 | // ---------- puerta de móvil y chip de disco ---------- |
| 2042 | // Declaradas con `function` para que se icen: preloadModel() las usa y está |
| 2043 | // escrita más arriba en el fichero. |
| 2044 | function avisoMovil(tam, onAccept) { |
| 2045 | // Se pinta FIJO sobre la pantalla, no dentro del layout: cuando esto corre, |
| 2046 | // #chat todavía no existe (Code construye su interfaz después), así que caía |
| 2047 | // al body y el propio layout lo tapaba — presente en el DOM y invisible para |
| 2048 | // el usuario, que es la peor variante de un aviso. |
| 2049 | const box = document.createElement('div'); |
| 2050 | box.style.cssText = 'position:fixed;left:50%;bottom:16px;transform:translateX(-50%);z-index:99999;' |
| 2051 | + 'width:min(92vw,520px);padding:16px;border:1px solid #3a3a4a;border-radius:14px;' |
| 2052 | + 'background:#15161f;color:#eae8f2;box-shadow:0 18px 50px -18px rgba(0,0,0,.8);' |
| 2053 | + 'display:flex;flex-direction:column;gap:8px;font:14px/1.5 system-ui,sans-serif'; |
| 2054 | const h = document.createElement('b'); h.textContent = '📱 En el móvil todavía no funciona'; |
| 2055 | const p1 = document.createElement('span'); p1.style.opacity = '.75'; |
| 2056 | p1.textContent = 'Elffuss Code ejecuta el modelo dentro de tu propio navegador. En el móvil eso hoy no sale bien: ' |
| 2057 | + 'habría que descargar ' + tam + ' y el navegador suele cerrar la pestaña antes de terminar. ' |
| 2058 | + 'Así que no te lo descargo sin preguntar.'; |
| 2059 | const p2 = document.createElement('span'); p2.style.opacity = '.75'; |
| 2060 | p2.textContent = 'Ábrelo en un ordenador y sí funciona: ahí es donde vive.'; |
| 2061 | const fila = document.createElement('div'); |
| 2062 | fila.style.cssText = 'display:flex;gap:8px;flex-wrap:wrap'; |
| 2063 | const b = document.createElement('button'); |
| 2064 | b.style.cssText = 'flex:1;padding:9px 12px;border-radius:9px;border:1px solid #4a4a5e;background:#22232f;color:inherit;font:inherit;cursor:pointer'; |
| 2065 | b.textContent = 'Descargarlo igualmente (' + tam + ')'; |
| 2066 | b.onclick = () => { try { localStorage.setItem('elffusscode.movil.ok', '1'); } catch {} box.remove(); onAccept(); }; |
| 2067 | const x = document.createElement('button'); |
| 2068 | x.style.cssText = 'padding:9px 12px;border-radius:9px;border:1px solid #4a4a5e;background:transparent;color:inherit;font:inherit;cursor:pointer'; |
| 2069 | x.textContent = 'Entendido'; |
| 2070 | x.onclick = () => box.remove(); |
| 2071 | fila.append(b, x); |
| 2072 | box.append(h, p1, p2, fila); |
| 2073 | document.body.appendChild(box); |
| 2074 | } |
| 2075 | |
| 2076 | function mountDiskChip() { |
| 2077 | const chip = document.getElementById('disk-chip'); |
| 2078 | if (!chip) return; |
| 2079 | const gb = n => n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : Math.round(n / 1048576) + ' MB'; |
| 2080 | async function paint() { |
| 2081 | const { usage, quota } = await cacheEstimate(); |
| 2082 | const compartido = await sharedUsage(await origenesAlmacen()); |
| 2083 | const total = usage + compartido.usage; |
| 2084 | if (!total) { chip.hidden = true; return; } |
| 2085 | chip.hidden = false; |
| 2086 | chip.textContent = '💾 ' + gb(total); |
| 2087 | chip.title = `Modelos guardados en este navegador: ${gb(total)}` |
| 2088 | + (quota ? ` de ${gb(quota)} disponibles` : '') + '. Pulsa para vaciarlo.'; |
| 2089 | } |
| 2090 | chip.addEventListener('click', async () => { |
| 2091 | const { usage } = await cacheEstimate(); |
| 2092 | const comp = await sharedUsage(await origenesAlmacen()); |
| 2093 | const total = usage + comp.usage; |
| 2094 | if (!confirm(`Vas a borrar ${gb(total)} de modelos guardados en este navegador.\n\n` |
| 2095 | + `No se pierde nada tuyo: solo los pesos descargados. La próxima vez habrá que bajarlos otra vez.\n\n¿Seguir?`)) return; |
| 2096 | chip.textContent = '💾 …'; |
| 2097 | // LOS DOS almacenes. Vaciar solo el de este origen dejaba intacto el modelo |
| 2098 | // grande —que es casi todo lo que ocupa— así que quien pulsaba para |
| 2099 | // recuperar espacio no lo recuperaba y no se enteraba. |
| 2100 | let fallo = null; |
| 2101 | try { await clearModelCache(); } catch (e) { fallo = e.message || String(e); } |
| 2102 | const r = await clearShared(); |
| 2103 | if (!r.ok && comp.usage) fallo = (fallo ? fallo + ' · ' : '') + 'el almacén compartido no se pudo vaciar'; |
| 2104 | if (fallo) alert('No se pudo vaciar del todo: ' + fallo); |
| 2105 | paint(); |
| 2106 | }); |
| 2107 | paint(); |
| 2108 | setInterval(paint, 20000); |
| 2109 | } |
| 2110 | mountDiskChip(); |
| 2111 | |
| 2112 | // ── Compositor: menú de modos, ancho del chat y caja que crece ────────────── |
| 2113 | // Los tres botones de modo siguen siendo los mismos elementos con los mismos |
| 2114 | // ids: lo único que cambia es que viven dentro de un desplegable. Así el JS que |
| 2115 | // ya los escuchaba no se entera de nada. |
| 2116 | { |
| 2117 | const modos = $('btn-modos'), menu = $('modos-menu'); |
| 2118 | if (modos && menu) { |
| 2119 | // Cada modo lleva DEBAJO lo que hace. El texto sale del `title` que ya |
| 2120 | // tenía el botón: estaba escrito y bien, pero solo lo veía quien dejara el |
| 2121 | // ratón quieto encima — o sea casi nadie, y en móvil nadie. «Auto», «Goal» |
| 2122 | // y «Hard Work» sueltos no dicen nada a quien llega nuevo. |
| 2123 | for (const b of menu.querySelectorAll('.cbtn')) { |
| 2124 | const que = b.getAttribute('title'); |
| 2125 | if (!que || b.querySelector('.modo-que')) continue; |
| 2126 | const span = document.createElement('span'); |
| 2127 | span.className = 'modo-que'; |
| 2128 | // Cortar por el primer paréntesis dejaba «Hard Work (RLM): lee tu |
| 2129 | // proyecto…» en «Hard Work», o sea una explicación que repite el nombre |
| 2130 | // del botón y no explica nada. Lo que sobra es el PREFIJO —«Nombre |
| 2131 | // (SIGLAS):»— no lo que viene detrás, que es justo la frase útil. |
| 2132 | span.textContent = que |
| 2133 | .replace(/^[^:]{0,40}:\s*/, '') // fuera «Hard Work (RLM): » |
| 2134 | .split('.')[0] // la primera frase |
| 2135 | .replace(/\s*\([^)]*\)\s*/g, ' ') // sin incisos entre paréntesis |
| 2136 | .replace(/\s+/g, ' ') |
| 2137 | .trim() |
| 2138 | .slice(0, 120); |
| 2139 | b.appendChild(span); |
| 2140 | // Ya está a la vista: dejar el title duplicaría el texto en un tooltip. |
| 2141 | b.removeAttribute('title'); |
| 2142 | } |
| 2143 | modos.addEventListener('click', (e) => { e.stopPropagation(); menu.hidden = !menu.hidden; }); |
| 2144 | // Cerrar al elegir y al pulsar fuera. Sin lo segundo, el menú se queda |
| 2145 | // abierto tapando la conversación y hay que adivinar cómo cerrarlo. |
| 2146 | menu.addEventListener('click', () => { menu.hidden = true; }); |
| 2147 | document.addEventListener('click', (e) => { |
| 2148 | if (!e.target.closest('#modos')) menu.hidden = true; |
| 2149 | }); |
| 2150 | } |
| 2151 | |
| 2152 | // El chat a toda la ventana. Al editor se le da cero de ancho en vez de |
| 2153 | // quitarlo: volver es instantáneo y no se pierde lo que hubiera abierto. |
| 2154 | const ancho = $('btn-ancho'); |
| 2155 | if (ancho) { |
| 2156 | const pinta = () => { |
| 2157 | const full = document.body.classList.contains('chat-full'); |
| 2158 | ancho.textContent = full ? '⇥' : '⇔'; |
| 2159 | ancho.title = full ? 'Recuperar el editor' : 'Ensanchar el chat a toda la ventana'; |
| 2160 | }; |
| 2161 | try { if (localStorage.getItem('elffusscode.chatfull') === '1') document.body.classList.add('chat-full'); } |
| 2162 | catch { /* sin localStorage se queda como está */ } |
| 2163 | pinta(); |
| 2164 | ancho.addEventListener('click', () => { |
| 2165 | document.body.classList.toggle('chat-full'); |
| 2166 | try { localStorage.setItem('elffusscode.chatfull', document.body.classList.contains('chat-full') ? '1' : '0'); } |
| 2167 | catch { /* — */ } |
| 2168 | pinta(); |
| 2169 | }); |
| 2170 | } |
| 2171 | |
| 2172 | // La caja crece con el texto hasta el tope que pone el CSS. Se recalcula |
| 2173 | // desde cero (`auto`) antes de medir: si no, una vez crecida ya no encoge al |
| 2174 | // borrar, y acaba ocupando media pantalla vacía. |
| 2175 | const caja = $('prompt'); |
| 2176 | if (caja && caja.tagName === 'TEXTAREA') { |
| 2177 | const crece = () => { |
| 2178 | caja.style.height = 'auto'; |
| 2179 | caja.style.height = Math.min(caja.scrollHeight, window.innerHeight * 0.4) + 'px'; |
| 2180 | }; |
| 2181 | caja.addEventListener('input', crece); |
| 2182 | // Al enviar, el valor se vacía desde fuera y no salta `input`: sin esto la |
| 2183 | // caja se queda alta y vacía después de cada mensaje. |
| 2184 | new MutationObserver(crece).observe(caja, { attributes: true, attributeFilter: ['value'] }); |
| 2185 | $('composer')?.addEventListener('submit', () => setTimeout(crece, 0)); |
| 2186 | } |
| 2187 | } |
| 2188 | |
| 2189 | // ── Instalable: es lo único que consigue almacenamiento persistente ───────── |
| 2190 | // Medido en este proyecto: `navigator.storage.persist()` devuelve false en un |
| 2191 | // perfil normal, así que Chrome puede desalojar los gigas del modelo cuando le |
| 2192 | // falte disco — y lo hizo. Chrome concede la persistencia a los sitios |
| 2193 | // instalados, y solo ofrece instalar si hay manifiesto Y un service worker con |
| 2194 | // manejador de `fetch`. De ahí `sw.js`, que no cachea nada a propósito. |
| 2195 | // |
| 2196 | // El registro va tras `load` para no competir con la carga del modelo, que es |
| 2197 | // lo que el usuario está esperando de verdad. |
| 2198 | if ('serviceWorker' in navigator) { |
| 2199 | addEventListener('load', () => { |
| 2200 | navigator.serviceWorker.register('sw.js').then(async () => { |
| 2201 | // Se vuelve a pedir la persistencia DESPUÉS de registrar: si el usuario ya |
| 2202 | // tenía el sitio instalado de una visita anterior, aquí es donde se |
| 2203 | // concede, y sin pedirla otra vez nadie se enteraría. |
| 2204 | try { |
| 2205 | if (navigator.storage?.persist && !(await navigator.storage.persisted())) { |
| 2206 | const ok = await navigator.storage.persist(); |
| 2207 | console.log('[elffuss] almacenamiento persistente: ' + (ok ? 'concedido' : 'denegado — instala la app para que el navegador no borre el modelo')); |
| 2208 | } |
| 2209 | } catch { /* el diagnóstico no vale un error */ } |
| 2210 | }).catch(e => console.warn('[elffuss] service worker no registrado: ' + e.message)); |
| 2211 | }); |
| 2212 | } |