From 5481e79dc40780799f11e644e184174ab51fbc80 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:39:59 +0200 Subject: [PATCH] feat(web): refresh the pages as the events arrive One `EventSource` for the whole dashboard, held in a single slot: a view that re-renders itself would otherwise register a second listener each time and double the work on every event. A refresh landing under someone's fingers is worse than data a few seconds old, so it waits while a dialog is open or a field has focus, a burst of writes collapses into one reload, and a background tab closes its stream. The Discord page stays off the tick because listing members calls the Discord API. When the stream cannot be established a timer takes over. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/app.js | 33 ++++++ src/web/public/core/live.js | 168 +++++++++++++++++++++++++++ src/web/public/styles.css | 36 ++++++ src/web/public/views/community.js | 3 + src/web/public/views/deployments.js | 4 + src/web/public/views/organization.js | 3 + src/web/public/views/overview.js | 5 + src/web/public/views/settings.js | 3 + 8 files changed, 255 insertions(+) create mode 100644 src/web/public/core/live.js diff --git a/src/web/public/app.js b/src/web/public/app.js index 23a54c3..ca2dc5b 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -1,5 +1,6 @@ import { api } from './core/api.js'; import { h, mount, qs } from './core/dom.js'; +import { onStatus, resetSubscriptions, startLive } from './core/live.js'; import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js'; /** Shell, navigation and hash routing of the dashboard (M16-T11). */ @@ -151,6 +152,34 @@ function highlightNav() { document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot'; } +const LIVE_LABELS = { + live: 'À jour en direct', + connecting: 'Connexion…', + reconnecting: 'Reconnexion…', + polling: 'Rafraîchissement périodique', + paused: 'En pause (onglet en arrière-plan)', + idle: 'Hors ligne', +}; + +let stopWatchingStatus = null; + +/** Small footer badge: says whether the page is following the bot live. */ +function liveIndicator() { + const dot = h('span', { class: 'live-dot' }); + const label = h('span', { text: LIVE_LABELS.idle }); + const node = h('div', { class: 'live', title: 'État de la mise à jour automatique' }, dot, label); + + stopWatchingStatus?.(); + stopWatchingStatus = onStatus(({ status, lastEventAt }) => { + node.dataset.status = status; + label.textContent = LIVE_LABELS[status] ?? status; + if (lastEventAt) { + node.title = `Dernière mise à jour à ${lastEventAt.toLocaleTimeString('fr-FR')}`; + } + }); + return node; +} + function sidebar() { const visible = ROUTES.filter( (route) => state.me.accessLevel >= route.level && (!route.advanced || state.mode === 'advanced'), @@ -196,6 +225,7 @@ function sidebar() { button('Simple', () => setMode('simple'), {}), button('Avancé', () => setMode('advanced'), {}), ), + liveIndicator(), h( 'div', { class: 'viewer' }, @@ -243,6 +273,7 @@ function applyModeButtons(node) { async function renderView(host) { const { segments } = currentRoute(); const route = ROUTES.find((entry) => entry.path === (segments[0] ?? '')); + resetSubscriptions(); highlightNav(); host.scrollIntoView?.({ block: 'start' }); @@ -303,6 +334,8 @@ async function boot() { state.me = me; state.config = config; + startLive(); + window.addEventListener('hashchange', () => { const main = qs('.main'); // Without the shell in place there is nothing to swap, so rebuild the page. diff --git a/src/web/public/core/live.js b/src/web/public/core/live.js new file mode 100644 index 0000000..85e05d5 --- /dev/null +++ b/src/web/public/core/live.js @@ -0,0 +1,168 @@ +/** + * Live updates (M16-T12). + * + * One `EventSource` for the whole dashboard; views declare what they want to + * hear and get called back. When the stream cannot be established — a proxy + * that buffers, a network that drops it — a timer takes over so the pages still + * refresh, just less promptly. + */ + +/** + * A single slot rather than a list: exactly one view is on screen, and a view + * that re-renders itself on refresh would otherwise register a second listener + * each time, doubling the work on every event. + */ +let viewRefresher = null; +const STATUS_LISTENERS = new Set(); +const FALLBACK_MS = 30_000; +/** Backoff between reconnection attempts, capped so it always keeps trying. */ +const RETRY_MS = [2000, 5000, 15_000, 30_000]; + +let source = null; +let fallbackTimer = null; +let attempts = 0; +let status = 'idle'; +let lastEventAt = null; + +function setStatus(next) { + if (status === next) return; + status = next; + for (const listener of STATUS_LISTENERS) listener({ status, lastEventAt }); +} + +function emit(event) { + lastEventAt = new Date(); + try { + viewRefresher?.(event); + } catch { + // A failing view must not take the stream down with it. + } + setStatus(fallbackTimer ? 'polling' : 'live'); +} + +function startFallback() { + if (fallbackTimer) return; + fallbackTimer = setInterval(() => emit({ topic: 'tick', fallback: true }), FALLBACK_MS); + setStatus('polling'); +} + +function stopFallback() { + clearInterval(fallbackTimer); + fallbackTimer = null; +} + +function connect() { + if (source || document.hidden) return; + + setStatus(attempts === 0 ? 'connecting' : 'reconnecting'); + source = new EventSource('/api/events', { withCredentials: true }); + + source.addEventListener('open', () => { + attempts = 0; + stopFallback(); + setStatus('live'); + }); + + for (const topic of [ + 'ready', + 'tick', + 'mutation', + 'deployments', + 'gitea', + 'discord', + 'community', + 'settings', + ]) { + source.addEventListener(topic, (event) => { + let payload = { topic }; + try { + payload = { ...JSON.parse(event.data), topic }; + } catch { + // A frame we cannot read is still a signal that something moved. + } + emit(payload); + }); + } + + source.addEventListener('error', () => { + source?.close(); + source = null; + + // The browser reconnects on its own, but only while the page stays open and + // the server keeps answering; the timer covers the rest. + startFallback(); + const delay = RETRY_MS[Math.min(attempts, RETRY_MS.length - 1)]; + attempts += 1; + setTimeout(connect, delay); + }); +} + +/** Stops the stream while the tab is in the background, resumes on return. */ +document.addEventListener('visibilitychange', () => { + if (document.hidden) { + source?.close(); + source = null; + stopFallback(); + setStatus('paused'); + } else { + connect(); + // Coming back to the tab, the page is stale by definition. + emit({ topic: 'tick', resumed: true }); + } +}); + +export function startLive() { + connect(); +} + +export function onStatus(listener) { + STATUS_LISTENERS.add(listener); + listener({ status, lastEventAt }); + return () => STATUS_LISTENERS.delete(listener); +} + +export const liveStatus = () => ({ status, lastEventAt }); + +/** Drops the current view subscription, called when navigating elsewhere. */ +export function resetSubscriptions() { + viewRefresher = null; +} + +/** + * Re-runs `refresh` when a relevant event arrives. + * + * Refreshing under someone's fingers is worse than showing slightly old data, + * so a refresh is skipped while a dialog is open or a field has focus, and + * replayed once the way is clear. + */ +export function autoRefresh(refresh, { topics = ['tick'], minIntervalMs = 5000 } = {}) { + const wanted = new Set(topics); + let lastRun = Date.now(); + let pending = false; + + const busy = () => + document.querySelector('.overlay') !== null || + ['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName); + + const run = () => { + if (busy()) { + pending = true; + return; + } + pending = false; + lastRun = Date.now(); + refresh(); + }; + + const listener = (event) => { + if (!wanted.has(event.topic) && !pending) return; + // A burst of writes must not turn into a burst of reloads. + if (Date.now() - lastRun < minIntervalMs && !pending) return; + run(); + }; + + viewRefresher = listener; + return () => { + if (viewRefresher === listener) viewRefresher = null; + }; +} diff --git a/src/web/public/styles.css b/src/web/public/styles.css index f24040a..94b8da0 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -690,6 +690,42 @@ pre code { padding-left: 1.2rem; } +.live { + display: flex; + align-items: center; + gap: 0.45rem; + font-size: 0.75rem; + color: var(--text-muted); + padding: 0 0.2rem; +} +.live-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--text-muted); + flex: none; +} +.live[data-status='live'] .live-dot { + background: var(--green); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--green) 25%, transparent); +} +.live[data-status='polling'] .live-dot { + background: var(--amber); +} +.live[data-status='connecting'] .live-dot, +.live[data-status='reconnecting'] .live-dot { + background: var(--blue); + animation: pulse 1.2s ease-in-out infinite; +} +.live[data-status='paused'] .live-dot { + background: var(--border); +} +@keyframes pulse { + 50% { + opacity: 0.25; + } +} + details summary { cursor: pointer; font-size: 0.85rem; diff --git a/src/web/public/views/community.js b/src/web/public/views/community.js index 79cc128..f312536 100644 --- a/src/web/public/views/community.js +++ b/src/web/public/views/community.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatRelative, h } from '../core/dom.js'; import { badge, @@ -346,6 +347,8 @@ export function render(host, { state }) { const level = state.me.accessLevel; const reload = () => render(host, { state }); + autoRefresh(reload, { topics: ['community', 'discord', 'tick'] }); + return renderAsync( host, async () => { diff --git a/src/web/public/views/deployments.js b/src/web/public/views/deployments.js index 9425501..1cf5502 100644 --- a/src/web/public/views/deployments.js +++ b/src/web/public/views/deployments.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatRelative, h, mount } from '../core/dom.js'; import { badge, @@ -220,6 +221,9 @@ export function render(host, { state }) { const level = state.me.accessLevel; const reload = () => render(host, { state }); + // A running deployment reports itself, so the log lands without a reload. + autoRefresh(reload, { topics: ['deployments', 'tick'], minIntervalMs: 2000 }); + return renderAsync( host, async () => { diff --git a/src/web/public/views/organization.js b/src/web/public/views/organization.js index 3ca94d0..c770d93 100644 --- a/src/web/public/views/organization.js +++ b/src/web/public/views/organization.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatBytes, formatRelative, h } from '../core/dom.js'; import { badge, @@ -104,6 +105,8 @@ export function render(host, { state }) { const level = state.me.accessLevel; const refresh = () => render(host, { state }); + autoRefresh(refresh, { topics: ['gitea'] }); + return renderAsync( host, () => api.get('/api/organization'), diff --git a/src/web/public/views/overview.js b/src/web/public/views/overview.js index 6ed05f7..7f46edb 100644 --- a/src/web/public/views/overview.js +++ b/src/web/public/views/overview.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatBytes, formatDuration, formatRelative, h } from '../core/dom.js'; import { badge, card, grid, renderAsync, stat, table } from '../core/ui.js'; @@ -162,6 +163,10 @@ function systemCard(database, features) { } export function render(host, { state }) { + autoRefresh(() => render(host, { state }), { + topics: ['tick', 'mutation', 'deployments', 'gitea', 'discord', 'community'], + }); + return renderAsync( host, () => api.get('/api/overview'), diff --git a/src/web/public/views/settings.js b/src/web/public/views/settings.js index f565808..944126c 100644 --- a/src/web/public/views/settings.js +++ b/src/web/public/views/settings.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatDate, formatRelative, h } from '../core/dom.js'; import { badge, @@ -436,6 +437,8 @@ export function render(host, { state }) { const level = state.me.accessLevel; const reload = () => render(host, { state }); + autoRefresh(reload, { topics: ['settings'] }); + return renderAsync( host, () => api.get('/api/settings'),