// Client state, kept fresh by a websocket with a polling fallback. // // The old dashboard re-fetched everything on a five second timer. Here the // server pushes health and change deltas, and the timer is only a safety net // for when the socket is down. import { api } from "./api.js"; const listeners = new Set(); export const state = { me: null, streams: [], overview: null, agents: [], deps: null, uptimeS: 0, connected: false, lastError: "", }; export function subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); } function emit(reason) { for (const fn of listeners) { try { fn(state, reason); } catch (err) { console.error("subscriber failed", err); } } } export function streamById(id) { return state.streams.find((s) => String(s.id) === String(id)) || null; } let inflight = null; /** Refresh the stream list and headline numbers. */ export async function refresh(reason = "poll") { // Coalesce: a websocket burst must not become a burst of requests. if (inflight) return inflight; inflight = (async () => { try { const [overview, streams, health] = await Promise.all([ api.overview().catch(() => null), api.streams(), api.health().catch(() => null), ]); state.streams = streams.streams || []; if (overview) state.overview = overview; if (health) { state.uptimeS = health.uptime_s || 0; if (health.deps) state.deps = health.deps; } state.lastError = ""; } catch (err) { state.lastError = err.message || String(err); } finally { inflight = null; emit(reason); } })(); return inflight; } export function setMe(me) { state.me = me; emit("me"); } export function isAdmin() { return state.me && state.me.role === "admin"; } export function canEdit() { return state.me && (state.me.role === "admin" || state.me.role === "operator"); } // ---------- websocket ---------- let ws = null; let reconnectTimer = null; let backoff = 1000; let pollTimer = null; let stopped = false; const scheduleRefresh = (() => { let t = null; return (reason) => { // Several pushes often arrive together (a restart touches health and the // stream row); one refresh shortly after covers them all. clearTimeout(t); t = setTimeout(() => refresh(reason), 220); }; })(); export function connect() { stopped = false; openSocket(); startPolling(); } export function disconnect() { stopped = true; clearTimeout(reconnectTimer); clearInterval(pollTimer); pollTimer = null; if (ws) { try { ws.close(); } catch { /* already closing */ } ws = null; } state.connected = false; } function startPolling() { clearInterval(pollTimer); // Slow when pushed to, brisk when the socket is down. pollTimer = setInterval(() => { if (!state.connected) refresh("poll-fallback"); else refresh("poll-slow"); }, 15000); } function openSocket() { if (stopped) return; if (ws) { try { ws.close(); } catch { /* ignore */ } } const proto = location.protocol === "https:" ? "wss:" : "ws:"; let sock; try { sock = new WebSocket(`${proto}//${location.host}/ws/ui`); } catch { scheduleReconnect(); return; } ws = sock; sock.onopen = () => { state.connected = true; backoff = 1000; emit("ws-open"); }; sock.onmessage = (ev) => { let msg; try { msg = JSON.parse(ev.data); } catch { return; } switch (msg.type) { case "agents": case "agent_online": case "agent_offline": state.agents = msg.agents || []; emit("agents"); if (msg.type !== "agents") scheduleRefresh("agent-change"); break; case "runtime": case "streams_changed": case "claims_changed": scheduleRefresh(msg.type); break; case "modules_changed": emit("modules_changed"); break; default: break; } }; sock.onclose = () => { if (ws === sock) ws = null; state.connected = false; emit("ws-close"); scheduleReconnect(); }; sock.onerror = () => { // onclose follows, which is where the reconnect is scheduled. }; } function scheduleReconnect() { if (stopped) return; clearTimeout(reconnectTimer); reconnectTimer = setTimeout(openSocket, backoff); backoff = Math.min(backoff * 2, 20000); }