Elffuss BraidHub

utopia-ia/elffuss-code public

Bridge client: several status listeners, a disconnect that sticks, forget token

onStatusChange() kept a single callback, so each subscriber replaced the
previous one; it now keeps a set and returns an unsubscribe function.
disconnect() was never called from the UI and, had it been, the background
auto-detection would have reconnected with the saved token within seconds:
a deliberate disconnect now pauses tryAutoConnect() and the auto-detection
until connect() is called again, and it notifies listeners. forgetToken()
removes the saved token from localStorage and disconnects; hasSavedToken()
lets the UI offer it only when there is one.

The Settings buttons that use this come in the next commit.
Changeset227590fdf25a905b920c05806ea95fe01a38af938b7235fd9ae459412444e169
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 16:27 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:15 +02:00
Parentsfa92ebd9325b

Browse the files at this changeset

1 file changed

modified web/js/bridge.js +31 −7
@@ -7,7 +7,13 @@
77 let ws = null, connected = false, authed = false;
88 let pending = new Map(); // id → { onOut, onErr, sock, terminar }
99 let nextId = 1;
10-let onStatus = () => {};
10+// Varios pueden querer saber si el bridge conecta o cae (Ajustes, la etiqueta
11+// del terminal…). Antes había UN solo oyente y cada uno pisaba al anterior.
12+const oyentes = new Set();
13+const onStatus = (s) => { for (const f of oyentes) { try { f(s); } catch { /* */ } } };
14+// «Desconectar» a propósito: la autodetección no vuelve a conectar sola hasta
15+// que se pulse «Conectar» otra vez (antes reconectaba a los pocos segundos).
16+let pausado = false;
1117 let savedFolder = '';
1218 try { savedFolder = localStorage.getItem('elffusscode.bridgeFolder') || ''; } catch { /* */ }
1319 let savedToken = '';
@@ -19,7 +25,8 @@
1925 savedFolder = (f || '').trim();
2026 try { localStorage.setItem('elffusscode.bridgeFolder', savedFolder); } catch { /* */ }
2127 }
22-export function onStatusChange(fn) { onStatus = fn; }
28+// Devuelve la función para dejar de escuchar.
29+export function onStatusChange(fn) { oyentes.add(fn); return () => oyentes.delete(fn); }
2330
2431 // sondeo ligero: ¿hay un bridge escuchando en 127.0.0.1, aunque no nos hayamos
2532 // autenticado todavía? (para saber si mostrar «detectado» antes de conectar)
@@ -33,6 +40,7 @@
3340 }
3441
3542 export function connect(token) {
43+ pausado = false;
3644 return new Promise((resolve, reject) => {
3745 let sock;
3846 try { sock = ws = new WebSocket('ws://' + HOST + '/ws'); }
@@ -70,12 +78,28 @@
7078 });
7179 }
7280
73-export function disconnect() { try { ws?.close(); } catch { /* */ } connected = false; authed = false; }
81+export function disconnect() {
82+ pausado = true;
83+ try { ws?.close(); } catch { /* */ }
84+ connected = false; authed = false;
85+ onStatus('disconnected');
86+}
87+// Olvidar el token guardado: desconecta y ya no se reconecta solo.
88+export function forgetToken() {
89+ savedToken = '';
90+ try { localStorage.removeItem('elffusscode.bridgeToken'); } catch { /* */ }
91+ disconnect();
92+}
93+export function hasSavedToken() { return !!savedToken; }
94+
95+// Lo que conecta SOLO (al abrir, o al detectar el bridge) no lo hace si el
96+// usuario desconectó a propósito; connect() a secas es el botón «Conectar».
97+function connectAuto(token) { return pausado ? Promise.reject(new Error('pausado')) : connect(token); }
7498
7599 // tratar de reconectar en silencio con el token guardado (al abrir la app)
76100 export async function tryAutoConnect() {
77- if (!savedToken) return false;
78- try { await connect(savedToken); return true; } catch { return false; }
101+ if (!savedToken || pausado) return false;
102+ try { await connectAuto(savedToken); return true; } catch { return false; }
79103 }
80104
81105 // Detección continua en segundo plano: si el usuario arranca el bridge
@@ -86,10 +110,10 @@
86110 export function startAutoDetect(intervalMs = 4000) {
87111 if (autoDetectTimer) return () => stopAutoDetect();
88112 autoDetectTimer = setInterval(async () => {
89- if (isConnected() || connecting || !savedToken) return;
113+ if (isConnected() || connecting || !savedToken || pausado) return;
90114 if (!(await probe())) return;
91115 connecting = true;
92- try { await connect(savedToken); } catch { /* el usuario aún no ha pegado token válido, o cayó de nuevo */ }
116+ try { await connectAuto(savedToken); } catch { /* el usuario aún no ha pegado token válido, o cayó de nuevo */ }
93117 finally { connecting = false; }
94118 }, intervalMs);
95119 return () => stopAutoDetect();