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