| 1 | // La Mente y el cerebro autónomo, sin modelo (proveedor de prueba cuando hace |
| 2 | // falta que piense): |
| 3 | // · cargar la página no trae three.js; abrir la Mente NO enciende el cerebro, |
| 4 | // no pide notificaciones ni carga SoundCloud; es modal (foco dentro, lo de |
| 5 | // detrás inerte, Escape cierra y el foco vuelve a 🧠); |
| 6 | // · el historial incluye lo que pasó con la Mente cerrada; |
| 7 | // · en Básico «Pensar ahora» explica por qué no piensa y no saca permisos; |
| 8 | // · ▶/⏸ dice siempre la verdad, y «Reprogramar» no enciende nada; |
| 9 | // · el cerebro solo puede LEER: un app.create suyo no crea nada; |
| 10 | // · la propuesta llega al chat, se guarda con su botón, sobrevive a recargar, |
| 11 | // su enlace abre la Mente en ella; en Básico no hay «Ejecutar»: en su sitio |
| 12 | // dice que hace falta un modelo, con un botón que lleva a elegirlo; |
| 13 | // · las etiquetas son botones clicables enteros y vuelven tras recargar; |
| 14 | // · «Ver el fichero» lo lee en el chat; la notificación lleva a la propuesta; |
| 15 | // · la Mente tampoco enseña «▶ Ejecutar» en Básico, y los avisos se ven y se |
| 16 | // pulsan con la Mente abierta (van encima y no quedan inertes); |
| 17 | // · cerrar la Mente limpia #/mente/… de la URL (el mismo enlace vuelve a abrir) |
| 18 | // y «Atrás» la cierra; cargar la página en #/mente o #/mente/<ruta> la abre; |
| 19 | // · sin el permiso «Archivos» el cerebro no arranca ni pide nada, y la clave |
| 20 | // vieja de encendido (la del primer clic en 🧠) ya no lo enciende. |
| 21 | // |
| 22 | // BASE=http://localhost:8743 node tests/ux-mente.mjs |
| 23 | import { createServer } from 'node:http'; |
| 24 | import { navegador, contexto, pagina, ok, hasta, espera, avisos, fin, kv, BASE, OUT } from './ux-comun.mjs'; |
| 25 | |
| 26 | const b = await navegador(); |
| 27 | const notifStub = () => { |
| 28 | window.__notifs = []; window.__pidioNotif = 0; |
| 29 | class N { |
| 30 | constructor(title, opts) { this.title = title; this.opts = opts; this.closed = false; window.__notifs.push(this); } |
| 31 | close() { this.closed = true; } |
| 32 | static get permission() { return window.__permNotif || 'default'; } |
| 33 | static requestPermission() { window.__pidioNotif++; return Promise.resolve(N.permission); } |
| 34 | } |
| 35 | window.Notification = N; |
| 36 | }; |
| 37 | const { ctx, fuera } = await contexto(b, { grants: ['fs'] }); |
| 38 | await ctx.addInitScript(notifStub); |
| 39 | // Todos los avisos que salen, aunque se vayan solos antes de mirarlos. |
| 40 | // (se observa desde antes de que corra la app: un aviso del arranque llega antes de DOMContentLoaded) |
| 41 | await ctx.addInitScript(() => { |
| 42 | window.__avisos = []; |
| 43 | new MutationObserver(ms => { |
| 44 | for (const m of ms) for (const n of m.addedNodes) if (n.nodeType === 1 && n.classList.contains('toast')) window.__avisos.push(n.textContent); |
| 45 | }).observe(document, { childList: true, subtree: true }); |
| 46 | }); |
| 47 | const { p, errores } = await pagina(ctx); |
| 48 | |
| 49 | // carpeta autorizada de prueba (OPFS registrada como carpeta, sin picker) |
| 50 | await p.evaluate(async () => { |
| 51 | const opfs = await navigator.storage.getDirectory(); |
| 52 | const f = await opfs.getFileHandle('README.md', { create: true }); |
| 53 | const w = await f.createWritable(); await w.write('# demo\nNOTA-LEIDA-7731\n'); await w.close(); |
| 54 | await (await import('/js/db.js')).set('fs', 'proyecto', opfs); |
| 55 | }); |
| 56 | |
| 57 | const three = () => fuera.filter(u => /cdn\.jsdelivr\.net\/npm\/three/.test(u)).length; |
| 58 | ok('cargar la página no pide three.js (la Mente se carga al abrirla)', three() === 0, fuera.filter(u => /jsdelivr/.test(u)).join(' | ')); |
| 59 | |
| 60 | // ── lo que pasa con la Mente cerrada queda en el historial ────────────────── |
| 61 | await p.evaluate(async () => { const ceo = await import('/js/ceo.js'); ceo.enable(); ceo.disable(); }); |
| 62 | ok('el botón 🧠 tiene nombre accesible', /Mente de Elffuss/.test(await p.getAttribute('#btn-mind', 'aria-label') || '')); |
| 63 | |
| 64 | // ── abrir: solo abrir ─────────────────────────────────────────────────────── |
| 65 | await p.evaluate(() => { localStorage.removeItem('elffuss.ceoEnabled'); localStorage.removeItem('elffuss.ceoDecision'); }); |
| 66 | await p.click('#btn-mind'); |
| 67 | ok('la Mente se abre (modal: role=dialog, aria-modal)', await hasta(() => p.evaluate(() => { |
| 68 | const o = document.getElementById('mind-overlay'); |
| 69 | return o && o.getAttribute('role') === 'dialog' && o.getAttribute('aria-modal') === 'true' && o.style.display !== 'none'; |
| 70 | }), { veces: 400 })); |
| 71 | await espera(300); |
| 72 | const abierta = await p.evaluate(async () => ({ |
| 73 | ceo: (await import('/js/ceo.js')).isEnabled(), |
| 74 | guardado: localStorage.getItem('elffuss.ceoDecision') ?? localStorage.getItem('elffuss.ceoEnabled'), |
| 75 | pidio: window.__pidioNotif, |
| 76 | foco: document.activeElement?.id, |
| 77 | inerte: document.querySelector('header').inert && document.querySelector('main').inert, |
| 78 | musica: !!document.querySelector('#mind-sc'), |
| 79 | boton: document.getElementById('mind-playstop').textContent, |
| 80 | })); |
| 81 | ok('abrir la Mente NO enciende el cerebro (ni lo guarda)', !abierta.ceo && abierta.guardado == null, JSON.stringify(abierta)); |
| 82 | ok('ni pide permiso de notificaciones', abierta.pidio === 0); |
| 83 | ok('ni carga SoundCloud: la música es un botón', !abierta.musica && !fuera.some(u => /soundcloud/.test(u))); |
| 84 | ok('el foco entra en la Mente y lo de detrás queda inerte', abierta.foco === 'mind-close' && abierta.inerte, JSON.stringify(abierta)); |
| 85 | ok('el interruptor dice lo que hará («activar cerebro»)', /activar cerebro/.test(abierta.boton), abierta.boton); |
| 86 | await p.click('#mind-history'); |
| 87 | const hist = await p.locator('#mind-log-body').innerText(); |
| 88 | ok('el historial incluye lo que pasó con la Mente cerrada', /CEO en guardia/.test(hist) && /CEO en pausa/.test(hist), hist.slice(-200)); |
| 89 | await p.keyboard.press('Escape'); |
| 90 | ok('Escape cierra primero el panel de historial', await p.evaluate(() => !document.getElementById('mind-log').classList.contains('show') |
| 91 | && document.getElementById('mind-overlay').style.display !== 'none')); |
| 92 | await p.keyboard.press('Escape'); |
| 93 | ok('y luego la Mente, devolviendo el foco a 🧠 y la página', await hasta(() => p.evaluate(() => |
| 94 | document.getElementById('mind-overlay').style.display === 'none' && document.activeElement?.id === 'btn-mind' && !document.querySelector('header').inert))); |
| 95 | |
| 96 | // ── música solo si la pides ───────────────────────────────────────────────── |
| 97 | await p.click('#btn-mind'); |
| 98 | await hasta(() => p.evaluate(() => document.getElementById('mind-overlay').style.display !== 'none')); |
| 99 | await p.click('#mind-music-btn'); |
| 100 | ok('♪ monta el reproductor solo al pedirlo', await hasta(() => p.evaluate(() => !!document.querySelector('#mind-sc'))) |
| 101 | && await p.getAttribute('#mind-music-btn', 'aria-pressed') === 'true'); |
| 102 | await p.click('#mind-music-btn'); |
| 103 | ok('y ♪ otra vez lo quita', await p.evaluate(() => !document.querySelector('#mind-sc'))); |
| 104 | |
| 105 | // ── Básico: «Pensar ahora» explica y no hace nada más ─────────────────────── |
| 106 | await p.click('#mind-config'); |
| 107 | await p.click('#cfg-think-now'); |
| 108 | ok('en Básico, «Pensar ahora» dice que hace falta un modelo y el panel sigue abierto', await hasta(async () => |
| 109 | /modelo cargado/.test(await p.locator('#cfg-status').innerText()) && await p.evaluate(() => document.getElementById('mind-cfg').classList.contains('show')))); |
| 110 | await espera(400); |
| 111 | ok('…sin diálogos de permiso ni apps creadas', !(await p.evaluate(() => document.getElementById('perm-dialog').open)) |
| 112 | && (await p.evaluate(async () => (await (await import('/js/db.js')).all('apps')).length)) === 0); |
| 113 | ok('la carpeta-alma dice dónde está («dentro de «proyecto»»)', /dentro de «proyecto»/.test(await p.locator('#cfg-dir-label').innerText())); |
| 114 | ok('los colores de perfil tienen nombre', await p.evaluate(() => [...document.querySelectorAll('.cp-color')].every(i => /^Color de /.test(i.getAttribute('aria-label') || '')))); |
| 115 | |
| 116 | // ── ▶/⏸: siempre la verdad; Reprogramar no enciende ───────────────────────── |
| 117 | await p.focus('#cfg-x'); |
| 118 | await p.keyboard.press('Enter'); |
| 119 | ok('✕ del panel ⚙ (con Enter) devuelve el foco a ⚙, no a <body>', await hasta(() => p.evaluate(() => |
| 120 | !document.getElementById('mind-cfg').classList.contains('show') && document.activeElement?.id === 'mind-config')), |
| 121 | await p.evaluate(() => document.activeElement?.id || document.activeElement?.tagName)); |
| 122 | await p.click('#mind-playstop'); |
| 123 | ok('▶ enciende: el botón pasa a «pausar»', /pausar/.test(await p.locator('#mind-playstop').innerText())); |
| 124 | await p.click('#mind-playstop'); |
| 125 | ok('⏸ pausa: «reanudar»', await hasta(async () => /reanudar/.test(await p.locator('#mind-playstop').innerText()))); |
| 126 | await p.click('#mind-config'); |
| 127 | await p.click('#cfg-save'); |
| 128 | const trasGuardar = await p.evaluate(async () => ({ on: (await import('/js/ceo.js')).isEnabled(), txt: document.getElementById('mind-playstop').textContent })); |
| 129 | ok('«Reprogramar» no enciende un cerebro pausado (y el botón sigue diciendo «reanudar»)', !trasGuardar.on && /reanudar/.test(trasGuardar.txt), JSON.stringify(trasGuardar)); |
| 130 | await p.evaluate(async () => (await import('/js/ceo.js')).enable()); |
| 131 | ok('si se enciende por otro lado, el botón se repinta solo', await hasta(async () => /pausar/.test(await p.locator('#mind-playstop').innerText()))); |
| 132 | await p.evaluate(async () => (await import('/js/ceo.js')).disable()); |
| 133 | const leyenda = await p.evaluate(() => [...document.querySelectorAll('#mind-legend .ml-item')].every(e => e.tagName === 'BUTTON')); |
| 134 | ok('la leyenda de perfiles son botones', leyenda); |
| 135 | await p.click('#mind-close'); |
| 136 | |
| 137 | // ── un ciclo de verdad (proveedor de prueba): solo lectura + propuesta ────── |
| 138 | await p.evaluate(async () => { |
| 139 | const ceo = await import('/js/ceo.js'); |
| 140 | window.__llamadas = []; |
| 141 | // solo el proveedor: el onEvent sigue siendo el del kernel (chat, historial…) |
| 142 | ceo.init({ |
| 143 | provider: () => ({ |
| 144 | chat: async (history) => { |
| 145 | const last = history[history.length - 1].content; |
| 146 | window.__llamadas.push(last.slice(0, 40)); |
| 147 | if (last.startsWith('[resultado app.create]')) { window.__bloqueado = last; return 'Propuesta de productividad: agrupar las apps de reloj y notas en un panel único que se abra al entrar, con atajos.'; } |
| 148 | if (last.startsWith('[resultado fs.read]')) return 'Propuesta basada en lo leído (' + (/NOTA-LEIDA-7731/.test(last) ? 'NOTA-LEIDA-7731' : 'nada') + '): ordenar el README por secciones y añadir un índice al principio.'; |
| 149 | if (/jefe de Productividad/.test(last)) return '```tool\n{"tool":"app.create","args":{"name":"boceto","html":"<h1>x</h1>"}}\n```'; |
| 150 | if (/jefe de Organización/.test(last)) return '```tool\n{"tool":"fs.read","args":{"path":"README.md"}}\n```'; |
| 151 | return 'Propuesta de memoria: recordar que el usuario trabaja con documentos en Markdown y prefiere índices claros.'; |
| 152 | }, |
| 153 | }), |
| 154 | }); |
| 155 | window.__permNotif = 'granted'; |
| 156 | const t0 = Date.now(); |
| 157 | while (!ceo.isThisTabLeader() && Date.now() - t0 < 5000) await new Promise(r => setTimeout(r, 100)); |
| 158 | window.__ciclo = await ceo.forceCycle(); |
| 159 | }); |
| 160 | ok('el ciclo corre', await p.evaluate(() => window.__ciclo === true)); |
| 161 | ok('el cerebro NO puede crear apps: su app.create recibe un error y no se crea nada', |
| 162 | /solo puedes leer/.test(await p.evaluate(() => window.__bloqueado || '')) && (await p.evaluate(async () => (await (await import('/js/db.js')).all('apps')).length)) === 0); |
| 163 | ok('…pero sí leer la carpeta (fs.read)', /NOTA-LEIDA-7731/.test(await p.locator('#log').innerText())); |
| 164 | const msg = p.locator('#log .msg.assistant', { hasText: 'Revisé tu espacio' }).last(); |
| 165 | ok('la propuesta llega al chat sin decir «mientras estabas fuera»', await msg.count() === 1 && !/Mientras estabas fuera/.test(await msg.innerText())); |
| 166 | const hist2 = await kv(p, 'history'); |
| 167 | ok('y se guarda en el historial con su propuesta', Array.isArray(hist2) && hist2.some(m => m.propuesta?.path?.includes('.elffuss/soul/'))); |
| 168 | const n = await p.evaluate(() => window.__notifs.map(x => x.title)); |
| 169 | ok('se notifica (permiso ya concedido)', n.length === 1, JSON.stringify(n)); |
| 170 | |
| 171 | // ── sin el permiso «Archivos», el cerebro ocioso NO saca diálogos de permiso ─ |
| 172 | // (antes isReady solo miraba si había carpetas, y el ciclo pasaba por fs.root(), |
| 173 | // que pide el permiso: «📁 Permiso: Archivos» con el usuario fuera) |
| 174 | await p.evaluate(async () => (await import('/js/permissions.js')).revoke('fs')); |
| 175 | const sinPermiso = await p.evaluate(async () => { |
| 176 | const ceo = await import('/js/ceo.js'); |
| 177 | const r = await Promise.race([ceo.forceCycle(), new Promise(res => setTimeout(() => res('colgado'), 4000))]); |
| 178 | return { r, dialogo: document.getElementById('perm-dialog').open }; |
| 179 | }); |
| 180 | ok('sin el permiso «Archivos» el ciclo no arranca y no pide nada', sinPermiso.r === false && !sinPermiso.dialogo, JSON.stringify(sinPermiso)); |
| 181 | if (sinPermiso.dialogo) await p.click('#perm-deny'); |
| 182 | await p.evaluate(async () => { // volver a concederlo para lo que sigue |
| 183 | const perms = await import('/js/permissions.js'); |
| 184 | perms.setAsker(async () => true); |
| 185 | await perms.require('fs'); |
| 186 | perms.setAsker((await import('/js/ui.js')).askPermission); |
| 187 | }); |
| 188 | await p.evaluate(() => window.__notifs[0].onclick()); |
| 189 | ok('pulsar la notificación abre la Mente en la propuesta', await hasta(() => p.evaluate(() => |
| 190 | document.getElementById('mind-overlay').style.display !== 'none' && document.getElementById('mind-panel').classList.contains('show')))); |
| 191 | const etiqueta = p.locator('.mind-node-label').first(); |
| 192 | ok('las etiquetas de propuesta son botones con clic propio', await etiqueta.evaluate(e => e.tagName === 'BUTTON' && getComputedStyle(e).pointerEvents === 'auto')); |
| 193 | await p.evaluate(() => document.getElementById('mind-panel').classList.remove('show')); |
| 194 | const caja = await etiqueta.boundingBox(); |
| 195 | await p.mouse.click(caja.x + 3, caja.y + caja.height / 2); // el borde, no el centro |
| 196 | ok('…y un clic en el BORDE de la etiqueta abre la propuesta', await hasta(() => p.evaluate(() => document.getElementById('mind-panel').classList.contains('show')))); |
| 197 | ok('el botón del fichero se llama «Ver el fichero»', (await p.locator('#mp-open').innerText()) === 'Ver el fichero'); |
| 198 | await p.click('#mp-open'); |
| 199 | ok('«Ver el fichero» cierra la Mente y lo lee en el chat', await hasta(async () => |
| 200 | await p.evaluate(() => document.getElementById('mind-overlay').style.display === 'none') |
| 201 | && /Propuestas de mejora/.test(await p.locator('#log').innerText()))); |
| 202 | |
| 203 | // ── en Básico no hay «Ejecutar»: se dice ya que hace falta un modelo ──────── |
| 204 | // (antes el botón estaba y solo al pulsarlo explicaba que no podía) |
| 205 | const antes = await p.locator('#log .msg.user').count(); |
| 206 | const enChat = await msg.evaluate(m => { |
| 207 | const b = m.querySelector('.proposal-exec-btn'), pista = m.querySelector('.proposal-needs-model'); |
| 208 | return { boton: !!b && b.getClientRects().length === 0, pista: !!pista && pista.getClientRects().length > 0 && /hace falta un modelo/.test(pista.textContent) }; |
| 209 | }); |
| 210 | ok('en Básico «Ejecutar» no se enseña: en su sitio dice que hace falta un modelo', enChat.boton && enChat.pista, JSON.stringify(enChat)); |
| 211 | await msg.locator('.proposal-needs-model button').click(); |
| 212 | ok('…y su «Elegir modelo» lleva al selector sin mandar nada', await hasta(() => p.evaluate(() => document.activeElement?.id === 'model-select')) |
| 213 | && await p.locator('#log .msg.user').count() === antes); |
| 214 | |
| 215 | // ── tras recargar: el aviso vuelve con su botón, y la Mente con su etiqueta ─ |
| 216 | await p.reload({ waitUntil: 'domcontentloaded' }); |
| 217 | await p.waitForFunction(() => !!window.elffuss?.agent); |
| 218 | ok('tras recargar, el aviso del cerebro sigue en el chat con su botón', await hasta(async () => |
| 219 | await p.locator('#log .msg.assistant', { hasText: 'Revisé tu espacio' }).locator('.proposal-exec-btn').count() === 1)); |
| 220 | const enlace = p.locator('#log .msg.assistant', { hasText: 'Revisé tu espacio' }).locator('a[href^="#/mente/"]'); |
| 221 | ok('el aviso enlaza a la propuesta en la Mente', await enlace.count() === 1); |
| 222 | await enlace.click(); |
| 223 | ok('el enlace abre la Mente en esa propuesta (la etiqueta volvió de la carpeta)', await hasta(() => p.evaluate(() => |
| 224 | document.getElementById('mind-panel')?.classList.contains('show') && document.querySelectorAll('.mind-node-label').length > 0), { veces: 300 })); |
| 225 | if (OUT) await p.screenshot({ path: OUT + '/ux-mente.png' }); |
| 226 | |
| 227 | // ── «▶ Ejecutar» DENTRO de la Mente, en Básico: tampoco está ───────────────── |
| 228 | // (antes solo el botón del chat lo comprobaba; el de la Mente mandaba la |
| 229 | // propuesta al motor de reglas, que creaba apps con lo que encontrara) |
| 230 | const enMente = await p.evaluate(() => ({ |
| 231 | exec: document.getElementById('mp-exec')?.getClientRects().length === 0, |
| 232 | pista: (document.getElementById('mp-pick')?.getClientRects().length || 0) > 0, |
| 233 | foco: document.activeElement?.id, |
| 234 | })); |
| 235 | ok('en Básico la Mente no enseña «▶ Ejecutar»: dice que hace falta un modelo y el foco va a «Elegir modelo»', |
| 236 | enMente.exec && enMente.pista && enMente.foco === 'mp-pick', JSON.stringify(enMente)); |
| 237 | // Los avisos se ven y se pulsan con la Mente abierta (antes quedaban detrás e |
| 238 | // inertes): uno con acción, como los que saltan con ella abierta (una tarea que |
| 239 | // se dispara con su «Ver», la bóveda que se cierra sola…). |
| 240 | await p.evaluate(async () => { |
| 241 | window.__accion = 0; |
| 242 | (await import('/js/ui.js')).toast('Aviso de prueba con la Mente abierta', { accion: { label: 'Hacer', run: () => { window.__accion++; } } }); |
| 243 | }); |
| 244 | const aviso = p.locator('#toasts .toast', { hasText: 'Aviso de prueba' }).last(); |
| 245 | const visible = !(await aviso.count()) ? { encima: false, falta: true } : await aviso.evaluate(el => { |
| 246 | const r = el.getBoundingClientRect(); |
| 247 | const arriba = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); |
| 248 | return { encima: el.contains(arriba), inerte: document.getElementById('toasts').inert }; |
| 249 | }); |
| 250 | ok('un aviso se ve ENCIMA de la Mente y no está inerte', visible.encima && !visible.inerte, JSON.stringify(visible)); |
| 251 | await aviso.locator('.toast-accion').click({ timeout: 5000 }).catch(() => {}); |
| 252 | ok('…y su acción se puede pulsar con la Mente abierta', await hasta(() => p.evaluate(() => window.__accion === 1))); |
| 253 | await p.click('#mp-pick', { timeout: 5000 }).catch(() => {}); |
| 254 | ok('«Elegir modelo» de la Mente la cierra y enfoca el selector, sin mandar nada', await hasta(() => p.evaluate(() => |
| 255 | document.getElementById('mind-overlay').style.display === 'none' && document.activeElement?.id === 'model-select')) |
| 256 | && await p.locator('#log .msg.user').count() === antes); |
| 257 | |
| 258 | // ── cerrar la Mente devuelve la URL a la pestaña; el mismo enlace vuelve a abrir ─ |
| 259 | ok('cerrar la Mente quita #/mente/… de la URL', await hasta(() => p.evaluate(() => !location.hash.startsWith('#/mente'))), |
| 260 | await p.evaluate(() => location.hash)); |
| 261 | await p.keyboard.press('Escape'); // por si la Mente siguiera abierta |
| 262 | await enlace.click({ timeout: 5000 }).catch(() => {}); |
| 263 | ok('pulsar OTRA VEZ el mismo enlace vuelve a abrir la Mente', await hasta(() => p.evaluate(() => |
| 264 | document.getElementById('mind-overlay').style.display !== 'none' && document.getElementById('mind-panel').classList.contains('show')), { veces: 300 })); |
| 265 | await p.keyboard.press('Escape'); // primero el panel de la propuesta |
| 266 | await p.keyboard.press('Escape'); // luego la Mente |
| 267 | ok('…y Escape la cierra con la URL limpia', await hasta(() => p.evaluate(() => |
| 268 | document.getElementById('mind-overlay').style.display === 'none' && !location.hash.startsWith('#/mente')))); |
| 269 | await p.click('#tabs button[data-tab="apps"]', { timeout: 5000 }).catch(() => {}); |
| 270 | await enlace.click({ timeout: 5000 }).catch(() => {}); |
| 271 | await hasta(() => p.evaluate(() => document.getElementById('mind-overlay').style.display !== 'none')); |
| 272 | await p.goBack(); |
| 273 | ok('«Atrás» con la Mente abierta la cierra y vuelve a Apps', await hasta(() => p.evaluate(() => |
| 274 | document.getElementById('mind-overlay').style.display === 'none' && location.hash === '#/apps'))); |
| 275 | |
| 276 | // ── abrir la PÁGINA en #/mente/<ruta> abre la Mente (antes: error de TDZ) ─── |
| 277 | const ruta = await enlace.getAttribute('href'); |
| 278 | const erroresAntes = errores.length; |
| 279 | // Carga de verdad (desde otra página): un goto que solo cambia el fragmento no recarga. |
| 280 | const cargarEn = async h => { |
| 281 | await p.goto('about:blank'); |
| 282 | await p.goto(BASE + '/' + h, { waitUntil: 'domcontentloaded' }); |
| 283 | await p.waitForFunction(() => !!window.elffuss?.agent); |
| 284 | }; |
| 285 | await cargarEn(ruta); |
| 286 | ok('cargar la página en #/mente/<ruta> abre la Mente en esa propuesta', await hasta(() => p.evaluate(() => |
| 287 | !!document.getElementById('mind-overlay') && document.getElementById('mind-overlay').style.display !== 'none' |
| 288 | && document.getElementById('mind-panel').classList.contains('show')), { veces: 300 })); |
| 289 | const avisosCarga = await p.evaluate(() => window.__avisos); |
| 290 | ok('…sin el aviso «No he podido abrir la Mente»', !avisosCarga.some(t => /No he podido abrir la Mente|before initialization/.test(t)), |
| 291 | JSON.stringify(avisosCarga)); |
| 292 | await cargarEn('#/mente/' + encodeURIComponent('.elffuss/soul/no-existe.md')); |
| 293 | ok('una propuesta que no existe abre la Mente y lo dice en un aviso visible', await hasta(async () => |
| 294 | await p.evaluate(() => !!document.getElementById('mind-overlay') && document.getElementById('mind-overlay').style.display !== 'none') |
| 295 | && (await avisos(p)).some(t => /No encuentro esa propuesta/.test(t)), { veces: 300 })); |
| 296 | const x = p.locator('#toasts .toast', { hasText: 'No encuentro esa propuesta' }).locator('.toast-x'); |
| 297 | await x.click({ timeout: 5000 }).catch(() => {}); |
| 298 | ok('…y su ✕ se puede pulsar con la Mente abierta', await hasta(async () => |
| 299 | !(await avisos(p)).some(t => /No encuentro esa propuesta/.test(t)))); |
| 300 | await cargarEn('#/mente'); |
| 301 | ok('cargar la página en #/mente abre la Mente', await hasta(() => p.evaluate(() => |
| 302 | !!document.getElementById('mind-overlay') && document.getElementById('mind-overlay').style.display !== 'none'), { veces: 300 })); |
| 303 | ok('ninguna carga en #/mente dejó errores de página', errores.length === erroresAntes, errores.slice(erroresAntes).join(' | ')); |
| 304 | |
| 305 | // ── la clave vieja del cerebro (la escribía el primer clic en 🧠) no lo enciende ─ |
| 306 | { |
| 307 | const { ctx: c2 } = await contexto(b, { extraInit: { 'elffuss.ceoEnabled': '1' } }); |
| 308 | const { p: q } = await pagina(c2); |
| 309 | const viejo = await q.evaluate(async () => ({ on: (await import('/js/ceo.js')).isEnabled(), vieja: localStorage.getItem('elffuss.ceoEnabled'), decidido: (await import('/js/ceo.js')).hasDecided() })); |
| 310 | ok('con la clave vieja (ceoEnabled=1) el cerebro NO se enciende al cargar, y la clave se borra', !viejo.on && viejo.vieja === null && !viejo.decidido, JSON.stringify(viejo)); |
| 311 | await c2.close(); |
| 312 | const { ctx: c3 } = await contexto(b, { extraInit: { 'elffuss.ceoDecision': 'on' } }); |
| 313 | const { p: r } = await pagina(c3); |
| 314 | ok('con un ▶ de verdad (ceoDecision=on) sí vuelve encendido', await hasta(() => r.evaluate(async () => (await import('/js/ceo.js')).isEnabled()))); |
| 315 | await c3.close(); |
| 316 | } |
| 317 | |
| 318 | // ── con modelo y carpeta pero sin «Archivos»: «Pensar ahora» dice por qué ─── |
| 319 | { |
| 320 | const srv = createServer((req, res) => { |
| 321 | const c = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'content-type, authorization' }; |
| 322 | if (req.method === 'OPTIONS') { res.writeHead(204, c); res.end(); return; } |
| 323 | req.resume(); |
| 324 | req.on('end', () => { res.writeHead(200, { ...c, 'Content-Type': 'text/event-stream' }); res.write('data: {"choices":[{"delta":{"content":"ok"}}]}\n\ndata: [DONE]\n\n'); res.end(); }); |
| 325 | }); |
| 326 | await new Promise(r => srv.listen(0, '127.0.0.1', r)); |
| 327 | const { ctx: c4 } = await contexto(b, { model: 'ext:ollama', grants: ['apps'], |
| 328 | extraInit: { 'elffuss.providers': JSON.stringify({ ollama: { enabled: true, baseURL: `http://127.0.0.1:${srv.address().port}/v1`, model: 'falso', apiKey: 'ollama' } }) } }); |
| 329 | const { p: q } = await pagina(c4); |
| 330 | await hasta(() => q.evaluate(() => document.getElementById('model-status').classList.contains('on'))); |
| 331 | await q.evaluate(async () => (await import('/js/db.js')).set('fs', 'proyecto', await navigator.storage.getDirectory())); |
| 332 | await q.click('#btn-mind'); |
| 333 | await hasta(() => q.evaluate(() => !!document.getElementById('mind-overlay') && document.getElementById('mind-overlay').style.display !== 'none'), { veces: 300 }); |
| 334 | await q.click('#mind-config'); |
| 335 | await q.click('#cfg-think-now'); |
| 336 | ok('con modelo y carpeta pero sin «Archivos», «Pensar ahora» lo dice y no saca el diálogo', await hasta(async () => |
| 337 | /permiso «Archivos»/.test(await q.locator('#cfg-status').innerText())) && !(await q.evaluate(() => document.getElementById('perm-dialog').open)), |
| 338 | await q.locator('#cfg-status').innerText()); |
| 339 | await c4.close(); |
| 340 | srv.close(); |
| 341 | } |
| 342 | |
| 343 | ok('sin errores de página', errores.length === 0, errores.slice(0, 3).join(' | ')); |
| 344 | await fin(b, 'MENTE: abrir no enciende, modal, historial completo, solo lectura, propuestas que se guardan y se enlazan'); |