Skip to content

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.

Connection: a line under the status bar says whenever the app is not connected to its server, and what to do about it

Duarte Santosb6c17b61b645
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 60e0f2916..9bc2ab4f4 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -143,7 +143,6 @@ function Shell() {
re-mounts the boundary, so the tab bar is always a way out */}
<div id="app" className="vfade" key={loc.pathname}>
<ErrorBoundary>
- {authed && !needsMobileOnboarding && <SyncBanner />}
{!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : (
<Routes>
<Route path="/home" element={<Home />} />
@@ -171,6 +170,10 @@ function Shell() {
)}
</ErrorBoundary>
</div>
+ {/* Outside #app: the view's fade-in animates a transform, and a fixed element inside it
+ would ride along with the page for the length of it. Decides for itself when to show —
+ including on the sign-in screen, when the server has just ended the session. */}
+ <SyncBanner />
{/* The chat owns the bottom of the screen: its composer sits where the tabs would be. */}
{loc.pathname !== '/coach' && <TabBar onStart={startFlow} />}
<RestTimer />
diff --git a/frontend/src/coach.css b/frontend/src/coach.css
index f5e8e15f5..c64147ffd 100644
--- a/frontend/src/coach.css
+++ b/frontend/src/coach.css
@@ -79,10 +79,11 @@
.chat-hdr{
display:flex;align-items:center;gap:10px;
/* Pinned like a messenger's title bar: it eats the app shell's top padding so the blur
- reaches the status bar, and gives it back as its own padding. */
+ reaches the status bar, and gives it back as its own padding — below the connection
+ indicator (--conn) when there is one. */
position:sticky;top:0;z-index:40;
- margin:calc(-1 * (var(--sat) + 8px)) calc(-1 * var(--pad)) 8px;
- padding:calc(var(--sat) + 8px) var(--pad) 8px;
+ margin:calc(-1 * (var(--sat) + var(--conn) + 8px)) calc(-1 * var(--pad)) 8px;
+ padding:calc(var(--sat) + var(--conn) + 8px) var(--pad) 8px;
background:color-mix(in srgb,var(--bg) 88%,transparent);
-webkit-backdrop-filter:saturate(180%) blur(12px);backdrop-filter:saturate(180%) blur(12px)
}
diff --git a/frontend/src/components/Icon.jsx b/frontend/src/components/Icon.jsx
index 065eb2429..41ca2ef99 100644
--- a/frontend/src/components/Icon.jsx
+++ b/frontend/src/components/Icon.jsx
@@ -100,6 +100,9 @@ const P = {
sun: <><circle cx="12" cy="12" r="4.4" /><path d="M12 3.6v2M12 18.4v2M20.4 12h-2M5.6 12h-2M17.94 6.06l-1.42 1.42M7.48 16.52l-1.42 1.42M17.94 17.94l-1.42-1.42M7.48 7.48 6.06 6.06" /></>,
key: <><circle cx="8.2" cy="15.8" r="3.8" /><path d="m10.9 13.1 8-8M16.6 7.4l2 2M14.6 9.4l2 2" /></>,
lock: <><rect x="5" y="10.4" width="14" height="10" rx="2.8" /><path d="M8.4 10.4V7.8a3.6 3.6 0 0 1 7.2 0v2.6" /></>,
+ // the connection to the server (components/SyncBanner.jsx): there, and not there
+ cloud: <path d="M7 18.2h10.2a3.6 3.6 0 0 0 .1-7.2 5.4 5.4 0 0 0-10.4.6A3.3 3.3 0 0 0 7 18.2Z" />,
+ cloudSlash: <><path d="M7 18.2h10.2a3.6 3.6 0 0 0 .1-7.2 5.4 5.4 0 0 0-10.4.6A3.3 3.3 0 0 0 7 18.2Z" /><path d="M4 3.6l16 16.8" /></>,
download: <path d="M12 3.8v11.4M7.6 11.2 12 15.6l4.4-4.4M4.6 19.4h14.8" />,
upload: <path d="M12 15.6V4.2M7.6 8.2 12 3.8l4.4 4.4M4.6 19.4h14.8" />,
wrench: <path d="M15.2 3.9a5 5 0 0 0-4.8 6.6l-6 6a2.1 2.1 0 0 0 3 3l6-6a5 5 0 0 0 6.1-6.3l-2.9 2.9-2.8-.7-.7-2.8Z" />,
diff --git a/frontend/src/components/ServerSync.jsx b/frontend/src/components/ServerSync.jsx
new file mode 100644
index 000000000..207c31acd
--- /dev/null
+++ b/frontend/src/components/ServerSync.jsx
@@ -0,0 +1,230 @@
+// The connection to the server, as the screens show it and act on it: the persistent indicator
+// (SyncBanner.jsx), the "Server & sync" block in Settings, and the question a sign-out or a
+// disconnect asks when the server has not got everything yet. The store decides the state
+// (useStore.js, `sync` — see statusOf there); this file only words it and offers what to do.
+import { useEffect, useState } from 'react'
+import { useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { t } from '../lib/i18n.js'
+import { fmtAgo, changeCount } from '../lib/format.js'
+import { passkeyLogin, webauthnOK } from '../lib/api.js'
+import { MOBILE } from '../lib/mobile.js'
+import { DEMO } from '../lib/demo.js'
+import { askAddDeviceData } from '../sheets.jsx'
+import { ConnectSheet } from '../views/MobileOnboarding.jsx'
+import { Section, Row, Button } from './ui.jsx'
+
+const ui = () => useUI.getState()
+const toast = m => ui().toast(m)
+
+// "gym.example.com" out of the base URL the store keeps (a subpath stays: it is part of which
+// server this is). Anything unparseable is shown as it is.
+export const hostOf = base => {
+ try { const u = new URL(base); return u.host + u.pathname.replace(/\/$/, '') } catch { return base || '' }
+}
+
+/* One state of `sync`, in words:
+ tone 'ok' | 'wait' | 'off' | 'bad' | 'quiet' — the colour, from fine to deliberate local use
+ line the short status line: Settings, and the toast after "Sync now"
+ banner the sentence the persistent indicator shows, or null when there is nothing to say
+ action what the indicator offers: 'retry' | 'pair' | 'signin' | 'connect' | null
+ `mobile` is the build (a phone pairs, a browser signs in). Every state that is not 'ok' says the
+ changes are kept on this device — that is the one thing the person needs to hear first. */
+export function connectionView(sync, { mobile = MOBILE } = {}) {
+ if (!sync) return null
+ const err = sync.lastError || {}
+ switch (sync.status) {
+ case 'ok':
+ return { tone: 'ok', icon: 'cloud', line: t('All synced'), banner: null, action: null }
+ case 'pending': // the sentence already says "tap to retry": no second word for it
+ return { tone: 'wait', icon: 'reset', line: t('Waiting to sync'), banner: t('Not synced yet — tap to retry.'), action: 'retry', label: null }
+ case 'offline':
+ return {
+ tone: 'off', icon: 'cloudSlash', action: 'retry',
+ line: err.code === 'timeout' ? t('The server did not answer in time.') : t('Offline — the server cannot be reached'),
+ banner: sync.pending ? t('Offline — your changes are saved on this device and sync when you are back online.') : t('Offline — showing the last copy synced with the server.'),
+ }
+ case 'error':
+ return err.code === 'bad-response'
+ ? { tone: 'bad', icon: 'warning', action: 'retry', line: t('Not an openGym answer (HTTP {0})', err.status), banner: t('Your server’s address answered with something other than openGym (HTTP {0}). Your changes are kept here.', err.status) }
+ : { tone: 'bad', icon: 'warning', action: 'retry', line: t('Server error (HTTP {0})', err.status), banner: t('Your server answered with an error (HTTP {0}). Your changes are kept here.', err.status) }
+ case 'auth':
+ if (!mobile) return { tone: 'bad', icon: 'lock', action: 'signin', line: t('The server refuses this browser'), banner: t('Your server no longer accepts this browser. Your changes are kept here.') }
+ // A phone an earlier version unpaired kept no address and no token: nothing refuses it,
+ // there is simply nothing to ask.
+ return err.code === 'not-paired'
+ ? { tone: 'bad', icon: 'lock', action: 'pair', line: t('This phone is not connected to a server.'), banner: t('This phone is no longer paired with your server. Your changes are kept here.') }
+ : { tone: 'bad', icon: 'lock', action: 'pair', line: t('The server refuses this phone'), banner: t('Your server no longer accepts this phone. Your changes are kept here.') }
+ default: // 'local': no server at all — chosen, so it is said quietly, but it is said
+ return mobile
+ ? { tone: 'quiet', icon: 'lock', action: 'connect', line: t('On this phone only — not connected to a server'), banner: t('On this phone only — not connected to a server') }
+ : { tone: 'quiet', icon: 'lock', action: webauthnOK() ? 'signin' : null, line: t('Guest mode — data lives only in this browser.'), banner: t('Guest mode — data lives only in this browser.') }
+ }
+}
+
+// The word on the indicator's button: the view's own `label` when it has one (null for none),
+// else the action's.
+export const actionLabel = view => (view.label !== undefined ? view.label : ({ retry: t('Try again'), pair: t('Pair again'), signin: t('Sign in'), connect: t('Connect') })[view.action] || null)
+
+// "Sync now": whatever is waiting goes, the server's copy is checked, and the answer is said.
+export async function syncNowWithToast() {
+ const sync = await useStore.getState().syncNow()
+ const view = connectionView(sync)
+ if (view) toast(view.line)
+ return sync
+}
+
+// A phone whose server refuses it, or that an earlier version unpaired: the connect sheet, with
+// the address it had where it still has one. The same account merges what the phone kept.
+export function pairAgain() {
+ const server = useStore.getState().sync?.server || ''
+ ui().openSheet(close => <ConnectSheet close={close} initialUrl={server} again />)
+}
+export function connectServer() {
+ ui().openSheet(close => <ConnectSheet close={close} />)
+}
+
+// A browser whose session ended, or a guest: the passkey sign-in, and the same account merges
+// what this browser kept (adoptProfile).
+export async function signInAgain() {
+ const st = useStore.getState()
+ try {
+ const u = await passkeyLogin()
+ st.setUser(u)
+ await st.adoptProfile(askAddDeviceData)
+ toast(t('Welcome back, {0}', u.name))
+ } catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Sign-in failed')) }
+}
+
+/* ---------------------------------------------------------- leaving the server ---------------
+ Disconnect (phone), Sign out and Sign out everywhere (browser) never wipe changes the server
+ has not received (useStore.js). When some are owed, the store refuses and says how many; this
+ asks what to do: try again, export a backup, or go ahead anyway — which keeps the changes on
+ the device until it reaches this server as this account again. `done(result)` runs once the
+ device has actually left. */
+const LEAVE = {
+ disconnect: { run: (st, o) => st.disconnectServer(o), anyway: () => t('Disconnect anyway') },
+ signout: { run: (st, o) => st.signOut(o), anyway: () => t('Sign out anyway') },
+ everywhere: { run: (st, o) => st.signOutAll(o), anyway: () => t('Sign out anyway') },
+}
+async function attempt(kind, opts) {
+ try { return await LEAVE[kind].run(useStore.getState(), opts) }
+ catch (e) { // only "sign out everywhere" throws: the other sessions are all still valid
+ toast(t('Could not sign out everywhere — you are still signed in.'))
+ return null
+ }
+}
+export async function leaveServer(kind, { exportBackup, done }) {
+ const r = await attempt(kind)
+ if (!r) return
+ if (r.owed && !r.stashed) {
+ ui().openSheet(close => <OwedSheet kind={kind} count={r.count} exportBackup={exportBackup} done={done} close={close} />, { kind: 'center', locked: true })
+ return
+ }
+ done(r)
+}
+
+export function OwedSheet({ kind, count: count0, exportBackup, done, close }) {
+ const sync = useStore(s => s.sync)
+ const [count, setCount] = useState(count0)
+ const [busy, setBusy] = useState(false)
+ const [tried, setTried] = useState(false)
+ const view = connectionView(sync)
+ // Refused because it is paired or signed in to a server that no longer takes it: trying
+ // again cannot work, and pairing or signing in again brings the changes to the server.
+ const refused = sync?.status === 'auth'
+ const finish = r => { close(); done(r) }
+ const retry = async () => {
+ setBusy(true)
+ await useStore.getState().syncNow()
+ const r = await attempt(kind)
+ setBusy(false)
+ if (!r) return
+ if (!r.owed || r.stashed) return finish(r)
+ setCount(r.count); setTried(true)
+ }
+ const anyway = async () => {
+ setBusy(true)
+ const r = await attempt(kind, { force: true })
+ setBusy(false)
+ if (!r) return
+ if (r.owed && !r.stashed) { toast(t('Could not keep a copy of the changes on this device — nothing was removed.')); return }
+ finish(r)
+ }
+ return <div style={{ textAlign: 'center', padding: '4px 0' }}>
+ <h3 style={{ marginBottom: 8 }}>{t('Not everything is on your server yet')}</h3>
+ <div style={{ marginBottom: 6, fontWeight: 600 }}>
+ {count > 0 ? t('Not on your server yet: {0}', changeCount(count)) : t('Some changes on this device have not reached your server.')}
+ </div>
+ {(tried || refused) && view && <div className="small" style={{ color: 'var(--red)', marginBottom: 6 }}>{view.line}</div>}
+ <div className="muted small" style={{ marginBottom: 18, lineHeight: 1.5 }}>
+ {t('Try again, or export a backup first. Going ahead anyway keeps a copy of these changes on this device until it connects to this server as this account again — then they are added back.')}
+ </div>
+ {refused && MOBILE && <><button className="btn primary" disabled={busy} onClick={() => { close(); pairAgain() }}>{t('Pair again')}</button><div style={{ height: 8 }} /></>}
+ {refused && !MOBILE && webauthnOK() && <><button className="btn primary" disabled={busy} onClick={() => { close(); signInAgain() }}>{t('Sign in with passkey')}</button><div style={{ height: 8 }} /></>}
+ {!refused && <><button className="btn primary" disabled={busy} onClick={retry}>{busy ? t('Syncing…') : t('Try again')}</button><div style={{ height: 8 }} /></>}
+ <Button icon="download" disabled={busy} onClick={exportBackup}>{t('Export backup (JSON)')}</Button>
+ <div style={{ height: 8 }} />
+ <button className="btn danger" disabled={busy} onClick={anyway}>{LEAVE[kind].anyway()}</button>
+ <div style={{ height: 8 }} />
+ <Button variant="ghost" className="dim" disabled={busy} onClick={close}>{t('Cancel')}</Button>
+ </div>
+}
+
+/* ---------------------------------------------------------------- Settings ------------------- */
+const TINT = { ok: 'var(--green)', wait: 'var(--orange)', off: 'var(--grey)', bad: 'var(--red)', quiet: 'var(--grey)' }
+
+// Settings → "Server & sync", for a device signed in or paired: which server, which account, how
+// things stand, since when, what is still waiting, and "Sync now". `children` are the account's
+// own rows (the phone's Admin and Disconnect), which belong in the same block.
+export function ServerSyncSection({ children }) {
+ const user = useStore(s => s.user)
+ const sync = useStore(s => s.sync)
+ useStore(s => s.S) // the count of waiting changes follows every edit
+ const unsynced = useStore(s => s.unsyncedChanges)
+ const [busy, setBusy] = useState(false)
+ // "Last synced: 3 minutes ago" goes stale on an open screen; a re-render now and then keeps it true.
+ const [, tick] = useState(0)
+ useEffect(() => { const iv = setInterval(() => tick(n => n + 1), 30000); return () => clearInterval(iv) }, [])
+ if (!user || !sync) return null
+ const view = connectionView(sync)
+ // While everything is fine, a change still in its short debounce is not news; once anything
+ // is wrong, how much is waiting is exactly what the person needs.
+ const owed = sync.status !== 'ok' && typeof unsynced === 'function' ? unsynced() : { owed: false }
+ const sub = [
+ sync.lastSynced ? t('Last synced: {0}', fmtAgo(sync.lastSynced)) : t('Not synced with this server yet'),
+ owed.owed && (owed.count > 0 ? t('Not on your server yet: {0}', changeCount(owed.count)) : owed.count == null ? t('Some changes on this device have not reached your server.') : null),
+ ].filter(Boolean).join(' · ')
+ const now = async () => {
+ if (busy) return
+ setBusy(true)
+ try { await syncNowWithToast() } finally { setBusy(false) }
+ }
+ return <Section title={t('Server & sync')}>
+ <Row icon="globe" iconTint="var(--blue)" title={sync.server ? hostOf(sync.server) : t('This phone is not connected to a server.')}
+ subtitle={t('Signed in as {0}', user.name)} />
+ <Row icon={view.icon} iconTint={TINT[view.tone]} title={view.line} subtitle={sub} className="sync-status" />
+ <Row icon="reset" iconTint="var(--acc)" title={busy ? t('Syncing…') : t('Sync now')} onClick={now} />
+ {sync.status === 'auth' && (MOBILE
+ ? <Row icon="link" iconTint="var(--indigo)" title={t('Pair again')} subtitle={t('Your changes are kept here, and merged into your account once it is paired again.')} accessory="chevron" onClick={pairAgain} />
+ : webauthnOK() && <Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} subtitle={t('Your changes are kept here, and merged into your account once you are signed in again.')} accessory="chevron" onClick={signInAgain} />)}
+ {children}
+ </Section>
+}
+
+// The changes a forced sign-out or disconnect kept on this device, waiting for their server and
+// account — so a device that went ahead anyway still says what it holds and for whom.
+export function KeptChangesRows() {
+ const kept = useStore(s => s.keptChanges)
+ const user = useStore(s => s.user)
+ const [rows, setRows] = useState([])
+ useEffect(() => {
+ let gone = false
+ if (typeof kept === 'function') kept().then(r => { if (!gone) setRows(r || []) }).catch(() => {})
+ return () => { gone = true }
+ }, [kept, user?.id])
+ if (DEMO) return null
+ return rows.map(k => <Row key={(k.server || '') + '|' + k.uid} icon="history" iconTint="var(--orange)"
+ title={t('Changes kept for {0}', k.name || k.uid)}
+ subtitle={(k.server ? hostOf(k.server) + ' · ' : '') + t('Added back when this device connects as that account again.')} />)
+}
diff --git a/frontend/src/components/SyncBanner.jsx b/frontend/src/components/SyncBanner.jsx
index d47cae978..d2cdd982e 100644
--- a/frontend/src/components/SyncBanner.jsx
+++ b/frontend/src/components/SyncBanner.jsx
@@ -1,22 +1,76 @@
+import { useEffect, useLayoutEffect, useRef, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
-import { t } from '../lib/i18n.js'
+import { DEMO } from '../lib/demo.js'
+import { connectionView, actionLabel, syncNowWithToast, pairAgain, connectServer, signInAgain } from './ServerSync.jsx'
import Icon from './Icon.jsx'
-// One line under the header for a signed-in user whose changes are not on the server: offline,
-// or a push the server refused. Guests and the standalone phone build have no server to sync
-// with, so it never shows for them. Tapping retries at once instead of waiting for the poll.
+// How long a change may sit unsent while the server is reachable before it is worth a word: the
+// push after an edit, or the one boot owes, lands well within this, and saying "not synced" for
+// every one of them would only teach people to ignore the line.
+export const PENDING_GRACE_MS = 5000
+
+/* The connection, always in view while the app is not connected to a server: offline, the server
+ unreachable or answering with an error (its HTTP code, for whoever runs it), a server that no
+ longer accepts this device, an answer that is not openGym's, and no server at all — a phone
+ kept local, a guest in a browser. It cannot be dismissed; it goes when the condition does.
+ The first ones say what is wrong and that the changes are kept here, with the one thing to do
+ about it (retry, pair again, sign in); the deliberate local setup only says so, quietly.
+
+ Pinned under the status bar, above the page and the pinned workout and chat headers, below the
+ tab bar, the timer and every sheet. Its height goes into --conn on the root, which the page's
+ top padding and those headers add in, so it takes its own room instead of covering a control.
+ The public demo has no server by design and says so itself; it never shows there. */
export default function SyncBanner() {
+ const nav = useNavigate()
const user = useStore(s => s.user)
const sync = useStore(s => s.sync)
- const pushState = useStore(s => s.pushState)
- const pullState = useStore(s => s.pullState)
- if (!user || !sync) return null
- if (!sync.offline && !sync.pending) return null
- const retry = () => { pushState(); pullState() }
- return <button className={'sync-banner' + (sync.offline ? ' off' : '')} onClick={retry}>
- <Icon name={sync.offline ? 'bellSlash' : 'reset'} />
- <span>{sync.offline
- ? (sync.pending ? t('Offline — your changes are saved on this device and sync when you are back online.') : t('Offline — showing the last copy synced with the server.'))
- : t('Not synced yet — tap to retry.')}</span>
- </button>
+ const guest = useStore(s => s.isGuest())
+ const onboarding = useStore(s => s.needsMobileOnboarding)
+ const [waited, setWaited] = useState(false)
+ const row = useRef(null)
+ const status = sync?.status
+ useEffect(() => {
+ setWaited(false)
+ if (status !== 'pending') return
+ const tm = setTimeout(() => setWaited(true), PENDING_GRACE_MS)
+ return () => clearTimeout(tm)
+ }, [status])
+
+ const view = connectionView(sync)
+ // Signed out on the web, the sign-in screen is the whole app: it hears only that the server
+ // ended the session, and that the changes are still here.
+ const show = !DEMO && !onboarding && !!view?.banner && (!!user || guest || status === 'auth') && (status !== 'pending' || waited)
+
+ useLayoutEffect(() => {
+ const root = document.documentElement
+ const el = row.current
+ if (!show || !el) { root.style.removeProperty('--conn'); return }
+ const fit = () => root.style.setProperty('--conn', el.offsetHeight + 'px')
+ fit()
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(fit) : null
+ ro?.observe(el)
+ return () => { ro?.disconnect(); root.style.removeProperty('--conn') }
+ }, [show])
+
+ if (!show) return null
+ const act = {
+ retry: () => { syncNowWithToast() },
+ pair: pairAgain,
+ connect: connectServer,
+ // Signed in, or with a session the server ended: the passkey right here. A guest goes to
+ // Settings, where signing in sits next to creating a profile.
+ signin: () => (user || status === 'auth' ? signInAgain() : nav('/settings')),
+ }[view.action]
+ const label = actionLabel(view)
+ const inner = <>
+ <Icon name={view.icon} />
+ <span className="conn-t">{view.banner}</span>
+ {act && label && <span className="conn-a">{label}</span>}
+ </>
+ return <div className={'conn-bar ' + view.tone}>
+ <div className="conn-row" ref={row} role="status" aria-live="polite">
+ {act ? <button className="conn" onClick={act}>{inner}</button> : <div className="conn">{inner}</div>}
+ </div>
+ </div>
}
diff --git a/frontend/src/components/SyncBanner.test.jsx b/frontend/src/components/SyncBanner.test.jsx
new file mode 100644
index 000000000..bda0d0a5e
--- /dev/null
+++ b/frontend/src/components/SyncBanner.test.jsx
@@ -0,0 +1,239 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import SyncBanner, { PENDING_GRACE_MS } from './SyncBanner.jsx'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+/* The connection indicator: every way the app can be without its server gets a line that stays
+ while the condition lasts — offline, an error with its HTTP code, a server that refuses this
+ device, an answer that is not openGym's, no server at all — and says what to do about it.
+ Never in the public demo, never during the phone's first-launch choice, and a change merely
+ waiting for its push does not flash it. The store is a stand-in: its `sync` is what each test
+ sets; ServerSync.jsx (the words and the actions) is the real one. */
+const mocks = vi.hoisted(() => {
+ const state = { MOBILE: false, DEMO: false, webauthn: true, user: null, guest: false, onboarding: false, sync: null, sheets: [], navs: [] }
+ state.toast = vi.fn()
+ state.syncNow = vi.fn(async () => state.sync)
+ state.passkeyLogin = vi.fn(async () => ({ id: 'u1', name: 'andi' }))
+ state.snapshot = () => ({
+ user: state.user, sync: state.sync, needsMobileOnboarding: state.onboarding,
+ isGuest: () => state.guest, syncNow: state.syncNow,
+ setUser: vi.fn(), adoptProfile: vi.fn(async () => ({})),
+ })
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: (render, opts) => { mocks.sheets.push({ render, opts }); return {} } })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => to => mocks.navs.push(to) }))
+vi.mock('../lib/mobile.js', () => ({ get MOBILE() { return mocks.MOBILE } }))
+vi.mock('../lib/demo.js', () => ({ get DEMO() { return mocks.DEMO } }))
+vi.mock('../lib/api.js', () => ({ webauthnOK: () => mocks.webauthn, passkeyLogin: (...a) => mocks.passkeyLogin(...a) }))
+vi.mock('../sheets.jsx', () => ({ askAddDeviceData: vi.fn() }))
+// What the connect sheet was opened with is the point; its own form is tested elsewhere.
+vi.mock('../views/MobileOnboarding.jsx', () => ({ ConnectSheet: props => <div className="connect" data-url={props.initialUrl ?? ''} data-again={String(!!props.again)} /> }))
+
+const BASE = 'https://gym.example.com'
+const sync = (status, extra = {}) => ({ status, offline: false, pending: false, auth: false, lastError: null, lastSynced: 0, server: BASE, ...extra })
+
+let host, root
+beforeEach(() => {
+ Object.assign(mocks, { MOBILE: false, DEMO: false, webauthn: true, user: { id: 'u1', name: 'andi' }, guest: false, onboarding: false, sync: sync('ok') })
+ mocks.sheets.length = 0
+ mocks.navs.length = 0
+ mocks.toast.mockClear(); mocks.syncNow.mockClear(); mocks.passkeyLogin.mockClear()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ vi.useRealTimers()
+})
+
+const render = () => act(() => root.render(<SyncBanner />))
+const bar = () => host.querySelector('.conn-bar')
+const text = () => host.querySelector('.conn-t')?.textContent || null
+const button = () => host.querySelector('button.conn')
+const label = () => host.querySelector('.conn-a')?.textContent || null
+const conn = () => document.documentElement.style.getPropertyValue('--conn')
+const openedConnect = () => { const s = mocks.sheets.at(-1); const r = document.createElement('div'); document.body.appendChild(r); const rr = createRoot(r); act(() => rr.render(s.render(() => {}))); const el = r.querySelector('.connect'); act(() => rr.unmount()); r.remove(); return el }
+
+describe('connected and in step', () => {
+ it('shows nothing, and leaves the page its full height', () => {
+ render()
+ expect(bar()).toBeNull()
+ expect(conn()).toBe('')
+ })
+})
+
+describe('not connected — it says so, and what to do', () => {
+ it('offline with changes waiting: kept on this device, and a retry that reports back', async () => {
+ mocks.sync = sync('offline', { offline: true, pending: true, lastError: { status: 0, code: 'network' } })
+ render()
+ expect(text()).toBe('Offline — your changes are saved on this device and sync when you are back online.')
+ expect(bar().className).toContain('off')
+ expect(label()).toBe('Try again')
+ // Its row's height is what the page and the pinned headers leave free.
+ expect(conn()).not.toBe('')
+ await act(async () => { button().click() })
+ expect(mocks.syncNow).toHaveBeenCalledTimes(1)
+ expect(mocks.toast).toHaveBeenCalledWith('Offline — the server cannot be reached')
+ })
+
+ it('offline with nothing waiting: the copy on screen is the last synced one', () => {
+ mocks.sync = sync('offline', { offline: true, lastError: { status: 0, code: 'timeout' } })
+ render()
+ expect(text()).toBe('Offline — showing the last copy synced with the server.')
+ })
+
+ it('a server error carries its HTTP code, for whoever runs the server', () => {
+ mocks.sync = sync('error', { pending: true, lastError: { status: 502, code: 'http' } })
+ render()
+ expect(text()).toBe('Your server answered with an error (HTTP 502). Your changes are kept here.')
+ expect(bar().className).toContain('bad')
+ })
+
+ it('an answer that is not openGym\'s (a proxy\'s login page) is named as such', () => {
+ mocks.sync = sync('error', { lastError: { status: 200, code: 'bad-response' } })
+ render()
+ expect(text()).toBe('Your server’s address answered with something other than openGym (HTTP 200). Your changes are kept here.')
+ })
+
+ it('phone refused by its server: "Pair again" opens the connect sheet with the address it had', () => {
+ mocks.MOBILE = true
+ mocks.sync = sync('auth', { auth: true, pending: true, lastError: { status: 401, code: 'auth' } })
+ render()
+ expect(text()).toBe('Your server no longer accepts this phone. Your changes are kept here.')
+ expect(label()).toBe('Pair again')
+ act(() => button().click())
+ const sheet = openedConnect()
+ expect(sheet.dataset.url).toBe(BASE)
+ expect(sheet.dataset.again).toBe('true')
+ })
+
+ it('a phone an earlier version unpaired has no address left: pairing asks for it', () => {
+ mocks.MOBILE = true
+ mocks.sync = sync('auth', { auth: true, pending: true, server: null, lastError: { status: 0, code: 'not-paired' } })
+ render()
+ expect(text()).toBe('This phone is no longer paired with your server. Your changes are kept here.')
+ act(() => button().click())
+ expect(openedConnect().dataset.url).toBe('')
+ })
+
+ it('browser refused mid-session: "Sign in" is the passkey, right there', async () => {
+ mocks.sync = sync('auth', { auth: true, pending: true, lastError: { status: 401, code: 'auth' } })
+ render()
+ expect(text()).toBe('Your server no longer accepts this browser. Your changes are kept here.')
+ expect(label()).toBe('Sign in')
+ await act(async () => { button().click() })
+ expect(mocks.passkeyLogin).toHaveBeenCalledTimes(1)
+ })
+
+ it('on the sign-in screen after the server ended the session, it says the changes are still here', () => {
+ mocks.user = null
+ mocks.sync = sync('auth', { auth: true, lastError: { status: 401, code: 'auth' } })
+ render()
+ expect(text()).toBe('Your server no longer accepts this browser. Your changes are kept here.')
+ })
+})
+
+describe('no server at all', () => {
+ it('a phone kept local says so quietly, with a way to connect', () => {
+ mocks.MOBILE = true
+ mocks.user = null
+ mocks.guest = true
+ mocks.sync = sync('local', { server: null })
+ render()
+ expect(bar().className).toContain('quiet')
+ expect(text()).toBe('On this phone only — not connected to a server')
+ expect(label()).toBe('Connect')
+ act(() => button().click())
+ expect(openedConnect().dataset.again).toBe('false')
+ })
+
+ it('a guest in a browser: "Sign in" leads to Settings, where signing in and creating a profile are', () => {
+ mocks.user = null
+ mocks.guest = true
+ mocks.sync = sync('local')
+ render()
+ expect(text()).toBe('Guest mode — data lives only in this browser.')
+ act(() => button().click())
+ expect(mocks.navs).toEqual(['/settings'])
+ expect(mocks.passkeyLogin).not.toHaveBeenCalled()
+ })
+
+ it('a browser without passkeys still hears it, with nothing to press', () => {
+ mocks.user = null
+ mocks.guest = true
+ mocks.webauthn = false
+ mocks.sync = sync('local')
+ render()
+ expect(text()).toBe('Guest mode — data lives only in this browser.')
+ expect(button()).toBeNull()
+ })
+
+ it('the sign-in screen of a browser nobody signed in on is left alone', () => {
+ mocks.user = null
+ mocks.sync = sync('local')
+ render()
+ expect(bar()).toBeNull()
+ })
+})
+
+describe('where it never shows', () => {
+ it('the public demo, which has no server by design', () => {
+ mocks.DEMO = true
+ mocks.user = null
+ mocks.guest = true
+ mocks.sync = sync('local')
+ render()
+ expect(bar()).toBeNull()
+ })
+
+ it('the phone\'s first-launch choice', () => {
+ mocks.MOBILE = true
+ mocks.user = null
+ mocks.onboarding = true
+ mocks.sync = sync('local', { server: null })
+ render()
+ expect(bar()).toBeNull()
+ })
+})
+
+describe('a change waiting while the server is reachable', () => {
+ it('does not flash: only a wait longer than the grace period is shown', () => {
+ vi.useFakeTimers()
+ mocks.sync = sync('pending', { pending: true })
+ render()
+ expect(bar()).toBeNull()
+ act(() => { vi.advanceTimersByTime(PENDING_GRACE_MS - 100) })
+ expect(bar()).toBeNull()
+ act(() => { vi.advanceTimersByTime(200) })
+ expect(text()).toBe('Not synced yet — tap to retry.')
+ expect(label()).toBeNull() // the sentence already says "tap to retry"
+ })
+
+ it('a push that lands inside the grace period never shows it at all', () => {
+ vi.useFakeTimers()
+ mocks.sync = sync('pending', { pending: true })
+ render()
+ act(() => { vi.advanceTimersByTime(PENDING_GRACE_MS / 2) })
+ mocks.sync = sync('ok', { lastSynced: Date.now() })
+ render()
+ act(() => { vi.advanceTimersByTime(PENDING_GRACE_MS) })
+ expect(bar()).toBeNull()
+ expect(conn()).toBe('')
+ })
+})
diff --git a/frontend/src/index.css b/frontend/src/index.css
index da086b7ac..cdf223e75 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -59,6 +59,9 @@
--sab:env(safe-area-inset-bottom,0px);
--sat:env(safe-area-inset-top,0px);
+ /* height of the connection indicator under the status bar, 0 while there is none — set by
+ components/SyncBanner.jsx. Whatever starts at the top of the screen starts below it. */
+ --conn:0px;
}
:root[data-theme="light"] {
@@ -162,7 +165,7 @@ button,.chip,.tile,.item,.wday,.cal-d,.swatch,.hm-c,.lrow,.seg button,.stp butto
/* ---------------------------------------------------------------- layout -- */
#app{
- padding:calc(var(--sat) + 8px) var(--pad) calc(88px + var(--sab));
+ padding:calc(var(--sat) + var(--conn) + 8px) var(--pad) calc(88px + var(--sab));
max-width:560px;margin:0 auto;
}
/* Keep the last workout controls clear of the mobile overlays without adding a second
@@ -172,14 +175,40 @@ body.resting #app{padding-bottom:calc(206px + var(--sab))}
@keyframes viewfade{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
#app.vfade{animation:viewfade var(--med) var(--ease)}
-/* sync banner: one line for a signed-in user whose changes are not on the server yet */
-.sync-banner{
- display:flex;align-items:center;gap:9px;width:100%;text-align:left;
- margin:0 0 12px;padding:9px 12px;border-radius:var(--r);
- background:color-mix(in srgb,var(--yellow) 16%,var(--surface));color:var(--label);font-size:13px;line-height:1.35;
+/* Connection indicator (components/SyncBanner.jsx): pinned under the status bar for as long as
+ the app is not connected to a server. It carries the page's own ground and blur, like the
+ pinned workout header, so rows scrolling under it read as under it; --conn is the height of
+ its row, which #app and the pinned headers leave free. Above those headers (20, 40), below the
+ tab bar (50), the timer and every sheet. The sentence is never cut: its last words are the ones
+ that say the changes are kept, so a narrow phone gets a third line rather than an ellipsis. */
+.conn-bar{
+ position:fixed;left:0;right:0;top:0;z-index:45;
+ padding:var(--sat) var(--pad) 0;
+ background:color-mix(in srgb,var(--bg) 94%,transparent);
+ -webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
+}
+.conn-row{max-width:560px;margin:0 auto;padding:6px 0}
+.conn{
+ display:flex;align-items:center;gap:9px;width:100%;text-align:left;min-height:34px;
+ padding:6px 8px 6px 12px;border-radius:var(--r);
+ background:color-mix(in srgb,var(--yellow) 16%,var(--surface));color:var(--label);font-size:13px;line-height:1.3;
+}
+.conn .icn{flex:none;font-size:16px;color:var(--label-2)}
+.conn-t{flex:1;min-width:0;overflow-wrap:break-word}
+.conn-a{flex:none;padding:4px 10px;border-radius:99px;background:var(--surface-3);font-weight:600;white-space:nowrap}
+button.conn:active{filter:brightness(1.12)}
+.conn-bar.off .conn{background:color-mix(in srgb,var(--label-3) 18%,var(--surface))}
+.conn-bar.bad .conn{background:color-mix(in srgb,var(--red) 16%,var(--surface))}
+.conn-bar.bad .conn .icn{color:var(--red)}
+/* a deliberate local setup: said, not flagged — one small line, no fill */
+.conn-bar.quiet .conn-row{padding:2px 0 4px}
+.conn-bar.quiet .conn{min-height:26px;padding:2px 2px 2px 4px;background:none;color:var(--label-2);font-size:12px;gap:6px}
+.conn-bar.quiet .conn .icn{font-size:13px;color:var(--label-3)}
+.conn-bar.quiet .conn-a{padding:2px 9px;font-size:12px;color:var(--acc);background:var(--acc-soft)}
+:root[data-theme="light"] .conn-bar:not(.quiet) .conn-a{background:var(--surface)}
+@supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){
+ .conn-bar{background:var(--bg)}
}
-.sync-banner.off{background:color-mix(in srgb,var(--label-3) 18%,var(--surface))}
-.sync-banner .icn,.sync-banner svg{flex:none;font-size:16px;color:var(--label-2)}
/* large title, the way a nav bar does it */
.hdr{display:flex;align-items:flex-end;justify-content:space-between;gap:12px;margin:8px 0 18px}
/* The title block gives way, the button on the right never does: a flex item will not shrink
@@ -674,11 +703,12 @@ body.chips-dragging *{cursor:inherit}
/* ------------------------------------------------------------- workout --- */
/* Workout header. In list mode it is pinned: pulled up over #app's top padding so it sits flush
with the screen edge from the first pixel, and given the page's own ground plus a light blur so
- the rows scrolling underneath read as underneath. */
+ the rows scrolling underneath read as underneath. The connection indicator, when there is
+ one, sits over its top (--conn) and its content starts below it. */
.whdr.stick{
position:sticky;top:0;z-index:20;
- margin:calc(-1 * (var(--sat) + 8px)) calc(-1 * var(--pad)) 6px;
- padding:calc(var(--sat) + 8px) var(--pad) 0;
+ margin:calc(-1 * (var(--sat) + var(--conn) + 8px)) calc(-1 * var(--pad)) 6px;
+ padding:calc(var(--sat) + var(--conn) + 8px) var(--pad) 0;
background:color-mix(in srgb,var(--bg) 94%,transparent);
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
}
@@ -1360,7 +1390,7 @@ body.chips-dragging *{cursor:inherit}
/* scrolled to when the list opens (#224): clear the sticky header above it. Workout.jsx
measures the header (--whdr-h on .workout-list, safe area included) because it grows when
the session name wraps; the fallback is the height of a one-line header. */
-.wl-unit{scroll-margin-top:calc(var(--whdr-h, var(--sat) + 80px) + 16px)}
+.wl-unit{scroll-margin-top:calc(var(--whdr-h, var(--sat) + var(--conn) + 80px) + 16px)}
.wl-unit.cur{box-shadow:inset 0 0 0 1.5px var(--acc-line)}
.wl-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px}
/* part of the give-back above — one edge for all three insets of a row in the list view */
@@ -1393,7 +1423,8 @@ body.chips-dragging *{cursor:inherit}
/* --------------------------------------------------- desktop (≥1000px) --- */
.cols{display:block}
@media (min-width:1000px){
- #app{max-width:1080px;padding-top:32px;padding-bottom:calc(128px + var(--sab))}
+ #app{max-width:1080px;padding-top:calc(var(--conn) + 32px);padding-bottom:calc(128px + var(--sab))}
+ .conn-row{max-width:640px} /* the width of the .narrow pages below it */
body.resting #app{padding-bottom:calc(250px + var(--sab))}
.workout-end-spacer{height:40px}
.cols{display:grid;grid-template-columns:1fr 1fr;gap:14px;align-items:start}
diff --git a/frontend/src/lib/format-ago.test.js b/frontend/src/lib/format-ago.test.js
new file mode 100644
index 000000000..23663f6e1
--- /dev/null
+++ b/frontend/src/lib/format-ago.test.js
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest'
+import { fmtAgo, changeCount } from './format.js'
+
+// "Last synced: …" in Settings — the platform words it, in the UI language (en-GB here).
+describe('fmtAgo', () => {
+ const now = Date.UTC(2026, 8, 23, 12, 0, 0)
+ it('reads the coarsest whole unit back from now', () => {
+ expect(fmtAgo(now - 20 * 1000, now)).toBe('now')
+ expect(fmtAgo(now - 5 * 60000, now)).toBe('5 minutes ago')
+ expect(fmtAgo(now - 3 * 3600000 - 59 * 60000, now)).toBe('3 hours ago')
+ expect(fmtAgo(now - 86400000, now)).toBe('yesterday')
+ expect(fmtAgo(now - 9 * 86400000, now)).toBe('9 days ago')
+ })
+
+ it('a time ahead of the clock (the clock was set back) reads as now, not "in 5 minutes"', () => {
+ expect(fmtAgo(now + 5 * 60000, now)).toBe('now')
+ })
+})
+
+describe('changeCount', () => {
+ it('has a singular', () => {
+ expect(changeCount(1)).toBe('1 change')
+ expect(changeCount(3)).toBe('3 changes')
+ })
+})
diff --git a/frontend/src/lib/format.js b/frontend/src/lib/format.js
index fe8b040d2..39f5e5245 100644
--- a/frontend/src/lib/format.js
+++ b/frontend/src/lib/format.js
@@ -52,6 +52,17 @@ export const fmtVol = (v, unit) => fmtNum(v) + ' ' + unit
// Plural forms are not automatic when the English string is the key.
export const exCount = n => t(n === 1 ? '{0} exercise' : '{0} exercises', n)
export const routineCount = n => t(n === 1 ? '{0} routine' : '{0} routines', n)
+export const changeCount = n => t(n === 1 ? '{0} change' : '{0} changes', n)
+
+// "5 minutes ago", "yesterday", "now" — in the UI language, from the platform's own rules
+// (Intl.RelativeTimeFormat), so no pack has to carry a word for every unit and plural. Used for
+// when this device last synced; a time in the future (a clock set back since) reads as now.
+export function fmtAgo(ts, now = Date.now()) {
+ const s = Math.max(0, Math.round((now - ts) / 1000))
+ const [n, unit] = s < 60 ? [0, 'second'] : s < 3600 ? [Math.floor(s / 60), 'minute'] : s < 86400 ? [Math.floor(s / 3600), 'hour'] : [Math.floor(s / 86400), 'day']
+ try { return new Intl.RelativeTimeFormat(dateLocale(), { numeric: 'auto' }).format(-n, unit) }
+ catch { return new Date(ts).toLocaleString(dateLocale()) }
+}
/* ---------------------------------------------------------------- week start --
Where a week begins is a local convention, not a fact: most of Europe starts on
diff --git a/frontend/src/views/MobileOnboarding.jsx b/frontend/src/views/MobileOnboarding.jsx
index 7f0527aaf..f05e299cb 100644
--- a/frontend/src/views/MobileOnboarding.jsx
+++ b/frontend/src/views/MobileOnboarding.jsx
@@ -9,13 +9,17 @@ import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { askAddDeviceData } from '../sheets.jsx'
-export function ConnectSheet({ close }) {
+// `again`: a phone whose server stopped accepting it (components/ServerSync.jsx pairAgain) — the
+// address it had is filled in when it still has one, so only the new code is left to type, and
+// the sheet says that what the phone kept is merged, not replaced.
+export function ConnectSheet({ close, initialUrl = '', again = false }) {
const { connectToServer } = useStore()
- const [url, setUrl] = useState('')
+ const [url, setUrl] = useState(initialUrl)
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const ref = useRef(null)
- useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
+ const codeRef = useRef(null)
+ useEffect(() => { setTimeout(() => (initialUrl ? codeRef : ref).current?.focus(), 250) }, [])
const go = async () => {
if (!url.trim() || !code.trim()) { useUI.getState().toast(t('Enter your server address and the code')); return }
setBusy(true)
@@ -24,14 +28,16 @@ export function ConnectSheet({ close }) {
finally { setBusy(false) }
}
return <>
- <h3>{t('Connect to my server')}</h3>
+ <h3>{again ? t('Pair again') : t('Connect to my server')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
- {t('Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.')}
+ {again
+ ? t('Open Settings → “Pair the mobile app” on your openGym site in a browser and enter the new code shown there. What this phone kept is merged into your account.')
+ : t('Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.')}
</div>
<input ref={ref} className="input" placeholder={t('Server address (e.g. gym.example.com)')} value={url}
onChange={e => setUrl(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
<div style={{ height: 10 }} />
- <input className="input" placeholder={t('Pairing code')} maxLength={8} value={code}
+ <input ref={codeRef} className="input" placeholder={t('Pairing code')} maxLength={8} value={code}
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
<div style={{ height: 12 }} />
<Button variant="primary" onClick={go} disabled={busy}>{busy ? t('Connecting…') : t('Connect')}</Button>