Elffuss BraidHub

utopia-ia/elffuss-code public

4eb6a3c2f5a8 · 37.0 KiBRawPermalink
1// Vista «Mente de Elffuss» — el pensamiento subyacente del cerebro CEO en un
2// mundo 3D de fantasía psicodélica trance, con la CIUDAD real del proyecto
3// (motor VibeCodeViewer) flotando por debajo.
4// · cada línea/tool-call que llega nace como una ESTRELLA de texto (color por
5// PERFIL, tamaño/tipografía según lo que ocurre) que se desvanece sola.
6// · los perfiles (nombre, foco, color) se editan desde ⚙ — el usuario los crea
7// a su gusto.
8// · «≡ historial»: panel con TODO lo que ha llegado, sin recortar.
9// · cuando lee/escribe un fichero real, un haz baja hasta él en la ciudad.
10// · overlay PERSISTENTE (música/animación no reinician al salir y volver).
11import * as THREE from 'three';
12import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
13import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
14import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
15import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
16import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
17import * as ceo from './ceo.js';
18import * as db from './db.js';
19import { renderMarkdown } from './md.js';
20import { t } from './i18n.js';
21
22const SOUNDCLOUD = 'https://soundcloud.com/dekel-official/dekel-baoba-festival-2023';
23const CEO_COLOR = '#ff4d8d';
24
25let open = false, built = false, raf = null;
26let overlay, S, widget, onOpenFile = () => {}, onExecute = () => {};
27// Ciudad de fondo (vista real del workspace) y semilla de pensamientos previos:
28// AMBOS opcionales e inyectados por la app anfitriona — Code tiene un motor
29// VibeCodeViewer sobre su proyecto único; Claw (v1) no lo ofrece y la Mente
30// funciona igual de bien sin ciudad de fondo.
31let loadThoughts = async () => []; // () => [{path, md}]
32let buildCityFn = null; // (scene) => {cityWrap, cityCity, cityModel} | null
33export function init({ loadThoughts: lt, buildCity: bc } = {}) {
34 if (lt) loadThoughts = lt;
35 if (bc) buildCityFn = bc;
36}
37let anchorMap = new Map(); // id de perfil (+ 'ceo') → Vector3 (anclas del mundo)
38const anchors = []; // { el, pos } — solo etiquetas de propuestas forjadas
39let nodesGroup, thoughtNodes = [];
40let starGroup, stars = []; // estrellas de pensamiento efímeras
41const lineBuf = new Map(); // canal → texto acumulado hasta la línea completa
42const streamed = new Map(); // canal → ¿llegaron tokens? (evita duplicar el texto final)
43let cityWrap = null, cityCity = null, cityModel = null;
44let beams = [], fileActivity = [];
45
46export function isOpen() { return open; }
47export function setOpenFile(fn) { onOpenFile = fn; }
48export function setExecuteProposal(fn) { onExecute = fn; }
49
50// También las comillas: estos textos van dentro de atributos (value, title,
51// aria-label) y un nombre de perfil con «"» rompía el atributo.
52const escHtml = s => String(s).replace(/[<>&"']/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;' }[c]));
53const profileOf = channel => channel === 'ceo'
54 ? { id: 'ceo', name: 'CEO', color: CEO_COLOR }
55 : ceo.getProfiles().find(p => p.id === channel) || { id: channel, name: channel, color: '#7c5cff' };
56
57// ── música: SOLO si la pides ────────────────────────────────────────────────
58// Antes se cargaba un reproductor de SoundCloud con autoplay cada vez que
59// abrías la Mente: una petición a un tercero en una app que promete que nada
60// sale de tu máquina, y sonido sin haberlo pedido. Ahora hay un botón; el
61// reproductor (con su propio control) solo existe mientras lo quieras, y «■
62// Quitar música» lo elimina del todo.
63let musicOn = false, musicWrap = null;
64function mountMusic(root) {
65 musicWrap = document.createElement('div');
66 musicWrap.className = 'mind-music';
67 root.appendChild(musicWrap);
68 paintMusic();
69}
70function paintMusic() {
71 if (!musicWrap) return;
72 musicWrap.replaceChildren();
73 const btn = document.createElement('button');
74 btn.type = 'button';
75 btn.className = 'mind-music-btn';
76 btn.style.cssText = 'display:block;width:100%;background:rgba(10,6,24,.8);border:none;color:#ffd7e6;padding:7px 12px;font:inherit;font-size:.74rem;cursor:pointer;text-align:center';
77 if (!musicOn) {
78 // Sin reproductor, la caja es solo el botón (sin el marco grande).
79 musicWrap.style.cssText = 'width:auto;border-radius:999px';
80 btn.textContent = t('mindMusic');
81 btn.title = t('mindMusicTitle');
82 btn.onclick = () => { musicOn = true; paintMusic(); };
83 musicWrap.appendChild(btn);
84 return;
85 }
86 musicWrap.style.cssText = '';
87 const url = 'https://w.soundcloud.com/player/?url=' + encodeURIComponent(SOUNDCLOUD) +
88 '&auto_play=true&hide_related=true&show_comments=false&show_user=false&show_reposts=false&visual=false&color=%23ff4d8d';
89 const iframe = document.createElement('iframe');
90 iframe.id = 'mind-sc'; iframe.title = t('mindMusicPlayer'); iframe.width = '100%'; iframe.height = '120';
91 iframe.setAttribute('frameborder', 'no'); iframe.allow = 'autoplay; encrypted-media'; iframe.src = url;
92 const cap = document.createElement('div'); cap.className = 'mind-music-cap'; cap.textContent = '▶ Dekel · Baoba Festival — modo trance';
93 btn.textContent = t('mindMusicOff');
94 btn.onclick = () => { musicOn = false; widget = null; paintMusic(); };
95 musicWrap.append(iframe, cap, btn);
96 const initWidget = () => { try { widget = window.SC.Widget(iframe); } catch { /* aún no */ } };
97 if (window.SC && window.SC.Widget) initWidget();
98 else { const sc = document.createElement('script'); sc.src = 'https://w.soundcloud.com/player/api.js'; sc.onload = initWidget; document.head.appendChild(sc); }
99}
100
101// ══ ESTRELLAS de pensamiento: cada línea/tool-call nace, brilla y se apaga ══
102function makeTextSprite(text, color, { fontSize = 16, bold = false, glow = 10 } = {}) {
103 const pad = 8;
104 const probe = document.createElement('canvas').getContext('2d');
105 probe.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`;
106 const w = Math.ceil(probe.measureText(text).width) + pad * 2;
107 const h = fontSize + pad * 2;
108 const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
109 const g = cv.getContext('2d');
110 g.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`;
111 g.textBaseline = 'middle';
112 g.shadowColor = color; g.shadowBlur = glow;
113 g.fillStyle = color;
114 g.fillText(text, pad, h / 2 + 1);
115 const tex = new THREE.CanvasTexture(cv);
116 const mat = new THREE.SpriteMaterial({ map: tex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending });
117 const sprite = new THREE.Sprite(mat);
118 const scale = 0.09;
119 sprite.scale.set(w * scale, h * scale, 1);
120 return sprite;
121}
122
123// kind: 'line' (charla normal) · 'tool' (tool-call) · 'event' (ciclo/estado) · 'built' (propuesta forjada)
124const KIND_STYLE = {
125 line: { fontSize: 13, bold: false, glow: 8, life: 6, jitter: 15 },
126 tool: { fontSize: 17, bold: true, glow: 16, life: 9, jitter: 9 },
127 event: { fontSize: 20, bold: true, glow: 14, life: 7, jitter: 6 },
128 built: { fontSize: 26, bold: true, glow: 22, life: 13, jitter: 4 },
129};
130function spawnStar(channel, text, kind = 'line') {
131 if (!starGroup || !text) return;
132 const prof = profileOf(channel);
133 const st = KIND_STYLE[kind] || KIND_STYLE.line;
134 const anchor = anchorMap.get(prof.id) || new THREE.Vector3(0, 20, 0);
135 const j = st.jitter;
136 const label = kind === 'tool' ? '⟐ ' + text : kind === 'event' ? '★ ' + text : kind === 'built' ? '✦ ' + text : text;
137 const sprite = makeTextSprite(label.slice(0, kind === 'line' ? 52 : 72), prof.color, st);
138 sprite.position.copy(anchor).add(new THREE.Vector3((Math.random() - 0.5) * j, (Math.random() - 0.5) * j * 0.6, (Math.random() - 0.5) * j));
139 sprite.material.opacity = 0;
140 starGroup.add(sprite);
141 stars.push({ obj: sprite, born: elapsed, life: st.life, seed: Math.random() * 1000, up: kind === 'built' ? 0.5 : 0.22 });
142 if (stars.length > 160) { const old = stars.shift(); starGroup.remove(old.obj); old.obj.material.map.dispose(); old.obj.material.dispose(); }
143}
144
145// ── historial COMPLETO (todo lo que llega, sin recortar) — PERSISTENTE: antes
146// vivía solo en el DOM/memoria y una recarga de página lo borraba entero.
147const LOG_CAP = 500;
148let logHistory = []; // [{channel, text}] — se guarda en IndexedDB
149let logSaveTimer = null;
150function saveLogSoon() {
151 clearTimeout(logSaveTimer);
152 logSaveTimer = setTimeout(() => db.set('kv', 'mindLog', logHistory).catch(() => {}), 400);
153}
154function renderLogRow(channel, text) {
155 const body = document.getElementById('mind-log-body');
156 if (!body) return;
157 const prof = profileOf(channel);
158 const row = document.createElement('div');
159 row.className = 'ml-row';
160 row.innerHTML = `<span class="ml-dot" style="background:${prof.color}"></span><b style="color:${prof.color}">${escHtml(prof.name)}</b> <span class="ml-t">${escHtml(text)}</span>`;
161 body.appendChild(row);
162 while (body.children.length > LOG_CAP) body.removeChild(body.firstChild);
163 body.scrollTop = body.scrollHeight;
164}
165function logLine(channel, text) {
166 logHistory.push({ channel, text });
167 if (logHistory.length > LOG_CAP) logHistory = logHistory.slice(-LOG_CAP);
168 saveLogSoon();
169 renderLogRow(channel, text);
170}
171async function loadPersistedLog() {
172 try {
173 const saved = await db.get('kv', 'mindLog');
174 if (!Array.isArray(saved) || !saved.length) return;
175 logHistory = saved;
176 for (const { channel, text } of saved) renderLogRow(channel, text);
177 } catch { /* aún no hay historial guardado */ }
178}
179
180function flushLine(channel, force = false) {
181 const buf = (lineBuf.get(channel) || '').trim();
182 if (!buf && !force) return;
183 if (buf) { spawnStar(channel, buf, 'line'); logLine(channel, buf); }
184 lineBuf.set(channel, '');
185}
186
187// alimenta estrellas + historial + haces sobre la ciudad (ceo.js → aquí)
188export function pushThought(channel, ev) {
189 if (!open) return;
190 if (channel === 'sys') { logLine('ceo', ev.text); return; }
191 if (channel === 'ceo') {
192 if (ev.type === 'cycle') { logLine('ceo', '● ' + ev.text); spawnStar('ceo', ev.text, 'event'); }
193 else if (ev.type === 'survey') { logLine('ceo', ev.text); }
194 else if (ev.type === 'reprogram') { logLine('ceo', '⚙ ' + ev.text); spawnStar('ceo', ev.text, 'event'); if (ev.profiles) rebuildWorld(); }
195 else if (ev.type === 'paused') { logLine('ceo', ev.text); spawnStar('ceo', ev.text, 'event'); }
196 else if (ev.type === 'built') { logLine('ceo', '✦ ' + ev.text); spawnStar('ceo', ev.text, 'built'); addThoughtNode(ev); }
197 else logLine('ceo', ev.text || '');
198 return;
199 }
200 if (ev.type === 'open') { lineBuf.set(channel, ''); streamed.set(channel, false); }
201 else if (ev.type === 'token') {
202 streamed.set(channel, true);
203 lineBuf.set(channel, (lineBuf.get(channel) || '') + ev.text);
204 const buf = lineBuf.get(channel);
205 if (/\n/.test(ev.text) || buf.length > 90) flushLine(channel);
206 } else if (ev.type === 'tool') {
207 flushLine(channel);
208 spawnStar(channel, ev.text, 'tool');
209 logLine(channel, '⟐ ' + ev.text);
210 if (ev.path) fileBeam(ev.path, /escrib/i.test(ev.text) ? 'write' : 'read');
211 } else if (ev.type === 'tool_result') {
212 // el RESULTADO real de la tool (lo que de verdad se leyó/escribió/ejecutó),
213 // enlazado justo debajo de su tool-call — no solo el nombre de la acción.
214 const t = '→ ' + (ev.text || '(sin salida)');
215 spawnStar(channel, t, 'line');
216 logLine(channel, t);
217 } else if (ev.type === 'done') {
218 flushLine(channel, true);
219 // el proveedor puede devolver el texto final SIN pasar por tokens (sin
220 // streaming) → si no vimos ningún token, esto es lo único que lo muestra.
221 if (ev.text && !streamed.get(channel)) { spawnStar(channel, ev.text, 'line'); logLine(channel, ev.text); }
222 }
223}
224
225// ── nodos de pensamiento clicables (cada .md forjado = un punto brillante) ──
226function addThoughtNode({ path, md, text }) {
227 if (!nodesGroup) return;
228 const i = thoughtNodes.length;
229 const a = i * 2.399963; // ángulo áureo
230 const r = 30 + i * 5;
231 const mesh = new THREE.Mesh(
232 new THREE.IcosahedronGeometry(3.2, 0),
233 new THREE.MeshBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.95, blending: THREE.AdditiveBlending, depthWrite: false }));
234 mesh.position.set(Math.cos(a) * r, 6 + Math.sin(i * 0.7) * 10, Math.sin(a) * r);
235 mesh.userData = { path, md, text };
236 nodesGroup.add(mesh);
237 thoughtNodes.push(mesh);
238 // Un BOTÓN, y con pointer-events propios: la hoja de estilos pone
239 // `pointer-events:none` a las etiquetas y a su contenedor (para que el ratón
240 // pase al lienzo y se pueda girar la cámara), así que el clic nunca llegaba a
241 // la etiqueta y solo un raycast con suerte sobre la diminuta malla abría el
242 // panel. El contenedor sigue sin capturar; la etiqueta sí, y con el teclado.
243 const lab = document.createElement('button');
244 lab.type = 'button';
245 lab.className = 'mind-node-label';
246 lab.style.pointerEvents = 'auto';
247 lab.style.cursor = 'pointer';
248 lab.style.fontFamily = 'inherit';
249 const nombre = (path || t('mindThought')).split('/').pop();
250 lab.textContent = nombre;
251 lab.setAttribute('aria-label', t('mindOpenProposal', { name: nombre }));
252 lab.addEventListener('click', () => selectThoughtNode(mesh));
253 document.getElementById('mind-anchors').appendChild(lab);
254 anchors.push({ el: lab, pos: mesh.position });
255 mesh.userData.label = lab;
256}
257
258async function loadExistingThoughts() {
259 try { for (const it of await loadThoughts()) addThoughtNode(it); } catch { /* aún no hay */ }
260}
261
262// selección de un nodo de propuesta — desde la malla 3D (raycast) o su etiqueta
263function selectThoughtNode(mesh) { showThoughtPanel(mesh); focusOn(mesh.position, 26); }
264
265// Abrir un fichero DESDE la Mente: primero se cierra la Mente. Antes la
266// pestaña se abría detrás de esta capa, que lo tapa todo, y parecía que el
267// botón no hacía nada.
268function openInEditor(path) {
269 document.getElementById('mind-panel')?.classList.remove('show');
270 closeMind();
271 onOpenFile(path);
272}
273// Las rutas `entre comillas invertidas` de una propuesta se pueden abrir.
274const PATH_RE = /^[\w.-]+(\/[\w.-]+)*\.[a-z0-9]{1,10}$/i;
275function linkifyPaths(root) {
276 root.querySelectorAll('code').forEach(el => {
277 const p = el.textContent.trim();
278 if (!PATH_RE.test(p) || /[{}()<>]/.test(p) || el.closest('pre')) return;
279 const a = document.createElement('a');
280 a.href = '#';
281 a.textContent = p;
282 a.title = t('mindOpenPath', { path: p });
283 a.style.cssText = 'color:inherit;text-decoration:underline dotted';
284 a.onclick = e => { e.preventDefault(); openInEditor(p); };
285 el.replaceChildren(a);
286 });
287}
288
289function showThoughtPanel(node) {
290 const root = document.getElementById('mind-panel');
291 const md = node.userData.md || node.userData.text || t('mindEmpty');
292 const path = node.userData.path || t('mindThought');
293 root.setAttribute('role', 'dialog');
294 root.setAttribute('aria-label', path);
295 root.innerHTML = `<div class="mp-head">${escHtml(path)}<button id="mp-x" aria-label="${escHtml(t('close'))}">✕</button></div>` +
296 `<div class="mp-body">${renderMarkdown(md)}</div>` +
297 `<div class="mp-actions">` +
298 `<button id="mp-exec" class="mp-exec">${escHtml(t('mindExec'))}</button>` +
299 (node.userData.path ? `<button id="mp-open" class="mp-open">${escHtml(t('mindOpenEditor'))}</button>` : '') +
300 `</div>`;
301 root.classList.add('show');
302 linkifyPaths(root.querySelector('.mp-body'));
303 root.querySelector('#mp-x').onclick = () => root.classList.remove('show');
304 root.querySelector('#mp-exec').onclick = () => { onExecute(md); root.classList.remove('show'); };
305 const openBtn = root.querySelector('#mp-open');
306 if (openBtn) openBtn.onclick = () => openInEditor(node.userData.path);
307 root.querySelector('#mp-exec').focus();
308}
309
310// ══ perfiles: anclas 3D + leyenda (recalculadas al abrir o al reprogramar) ══
311function computeAnchors() {
312 const map = new Map();
313 map.set('ceo', new THREE.Vector3(0, 46, 0));
314 const profs = ceo.getProfiles();
315 const n = Math.max(profs.length, 1);
316 profs.forEach((p, i) => {
317 const a = (i / n) * Math.PI * 2;
318 map.set(p.id, new THREE.Vector3(Math.cos(a) * 70, 8 + (i % 2) * 20, Math.sin(a) * 70));
319 });
320 return map;
321}
322// Botones (antes <div>: solo con ratón). Llevan la cámara a ese perfil.
323function renderLegend() {
324 const el = document.getElementById('mind-legend');
325 if (!el) return;
326 const profs = ceo.getProfiles();
327 const reset = 'background:none;border:none;font:inherit;color:inherit;text-align:left;width:100%';
328 el.innerHTML = `<button type="button" class="ml-item" data-id="ceo" style="${reset}"><span class="ml-sw" style="background:${CEO_COLOR}"></span>CEO</button>` +
329 profs.map(p => `<button type="button" class="ml-item" data-id="${escHtml(p.id)}" style="${reset}"><span class="ml-sw" style="background:${escHtml(p.color)}"></span>${escHtml(p.name)}</button>`).join('');
330 el.querySelectorAll('.ml-item').forEach(row => {
331 row.title = t('mindFlyTo', { name: row.textContent });
332 row.onclick = () => { const pos = anchorMap.get(row.dataset.id); if (pos) focusOn(pos, 46); };
333 });
334}
335// vuelo suave de la cámara hacia un punto — así «clic en algo → la cámara se centra»
336let flyTo = null;
337function focusOn(pos, distance = 40) {
338 if (!S) return;
339 const dir = new THREE.Vector3().subVectors(S.camera.position, S.controls.target);
340 if (dir.lengthSq() < 0.001) dir.set(0, 0.3, 1);
341 dir.normalize().multiplyScalar(distance);
342 flyTo = { fromPos: S.camera.position.clone(), toPos: pos.clone().add(dir), fromTarget: S.controls.target.clone(), toTarget: pos.clone(), t0: elapsed, dur: 1.1 };
343}
344const easeInOut = k => k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2;
345function rebuildWorld() { anchorMap = computeAnchors(); renderLegend(); }
346
347// ── panel ⚙: reprograma misión, carpeta-alma y PERFILES (editables) ──────
348function wireConfig(root) {
349 const btn = root.querySelector('#mind-config');
350 const cfg = root.querySelector('#mind-cfg');
351 cfg.setAttribute('role', 'dialog');
352 cfg.setAttribute('aria-labelledby', 'cfg-title');
353 const profRowHtml = p => `<div class="cfg-prof" data-id="${escHtml(p.id || '')}">
354 <input type="color" class="cp-color" value="${escHtml(p.color || '#7c5cff')}" aria-label="${escHtml(t('cfgColor'))}">
355 <input type="text" class="cp-name" value="${escHtml(p.name || '')}" placeholder="${escHtml(t('cfgName'))}" aria-label="${escHtml(t('cfgName'))}">
356 <input type="text" class="cp-focus" value="${escHtml(p.focus || '')}" placeholder="${escHtml(t('cfgFocus'))}" aria-label="${escHtml(t('cfgFocus'))}">
357 <button class="cp-del" title="${escHtml(t('cfgRemove'))}" aria-label="${escHtml(t('cfgRemove'))}">✕</button></div>`;
358 const notifState = () => (!('Notification' in window)) ? { txt: t('cfgNotifUnsupported'), can: false }
359 : Notification.permission === 'granted' ? { txt: t('cfgNotifGranted'), can: false }
360 : Notification.permission === 'denied' ? { txt: t('cfgNotifDenied'), can: false }
361 : { txt: t('cfgNotifDefault'), can: true };
362 const draw = () => {
363 const profs = ceo.getProfiles();
364 const ns = notifState();
365 // Etiquetas ASOCIADAS a sus campos (for/id): antes un lector de pantalla
366 // solo oía el placeholder, o nada.
367 cfg.innerHTML =
368 `<div class="cfg-head"><span id="cfg-title">${escHtml(t('cfgTitle'))}</span><button id="cfg-x" aria-label="${escHtml(t('close'))}">✕</button></div>` +
369 `<div class="cfg-notif">${escHtml(t('cfgNotif'))} ${escHtml(ns.txt)}` + (ns.can ? ` <button id="cfg-notif-ask" class="cfg-notif-btn">${escHtml(t('cfgNotifAsk'))}</button>` : '') + '</div>' +
370 `<label for="cfg-mission">${escHtml(t('cfgMission'))}</label>` +
371 '<textarea id="cfg-mission" rows="3">' + escHtml(ceo.getMission()) + '</textarea>' +
372 `<label for="cfg-dir">${escHtml(t('cfgDir'))}</label>` +
373 '<input id="cfg-dir" value="' + escHtml(ceo.getSoulDir()) + '">' +
374 `<label id="cfg-prof-lbl">${escHtml(t('cfgProfiles'))}</label>` +
375 '<div id="cfg-profiles" role="group" aria-labelledby="cfg-prof-lbl">' + profs.map(profRowHtml).join('') + '</div>' +
376 `<button id="cfg-add-prof" class="cfg-add">${escHtml(t('cfgAddProf'))}</button>` +
377 `<div class="cfg-actions"><button id="cfg-think-now" class="cfg-ghost">${escHtml(t('cfgThink'))}</button>` +
378 `<button id="cfg-save" class="cfg-save">${escHtml(t('cfgSave'))}</button></div>` +
379 `<div class="cfg-note" id="cfg-note" role="status">${escHtml(t('cfgNote'))}</div>`;
380 cfg.querySelector('#cfg-x').onclick = () => cfg.classList.remove('show');
381 cfg.querySelector('#cfg-notif-ask')?.addEventListener('click', () => { Notification.requestPermission().then(draw); });
382 cfg.querySelector('#cfg-add-prof').onclick = () => {
383 cfg.querySelector('#cfg-profiles').insertAdjacentHTML('beforeend', profRowHtml({ color: '#ff9f45', name: '', focus: '' }));
384 wireRows();
385 };
386 // «Pensar ahora» sin modelo de verdad (modo básico) o sin proyecto: se dice
387 // aquí mismo en vez de cerrar el panel como si hubiera empezado.
388 cfg.querySelector('#cfg-think-now').onclick = async () => {
389 const motivo = await ceo.whyNotThink();
390 if (motivo) { cfg.querySelector('#cfg-note').textContent = '⚠️ ' + t('cfgCant_' + motivo); return; }
391 ceo.forceCycle();
392 cfg.classList.remove('show');
393 };
394 cfg.querySelector('#cfg-save').onclick = () => {
395 // preserva el id original de cada perfil (si no, cada guardado los
396 // regeneraría desde el nombre y los ciclos en curso perderían el hilo)
397 const rows = [...cfg.querySelectorAll('.cfg-prof')].map(r => ({
398 id: r.dataset.id || undefined,
399 color: r.querySelector('.cp-color').value,
400 name: r.querySelector('.cp-name').value.trim(),
401 focus: r.querySelector('.cp-focus').value.trim(),
402 }));
403 ceo.setMission(cfg.querySelector('#cfg-mission').value);
404 ceo.setSoulDir(cfg.querySelector('#cfg-dir').value);
405 ceo.setProfiles(rows);
406 if (!ceo.isEnabled()) ceo.enable();
407 paintPlay();
408 cfg.classList.remove('show');
409 };
410 wireRows();
411 function wireRows() { cfg.querySelectorAll('.cp-del').forEach(b => { b.onclick = () => b.closest('.cfg-prof').remove(); }); }
412 };
413 btn.onclick = () => {
414 if (cfg.classList.contains('show')) { cfg.classList.remove('show'); return; }
415 draw(); cfg.classList.add('show');
416 cfg.querySelector('#cfg-mission')?.focus();
417 };
418}
419function wireHistory(root) {
420 const btn = root.querySelector('#mind-history'), panel = root.querySelector('#mind-log');
421 btn.onclick = () => panel.classList.toggle('show');
422 panel.querySelector('#ml-x').onclick = () => panel.classList.remove('show');
423}
424
425// play/stop del cerebro, visible dentro de la Mente. La elección la persiste
426// ceo.js → sobrevive a recargar. Abrir la Mente YA NO enciende el cerebro: se
427// enciende aquí, a propósito, y el botón dice qué hace («activar» la primera
428// vez, «reanudar» si lo pausaste).
429let paintPlay = () => {};
430function wirePlayStop(root) {
431 const btn = root.querySelector('#mind-playstop');
432 paintPlay = () => {
433 const on = ceo.isEnabled();
434 btn.textContent = on ? t('mindPause') : (ceo.hasDecided() ? t('mindResume') : t('mindActivate'));
435 btn.title = on ? t('mindPauseTitle') : t('mindActivateTitle', { dir: ceo.getSoulDir() });
436 btn.setAttribute('aria-pressed', on ? 'true' : 'false');
437 btn.classList.toggle('paused', !on);
438 };
439 btn.onclick = () => { if (ceo.isEnabled()) ceo.disable(); else ceo.enable(); paintPlay(); };
440 paintPlay();
441}
442
443// ══ ciudad de fondo (motor de la app anfitriona, por debajo del mundo) ══════
444async function buildBackgroundCity(scene) {
445 if (!buildCityFn) return;
446 try {
447 const city = await buildCityFn(scene);
448 if (!city) return;
449 cityWrap = city.cityWrap; cityCity = city.cityCity; cityModel = city.cityModel;
450 } catch { /* sigue sin ciudad de fondo */ }
451}
452// haz de luz que baja hasta el fichero real en la ciudad + resalta su celda
453function fileBeam(path, kind) {
454 if (!cityModel || !cityCity || !S) return;
455 const rel = String(path).replace(/^\.?\//, '');
456 const f = cityModel.fileByRel.get(rel);
457 if (!f) return;
458 const local = new THREE.Vector3(f.box.cx, f.box.cy, f.box.cz);
459 const world = cityWrap.localToWorld(local.clone());
460 const top = world.clone(); top.y += 50;
461 const geo = new THREE.BufferGeometry().setFromPoints([top, world]);
462 const mat = new THREE.LineBasicMaterial({ color: kind === 'write' ? 0xff4d8d : 0x49e8ff, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false });
463 const line = new THREE.Line(geo, mat);
464 S.scene.add(line);
465 beams.push({ obj: line, born: elapsed, life: 1.4 });
466 fileActivity.push({ id: f.id, born: elapsed, life: 2.2 });
467}
468
469// ── mundo psicodélico ───────────────────────────────────────────────────────
470function buildScene(canvas, W, H) {
471 const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
472 renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
473 renderer.setSize(W, H, false);
474 renderer.toneMapping = THREE.ACESFilmicToneMapping;
475 const scene = new THREE.Scene();
476 const camera = new THREE.PerspectiveCamera(60, W / H, 0.1, 2000);
477 camera.position.set(0, 40, 150);
478 const controls = new OrbitControls(camera, canvas);
479 controls.enableDamping = true; controls.dampingFactor = 0.06; controls.autoRotate = false;
480 controls.enablePan = false; controls.minDistance = 60; controls.maxDistance = 420;
481
482 const N = 14000;
483 const pos = new Float32Array(N * 3), rad = new Float32Array(N);
484 let s = 987654321; const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647;
485 for (let i = 0; i < N; i++) {
486 const arm = Math.floor(rnd() * 4);
487 const r = Math.pow(rnd(), 0.6) * 120 + 6;
488 const a = arm * (Math.PI / 2) + r * 0.03 + (rnd() - 0.5) * 0.5;
489 const y = (rnd() - 0.5) * (14 - r * 0.06);
490 pos[i * 3] = Math.cos(a) * r; pos[i * 3 + 1] = y; pos[i * 3 + 2] = Math.sin(a) * r; rad[i] = r;
491 }
492 const geo = new THREE.BufferGeometry();
493 geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
494 geo.setAttribute('aRad', new THREE.BufferAttribute(rad, 1));
495 const mat = new THREE.ShaderMaterial({
496 uniforms: { uTime: { value: 0 }, uBass: { value: 0 }, uMid: { value: 0 } },
497 transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
498 vertexShader: `uniform float uTime, uBass, uMid; attribute float aRad; varying vec3 vC;
499 vec3 hsv(float h){ vec3 k=vec3(1.,2./3.,1./3.); vec3 p=abs(fract(h+k)*6.-3.); return clamp(p-1.,0.,1.);}
500 float hash(vec3 p){ p=fract(p*0.3183099+0.1); p*=17.0; return fract(p.x*p.y*p.z*(p.x+p.y+p.z)); }
501 float vnoise(vec3 x){ vec3 i=floor(x),f=fract(x); f=f*f*(3.0-2.0*f);
502 return mix(mix(mix(hash(i+vec3(0,0,0)),hash(i+vec3(1,0,0)),f.x),mix(hash(i+vec3(0,1,0)),hash(i+vec3(1,1,0)),f.x),f.y),
503 mix(mix(hash(i+vec3(0,0,1)),hash(i+vec3(1,0,1)),f.x),mix(hash(i+vec3(0,1,1)),hash(i+vec3(1,1,1)),f.x),f.y),f.z); }
504 float fbm(vec3 p){ float a=0.5,s=0.0; for(int i=0;i<4;i++){ s+=a*vnoise(p); p*=2.02; a*=0.5;} return s; }
505 void main(){
506 vec3 pos=position;
507 float n=fbm(pos*0.03 + vec3(0.0,uTime*0.18,0.0));
508 pos += normalize(pos+0.001) * (n-0.5) * (5.0 + uMid*4.0 + uBass*7.0);
509 float sw = uTime*0.14 + aRad*0.015 + uBass*0.18;
510 float cs=cos(sw), sn=sin(sw);
511 pos.xz = mat2(cs,-sn,sn,cs) * pos.xz;
512 pos *= (1.0 + uBass*0.05);
513 float h=fract(aRad*0.004+uTime*0.03+n*0.12); vC=hsv(h)*(1.3-aRad*0.004)*(0.95+uMid*0.18+uBass*0.12);
514 vec4 mv=modelViewMatrix*vec4(pos,1.0); gl_PointSize=(2.2+60.0/-mv.z)*(1.0+uBass*0.18); gl_Position=projectionMatrix*mv; }`,
515 fragmentShader: `varying vec3 vC; void main(){ vec2 d=gl_PointCoord-0.5; float m=smoothstep(0.5,0.0,length(d)); gl_FragColor=vec4(vC*2.0,m); }`,
516 });
517 const galaxy = new THREE.Points(geo, mat); scene.add(galaxy);
518 const core = new THREE.LineSegments(new THREE.WireframeGeometry(new THREE.IcosahedronGeometry(18, 1)),
519 new THREE.LineBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false }));
520 scene.add(core);
521 const rings = [];
522 for (let i = 0; i < 24; i++) {
523 const ring = new THREE.Mesh(new THREE.TorusGeometry(22, 0.5, 8, 80),
524 new THREE.MeshBasicMaterial({ color: 0x7c5cff, transparent: true, opacity: 0.45, blending: THREE.AdditiveBlending, depthWrite: false }));
525 ring.rotation.x = Math.PI / 2; ring.position.y = -70 + i * 6; ring.userData.i = i;
526 scene.add(ring); rings.push(ring);
527 }
528 nodesGroup = new THREE.Group(); scene.add(nodesGroup);
529 starGroup = new THREE.Group(); scene.add(starGroup);
530 const composer = new EffectComposer(renderer);
531 composer.setSize(W, H); composer.addPass(new RenderPass(scene, camera));
532 const bloom = new UnrealBloomPass(new THREE.Vector2(W, H), 1.1, 0.5, 0.2);
533 composer.addPass(bloom); composer.addPass(new OutputPass());
534 return { renderer, scene, camera, controls, composer, bloom, mat, galaxy, core, rings };
535}
536
537export async function openMind() {
538 if (open) return;
539 open = true;
540 if (built) { overlay.style.display = ''; if (musicOn) { try { widget?.play(); } catch {} } paintPlay(); startLoop(); return; }
541
542 overlay = document.createElement('div');
543 overlay.id = 'mind-overlay';
544 overlay.setAttribute('role', 'dialog');
545 overlay.setAttribute('aria-modal', 'true');
546 overlay.setAttribute('aria-label', t('mindTitle'));
547 overlay.innerHTML =
548 '<canvas id="mind-canvas" aria-hidden="true"></canvas>' +
549 `<div id="mind-title">${t('mindTitle')}</div>` +
550 `<div id="mind-legend" role="group" aria-label="${escHtml(t('mindLegend'))}"></div>` +
551 '<button id="mind-playstop"></button>' +
552 `<button id="mind-config" title="${escHtml(t('mindConfigTitle'))}">${escHtml(t('mindConfig'))}</button>` +
553 `<button id="mind-history" title="${escHtml(t('mindHistoryTitle'))}">${escHtml(t('mindHistory'))}</button>` +
554 `<button id="mind-close" title="${escHtml(t('mindCloseTitle'))}">${escHtml(t('mindClose'))}</button>` +
555 '<div id="mind-anchors"></div><div id="mind-panel"></div><div id="mind-cfg"></div>' +
556 `<div id="mind-log"><div class="ml-head">${escHtml(t('mindLogTitle'))}<button id="ml-x" aria-label="${escHtml(t('close'))}">✕</button></div><div id="mind-log-body" role="log"></div></div>`;
557 document.body.appendChild(overlay);
558 wireConfig(overlay); wireHistory(overlay); wirePlayStop(overlay);
559 mountMusic(overlay);
560 anchors.length = 0; thoughtNodes = []; stars = []; lineBuf.clear();
561 rebuildWorld();
562
563 const canvas = overlay.querySelector('#mind-canvas');
564 S = buildScene(canvas, window.innerWidth, window.innerHeight);
565 buildBackgroundCity(S.scene);
566 await loadExistingThoughts();
567 await loadPersistedLog(); // el historial de «≡ historial» sobrevive a recargas
568
569 const ray = new THREE.Raycaster(), ptr = new THREE.Vector2();
570 let downXY = null;
571 canvas.addEventListener('pointerdown', e => { downXY = [e.clientX, e.clientY]; });
572 canvas.addEventListener('pointerup', e => {
573 if (!downXY) return; const moved = Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]); downXY = null;
574 if (moved > 5 || !thoughtNodes.length) return;
575 ptr.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1);
576 ray.setFromCamera(ptr, S.camera);
577 const hit = ray.intersectObjects(thoughtNodes)[0];
578 if (hit) selectThoughtNode(hit.object);
579 });
580
581 const onResize = () => {
582 const w = window.innerWidth, h = window.innerHeight;
583 S.renderer.setSize(w, h, false); S.composer.setSize(w, h); S.bloom.resolution.set(w, h);
584 S.camera.aspect = w / h; S.camera.updateProjectionMatrix();
585 };
586 window.addEventListener('resize', onResize); S.onResize = onResize;
587 overlay.querySelector('#mind-close').addEventListener('click', closeMind);
588 S.onKey = e => { if (e.key === 'Escape') closeMind(); };
589 document.addEventListener('keydown', S.onKey);
590 built = true;
591 startLoop();
592}
593
594// Etiquetas de propuestas: se proyectan del mundo 3D a la pantalla, así que
595// con muchas acumuladas acaban solapándose ilegibles según el ángulo de
596// cámara. Aquí: cap a las más cercanas y reparto anti-solape (empuja hacia
597// abajo la que choca con otra ya colocada), para que se apilen separadas.
598const MAX_LABELS = 14, LABEL_W = 90, LABEL_H = 20;
599function projectAnchors() {
600 const w = window.innerWidth, h = window.innerHeight, v = new THREE.Vector3();
601 const projected = [];
602 for (const a of anchors) {
603 v.copy(a.pos).project(S.camera);
604 if (v.z > 1) { a.el.style.display = 'none'; continue; } // detrás de la cámara
605 projected.push({ a, x: (v.x * 0.5 + 0.5) * w, y: (-v.y * 0.5 + 0.5) * h, depth: v.z });
606 }
607 projected.sort((p1, p2) => p1.depth - p2.depth); // las más cercanas a la cámara, prioridad
608 projected.forEach((p, i) => { p.a.el.style.display = i < MAX_LABELS ? '' : 'none'; });
609 const visible = projected.slice(0, MAX_LABELS).sort((p1, p2) => p1.x - p2.x || p1.y - p2.y);
610 const placed = [];
611 for (const p of visible) {
612 let y = p.y;
613 for (const q of placed) if (Math.abs(q.x - p.x) < LABEL_W && Math.abs(q.y - y) < LABEL_H) y = q.y + LABEL_H;
614 placed.push({ x: p.x, y });
615 p.a.el.style.left = p.x + 'px'; p.a.el.style.top = y + 'px';
616 p.a.el.style.transform = 'translate(-50%,-50%)';
617 }
618}
619const wob = (t, seed, freq = 0.1) => Math.sin(t * freq + seed) * 0.6 + Math.sin(t * freq * 0.43 + seed * 2.1) * 0.3 + Math.sin(t * freq * 0.19 + seed * 4.7) * 0.1;
620
621let elapsed = 0, lastMs = 0, smBass = 0, smMid = 0;
622function startLoop() {
623 if (raf) return;
624 const loop = (ms) => {
625 raf = requestAnimationFrame(loop);
626 const dt = lastMs ? (ms - lastMs) / 1000 : 0;
627 elapsed += dt; lastMs = ms;
628 const t = elapsed;
629 const beat = 60 / 138;
630 const bp = (t % beat) / beat;
631 const bassRaw = Math.pow(1 - bp, 3);
632 const midRaw = 0.5 + 0.5 * Math.sin(t * 6.0);
633 smBass += (bassRaw - smBass) * 0.05;
634 smMid += (midRaw - smMid) * 0.06;
635 S.mat.uniforms.uTime.value = t;
636 S.mat.uniforms.uBass.value = smBass;
637 S.mat.uniforms.uMid.value = smMid;
638 S.galaxy.rotation.y = t * 0.05;
639 S.galaxy.rotation.x = wob(t, 1.7, 0.05) * 0.15;
640 S.galaxy.rotation.z = wob(t, 5.2, 0.04) * 0.1;
641 S.galaxy.scale.setScalar(1 + smBass * 0.02);
642 const pulse = 1 + smBass * 0.05 + Math.sin(t * 0.9) * 0.03;
643 S.core.scale.setScalar(pulse); S.core.rotation.y = t * 0.16; S.core.rotation.x = t * 0.09;
644 S.core.position.x = wob(t, 3.1, 0.11) * 6; S.core.position.z = wob(t, 9.4, 0.09) * 6;
645 S.core.material.color.setHSL((t * 0.04) % 1, 0.9, 0.6);
646 for (const r of S.rings) {
647 r.position.y += 0.14 + smBass * 0.12;
648 if (r.position.y > 74) r.position.y -= 144;
649 r.position.x = wob(t, r.userData.i * 1.3 + 1, 0.08) * 3;
650 r.scale.setScalar(1 + smBass * 0.12 + Math.sin(t * 0.8 + r.userData.i) * 0.04);
651 r.material.opacity = 0.2 + smBass * 0.16;
652 r.material.color.setHSL((t * 0.05 + r.userData.i * 0.03) % 1, 0.85, 0.6);
653 }
654 for (let i = 0; i < thoughtNodes.length; i++) { const n = thoughtNodes[i]; n.rotation.y = t + i; n.scale.setScalar(1 + Math.sin(t * 2 + i) * 0.14); }
655 // estrellas: nacen (fade-in), viven, se apagan solas y se reciclan
656 for (let i = stars.length - 1; i >= 0; i--) {
657 const st = stars[i], age = t - st.born;
658 if (age > st.life) { starGroup.remove(st.obj); st.obj.material.map.dispose(); st.obj.material.dispose(); stars.splice(i, 1); continue; }
659 const fadeIn = Math.min(1, age / 0.5), fadeOut = Math.min(1, (st.life - age) / (st.life * 0.35));
660 st.obj.material.opacity = Math.min(fadeIn, fadeOut);
661 st.obj.position.y += st.up * dt;
662 st.obj.position.x += Math.sin(t * 0.6 + st.seed) * 0.3 * dt;
663 }
664 // haces sobre la ciudad + celdas de fichero resaltadas por actividad
665 for (let i = beams.length - 1; i >= 0; i--) {
666 const b = beams[i], age = t - b.born;
667 if (age > b.life) { S.scene.remove(b.obj); b.obj.geometry.dispose(); b.obj.material.dispose(); beams.splice(i, 1); continue; }
668 b.obj.material.opacity = 0.9 * Math.max(0, 1 - age / b.life);
669 }
670 if (cityCity) for (let i = fileActivity.length - 1; i >= 0; i--) {
671 const a = fileActivity[i], age = t - a.born;
672 if (age > a.life) { cityCity.paintFile(a.id, 0); fileActivity.splice(i, 1); continue; }
673 cityCity.paintFile(a.id, Math.max(0, 1 - age / a.life));
674 }
675 if (flyTo) {
676 const k = Math.min(1, (t - flyTo.t0) / flyTo.dur), e = easeInOut(k);
677 S.camera.position.lerpVectors(flyTo.fromPos, flyTo.toPos, e);
678 S.controls.target.lerpVectors(flyTo.fromTarget, flyTo.toTarget, e);
679 if (k >= 1) flyTo = null;
680 }
681 S.controls.update();
682 projectAnchors();
683 S.composer.render();
684 };
685 loop(performance.now());
686}
687
688export function closeMind() {
689 open = false;
690 if (raf) { cancelAnimationFrame(raf); raf = null; }
691 lastMs = 0;
692 try { widget?.pause(); } catch {}
693 if (overlay) overlay.style.display = 'none';
694}
695
696// para tests/depuración
697export function _debug() {
698 return {
699 starCount: stars.length, hasCity: !!cityCity, profileCount: ceo.getProfiles().length,
700 beamCount: beams.length, fileActivityCount: fileActivity.length,
701 cameraPos: S ? [S.camera.position.x, S.camera.position.y, S.camera.position.z] : null,
702 flying: !!flyTo,
703 };
704}
705export function _debugFocusOn(id) { const p = anchorMap.get(id); if (p) focusOn(p, 46); }