Elffuss BraidHub

utopia-ia/elffuss-code public

Bridge: say when the connected bridge is older than 1.1.2, and fix two stale texts

- Since 1.1.2 a stop kills the whole command tree (npm scripts, servers,
  "a; b") and a closed connection kills what was left running. With an older
  bridge the agent and the terminal report the command as stopped (130) while
  its children keep running, and nothing told the user. The bridge has always
  sent its version on /ping; the client now reads it (probe() at connect), and
  when it is older than the one this site ships, Settings explains what is
  missing and asks for 1.1.2, and the status bar says it once per version even
  when the bridge connects by itself.
- The setup text asked to download "version 1.1.1" (the downloads are 1.1.2;
  1.1.1 is the oldest that accepts the new address), and the folder label said
  an empty folder meant a temporary one. Since f594431 it is the folder the
  bridge was started from, and nothing runs outside it.

tests/bridge-version.mjs (a stand-in bridge: /ping answered by page.route, a
WebSocket double that accepts the token): with 1.1.1 Settings and the status
bar ask for 1.1.2 and say why; with 1.1.2 there is no warning; the setup text
asks for 1.1.2 and the folder label describes the start folder, in es and en.
Changeset3402fd88d9635f8e671ff13e29eea56aeb108d6fb45e79f876a38b3c2c8d0932
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00
Parents97ba245c0fe7

Browse the files at this changeset

4 files changed

