Admin dashboard (phase 2): live 'training now' heartbeat + release v1.1.4

Backend: in-memory presence map + POST /api/activity heartbeat (authed);
each /api/admin/users row carries a fresh 'live' snapshot (routine,
exercise x/y, sets done/total, started-at) with a ~70s TTL. Disabling a
user clears their presence immediately.

Frontend: the workout screen pings /api/activity every 20s (signed-in
only) and sends a leave signal on unmount (fetch + sendBeacon). The
dashboard gains a 'Training now' section and live markers, auto-
refreshing every 15s.

Cuts the complete admin-dashboard feature (phases 1+2) as v1.1.4.
This commit is contained in:
Duarte Santos committed 2026-07-22 02:06:19 +02:00
1 parent 046217079c
commit f3ba05aece
5 files changed
+96 -7

No files matched your search

+17
View File
@@ -1,5 +1,22 @@
# Changelog
## v1.1.4 — 2026-07-22
Admin dashboard for self-hosters (opt-in — off by default).
- 🛠️ **Admin dashboard** (Settings → Admin dashboard) for whoever runs the instance: a users
overview with workout counts and last-active times, plus a per-user drill-down into their full
workout history and body-weight log.
- 🟢 **Live "training now"** — see who's mid-workout in real time, with their current exercise and
set progress, updated by a lightweight heartbeat while a workout is on screen.
- 🚫 **Disable / enable accounts** — a disabled account is signed out and locked out everywhere
until you re-enable it.
- 🔑 **Invite-only signup** (optional) — require an invite code to create a profile; generate and
revoke codes from the dashboard. Existing accounts are unaffected.
- ⚙️ Configured via environment: `ADMIN_UIDS` (comma-separated user ids who are admins) and
`INVITE_ONLY=1`; both default off, so a fresh instance stays open with no admin. See
`.env.example`. Admin access is gated by your passkey and enforced server-side.
## v1.1.3 — 2026-07-22
- 🔎 **Minimize the exercise animation during a workout** (#12). A ⤡ Minimize / ⤢ Expand button
+34 -2
View File
@@ -223,6 +223,19 @@ function readBody(req) {
}
const b64uToBuf = s => Buffer.from(s, 'base64url');
/* ---------- live presence (in-memory) ---------- */
// Clients heartbeat /api/activity while a workout is on screen; the admin dashboard reads who's
// live. Purely ephemeral — never persisted. Expires shortly after the last ping.
const presence = new Map(); // uid -> { name, exIdx, exTotal, setsDone, setsTotal, startedAt, updatedAt }
const PRESENCE_TTL = 70000; // ~3.5× the 20s client heartbeat
function livePresence(uid) {
const p = presence.get(uid);
if (!p) return null;
if (Date.now() - p.updatedAt > PRESENCE_TTL) { presence.delete(uid); return null; }
return p;
}
setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt > PRESENCE_TTL) presence.delete(k); }, 30000).unref();
/* ---------- routes ---------- */
const routes = {
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
@@ -398,6 +411,23 @@ const routes = {
json(res, 200, { ok: true });
},
// Live-workout heartbeat: client pings while a workout is on screen; { active:false } drops it.
'POST /api/activity': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
if (body.active) {
presence.set(user.id, {
name: String(body.name || '').slice(0, 60),
exIdx: +body.exIdx || 0, exTotal: +body.exTotal || 0,
setsDone: +body.setsDone || 0, setsTotal: +body.setsTotal || 0,
startedAt: +body.startedAt || Date.now(),
updatedAt: Date.now()
});
} else presence.delete(user.id);
json(res, 200, { ok: true });
},
/* ---------- admin dashboard ---------- */
// One row per user, cheap enough for a personal instance (reads each state file once).
'GET /api/admin/users': async (req, res) => {
@@ -412,10 +442,11 @@ const routes = {
workouts: workouts.length,
lastWorkout: last ? last.d : null,
lastSync: S._ts || null,
hasPush: db.subs.some(s => s.userId === u.id)
hasPush: db.subs.some(s => s.userId === u.id),
live: livePresence(u.id)
};
});
json(res, 200, { users, invite_only: INVITE_ONLY });
json(res, 200, { users, invite_only: INVITE_ONLY, now: Date.now() });
},
// Drill-down: full workout history + body-weight log for one user.
@@ -442,6 +473,7 @@ const routes = {
if (!u) return json(res, 404, { error: 'no such user' });
if (isAdmin(u)) return json(res, 400, { error: 'cannot disable an admin' });
u.disabled = !!body.disabled;
if (u.disabled) presence.delete(u.id); // drop them off "training now" at once
saveDb();
json(res, 200, { ok: true, id: u.id, disabled: u.disabled });
},
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.1.3",
"version": "1.1.4",
"type": "module",
"scripts": {
"dev": "vite",
+16 -4
View File
@@ -19,6 +19,7 @@ const rel = ts => {
if (s < 86400) return Math.floor(s / 3600) + 'h ago'
return Math.floor(s / 86400) + 'd ago'
}
const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + 'm' : Math.floor(m / 60) + 'h' + (m % 60) + 'm' }
function UserDetail({ id, onChanged, close }) {
const [d, setD] = useState(null)
@@ -96,10 +97,12 @@ export default function Admin() {
const loadUsers = () => api('/api/admin/users').then(d => { setUsers(d.users); setInviteOnly(d.invite_only) }).catch(e => toast(e.message || 'Failed to load'))
const loadInvites = () => api('/api/admin/invites').then(d => setInvites(d.invites)).catch(() => {})
useEffect(() => { if (user?.admin) { loadUsers(); loadInvites() } }, [])
// poll every 15s so the "training now" section stays live without a manual refresh
useEffect(() => { if (!user?.admin) return; loadUsers(); loadInvites(); const iv = setInterval(loadUsers, 15000); return () => clearInterval(iv) }, [])
if (!user?.admin) return null
const openUser = id => openSheet(close => <UserDetail id={id} onChanged={loadUsers} close={close} />)
const liveUsers = (users || []).filter(u => u.live)
const activeCount = (users || []).filter(u => u.lastSync && Date.now() - u.lastSync < 7 * 86400000).length
const disabledCount = (users || []).filter(u => u.disabled).length
@@ -113,18 +116,27 @@ export default function Admin() {
<div className="tiles" style={{ marginBottom: 12 }}>
<div className="tile"><div className="l">Users</div><div className="v">{users ? users.length : '—'}</div></div>
<div className="tile"><div className="l">Training now</div><div className="v" style={{ color: liveUsers.length ? 'var(--acc)' : undefined }}>{users ? liveUsers.length : '—'}</div></div>
<div className="tile"><div className="l">Active 7d</div><div className="v">{users ? activeCount : '—'}</div></div>
<div className="tile"><div className="l">Disabled</div><div className="v">{users ? disabledCount : '—'}</div></div>
<div className="tile"><div className="l">Signup</div><div className="v" style={{ fontSize: '.95rem' }}>{inviteOnly ? 'invite' : 'open'}</div></div>
</div>
{liveUsers.length > 0 && <div className="card" style={{ borderColor: 'var(--acc)' }}>
<h2 style={{ margin: '0 0 8px' }}>🟢 Training now</h2>
{liveUsers.map(u => <div key={u.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--bg2)' }} onClick={() => openUser(u.id)}>
<div><div className="small" style={{ fontWeight: 700 }}>{u.name}</div>
<div className="dim" style={{ fontSize: '.72rem' }}>{u.live.name} · ex {u.live.exIdx}/{u.live.exTotal} · {u.live.setsDone}/{u.live.setsTotal} sets</div></div>
<span className="tag acc">{dur(Date.now() - u.live.startedAt)}</span>
</div>)}
</div>}
<InvitesCard invites={invites} reload={loadInvites} />
<h4 className="sec">Users</h4>
<div className="list">
{(users || []).map(u => <div key={u.id} className="item" onClick={() => openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}>
<div className="grow"><div className="tt">{u.name} {u.admin && <span className="tag acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="tag" style={{ marginLeft: 4, color: 'var(--red)' }}>off</span>}</div>
<div className="ss">{u.workouts} workouts{u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : ''} · synced {rel(u.lastSync)}</div></div>
<div className="grow"><div className="tt">{u.live && '🟢 '}{u.name} {u.admin && <span className="tag acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="tag" style={{ marginLeft: 4, color: 'var(--red)' }}>off</span>}</div>
<div className="ss">{u.live ? 'training now · ' + u.live.name : u.workouts + ' workouts' + (u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : '') + ' · synced ' + rel(u.lastSync)}</div></div>
{u.hasPush && <span title="push enabled">🔔</span>}<span className="chev">›</span>
</div>)}
{users && !users.length && <div className="empty">No users yet.</div>}
+28
View File
@@ -7,6 +7,7 @@ import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActiv
import { fmtNum, fmtDate, todayISO, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import Media from '../components/Media.jsx'
import NumField from '../components/NumField.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx'
@@ -147,6 +148,33 @@ function ActiveWorkout() {
else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged 🏃'))
}
// Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only —
// guests have no server session. Reads fresh state each tick so progress stays current.
useEffect(() => {
if (!useStore.getState().user) return
let stopped = false
const ping = active => {
const A2 = useStore.getState().S.active
if (!A2) return
const u = supersetUnits(A2.entries)
const c = Math.min(A2.cur, Math.max(0, A2.entries.length - 1))
const ui = u.findIndex(x => x.includes(c))
const tot = A2.entries.reduce((n, e) => n + e.sets.length, 0)
api('/api/activity', { method: 'POST', body: JSON.stringify({
active, name: A2.name, exIdx: ui + 1, exTotal: u.length,
setsDone: setsDoneActive(A2), setsTotal: tot, startedAt: A2.start
}) }).catch(() => {})
}
ping(true)
const iv = setInterval(() => { if (!stopped) ping(true) }, 20000)
return () => {
stopped = true; clearInterval(iv)
// best-effort "left" signal: sendBeacon survives a tab close, fetch covers in-app nav
try { navigator.sendBeacon?.('/api/activity', new Blob([JSON.stringify({ active: false })], { type: 'application/json' })) } catch { /* */ }
api('/api/activity', { method: 'POST', body: JSON.stringify({ active: false }) }).catch(() => {})
}
}, [])
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" onClick={() => confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); nav('/home') } })}>✕</button>