utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | 2e2bee2926089b31a1f21a6cd5124e668ed9bcc45e642a2d42f9e8fa2daff238 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00 |
| Parents | 8596c12fa009 |
5 files changed
added tests/notif-run.mjs +95 −0
| @@ -0,0 +1,95 @@ | ||
| 1 | +// «▶ Ejecutar» en una notificación con la app CERRADA: el IDE se abre con | |
| 2 | +// ?notif=execute&id=… (sw.js guardó la propuesta en Cache Storage con ese id) y | |
| 3 | +// la propuesta se manda en cuanto hay un modelo de verdad cargado. Antes la | |
| 4 | +// ventana nueva no recibía la propuesta: abría la Mente y no ejecutaba nada, | |
| 5 | +// sin decirlo. (La parte del service worker la prueba tests/sw-notif.mjs.) | |
| 6 | +// | |
| 7 | +// 1. Con un modelo que carga (transformers.js de mentira): la propuesta sale | |
| 8 | +// sola cuando está listo, y la guardada se borra. | |
| 9 | +// 2. En modo Básico no se gasta con el motor de reglas: se dice que espera a | |
| 10 | +// un modelo, y sale al elegir uno. | |
| 11 | +// 3. Si la propuesta ya no está: se dice y se abre la Mente. | |
| 12 | +// | |
| 13 | +// BASE=http://localhost:8799 node tests/notif-run.mjs | |
| 14 | +import { chromium } from 'playwright'; | |
| 15 | +const BASE = process.env.BASE || 'http://localhost:8799'; | |
| 16 | +let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; | |
| 17 | + | |
| 18 | +const FALSO_TF = ` | |
| 19 | +export const env = {}; | |
| 20 | +export class TextStreamer { constructor(t, o) { this.o = o; } } | |
| 21 | +export class InterruptableStoppingCriteria { interrupt() {} } | |
| 22 | +export async function pipeline() { | |
| 23 | + const g = async (messages) => { (window.__recibido ||= []).push(messages.at(-1)?.content || ''); return [{ generated_text: 'hecho' }]; }; | |
| 24 | + g.tokenizer = {}; g.dispose = () => {}; | |
| 25 | + return g; | |
| 26 | +}`; | |
| 27 | +const MD = '# Propuestas de mejora — ciclo 7\n\n## Calidad\nAñadir pruebas a app.js'; | |
| 28 | +const b = await chromium.launch(); | |
| 29 | +const errs = []; | |
| 30 | + | |
| 31 | +async function abre({ modelo, sembrar = true, id = 'abc123def' }) { | |
| 32 | + const ctx = await b.newContext({ locale: 'es-ES' }); | |
| 33 | + await ctx.addInitScript(m => { | |
| 34 | + try { Object.defineProperty(Navigator.prototype, 'gpu', { get() { return undefined; }, configurable: true }); } catch { /* */ } | |
| 35 | + try { localStorage.setItem('elffusscode.model', m); } catch { /* */ } | |
| 36 | + }, modelo); | |
| 37 | + const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } }); | |
| 38 | + p.on('pageerror', e => errs.push(e.message.slice(0, 160))); | |
| 39 | + await p.route(/cdn\.jsdelivr\.net\/npm\/@huggingface\/transformers@4/, r => r.fulfill({ status: 200, contentType: 'text/javascript', body: FALSO_TF })); | |
| 40 | + await p.goto(BASE + '/manifest.json'); | |
| 41 | + if (sembrar) await p.evaluate(async ({ id, md }) => { await (await caches.open('elffuss-notif')).put('./notif/' + id, new Response(md)); }, { id, md: MD }); | |
| 42 | + await p.goto(BASE + `/?test-opfs¬if=execute&id=${id}`, { waitUntil: 'domcontentloaded' }); | |
| 43 | + await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.(), null, { timeout: 20000 }); | |
| 44 | + return { ctx, p }; | |
| 45 | +} | |
| 46 | +const estado = p => p.evaluate(async () => ({ | |
| 47 | + url: location.search, | |
| 48 | + usuario: [...document.querySelectorAll('#chat-log .msg.user')].map(n => n.textContent.slice(0, 60)), | |
| 49 | + sistema: [...document.querySelectorAll('#chat-log .msg.sys')].map(n => n.textContent).join(' | '), | |
| 50 | + recibido: window.__recibido || [], | |
| 51 | + guardada: await (await caches.open('elffuss-notif')).match('./notif/abc123def').then(r => !!r), | |
| 52 | + mente: !!document.getElementById('mind-overlay') && getComputedStyle(document.getElementById('mind-overlay')).display !== 'none', | |
| 53 | +})); | |
| 54 | + | |
| 55 | +// 1 · con un modelo que carga | |
| 56 | +{ | |
| 57 | + const { ctx, p } = await abre({ modelo: 'onnx:qwen3.5-0.8b' }); | |
| 58 | + await p.waitForFunction(() => (window.__recibido || []).length > 0, null, { timeout: 20000 }).catch(() => {}); | |
| 59 | + await p.waitForFunction(() => !window.elffussClaw.conv.isBusy(), null, { timeout: 10000 }).catch(() => {}); | |
| 60 | + const e = await estado(p); | |
| 61 | + ok('1 · la propuesta de la notificación se manda sola en cuanto el modelo está listo', e.usuario.some(u => /Implementa esta propuesta/.test(u)) && e.recibido.some(r => /Añadir pruebas a app\.js/.test(r)), JSON.stringify({ usuario: e.usuario, recibido: e.recibido.length })); | |
| 62 | + ok('1 · …una sola vez', e.usuario.filter(u => /Implementa esta propuesta/.test(u)).length === 1, JSON.stringify(e.usuario)); | |
| 63 | + ok('1 · …la guardada se borra y la URL queda limpia', !e.guardada && !/notif|id=/.test(e.url), JSON.stringify({ guardada: e.guardada, url: e.url })); | |
| 64 | + await ctx.close(); | |
| 65 | +} | |
| 66 | + | |
| 67 | +// 2 · modo Básico: espera a un modelo y no se gasta con las reglas | |
| 68 | +{ | |
| 69 | + const { ctx, p } = await abre({ modelo: 'rules' }); | |
| 70 | + await p.waitForTimeout(800); | |
| 71 | + const e = await estado(p); | |
| 72 | + ok('2 · en modo Básico no se manda (se gastaría con el motor de reglas)', !e.usuario.some(u => /Implementa esta propuesta/.test(u)), JSON.stringify(e.usuario)); | |
| 73 | + ok('2 · …y se dice que espera a un modelo', /se ejecuta en cuanto haya un modelo cargado/.test(e.sistema), e.sistema.slice(0, 200)); | |
| 74 | + await p.click('#btn-settings'); | |
| 75 | + await p.locator('.model-card[data-model="onnx:qwen3.5-0.8b"]').click(); | |
| 76 | + await p.waitForFunction(() => (window.__recibido || []).length > 0, null, { timeout: 20000 }).catch(() => {}); | |
| 77 | + const e2 = await estado(p); | |
| 78 | + ok('2 · al elegir un modelo, sale', e2.recibido.some(r => /Añadir pruebas a app\.js/.test(r)), JSON.stringify(e2.recibido.length)); | |
| 79 | + await ctx.close(); | |
| 80 | +} | |
| 81 | + | |
| 82 | +// 3 · la propuesta ya no está | |
| 83 | +{ | |
| 84 | + const { ctx, p } = await abre({ modelo: 'rules', sembrar: false }); | |
| 85 | + await p.waitForTimeout(800); | |
| 86 | + const e = await estado(p); | |
| 87 | + ok('3 · sin la propuesta guardada lo dice y abre la Mente', /No encuentro la propuesta/.test(e.sistema) && e.mente, JSON.stringify({ sistema: e.sistema.slice(0, 120), mente: e.mente })); | |
| 88 | + await ctx.close(); | |
| 89 | +} | |
| 90 | + | |
| 91 | +console.log('\n errores JS:', errs[0] || 'ninguno'); | |
| 92 | +ok('sin errores de página', errs.length === 0, errs.join(' | ')); | |
| 93 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ NOTIFICACIÓN «▶ Ejecutar» CON LA APP CERRADA: la propuesta llega y sale'); | |
| 94 | +await b.close(); | |
| 95 | +process.exit(fails ? 1 : 0); |
added tests/sw-notif.mjs +77 −0
| @@ -0,0 +1,77 @@ | ||
| 1 | +// El service worker (web/sw.js) al pulsar una notificación, en Node: se carga | |
| 2 | +// en una sandbox con self, clients y caches de mentira y se le dispara el | |
| 3 | +// evento `notificationclick`. | |
| 4 | +// | |
| 5 | +// 1. «▶ Ejecutar» con la app cerrada: guarda la propuesta en Cache Storage y | |
| 6 | +// abre el IDE con su id en la URL (antes abría ?notif=execute sin la | |
| 7 | +// propuesta, y no se ejecutaba nada). | |
| 8 | +// 2. Con el IDE abierto: le manda la propuesta a esa ventana, sin abrir otra. | |
| 9 | +// 3. Con solo el Lab abierto: el Lab no es el IDE, se abre el IDE. | |
| 10 | +// 4. «Ver»: abre el IDE para ver la Mente, sin guardar nada. | |
| 11 | +// | |
| 12 | +// node tests/sw-notif.mjs | |
| 13 | +import { readFileSync } from 'node:fs'; | |
| 14 | +import { join, dirname } from 'node:path'; | |
| 15 | +import { fileURLToPath } from 'node:url'; | |
| 16 | +import vm from 'node:vm'; | |
| 17 | +const SW = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'web', 'sw.js'), 'utf8'); | |
| 18 | +let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; | |
| 19 | + | |
| 20 | +function sandbox(ventanas = []) { | |
| 21 | + const handlers = {}; | |
| 22 | + const guardado = new Map(); | |
| 23 | + const abiertas = []; | |
| 24 | + const self = { | |
| 25 | + addEventListener: (tipo, fn) => { handlers[tipo] = fn; }, | |
| 26 | + skipWaiting() {}, clients: { | |
| 27 | + async matchAll() { return ventanas; }, | |
| 28 | + async openWindow(u) { abiertas.push(u); return {}; }, | |
| 29 | + claim() {}, | |
| 30 | + }, | |
| 31 | + }; | |
| 32 | + const caches = { async open(nombre) { return { async put(k, r) { guardado.set(nombre + '|' + k, await r.text()); } }; }, async delete() {} }; | |
| 33 | + const ctx = vm.createContext({ self, caches, Response: globalThis.Response, URL, console }); | |
| 34 | + vm.runInContext(SW, ctx); | |
| 35 | + const clic = async (action, data) => { | |
| 36 | + let espera = null; | |
| 37 | + handlers.notificationclick({ action, notification: { data, close() {} }, waitUntil(p) { espera = p; } }); | |
| 38 | + await espera; | |
| 39 | + }; | |
| 40 | + return { clic, guardado, abiertas }; | |
| 41 | +} | |
| 42 | +const ventana = url => { const v = { url, mensajes: [], enfocada: false, postMessage(m) { v.mensajes.push(m); }, focus() { v.enfocada = true; } }; return v; }; | |
| 43 | + | |
| 44 | +// 1 · ▶ Ejecutar con la app cerrada | |
| 45 | +{ | |
| 46 | + const s = sandbox([]); | |
| 47 | + await s.clic('execute', { md: '# Propuesta\nhaz pruebas' }); | |
| 48 | + const url = s.abiertas[0] || ''; | |
| 49 | + const id = (/[?&]id=([a-z0-9]+)/.exec(url) || [])[1]; | |
| 50 | + ok('1 · ▶ Ejecutar con la app cerrada abre el IDE con la acción y un id', /^\.\/\?notif=execute&id=[a-z0-9]+$/.test(url), url); | |
| 51 | + ok('1 · …y la propuesta queda guardada bajo ese id', s.guardado.get('elffuss-notif|./notif/' + id) === '# Propuesta\nhaz pruebas', JSON.stringify([...s.guardado])); | |
| 52 | + ok('1 · …y no va en la URL', !/Propuesta|pruebas/.test(url), url); | |
| 53 | +} | |
| 54 | +// 2 · con el IDE abierto | |
| 55 | +{ | |
| 56 | + const ide = ventana('https://code.example/?x'); | |
| 57 | + const s = sandbox([ide]); | |
| 58 | + await s.clic('execute', { md: '# P' }); | |
| 59 | + ok('2 · con el IDE abierto le manda la propuesta a esa ventana y la enfoca', ide.mensajes[0]?.type === 'notif-action' && ide.mensajes[0]?.md === '# P' && ide.enfocada, JSON.stringify(ide.mensajes)); | |
| 60 | + ok('2 · …sin abrir otra ni guardar nada', s.abiertas.length === 0 && s.guardado.size === 0, JSON.stringify(s.abiertas)); | |
| 61 | +} | |
| 62 | +// 3 · solo el Lab abierto | |
| 63 | +{ | |
| 64 | + const lab = ventana('https://code.example/lab.html'); | |
| 65 | + const s = sandbox([lab]); | |
| 66 | + await s.clic('execute', { md: '# P' }); | |
| 67 | + ok('3 · con solo el Lab abierto, abre el IDE (el Lab no lo ejecutaría)', lab.mensajes.length === 0 && /^\.\/\?notif=execute&id=/.test(s.abiertas[0] || ''), JSON.stringify(s.abiertas)); | |
| 68 | +} | |
| 69 | +// 4 · Ver | |
| 70 | +{ | |
| 71 | + const s = sandbox([]); | |
| 72 | + await s.clic('open', { md: '# P' }); | |
| 73 | + ok('4 · «Ver» abre el IDE para la Mente y no guarda nada', s.abiertas[0] === './?notif=open' && s.guardado.size === 0, JSON.stringify(s.abiertas)); | |
| 74 | +} | |
| 75 | + | |
| 76 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ NOTIFICACIONES: ▶ Ejecutar llega con la propuesta, también con la app cerrada'); | |
| 77 | +process.exit(fails ? 1 : 0); |
modified web/js/i18n.js +4 −0
| @@ -46,6 +46,8 @@ | ||
| 46 | 46 | mTerminal: 'Terminal', mArch: 'Arquitectura', mAbout: 'Acerca de Elffuss Code (GitHub)', |
| 47 | 47 | gNotRepo: 'No es un repositorio git', gBranch: 'Rama: {b}', gLast: 'Último: {m}', gCommit: 'Redactar el mensaje de commit', |
| 48 | 48 | nExec: '▶ Ejecutar', nView: 'Ver en la Mente', |
| 49 | + notifExecWaiting: '▶ La propuesta de la notificación se ejecuta en cuanto haya un modelo cargado (en modo Básico no: elige uno en ⚙️ Ajustes → Cerebro).', | |
| 50 | + notifExecLost: 'No encuentro la propuesta de la notificación (quizá ya se ejecutó en otra ventana): te abro la Mente, donde están todas.', | |
| 49 | 51 | fallbackToast: 'Ese Gemma no cargó (memoria/GPU) — uso el ligero…', |
| 50 | 52 | setStoreTitle: 'Modelo descargado (se cachea en tu navegador)', setClear: 'Vaciar caché', setClearing: 'Vaciando…', |
| 51 | 53 | setCached: '{gb} en modelos guardados', setNone: 'Ningún modelo guardado todavía', |
| @@ -275,6 +277,8 @@ | ||
| 275 | 277 | mTerminal: 'Terminal', mArch: 'Architecture', mAbout: 'About Elffuss Code (GitHub)', |
| 276 | 278 | gNotRepo: 'Not a git repository', gBranch: 'Branch: {b}', gLast: 'Latest: {m}', gCommit: 'Draft the commit message', |
| 277 | 279 | nExec: '▶ Run', nView: 'View in the Mind', |
| 280 | + notifExecWaiting: '▶ The proposal from the notification runs as soon as a model is loaded (not in Basic mode: pick one in ⚙️ Settings → Brain).', | |
| 281 | + notifExecLost: "I can't find the proposal from the notification (maybe it already ran in another window): opening the Mind, where they all are.", | |
| 278 | 282 | fallbackToast: 'That Gemma didn’t load (memory/GPU) — using the light one…', |
| 279 | 283 | setStoreTitle: 'Downloaded model (cached in your browser)', setClear: 'Clear cache', setClearing: 'Clearing…', |
| 280 | 284 | setCached: '{gb} of stored models', setNone: 'No model stored yet', |
modified web/js/main.js +36 −4
| @@ -845,6 +845,9 @@ | ||
| 845 | 845 | `Escribe otra cosa para seguir, o vuelve a enviarlo si quieres insistir.`); |
| 846 | 846 | conv.descartarPendiente(convId); |
| 847 | 847 | }); |
| 848 | + // La propuesta de una notificación que esperaba a que hubiera modelo. | |
| 849 | + // (activeModel aún no es este: se pone justo debajo; por eso el `id`.) | |
| 850 | + queueMicrotask(() => ejecutaPropuestaDeAviso()); | |
| 848 | 851 | // El medidor de contexto pasa a hablar del modelo QUE ESTÁ CARGADO. Quien no |
| 849 | 852 | // sepa decir su contexto deja el valor de reserva, así que esto no puede |
| 850 | 853 | // romper a un proveedor que no lo implemente. |
| @@ -1369,14 +1372,33 @@ | ||
| 1369 | 1372 | renderActiveLog(); |
| 1370 | 1373 | addMsg('sys', t('welcome', { name })); |
| 1371 | 1374 | abreDesdeHash(); |
| 1372 | - // Abierto desde una notificación con la app cerrada (sw.js → ?notif=…): | |
| 1373 | - // la propuesta está en la Mente, que se abre ya con el proyecto cargado. | |
| 1375 | + // Abierto desde una notificación con la app cerrada (sw.js → ?notif=…). | |
| 1376 | + // «Ver»: la Mente, ya con el proyecto cargado. «▶ Ejecutar»: la propuesta que | |
| 1377 | + // sw.js dejó guardada con un id, que se manda en cuanto haya un modelo de | |
| 1378 | + // verdad (con el de reglas se gastaría sin hacer nada). Antes solo llegaba la | |
| 1379 | + // acción: se abría la Mente y no se ejecutaba nada, sin decirlo. | |
| 1374 | 1380 | try { |
| 1375 | 1381 | const u = new URL(location.href); |
| 1376 | 1382 | if (u.searchParams.has('notif')) { |
| 1377 | - u.searchParams.delete('notif'); | |
| 1383 | + const accion = u.searchParams.get('notif'), id = u.searchParams.get('id'); | |
| 1384 | + u.searchParams.delete('notif'); u.searchParams.delete('id'); | |
| 1378 | 1385 | history.replaceState(null, '', u.pathname + u.search + u.hash); |
| 1379 | - mind.openMind(); | |
| 1386 | + let md = null; | |
| 1387 | + if (accion === 'execute' && id && /^[a-z0-9]{4,40}$/.test(id)) { | |
| 1388 | + try { | |
| 1389 | + const c = await caches.open('elffuss-notif'); | |
| 1390 | + const r = await c.match('./notif/' + id); | |
| 1391 | + if (r) md = await r.text(); | |
| 1392 | + await c.delete('./notif/' + id); | |
| 1393 | + } catch { /* sin Cache Storage */ } | |
| 1394 | + } | |
| 1395 | + if (md) { | |
| 1396 | + propuestaDeAviso = md; | |
| 1397 | + if (!ejecutaPropuestaDeAviso()) addMsg('sys', t('notifExecWaiting')); | |
| 1398 | + } else { | |
| 1399 | + if (accion === 'execute') addMsg('sys', t('notifExecLost')); | |
| 1400 | + mind.openMind(); | |
| 1401 | + } | |
| 1380 | 1402 | } |
| 1381 | 1403 | } catch { /* — */ } |
| 1382 | 1404 | refreshGit(); |
| @@ -1809,6 +1831,16 @@ | ||
| 1809 | 1831 | // manda una propuesta (el .md completo del ciclo) a la MISMA cola/agente real |
| 1810 | 1832 | // del chat — usado tanto por el botón del chat como por el de la notificación. |
| 1811 | 1833 | function executeProposal(md) { send(t('pProposal') + md); } |
| 1834 | +// La de una notificación pulsada con la app cerrada espera aquí a que haya un | |
| 1835 | +// modelo cargado (ver enterIDE y changeModel). Devuelve si salió ya. | |
| 1836 | +let propuestaDeAviso = null; | |
| 1837 | +function ejecutaPropuestaDeAviso() { | |
| 1838 | + if (!propuestaDeAviso || activeModel === 'rules' || loadingId) return false; | |
| 1839 | + const md = propuestaDeAviso; | |
| 1840 | + propuestaDeAviso = null; | |
| 1841 | + executeProposal(md); | |
| 1842 | + return true; | |
| 1843 | +} | |
| 1812 | 1844 | |
| 1813 | 1845 | // Botón REAL para ejecutar la propuesta desde el propio chat. |
| 1814 | 1846 | function botonPropuesta(div, md) { |
modified web/sw.js +15 −1
| @@ -43,10 +43,24 @@ | ||
| 43 | 43 | client.postMessage({ type: 'notif-action', action, md: data.md }); |
| 44 | 44 | client.focus?.(); |
| 45 | 45 | } else if (self.clients.openWindow) { |
| 46 | - await self.clients.openWindow('./?notif=' + (action === 'execute' ? 'execute' : 'open')); | |
| 46 | + let q = 'notif=' + (action === 'execute' ? 'execute' : 'open'); | |
| 47 | + // «▶ Ejecutar» con la app cerrada: la propuesta viaja guardada en Cache | |
| 48 | + // Storage (la ven este SW y la página) y la URL lleva solo su id. Antes la | |
| 49 | + // ventana nueva recibía la acción sin la propuesta: abría la Mente y no | |
| 50 | + // ejecutaba nada, sin decirlo. En la URL entera no va: quedaría en el | |
| 51 | + // historial del navegador. | |
| 52 | + if (action === 'execute' && data.md) { | |
| 53 | + try { | |
| 54 | + const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8); | |
| 55 | + await (await caches.open(NOTIF_CACHE)).put('./notif/' + id, new Response(String(data.md))); | |
| 56 | + q += '&id=' + id; | |
| 57 | + } catch { /* sin guardarla: la página lo dice y abre la Mente */ } | |
| 58 | + } | |
| 59 | + await self.clients.openWindow('./?' + q); | |
| 47 | 60 | } |
| 48 | 61 | })()); |
| 49 | 62 | }); |
| 63 | +const NOTIF_CACHE = 'elffuss-notif'; | |
| 50 | 64 | |
| 51 | 65 | // ── Manejador de `fetch`, añadido para poder INSTALAR el sitio ────────────── |
| 52 | 66 | // Chrome solo ofrece instalar si hay manifiesto Y un service worker con |