added tests/bridge-version.mjs +72 −0
@@ -0,0 +1,72 @@
1+// El bridge viejo se nota, y la ayuda del bridge dice lo que hay.
2+//
3+// Desde la 1.1.2 parar un comando mata también lo que arrancó (npm scripts,
4+// servidores, «a; b»). Con una anterior la web da el comando por parado (130)
5+// pero el proceso sigue vivo, y nadie lo decía: la web no miraba la versión que
6+// el bridge da en /ping. Ahora, conectado a uno anterior a la 1.1.2, Ajustes lo
7+// dice (y la barra de estado, una vez). Y dos textos que se habían quedado
8+// viejos: «descárgalo otra vez (versión 1.1.1)» y «carpeta vacía = una
9+// temporal» (desde f594431 es la carpeta desde la que arrancó el bridge).
10+//
11+// Sin bridge de verdad: /ping lo contesta page.route y el WebSocket es un doble
12+// en la página que acepta el token.
13+//
14+// BASE=http://localhost:8799 node tests/bridge-version.mjs
15+import { chromium } from 'playwright';
16+const BASE = process.env.BASE || 'http://localhost:8799';
17+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
18+
19+const b = await chromium.launch();
20+const errs = [];
21+async function conBridge(version, locale = 'es-ES') {
22+ const ctx = await b.newContext({ locale });
23+ await ctx.addInitScript(() => {
24+ try { localStorage.setItem('elffusscode.model', 'rules'); } catch { /* */ }
25+ // Un bridge de mentira: abre, acepta el token y no ejecuta nada.
26+ window.WebSocket = class {
27+ constructor(url) { this.url = url; setTimeout(() => this.onopen?.(), 10); }
28+ send(d) { const m = JSON.parse(d); if (m.type === 'auth') setTimeout(() => this.onmessage?.({ data: JSON.stringify({ type: 'auth-ok' }) }), 10); }
29+ close() { setTimeout(() => this.onclose?.(), 0); }
30+ };
31+ });
32+ const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } });
33+ p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
34+ await p.route('http://127.0.0.1:8765/ping', r => r.fulfill({ status: 200, contentType: 'application/json',
35+ headers: { 'access-control-allow-origin': '*' }, body: JSON.stringify({ ok: true, version }) }));
36+ await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
37+ await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.(), null, { timeout: 20000 });
38+ await p.click('#btn-settings');
39+ await p.waitForSelector('#br-token');
40+ await p.fill('#br-token', 'token-de-prueba');
41+ await p.click('#br-connect');
42+ await p.waitForFunction(() => document.getElementById('br-dot')?.classList.contains('on'), null, { timeout: 5000 }).catch(() => {});
43+ await p.waitForTimeout(400); // la versión llega justo después de conectar
44+ const r = await p.evaluate(() => ({
45+ conectado: document.getElementById('br-dot')?.classList.contains('on'),
46+ aviso: document.getElementById('br-viejo')?.hidden ? '' : document.getElementById('br-viejo')?.textContent || '',
47+ estado: document.getElementById('statusbar').textContent,
48+ ayuda: document.querySelector('#settings-panel .bridge-card')?.textContent || '',
49+ carpeta: document.querySelector('label[for="br-folder"]')?.textContent || '',
50+ }));
51+ await ctx.close();
52+ return r;
53+}
54+
55+const viejo = await conBridge('1.1.1');
56+ok('conectado a un bridge 1.1.1, Ajustes dice que hay que bajar la 1.1.2', viejo.conectado && /1\.1\.1/.test(viejo.aviso) && /1\.1\.2/.test(viejo.aviso), JSON.stringify(viejo.aviso));
57+ok(' …y por qué (parar no para lo que el comando arrancó)', /no para lo que este arrancó/.test(viejo.aviso), viejo.aviso);
58+ok(' …y la barra de estado lo dice también', /1\.1\.2/.test(viejo.estado), viejo.estado);
59+
60+const nuevo = await conBridge('1.1.2');
61+ok('con el 1.1.2 no hay aviso', nuevo.conectado && nuevo.aviso === '' && !/1\.1\.1/.test(nuevo.estado), JSON.stringify({ aviso: nuevo.aviso, estado: nuevo.estado }));
62+ok('la ayuda del bridge pide la versión 1.1.2, no la 1.1.1', /Descárgalo otra vez \(versión 1\.1\.2\)/.test(nuevo.ayuda), nuevo.ayuda.slice(0, 200));
63+ok('la carpeta vacía es la de arranque del bridge (no «una temporal»)', /desde la que arrancaste el bridge/.test(nuevo.carpeta) && !/temporal/.test(nuevo.carpeta), nuevo.carpeta);
64+
65+const en = await conBridge('1.1.1', 'en-US');
66+ok('en inglés: el aviso del bridge viejo, en inglés', /Your bridge is version 1\.1\.1: download 1\.1\.2/.test(en.aviso), en.aviso);
67+ok('en inglés: la carpeta vacía es la de arranque', /folder you started the bridge from/.test(en.carpeta) && !/temporary/.test(en.carpeta), en.carpeta);
68+
69+ok('sin errores de página', errs.length === 0, errs.join(' | '));
70+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ BRIDGE: el viejo se nota y la ayuda dice lo que hay');
71+await b.close();
72+process.exit(fails ? 1 : 0);
modified web/js/bridge.js +20 −0
@@ -26,6 +26,23 @@
2626 try { savedToken = localStorage.getItem('elffusscode.bridgeToken') || ''; } catch { /* */ }
2727
2828 export function isConnected() { return connected && authed; }
29+
30+// La versión que se descarga desde esta web (web/bridge-dl). Desde la 1.1.2,
31+// parar un comando mata también lo que ese comando arrancó (un «npm run dev»,
32+// un servidor, «a; b») y cerrar la conexión mata lo que quedara corriendo. Con
33+// una anterior el agente y el terminal lo dan por parado, pero el proceso sigue
34+// vivo en la máquina: hay que decirle al usuario que la actualice. El bridge
35+// dice su versión en /ping desde siempre; antes nadie la miraba.
36+export const VERSION_ACTUAL = '1.1.2';
37+let versionVista = null;
38+export function version() { return versionVista; }
39+const partesVersion = v => String(v).split('.').map(n => parseInt(n, 10) || 0);
40+export function esViejo() {
41+ if (!versionVista) return false;
42+ const [a, b] = [partesVersion(versionVista), partesVersion(VERSION_ACTUAL)];
43+ for (let i = 0; i < 3; i++) if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) < (b[i] || 0);
44+ return false;
45+}
2946 export function getFolder() { return savedFolder; }
3047 export function setFolder(f) {
3148 savedFolder = (f || '').trim();
@@ -41,6 +58,7 @@
4158 const r = await fetch('http://' + HOST + '/ping', { mode: 'cors' });
4259 if (!r.ok) return false;
4360 const j = await r.json();
61+ if (j.version) versionVista = String(j.version);
4462 return !!j.ok;
4563 } catch { return false; }
4664 }
@@ -71,6 +89,8 @@
7189 try { localStorage.setItem('elffusscode.bridgeToken', token); } catch { /* */ }
7290 onStatus('connected');
7391 resolve(true);
92+ // Qué versión es (para avisar si es vieja): se avisa otra vez al saberlo.
93+ probe().then(() => { if (ws === sock && isConnected()) onStatus('version'); }).catch(() => {});
7494 return;
7595 }
7696 if (m.type === 'auth-fail') { clearTimeout(timeout); connected = true; authed = false; onStatus('auth-fail'); reject(new Error('token incorrecto')); return; }
modified web/js/i18n.js +6 −4
@@ -123,11 +123,12 @@
123123 stModelLoadingAI: "Cargando el modelo IA…",
124124 termCapsBridge: "🔌 Bridge local: node/npm/python reales",
125125 termCapsNoBridge: "shell del proyecto · node/npm/python → Bridge local (⚙ Ajustes)",
126- setBridgeFolderLabel: "Carpeta de trabajo (opcional — si no, usa una temporal)",
126+ setBridgeFolderLabel: "Carpeta de trabajo (opcional — si no, la carpeta desde la que arrancaste el bridge; fuera de ella no ejecuta nada)",
127127 setBridgeDesc: "Un pequeño programa que TÚ ejecutas en tu ordenador — le da a la elfa ejecución real (node, npm, python…) sin salir de tu máquina. Nada se instala en el navegador.",
128128 setBridgeDownload: "⬇ Descargar para {os}",
129129 setBridgeOtherOS: "otro sistema operativo",
130- setBridgeOld: "¿Ya tenías un bridge y ahora no conecta? Descárgalo otra vez (versión 1.1.1): los anteriores no aceptan la dirección nueva de Elffuss Code.",
130+ setBridgeOld: "¿Ya tenías un bridge y ahora no conecta? Descárgalo otra vez (versión 1.1.2): los anteriores a la 1.1.1 no aceptan la dirección nueva de Elffuss Code.",
131+ setBridgeUpdate: "Tu bridge es la versión {v}: descarga la {want}. Con la tuya, parar un comando no para lo que este arrancó (un «npm run dev», un servidor…), que sigue corriendo en tu máquina.",
131132 setModelRulesName: "Básico (sin modelo)",
132133 // ronda UX 2026-10: cola, guardar, avisos honestos
133134 queuedTitle: "En cola: sale en cuanto termine lo de ahora",
@@ -354,11 +355,12 @@
354355 stModelLoadingAI: "Loading the AI model…",
355356 termCapsBridge: "🔌 Local bridge: real node/npm/python",
356357 termCapsNoBridge: "project shell · node/npm/python → Local bridge (⚙ Settings)",
357- setBridgeFolderLabel: "Working folder (optional — otherwise a temporary one is used)",
358+ setBridgeFolderLabel: "Working folder (optional — otherwise the folder you started the bridge from; it runs nothing outside it)",
358359 setBridgeDesc: "A small program that YOU run on your computer — it gives the elf real execution (node, npm, python…) without leaving your machine. Nothing is installed in the browser.",
359360 setBridgeDownload: "⬇ Download for {os}",
360361 setBridgeOtherOS: "another operating system",
361- setBridgeOld: "Already had a bridge and now it won't connect? Download it again (version 1.1.1): older ones don't accept Elffuss Code's new address.",
362+ setBridgeOld: "Already had a bridge and now it won't connect? Download it again (version 1.1.2): versions before 1.1.1 don't accept Elffuss Code's new address.",
363+ setBridgeUpdate: "Your bridge is version {v}: download {want}. With yours, stopping a command doesn't stop what it started (an “npm run dev”, a server…), which keeps running on your machine.",
362364 setModelRulesName: "Basic (no model)",
363365 // UX round 2026-10: queue, save, honest notices
364366 queuedTitle: "Queued: it goes out as soon as the current work ends",
modified web/js/main.js +16 −1
@@ -1189,6 +1189,7 @@
11891189 `<div class="prov-head"><span id="br-dot" class="dot off" aria-hidden="true"></span><b>${escapeHtml(t('setBridgeName'))}</b><span id="br-status" class="muted" role="status" style="margin-left:auto;font-size:.72rem">${escapeHtml(t('setBridgeDisconnected'))}</span></div>` +
11901190 `<p class="muted" style="font-size:.72rem;margin:6px 0">${t('setBridgeDesc')}</p>` +
11911191 `<p class="muted" style="font-size:.7rem;margin:0 0 6px">${t('setBridgeOld')}</p>` +
1192+ `<p id="br-viejo" class="br-viejo" role="status" style="font-size:.72rem;margin:0 0 6px" hidden></p>` +
11921193 `<div id="br-dl"></div>` +
11931194 `<details style="margin-top:6px"><summary class="muted" style="font-size:.7rem;cursor:pointer">${t('setBridgeOtherOS')}</summary><div id="br-dl-other"></div></details>` +
11941195 `<p class="muted" style="font-size:.7rem;margin:6px 0 0"><a href="https://github.com/KikoCis/elffuss-code/tree/main/bridge" target="_blank" rel="noopener noreferrer" style="color:var(--accent2)">${escapeHtml(t('setBridgeSource'))} ↗</a></p>` +
@@ -1208,6 +1209,11 @@
12081209 if (on) brCard.querySelector('#br-token').value = localStorage.getItem('elffusscode.bridgeToken') || '';
12091210 brCard.querySelector('#br-disconnect').hidden = !on;
12101211 brCard.querySelector('#br-forget').hidden = !bridge.hasSavedToken();
1212+ // Conectado a un bridge anterior al de esta web: se dice qué le falta.
1213+ const viejo = brCard.querySelector('#br-viejo');
1214+ const avisar = on && bridge.esViejo();
1215+ viejo.hidden = !avisar;
1216+ viejo.textContent = avisar ? '⚠️ ' + t('setBridgeUpdate', { v: bridge.version(), want: bridge.VERSION_ACTUAL }) : '';
12111217 };
12121218 paintBridge();
12131219 // repinta si el bridge conecta/cae mientras Ajustes está abierto; al cerrarse
@@ -1945,7 +1951,16 @@
19451951 const cap = shell.capabilities();
19461952 $('term-caps').textContent = cap.bridge ? t("termCapsBridge") : t("termCapsNoBridge");
19471953 }
1948-bridge.onStatusChange(() => { if (!$('terminal-panel').hidden) pintaCapacidades(); });
1954+bridge.onStatusChange(estado => {
1955+ if (!$('terminal-panel').hidden) pintaCapacidades();
1956+ // Un bridge viejo conectado (también el que conecta solo, sin abrir Ajustes):
1957+ // una vez por versión, en la barra de estado.
1958+ if (estado === 'version' && bridge.esViejo() && avisoBridgeViejo !== bridge.version()) {
1959+ avisoBridgeViejo = bridge.version();
1960+ $('statusbar').textContent = '⚠️ ' + t('setBridgeUpdate', { v: bridge.version(), want: bridge.VERSION_ACTUAL });
1961+ }
1962+});
1963+let avisoBridgeViejo = null;
19491964 $('act-term').addEventListener('click', () => toggleTerminal());
19501965 $('term-close').addEventListener('click', () => toggleTerminal(false));
19511966 $('term-clear').addEventListener('click', () => terminal.clearScreen());