Elffuss BraidHub

utopia-ia/elffuss-code public

Notification "Run" with the app closed carries the proposal and runs it once a model is loaded

Pressing "Run" on a CEO notification with no IDE window open opened
./?notif=execute without the proposal, and the IDE treated it like "View":
it showed the Mind, ran nothing and did not say so.

- sw.js keeps the proposal in Cache Storage ('elffuss-notif') under a fresh
  id and opens ./?notif=execute&id=<id>; the proposal itself never goes in the
  URL, where it would stay in the browser history. With an IDE window open it
  is posted to that window, as before, and the Lab does not count as one.
- The IDE takes the proposal by its id when the project opens, deletes it,
  cleans the URL, and sends it as soon as a real model is loaded (now, or when
  changeModel() finishes). With the rules engine it would be spent without
  doing anything, so in Basic mode it waits and says so until a model is
  picked. A missing proposal is reported and the Mind opens.

tests/sw-notif.mjs runs sw.js in a Node sandbox and fires notificationclick:
with the app closed the proposal is stored under the id in the URL; with the
IDE open it goes to that window; with only the Lab open the IDE is opened;
"View" stores nothing. Against the previous sw.js it fails 3 checks.
tests/notif-run.mjs (transformers.js stood in, no model downloaded): the
proposal runs once when the model is ready, its stored copy is deleted and the
URL cleaned; in Basic mode it waits, says so and runs when a model is picked;
a missing proposal is reported and opens the Mind.
Changeset2e2bee2926089b31a1f21a6cd5124e668ed9bcc45e642a2d42f9e8fa2daff238
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00
Parents8596c12fa009

Browse the files at this changeset

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&notif=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 @@
4646 mTerminal: 'Terminal', mArch: 'Arquitectura', mAbout: 'Acerca de Elffuss Code (GitHub)',
4747 gNotRepo: 'No es un repositorio git', gBranch: 'Rama: {b}', gLast: 'Último: {m}', gCommit: 'Redactar el mensaje de commit',
4848 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.',
4951 fallbackToast: 'Ese Gemma no cargó (memoria/GPU) — uso el ligero…',
5052 setStoreTitle: 'Modelo descargado (se cachea en tu navegador)', setClear: 'Vaciar caché', setClearing: 'Vaciando…',
5153 setCached: '{gb} en modelos guardados', setNone: 'Ningún modelo guardado todavía',
@@ -275,6 +277,8 @@
275277 mTerminal: 'Terminal', mArch: 'Architecture', mAbout: 'About Elffuss Code (GitHub)',
276278 gNotRepo: 'Not a git repository', gBranch: 'Branch: {b}', gLast: 'Latest: {m}', gCommit: 'Draft the commit message',
277279 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.",
278282 fallbackToast: 'That Gemma didn’t load (memory/GPU) — using the light one…',
279283 setStoreTitle: 'Downloaded model (cached in your browser)', setClear: 'Clear cache', setClearing: 'Clearing…',
280284 setCached: '{gb} of stored models', setNone: 'No model stored yet',
modified web/js/main.js +36 −4
@@ -845,6 +845,9 @@
845845 `Escribe otra cosa para seguir, o vuelve a enviarlo si quieres insistir.`);
846846 conv.descartarPendiente(convId);
847847 });
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());
848851 // El medidor de contexto pasa a hablar del modelo QUE ESTÁ CARGADO. Quien no
849852 // sepa decir su contexto deja el valor de reserva, así que esto no puede
850853 // romper a un proveedor que no lo implemente.
@@ -1369,14 +1372,33 @@
13691372 renderActiveLog();
13701373 addMsg('sys', t('welcome', { name }));
13711374 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.
13741380 try {
13751381 const u = new URL(location.href);
13761382 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');
13781385 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+ }
13801402 }
13811403 } catch { /* — */ }
13821404 refreshGit();
@@ -1809,6 +1831,16 @@
18091831 // manda una propuesta (el .md completo del ciclo) a la MISMA cola/agente real
18101832 // del chat — usado tanto por el botón del chat como por el de la notificación.
18111833 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+}
18121844
18131845 // Botón REAL para ejecutar la propuesta desde el propio chat.
18141846 function botonPropuesta(div, md) {
modified web/sw.js +15 −1
@@ -43,10 +43,24 @@
4343 client.postMessage({ type: 'notif-action', action, md: data.md });
4444 client.focus?.();
4545 } 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);
4760 }
4861 })());
4962 });
63+const NOTIF_CACHE = 'elffuss-notif';
5064
5165 // ── Manejador de `fetch`, añadido para poder INSTALAR el sitio ──────────────
5266 // Chrome solo ofrece instalar si hay manifiesto Y un service worker con