Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
web: send the workout "left" signal when the page goes away, and say why
Boris 'B' Kurktchiev61602f863ef5
diff --git a/api/openapi.yaml b/api/openapi.yamlindex abb279e45..a52ad3e3a 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -1974,8 +1974,12 @@ paths:description: |The client pings this every ~20 s while a workout is on screen; the admindashboard reads who is training right now. Purely ephemeral, in-memory, never- persisted; entries expire ~70 s after the last ping. `{"active": false}`- drops the caller's entry immediately.+ persisted; entries expire 70 s after the last ping. `{"active": false}` is the+ "left" signal: with `reason` `navigated` or `closed`, or with no reason, it+ drops the caller's entry immediately. With `reason: hidden` (the page went to+ the background) it marks the entry away instead, and the entry stops being+ listed 45 s after that mark unless a heartbeat arrives first; a heartbeat+ clears the mark. The 70 s expiry applies either way.requestBody:required: truecontent:@@ -1985,7 +1989,16 @@ paths:properties:active:type: boolean- description: false ends the presence; true (with the fields below) updates it.+ description: false ends the presence (see `reason`); true (with the fields below) updates it.+ reason:+ type: string+ enum: [navigated, closed, hidden]+ description: >-+ Why the client sent `active: false`: `navigated` (an in-app route+ change), `closed` (the page is going away) or `hidden` (the page went+ to the background). `navigated` and `closed` drop the entry at once,+ as no reason does; `hidden` marks it away rather than dropping it.+ Ignored with `active: true`.name:type: stringmaxLength: 60diff --git a/api/server.js b/api/server.jsindex debdd4840..4269f3dc4 100644--- a/api/server.js+++ b/api/server.js@@ -665,15 +665,28 @@ 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 = new Map(); // uid -> { name, exIdx, exTotal, setsDone, setsTotal, startedAt, updatedAt, hiddenAt? }const PRESENCE_TTL = 70000; // ~3.5× the 20s client heartbeat+// A "left" signal with reason `hidden` (the workout page went to the background) marks the row+// away at that moment instead of dropping it. A phone locked between sets keeps the page running+// and heartbeating, and the next heartbeat clears the mark, so the athlete never blinks off the+// dashboard; an iOS home-screen app swiped away sends `hidden` and nothing after it, so it is gone+// this long after instead of the full TTL. Two heartbeat intervals and 5 s: browsers throttle a+// hidden page's timers, so its first heartbeat after the hide can run late, and one late+// heartbeat must not take a locked phone off the list.+const PRESENCE_HIDDEN_GRACE = 45000;+// Whether a row counts as "training now". The one place that decides it: the admin list and the+// sweep below both ask here.+const presenceListed = (p, now) =>+ now - p.updatedAt < PRESENCE_TTL && (p.hiddenAt === undefined || now - p.hiddenAt < PRESENCE_HIDDEN_GRACE);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;+ if (!presenceListed(p, Date.now())) { presence.delete(uid); return null; }+ const { hiddenAt: _away, ...live } = p; // the mark is bookkeeping; the dashboard gets the row it always did+ return live;}-setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt > PRESENCE_TTL) presence.delete(k); }, 30000).unref();+setInterval(() => { const now = Date.now(); for (const [k, v] of presence) if (!presenceListed(v, now)) presence.delete(k); }, 30000).unref();/* ---------- audit log ---------- */// Who signed in, who tried and failed, and what an admin changed. One JSON object per line in@@ -2153,12 +2166,15 @@ const routes = {json(res, 200, { ok: true });},- // Live-workout heartbeat: client pings while a workout is on screen; { active:false } drops it.+ // Live-workout heartbeat: client pings while a workout is on screen; { active:false } drops it,+ // except with reason `hidden`, which marks it away (see PRESENCE_HIDDEN_GRACE). `navigated`,+ // `closed`, and no reason at all (older clients), drop it at once.'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) {+ // a fresh row, which also clears any hidden markpresence.set(user.id, {name: text(body.name).slice(0, 60),exIdx: +body.exIdx || 0, exTotal: +body.exTotal || 0,@@ -2166,6 +2182,10 @@ const routes = {startedAt: +body.startedAt || Date.now(),updatedAt: Date.now()});+ } else if (body.reason === 'hidden') {+ // The first mark stands: a repeat without a heartbeat between cannot stretch the grace.+ const p = presence.get(user.id);+ if (p && p.hiddenAt === undefined) p.hiddenAt = Date.now();} else presence.delete(user.id);json(res, 200, { ok: true });},diff --git a/api/test/fake-clock.mjs b/api/test/fake-clock.mjsnew file mode 100644index 000000000..b8dbb2df8--- /dev/null+++ b/api/test/fake-clock.mjs@@ -0,0 +1,16 @@+/* A clock the test drives, for a server.js spawned in a child. Load it ahead of the server with+ * `node --import ./test/fake-clock.mjs server.js` and an 'ipc' entry in stdio.+ *+ * Date.now() is the real clock until the parent sends { now: <ms> }; from then on it returns that+ * value and stands still until the next one. Every message is answered with { now } once it has+ * taken effect, so a request the test sends after the answer is served at the new time. Only+ * Date.now() moves: timers keep real time, so nothing fires early or late because of it.+ */+const realNow = Date.now;+let fixed = null;+Date.now = () => (fixed === null ? realNow() : fixed);+process.on('message', m => {+ if (!m || typeof m.now !== 'number') return;+ fixed = m.now;+ process.send({ now: fixed });+});diff --git a/api/test/server-presence.test.js b/api/test/server-presence.test.jsnew file mode 100644index 000000000..eb4835fe4--- /dev/null+++ b/api/test/server-presence.test.js@@ -0,0 +1,172 @@+/* "Training now" on the admin dashboard, and the reasons a workout page gives when it sends its+ "left" signal (POST /api/activity { active: false, reason }).++ - `navigated` (in-app route change) and `closed` (pagehide) drop the athlete at once, and so+ does no reason at all, which is what older clients send.+ - `hidden` (the page went to the background) only marks the row. A phone locked between sets+ keeps heartbeating and the heartbeat clears the mark, so the athlete never blinks off the+ list; with no heartbeat after it (an iOS home-screen app swiped away) the athlete is gone+ 45 s after the mark, and at the 70 s expiry after the last heartbeat whatever the mark says.++ Real server.js in a child, with its Date.now() driven by test/fake-clock.mjs over IPC, so each+ step below happens at an exact server time. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { boundPort } from './helpers.mjs';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');+// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET.+const mintSession = uid => {+ const payload = `${uid}:${Date.now() + 86400000}:0`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+};+const ADMIN = 'u_adm_1', ATHLETE = 'u_ath_1';+const as = uid => ({ Cookie: `gymsid=${mintSession(uid)}`, 'Content-Type': 'application/json', Origin: 'http://localhost:8080' });+const TTL = 70000, GRACE = 45000;+const T0 = Math.floor(Date.now() / 1000) * 1000;++async function startServer(t) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-presence-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({+ users: [+ { id: ADMIN, name: 'Adminna', created: new Date().toISOString(), admin: true },+ { id: ATHLETE, name: 'Athlete', created: new Date().toISOString() }+ ], creds: [], subs: [], invites: []+ }));+ const child = spawn(process.execPath, ['--import', './test/fake-clock.mjs', 'server.js'], {+ cwd: API, stdio: ['ignore', 'pipe', 'pipe', 'ipc'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }+ });+ let log = '';+ child.stdout.on('data', d => log += d);+ child.stderr.on('data', d => log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ const api = `http://127.0.0.1:${await boundPort(child, () => log)}`;++ const post = async body => {+ const r = await fetch(`${api}/api/activity`, { method: 'POST', headers: as(ATHLETE), body: JSON.stringify(body) });+ assert.equal(r.status, 200, log);+ };+ return {+ // Set the server's clock and wait until it has taken.+ at: now => new Promise(resolve => {+ const done = m => { if (m && m.now === now) { child.off('message', done); resolve(); } };+ child.on('message', done);+ child.send({ now });+ }),+ beat: () => post({ active: true, name: 'Push Day', exIdx: 2, exTotal: 5, setsDone: 7, setsTotal: 16, startedAt: T0 - 600000 }),+ left: reason => post(reason === undefined ? { active: false } : { active: false, reason }),+ // The athlete's row as the dashboard gets it: the presence object, or null.+ live: async () => {+ const r = await fetch(`${api}/api/admin/users`, { headers: as(ADMIN) });+ assert.equal(r.status, 200, log);+ return (await r.json()).users.find(u => u.id === ATHLETE).live;+ }+ };+}++test('navigated, closed and no reason at all drop the athlete at once', async t => {+ const h = await startServer(t);+ for (const reason of ['navigated', 'closed', undefined]) {+ await h.at(T0);+ await h.beat();+ assert.ok(await h.live(), `listed before ${reason}`);+ await h.left(reason);+ assert.equal(await h.live(), null, `gone at once after ${reason}`);+ }+});++test('hidden keeps the athlete listed for 45 s after the mark, then drops them', async t => {+ const h = await startServer(t);+ await h.at(T0);+ await h.beat();+ await h.at(T0 + 5000);+ await h.left('hidden');+ const live = await h.live();+ assert.equal(live.name, 'Push Day', 'still listed right after the mark');+ assert.deepEqual(Object.keys(live).sort(), ['exIdx', 'exTotal', 'name', 'setsDone', 'setsTotal', 'startedAt', 'updatedAt'],+ 'the dashboard gets the row it always did, with no mark in it');+ await h.at(T0 + 5000 + GRACE - 1);+ assert.ok(await h.live(), 'listed until the grace is up');+ await h.at(T0 + 5000 + GRACE);+ assert.equal(await h.live(), null, 'gone 45 s after the mark, before the 70 s expiry');+});++test('a heartbeat after hidden (a phone locked between sets) clears the mark', async t => {+ const h = await startServer(t);+ await h.at(T0);+ await h.beat();+ await h.at(T0 + 1000);+ await h.left('hidden');+ await h.at(T0 + 20000);+ await h.beat();+ await h.at(T0 + 1000 + GRACE);+ assert.ok(await h.live(), 'past the grace, still listed: the heartbeat cleared the mark');+ await h.at(T0 + 20000 + TTL - 1);+ assert.ok(await h.live(), 'listed until the expiry after that heartbeat');+ await h.at(T0 + 20000 + TTL);+ assert.equal(await h.live(), null, 'and gone at it');+});++test('the 70 s expiry after the last heartbeat applies whatever the hidden mark says', async t => {+ const h = await startServer(t);+ await h.at(T0);+ await h.beat();+ await h.at(T0 + 60000);+ await h.left('hidden');+ await h.at(T0 + TTL - 1);+ assert.ok(await h.live(), 'listed: 10 s into the grace and inside the expiry');+ await h.at(T0 + TTL);+ assert.equal(await h.live(), null, 'gone at the expiry, 10 s into a 45 s grace');+});++test('a second hidden with no heartbeat between does not stretch the grace', async t => {+ const h = await startServer(t);+ await h.at(T0);+ await h.beat();+ await h.at(T0 + 1000);+ await h.left('hidden');+ await h.at(T0 + 20000);+ await h.left('hidden');+ await h.at(T0 + 1000 + GRACE);+ assert.equal(await h.live(), null, 'gone 45 s after the first mark');+});++test('hidden with no row (it arrived after closed) lists nobody', async t => {+ const h = await startServer(t);+ await h.at(T0);+ await h.beat();+ await h.left('closed');+ await h.left('hidden');+ assert.equal(await h.live(), null);+});++// The `hidden` beacon and the heartbeat go out on different connections, so the beacon can land+// after a heartbeat the page sent later than it and mark that fresh row. The page's next+// heartbeat, at most 20 s on, replaces the row inside the 45 s grace, so an athlete whose page+// keeps heartbeating is listed at every second, however late in the interval the beacon lands.+test('a hidden that lands after a later heartbeat cannot drop an athlete who keeps heartbeating', async t => {+ const h = await startServer(t);+ let base = T0;+ for (const late of [0, 10000, 19999]) {+ await h.at(base);+ await h.beat();+ await h.at(base + late);+ await h.left('hidden'); // lands after the heartbeat it raced+ assert.ok(await h.live(), `listed right after a beacon ${late} ms late`);+ for (let s = 1; s <= 100; s++) {+ await h.at(base + s * 1000);+ if (s % 20 === 0) await h.beat();+ assert.ok(await h.live(), `listed ${s} s on, with the beacon ${late} ms late`);+ }+ base += 200000;+ }+});diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 39340a4ed..831e38a20 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -1235,13 +1235,38 @@ function ActiveWorkout() {setsDone: setsDoneActive(A2), setsTotal: tot, startedAt: A2.start}) }).catch(() => {})}- ping(true)- const iv = setInterval(() => { if (!stopped) ping(true) }, 20000)+ // The cleanup below runs on in-app navigation only. A closed tab, or a home-screen app swiped+ // away or killed by the phone, unmounts nothing, so "training now" kept the athlete until the+ // server's presence expiry, 70 s after they had gone. So the page going away sends the "left"+ // signal itself, and says why: `closed` on pagehide, which the server acts on at once, and+ // `hidden` on visibilitychange, because iOS kills a hidden home-screen app without a pagehide.+ // The server keeps a `hidden` athlete listed for 45 s and a heartbeat cancels it, so a hidden+ // page that keeps running (a phone locked between sets) goes on heartbeating and never blinks+ // off the list; an iOS app swiped away sends nothing after `hidden` and is gone in 45 s. Each+ // is sent once per hide, re-armed by a heartbeat; the pagehide of a close that went hidden+ // first still sends `closed`, and nothing follows `closed`. A page shown again heartbeats at once.+ let sent = null+ const live = () => { sent = null; ping(true) }+ const leave = reason => {+ if (sent === 'closed' || sent === reason) return+ sent = reason; beacon('/api/activity', { active: false, reason })+ }+ const onVisibility = () => { if (document.visibilityState === 'hidden') leave('hidden'); else if (sent && !stopped) live() }+ const onHide = () => leave('closed')+ const onShow = e => { if (e.persisted && sent && !stopped) live() }+ live()+ const iv = setInterval(() => { if (!stopped) live() }, 20000)+ document.addEventListener('visibilitychange', onVisibility)+ window.addEventListener('pagehide', onHide)+ window.addEventListener('pageshow', onShow)return () => {stopped = true; clearInterval(iv)+ document.removeEventListener('visibilitychange', onVisibility)+ window.removeEventListener('pagehide', onHide)+ window.removeEventListener('pageshow', onShow)// best-effort "left" signal: the beacon survives a tab close, fetch covers in-app nav- beacon('/api/activity', { active: false })- api('/api/activity', { method: 'POST', body: JSON.stringify({ active: false }) }).catch(() => {})+ beacon('/api/activity', { active: false, reason: 'navigated' })+ api('/api/activity', { method: 'POST', body: JSON.stringify({ active: false, reason: 'navigated' }) }).catch(() => {})}}, [])diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsxindex f9413ea94..93707279f 100644--- a/frontend/src/views/Workout.test.jsx+++ b/frontend/src/views/Workout.test.jsx@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client'import { parseHTML } from 'linkedom'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import Workout from './Workout.jsx'+import { api, beacon } from '../lib/api.js'import { nextPrescription } from '../lib/progression.js'import { buildCombinedEntries } from '../lib/session-merge.js'import { buildCompletedWorkout } from '../lib/finish-workout.js'@@ -11,6 +12,7 @@ import { isWarmupRow } from '../lib/workout-model.js'const mocks = vi.hoisted(() => {const state = {S: null,+ user: null,timer: null,work: null,startRest: vi.fn(),@@ -35,7 +37,7 @@ const mocks = vi.hoisted(() => {state.stopWork = vi.fn(() => { state.work = null })state.storeSnapshot = () => ({S: state.S,- user: null,+ user: state.user,update: mut => {const next = structuredClone(state.S)mut(next)@@ -93,6 +95,7 @@ vi.mock('../components/Media.jsx', () => ({ default: () => null }))// tests rather than declaring a vitest environment, so it must not depend on an ambient one.vi.mock('../lib/api.js', () => ({api: vi.fn(() => Promise.resolve({})),+ beacon: vi.fn(),IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',}))@@ -217,6 +220,7 @@ async function rerenderAt(cur) {beforeEach(() => {vi.clearAllMocks()+ mocks.user = nullmocks.timer = nullmocks.work = nullmocks.scrollCalls.length = 0@@ -808,6 +812,137 @@ describe('Workout discard timer lifecycle', () => {})})+// The live-presence "left" signal goes through lib/api.js beacon() (upstream's: the web app's+// own origin, nothing on a phone, where the api() call beside it reaches the server).+describe('Workout live-presence heartbeat', () => {+ it('leaving the screen signed in sends the "left" signal through beacon() and the API, as navigated', async () => {+ mocks.user = { id: 'u1', name: 'Boris' }+ await mount([exercise('plain-bench', [false])])+ expect(api).toHaveBeenCalledWith('/api/activity', expect.objectContaining({ method: 'POST' }))+ await unmount()+ expect(beacon).toHaveBeenCalledTimes(1)+ expect(beacon).toHaveBeenCalledWith('/api/activity', { active: false, reason: 'navigated' })+ expect(api).toHaveBeenLastCalledWith('/api/activity', { method: 'POST', body: JSON.stringify({ active: false, reason: 'navigated' }) })+ })++ it('a guest has no server session, so there is no heartbeat and no signal', async () => {+ await mount([exercise('plain-bench', [false])])+ await unmount()+ expect(beacon).not.toHaveBeenCalled()+ expect(api).not.toHaveBeenCalledWith('/api/activity', expect.anything())+ })+})++// A closed tab, or a home-screen app swiped away or killed by the phone, never unmounts the screen,+// so the "left" signal in the effect cleanup never went and "training now" kept the athlete until+// the server's presence expiry. The page going away sends it itself, with the reason the server+// goes by: `closed` drops the athlete at once, `hidden` gives a heartbeat 45 s to cancel it.+describe('Workout live-presence "left" signal when the page goes away', () => {+ let visibility+ const setVisibility = async state => {+ visibility = state+ await act(async () => { document.dispatchEvent(new dom.Event('visibilitychange')) })+ }+ const pagehide = async () => { await act(async () => { window.dispatchEvent(new dom.Event('pagehide')) }) }+ const pageshow = async persisted => {+ await act(async () => { window.dispatchEvent(Object.assign(new dom.Event('pageshow'), { persisted })) })+ }+ const heartbeats = () => vi.mocked(api).mock.calls.filter(([path, opts]) => path === '/api/activity' && JSON.parse(opts.body).active === true).length+ const reasons = () => vi.mocked(beacon).mock.calls.map(([, body]) => body.reason)+ const signedInMount = async () => {+ mocks.user = { id: 'u1', name: 'Boris' }+ await mount([exercise('plain-bench', [false])])+ visibility = 'visible'+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility })+ }+ afterEach(() => { vi.useRealTimers() })++ it('a closing tab (pagehide) sends it through beacon() as closed while the screen is still mounted', async () => {+ await signedInMount()+ await pagehide()+ expect(beacon).toHaveBeenCalledTimes(1)+ expect(beacon).toHaveBeenCalledWith('/api/activity', { active: false, reason: 'closed' })+ })++ it('an iOS home-screen app going hidden sends it as hidden, once, however many hidden events follow', async () => {+ await signedInMount()+ await setVisibility('hidden')+ await setVisibility('hidden')+ expect(beacon).toHaveBeenCalledTimes(1)+ expect(beacon).toHaveBeenCalledWith('/api/activity', { active: false, reason: 'hidden' })+ })++ it('a close whose pagehide follows the hidden visibilitychange still sends closed, once', async () => {+ await signedInMount()+ await setVisibility('hidden')+ await pagehide()+ await pagehide()+ expect(reasons()).toEqual(['hidden', 'closed'])+ })++ it('nothing follows closed: a visibilitychange to hidden after the pagehide sends nothing more', async () => {+ await signedInMount()+ await pagehide()+ await setVisibility('hidden')+ expect(reasons()).toEqual(['closed'])+ })++ it('shown again, the page heartbeats at once, and the next hide sends it again', async () => {+ await signedInMount()+ const before = heartbeats()+ await setVisibility('hidden')+ await setVisibility('visible')+ expect(heartbeats()).toBe(before + 1)+ await setVisibility('hidden')+ expect(reasons()).toEqual(['hidden', 'hidden'])+ })++ it('a page back from the back/forward cache heartbeats at once, and its next close sends closed again', async () => {+ await signedInMount()+ const before = heartbeats()+ await pagehide()+ await pageshow(false)+ expect(heartbeats()).toBe(before)+ await pageshow(true)+ expect(heartbeats()).toBe(before + 1)+ await pagehide()+ expect(reasons()).toEqual(['closed', 'closed'])+ })++ it('a hidden page that keeps heartbeating is re-armed, for hidden and for the close that follows', async () => {+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] })+ await signedInMount()+ await setVisibility('hidden')+ expect(reasons()).toEqual(['hidden'])+ const before = heartbeats()+ await act(async () => { vi.advanceTimersByTime(20000) })+ expect(heartbeats()).toBe(before + 1)+ await setVisibility('hidden')+ expect(reasons()).toEqual(['hidden', 'hidden'])+ await pagehide()+ expect(reasons()).toEqual(['hidden', 'hidden', 'closed'])+ })++ it('a guest sends nothing, and an unmounted screen stops listening', async () => {+ await mount([exercise('plain-bench', [false])])+ await pagehide()+ expect(beacon).not.toHaveBeenCalled()+ await unmount()++ await signedInMount()+ const win = window+ const doc = document+ await unmount()+ expect(reasons()).toEqual(['navigated']) // the cleanup's own+ const after = heartbeats()+ win.dispatchEvent(new win.Event('pagehide'))+ visibility = 'hidden'+ doc.dispatchEvent(new win.Event('visibilitychange'))+ expect(beacon).toHaveBeenCalledTimes(1)+ expect(heartbeats()).toBe(after)+ })+})+describe('progression guidance', () => {it('labels the visible outcome with the policy that calculated it', async () => {await mount([exercise('plain-bench', [false, false, false], {diff --git a/website/api.html b/website/api.htmlindex 9a2713946..670341cb9 100644--- a/website/api.html+++ b/website/api.html@@ -1800,14 +1800,19 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<span class="ep-sum">Live-workout presence heartbeat</span></summary><div class="ep-body">-<p>The client pings this every ~20 s while a workout is on screen; the admin dashboard reads who is training right now. Purely ephemeral, in-memory, never persisted; entries expire ~70 s after the last ping. <code>{"active": false}</code> drops the caller's entry immediately.</p>+<p>The client pings this every ~20 s while a workout is on screen; the admin dashboard reads who is training right now. Purely ephemeral, in-memory, never persisted; entries expire 70 s after the last ping. <code>{"active": false}</code> is the "left" signal: with <code>reason</code> <code>navigated</code> or <code>closed</code>, or with no reason, it drops the caller's entry immediately. With <code>reason: hidden</code> (the page went to the background) it marks the entry away instead, and the entry stops being listed 45 s after that mark unless a heartbeat arrives first; a heartbeat clears the mark. The 70 s expiry applies either way.</p><p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p><p class="ep-h">Request body <span class="p-hint">(JSON)</span></p><div class="ptab"><div class="prow"><span class="p-name">active</span><span class="p-type">boolean</span>- <span class="p-desc">false ends the presence; true (with the fields below) updates it.</span>+ <span class="p-desc">false ends the presence (see <code>reason</code>); true (with the fields below) updates it.</span>+ </div>+ <div class="prow">+ <span class="p-name">reason</span>+ <span class="p-type">"navigated" | "closed" | "hidden"</span>+ <span class="p-desc">Why the client sent <code>active: false</code>: <code>navigated</code> (an in-app route change), <code>closed</code> (the page is going away) or <code>hidden</code> (the page went to the background). <code>navigated</code> and <code>closed</code> drop the entry at once, as no reason does; <code>hidden</code> marks it away rather than dropping it. Ignored with <code>active: true</code>.</span></div><div class="prow"><span class="p-name">name</span>