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
Sync: a server that refuses this device, a stale tab or a sign-out no longer loses changes (#283)
Duarte Santosd57b801011aa
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 339365131..e020eb786 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -5,19 +5,30 @@ import { t } from '../lib/i18n.js'import { registerCustom } from '../lib/exercises.js'import { DEMO, DEMO_SEEDED } from '../lib/demo.js'import { guestAllowed } from '../lib/guest.js'-import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, syncReminder, writeAutoBackup } from '../lib/mobile.js'-import { mergeStates, localExtras } from '../lib/sync-merge.js'-import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'+import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'+import { mergeStates, localExtras, stampRoutines } from '../lib/sync-merge.js'+import { countChanges, syncFingerprint } from '../lib/sync-changes.js'+import { appBase } from '../lib/app-base.js'+import { loadRemote, chooseLocal, forgetRemote, connect, normalizeServerUrl } from '../lib/remote.js'import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'import { WC_DEFAULT } from '../lib/workout-controls.js'const KEY = 'gym_state_v1'-// Where this device stands with the server: the revision it last adopted or pushed, and its own-// `_ts` at that moment. `rev` goes back to the server as `baseRev` on every push, so a write over-// a document this device never saw is refused (409) instead of dropping another device's work;-// `ts` tells a pull whether anything changed here since. See pushState/pullState.+// Where the saved copy stands with the server: the revision it descends from, and its own `_ts`+// at that moment. `rev` goes back to the server as `baseRev` on every push, so a write over a+// document this device never saw is refused (409) instead of dropping another device's work;+// `ts` tells a pull whether anything changed here since. Each tab keeps its own in memory (`meta`+// in the store); this marker is written beside the saved copy for whichever tab loads it next.+// See pushState/pullState.const SYNC_KEY = 'gym_sync'+const DIRTY_KEY = 'gym_dirty' // the saved copy owes the server a change+const SYNCED_AT_KEY = 'gym_synced_at' // when this device and the server last held the same copy+const SYNCED_FP_KEY = 'gym_synced_fp' // a fingerprint of that copy (lib/sync-changes.js)+// Changes a forced sign-out or disconnect kept on this device, by server and account, until it+// reaches that server as that account again. On a phone also a file beside the state mirror.+const STASH_KEY = 'gym_stash'+const STASH_FILE = 'opengym-stash.json'const CHECK_MIN_MS = 3000 // rev checks closer together than this are the same event (focus + visibility)const POLL_MS = 30000 // while the app is open and signed in, ask the server for its revision this oftenexport const DEF = {@@ -118,17 +129,105 @@ export const useStore = create((set, get) => {let lastCheck = 0let pollTm = nulllet offlineChanges = false // a push failed for lack of network — the next one that lands says so+ let rejoined = false // the account signing in is the one this copy already belongs to (setUser)+ let pairedBase = null // mobile build: the address of the paired server, while there is one+ let fpOf = null // the copy the stored fingerprint was last taken of (confirmed)- const readSync = () => { try { return JSON.parse(localStorage.getItem(SYNC_KEY)) || null } catch { return null } }- const writeSync = (rev, ts) => localStorage.setItem(SYNC_KEY, JSON.stringify({ rev, ts: ts || 0 }))- // What the banner shows a signed-in user: `offline` when the server could not be reached at- // all, `pending` while a change is still owed to it (either way, or a push the server refused).+ const readStoredSync = () => { try { return JSON.parse(localStorage.getItem(SYNC_KEY)) || null } catch { return null } }+ const storedOwed = () => { try { return localStorage.getItem(DIRTY_KEY) === '1' } catch { return false } }++ /* Where the copy in memory stands with the server: the revision it descends from (`base`, as+ { rev, ts }) and whether it owes the server a change (`owed`). Both belong to the copy, per+ tab. The marker and the dirty flag in localStorage are shared by every tab of the browser:+ a tab left open used to quote the revision ANOTHER tab had just synced, so the server saw a+ current baseRev, took the stale copy without a 409, and the workout logged in the other tab+ was gone (#283); and a tab that owed nothing read another tab's failed push as its own,+ merged where it should have adopted, and brought back what the other tab had just deleted.+ Every copy this store puts in place records where it stands; storage is only where a copy+ loaded fresh (a new tab, a reload) learns it, which is why persist writes them beside it.+ A copy set on the store directly, not through persist, has nothing recorded yet: it takes+ what storage says the first time it is asked, and keeps that. */+ const meta = new WeakMap()+ const metaOf = (S = get().S) => {+ let m = meta.get(S)+ if (!m) { m = { base: readStoredSync(), owed: storedOwed() }; meta.set(S, m) }+ return m+ }+ const saveMarker = base => {+ try {+ if (!base) { localStorage.removeItem(SYNC_KEY); return }+ const v = JSON.stringify(base)+ // Unchanged, it is not written again: other tabs react to this key moving (see below).+ if (localStorage.getItem(SYNC_KEY) !== v) localStorage.setItem(SYNC_KEY, v)+ } catch { /* storage refused — the copy in memory still knows */ }+ }+ const saveOwed = owed => { try { if (owed) localStorage.setItem(DIRTY_KEY, '1'); else localStorage.removeItem(DIRTY_KEY) } catch { /* as above */ } }+ const writeSync = (rev, ts) => {+ const base = { rev, ts: ts || 0 }+ meta.set(get().S, { ...metaOf(), base })+ saveMarker(base)+ }+ const dropSync = () => { meta.set(get().S, { ...metaOf(), base: null }); saveMarker(null) }+ const markOwed = owed => { meta.set(get().S, { ...metaOf(), owed }); saveOwed(owed) }+ // Whether anything here is still on its way to the server: a push that failed, one waiting in+ // the debounce or in flight, a change made while boot was pulling, or a copy changed since the+ // revision it descends from.+ const localChanged = (S = get().S) => { const { base } = metaOf(S); return !!base && (S._ts || 0) > (base.ts || 0) }+ const owes = () => metaOf().owed || pushPending || pushTm !== null || !!pushing || localChanged()++ /* The connection as the screens show it (components/SyncBanner.jsx, Settings). The flags are set+ where each outcome is known; `status` is derived from them here, once, so no screen has to+ rank them:+ 'local' no server: a phone in local mode, a guest, nobody signed in+ 'auth' the server refuses this device (a 401), or the phone has lost its pairing+ 'offline' the server could not be reached at all (no network, DNS, a timeout)+ 'error' it answered with a failure: 5xx, 403, 413, a page that is not openGym's+ 'pending' reachable, and a change is still waiting to reach it+ 'ok' this device holds what the server holds+ `pending`: a change is owed and the last attempt did not land. `lastSynced`: when this device+ and the server last held the same copy. `lastError`: { status, code } of the failure behind+ 'auth', 'offline' or 'error' (status 0 without an HTTP answer). `server`: the base URL this+ device syncs with, or null on a phone that has none. */+ const statusOf = (x, user) => x.auth ? 'auth' : !user ? 'local' : x.offline ? 'offline' : x.lastError ? 'error' : x.pending ? 'pending' : 'ok'+ const sameError = (a, b) => (a && b ? a.status === b.status && a.code === b.code : a === b)const setSync = patch => {const cur = get().syncconst next = { ...cur, ...patch }- if (next.offline !== cur.offline || next.pending !== cur.pending || next.lastSynced !== cur.lastSynced) set({ sync: next })+ next.status = statusOf(next, get().user)+ if (Object.keys(next).some(k => (k === 'lastError' ? !sameError(next[k], cur[k]) : next[k] !== cur[k]))) set({ sync: next })+ }+ const isNetworkError = e => e && e.status == null // fetch itself failed, or gave up: no response at all+ const refused = e => e?.status === 401 || e?.code === 'not-paired'+ // The server answered: whatever was wrong with the connection is over.+ const reached = (extra = {}) => setSync({ offline: false, auth: false, lastError: null, ...extra })+ // What a failed request says about the connection. A refused token and a phone without a+ // pairing are the same thing to the person holding it — the device has to be paired or signed+ // in again, and nothing on it is lost meanwhile.+ const failed = (e, extra = {}) => {+ const lastError = { status: e?.status ?? 0, code: e?.code || (e?.status === 401 ? 'auth' : isNetworkError(e) ? 'network' : 'http') }+ if (refused(e)) setSync({ auth: true, offline: false, lastError, ...extra })+ else if (isNetworkError(e)) setSync({ offline: true, lastError, ...extra })+ else setSync({ offline: false, lastError, ...extra })+ }+ // This device and the server hold the same copy: a push landed, a pull adopted, or a check found+ // that nothing moved on either side. The fingerprint is what signing out counts changes against.+ const confirmed = S => {+ const at = Date.now()+ try {+ localStorage.setItem(SYNCED_AT_KEY, String(at))+ if (fpOf !== S) { localStorage.setItem(SYNCED_FP_KEY, JSON.stringify(syncFingerprint(S))); fpOf = S }+ } catch { /* storage refused — only the count is lost */ }+ reached({ pending: false, lastSynced: at })+ }+ const readFingerprint = () => { try { return JSON.parse(localStorage.getItem(SYNCED_FP_KEY)) } catch { return null } }++ // The server this device syncs with: the paired address on a phone, the page's own origin and+ // subpath (#238) in a browser. null on a phone without one — local mode, or a pairing lost+ // under an earlier version, which kept no address.+ const serverBase = () => {+ if (MOBILE) return pairedBase+ try { return location.origin && location.origin !== 'null' ? location.origin + appBase().replace(/\/$/, '') : null } catch { return null }}- const isNetworkError = e => e && e.status == null // fetch itself failed: no response at allinitReminderSync(() => get().S)@@ -142,19 +241,27 @@ export const useStore = create((set, get) => {// `_ts` is when this device last changed the data — it decides which copy wins on the next// pull (restoredStateFor). A copy merely adopted from the server or the file mirror keeps the// stamp it came with: re-stamping a read would make an unchanged copy look newer than a real- // change made on another device, and push it over that change.+ // change made on another device, and push it over that change. A change is never stamped+ // before the revision it builds on: that stamp came from the clock of whichever device wrote+ // it, and with this clock behind, the change looked older than its own base — unchanged — and+ // a pull replaced it with the server's copy.const persist = (S, push = true, stamp = true) => {- if (stamp) S._ts = Date.now()+ const { base, owed } = metaOf() // the copy being replaced; the new one stands where it stood+ if (stamp) S._ts = Math.max(Date.now(), (base?.ts || 0) + 1)registerCustom(S.customEx)// A refused write used to take the change with it — Finish looked like it simply did// nothing. The copy is kept in memory either way and marked as owed to the server, so a// signed-in device still gets it there; and it is said out loud once, because a change that// is not on the device is the one thing the screen cannot show on its own.+ let saved = truetry {+ // The marker goes first: a tab that loads the copy in between gets an older base than the+ // copy's, which costs one merge at worst — never a newer one, which would lose data.+ saveMarker(base)localStorage.setItem(KEY, JSON.stringify(S))toldNoRoom = false} catch (e) {- try { localStorage.setItem('gym_dirty', '1') } catch { /* the same wall */ }+ saved = falseif (!toldNoRoom) {toldNoRoom = trueimport('./useUI.js')@@ -162,6 +269,8 @@ export const useStore = create((set, get) => {.catch(() => {})}}+ meta.set(S, { base, owed: owed || !saved })+ if (!saved) saveOwed(true)set({ S })if (MOBILE) nativePersist()if (push && get().user) {@@ -192,16 +301,14 @@ export const useStore = create((set, get) => {if (!force && Date.now() - lastCheck < CHECK_MIN_MS) returnlastCheck = Date.now()if (pulling) return pulling- const sync = readSync()- const owed = localStorage.getItem('gym_dirty') === '1' || pushTm !== null || pushPending- if (!sync || owed) return get().pullState()+ const { base } = metaOf()+ if (!base || owes()) return get().pullState()try {const { rev } = await api('/api/data/rev')- setSync({ offline: false })- if (rev !== sync.rev) return get().pullState()+ if (rev !== base.rev) return get().pullState()+ confirmed(get().S) // nothing moved on either side} catch (e) {- if (e.status === 401) return- if (isNetworkError(e)) setSync({ offline: true })+ if (isNetworkError(e) || refused(e)) failed(e)else return get().pullState() // a server that lacks the route (older API) — the full pull knows the old protocol}}@@ -219,56 +326,61 @@ export const useStore = create((set, get) => {// Both copies changed: keep both sides' entries, let the newer copy decide the rest// (lib/sync-merge.js), and remember the server's revision so the push that follows is// conditional on exactly the document that was merged. The merged copy is stamped — it is a- // real change this device now holds — while `ts` in the marker stays old, so a pull that+ // real change this device now holds — while `ts` in the base stays old, so a pull that// happens before the push lands still sees it as unsent.const mergeInto = (local, remote, rev) => {+ const ts = metaOf().base?.ts || 0const merged = Object.assign(clone(DEF), mergeStates(local, remote))merged.active = local.active || nullpersist(merged, false)- writeSync(rev, readSync()?.ts || 0)+ if (rev == null) dropSync()+ else writeSync(rev, ts)}// Take the server's copy as this device's own, timestamp and all (see persist).- const adopt = (next, rev) => { persist(next, false, false); writeSync(rev, next._ts) }+ const adopt = (next, rev) => { persist(next, false, false); writeSync(rev, next._ts); markOwed(false) }const doPush = async (attempt = 0) => {const S = get().S- const sync = readSync()+ const { base } = metaOf()+ // A forced push is one attempt. One that fails is retried as an ordinary push against the+ // revision this copy descends from: kept armed, it went out later without a baseRev and+ // replaced whatever another device had written in the meantime.const force = forceNext+ forceNext = falseconst body = { state: S }- if (!force && sync) body.baseRev = sync.rev+ if (!force && base) body.baseRev = base.revtry {const r = await api('/api/data', { method: 'PUT', body: JSON.stringify(body) })- if (force) forceNext = false// A server from before revisions answers without one — then there is nothing to hold the// next push to, and the marker must not pretend otherwise.- if (r.rev == null) localStorage.removeItem(SYNC_KEY)+ if (r.rev == null) dropSync()else writeSync(r.rev, S._ts)- localStorage.removeItem('gym_dirty')+ markOwed(false)toldTooLarge = false+ confirmed(S)// Back from offline with changes that were waiting: say so once — the banner that promised// "syncs when you're back online" has just kept its word.- setSync({ offline: false, pending: false, lastSynced: Date.now() })if (offlineChanges) {offlineChanges = falseimport('./useUI.js').then(({ useUI }) => useUI.getState().toast(t('Back online — synced with the server.'))).catch(() => {})}} catch (e) {- // A session that is gone is boot's business (/api/me); the copy stays owed to the server.- if (e.status === 401) { localStorage.setItem('gym_dirty', '1'); return }- if (isNetworkError(e)) { localStorage.setItem('gym_dirty', '1'); offlineChanges = true; setSync({ offline: true, pending: true }); return }if (e.status === 409 && e.data && attempt < 2) {// Another device wrote since this one last read. The server sent its document along;// merge and push once more against that revision. A second refusal in a row leaves the- // copy dirty and the next resume pull takes it from there.+ // copy owed and the next resume pull takes it from there.mergeInto(get().S, e.data.state, e.data.rev || 0)return doPush(attempt + 1)}- localStorage.setItem('gym_dirty', '1')- setSync({ offline: false, pending: true })+ // Whatever went wrong — no network, a refused token, a phone without a pairing, a server+ // error — the copy stays owed to the server and the next check retries it.+ markOwed(true)+ if (isNetworkError(e)) offlineChanges = true+ failed(e, { pending: true })// A 413 comes from the proxy in front of the API (nginx: client_max_body_size), which// caps the request body. Every later push is at least as big, so nothing reaches the- // server until the limit is raised — said once per refusal streak; gym_dirty keeps the- // retries going. useUI imports this store, hence the lazy import.+ // server until the limit is raised — said once per refusal streak; the owed copy keeps+ // the retries going. useUI imports this store, hence the lazy import.if (e.status === 413 && !toldTooLarge) {toldTooLarge = trueimport('./useUI.js')@@ -311,27 +423,136 @@ export const useStore = create((set, get) => {if (!user || e.newValue === user.id) returnclearTimeout(pushTm)pushTm = null- set({ user: null, S: e.newValue ? loadState() : clone(DEF) })+ const S = e.newValue ? loadState() : clone(DEF)+ meta.set(S, e.newValue ? { base: readStoredSync(), owed: storedOwed() } : { base: null, owed: false })+ set({ user: null, S })+ })+ // Another tab of this browser synced — its marker moved to a revision this tab's copy does not+ // descend from. Rather than take that tab's saved copy (storage holds the copy and its marker+ // under two keys, and an event can arrive with one updated and not the other), this tab asks+ // the server, as it would on coming back to it: one small request, and a pull only if the+ // revision really moved. A hidden tab does the same when it is shown again. Its own base still+ // guards the push either way: a copy this tab has not refreshed gets a 409 and a merge.+ window.addEventListener('storage', e => {+ if (e.key !== SYNC_KEY || !e.newValue) return+ const user = get().user+ if (!user || localStorage.getItem('gym_owner') !== user.id) return+ let theirs = null+ try { theirs = JSON.parse(e.newValue) } catch { return }+ if (theirs?.rev == null || theirs.rev === metaOf().base?.rev) return+ checkRev(true)})+ // Before a sign-out decides anything: the pull on its way has landed, and every push asked+ // for — including one queued behind the push in flight — has run.+ const settle = async () => {+ if (pulling) await pulling+ await get().pushState() // never throws — an owed copy stays owed when it does not land+ while (pushing) await pushing+ }++ // Forget where this device stood with the server — a different account, a sign-out. The copy+ // that replaces it descends from no revision and owes nothing.+ const forgetSync = () => {+ meta.set(get().S, { base: null, owed: false })+ try { for (const k of [SYNC_KEY, DIRTY_KEY, SYNCED_AT_KEY, SYNCED_FP_KEY]) localStorage.removeItem(k) } catch { /* nothing to keep */ }+ fpOf = null+ }+// Everything a sign-out leaves behind on this device, whichever way it was triggered. The owner// goes last, after the wiped copy is written — the storage listener above relies on the order.const clearLocalSession = () => {get().setUser(null)localStorage.removeItem('gym_guest')- localStorage.removeItem('gym_dirty')- localStorage.removeItem(SYNC_KEY)+ forgetSync()localStorage.removeItem(KEY)persist(clone(DEF), false)localStorage.removeItem('gym_owner')+ setSync({ offline: false, auth: false, lastError: null, pending: false, lastSynced: 0 })+ }++ /* The changes a forced sign-out or disconnect keeps, so that no change is ever lost silently.+ Keyed by server and account — '' for the server of a phone whose pairing was lost with its+ address — in localStorage and, on a phone, in a file beside the state mirror, since the+ sign-out wipes the rest. */+ const stashKey = (server, uid) => (server || '') + '|' + uid+ const readStashes = async () => {+ let all = {}+ try { all = JSON.parse(localStorage.getItem(STASH_KEY)) || {} } catch { /* none */ }+ if (MOBILE) { const f = await readJsonFile(STASH_FILE); if (f && typeof f === 'object') all = { ...all, ...f } }+ return all+ }+ // True when at least one durable copy of the stashes was written.+ const writeStashes = async all => {+ const empty = !Object.keys(all).length+ let ok = false+ try { if (empty) localStorage.removeItem(STASH_KEY); else localStorage.setItem(STASH_KEY, JSON.stringify(all)); ok = true } catch { /* full */ }+ if (MOBILE) {+ await writeJsonFile(STASH_FILE, all)+ const back = await readJsonFile(STASH_FILE)+ ok = ok || (!!back && Object.keys(back).length === Object.keys(all).length)+ }+ return ok || empty+ }+ const stashOwed = async () => {+ const user = get().user+ if (!user) return true+ const all = await readStashes()+ const server = serverBase()+ const key = stashKey(server, user.id)+ const prev = all[key]?.state+ const state = prev ? mergeStates(get().S, prev) : clone(get().S)+ state.active = get().S.active || prev?.active || null+ all[key] = { server: server || null, uid: user.id, name: user.name || '', at: Date.now(), state }+ return writeStashes(all)+ }+ // Back on the server and account a forced sign-out or disconnect left: the kept changes are+ // merged in like a conflict (lib/sync-merge.js), marked owed and pushed, and the stash goes.+ // If the push does not land, the copy itself owes them from here and nothing wipes it.+ const applyStash = async () => {+ const user = get().user+ if (!user) return+ const all = await readStashes()+ const exact = stashKey(serverBase(), user.id)+ const keys = Object.keys(all).filter(k => k === exact || (all[k]?.uid === user.id && !all[k]?.server))+ if (!keys.length) return+ const S = get().S+ let merged = S+ for (const k of keys) merged = mergeStates(merged, all[k].state)+ merged = Object.assign(clone(DEF), merged)+ merged.active = S.active || keys.map(k => all[k].state?.active).find(Boolean) || null+ persist(merged, false)+ markOwed(true)+ if (MOBILE) await nativeSave(get().S) // the durable copy holds it before the stash goes+ await get().pushState()+ for (const k of keys) delete all[k]+ await writeStashes(all)}+ // The file mirror is the durable copy: WebView storage can be evicted while the files+ // directory survives. A mirror newer than what localStorage holds is a change this phone made+ // and may not have sent — it is taken, and owed, so the pull merges it with the server's copy+ // instead of letting either win outright.+ const restoreFromMirror = async () => {+ const saved = await nativeLoad()+ if (!saved || (saved._ts || 0) <= (get().S._ts || 0)) return+ persist(Object.assign(clone(DEF), saved), false, false)+ markOwed(true)+ }++ const S0 = loadState()+ registerCustom(S0.customEx)+ meta.set(S0, { base: readStoredSync(), owed: storedOwed() })+ const user0 = (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })()+ const sync0 = { offline: false, pending: storedOwed(), auth: false, lastError: null, lastSynced: (() => { try { return +localStorage.getItem(SYNCED_AT_KEY) || 0 } catch { return 0 } })(), server: serverBase() }+ sync0.status = statusOf(sync0, user0)+return {- S: (() => { const s = loadState(); registerCustom(s.customEx); return s })(),- user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),+ S: S0,+ user: user0,ready: false,- // Server sync as the banner sees it (components/SyncBanner.jsx). Only meaningful signed in.- sync: { offline: false, pending: localStorage.getItem('gym_dirty') === '1', lastSynced: 0 },+ // The connection as the screens show it — see statusOf above for every field.+ sync: sync0,/* Instance capabilities from GET /api/config. `config.coach` is present only when the ownerhas both enabled the Coach and connected a provider — every Coach entry point in the apphangs off it via coachAvailable(), so an unconfigured instance renders exactly what it@@ -345,10 +566,13 @@ export const useStore = create((set, get) => {set({ coachLocal: coachDeviceSettings(await saveCoachDevice(patch)) })},- // Mutate a draft of S via producer fn, then persist + schedule sync.+ // Mutate a draft of S via producer fn, then persist + schedule sync. Every routine the change+ // touched carries the time of it, for a conflict to keep the version edited last.update(mut, push = true) {- const S = clone(get().S)+ const prev = get().S+ const S = clone(prev)mut(S)+ stampRoutines(prev.routines, S.routines)persist(S, push)},// A replace that is meant to reach the server (backup import, reset) is a deliberate@@ -364,7 +588,12 @@ export const useStore = create((set, get) => {},isGuest: () => localStorage.getItem('gym_guest') === '1',- setGuest(v) { if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest'); set({}) },+ // Choosing to go on without a server ends whatever was said about the last one.+ setGuest(v) {+ if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest')+ set({})+ if (v) setSync({ auth: false, offline: false, lastError: null })+ },// Public config from /api/config (invite_only, allow_guest). null until the first successful// fetch — the login screen and boot both read it, so it is fetched once and cached here@@ -387,18 +616,21 @@ export const useStore = create((set, get) => {// revoked elsewhere, boot() only drops the user and the data stays; a different profile// signing in next must not inherit it (pullState would push it into that account, and// carry the in-progress workout along). A proper sign-out clears the owner, so a guest's- // data still moves into a freshly created profile.+ // data still moves into a freshly created profile. The same account coming back — a+ // phone paired again, a browser signed in again — is remembered for adoptProfile.const owner = localStorage.getItem('gym_owner')+ rejoined = owner === u.idif (owner && owner !== u.id) {- localStorage.removeItem('gym_dirty')- localStorage.removeItem(SYNC_KEY)+ forgetSync()localStorage.removeItem(KEY)persist(clone(DEF), false)+ setSync({ pending: false, lastSynced: 0, lastError: null })}localStorage.setItem('gym_owner', u.id)localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest')- } else localStorage.removeItem('gym_user')+ } else { rejoined = false; localStorage.removeItem('gym_user') }set({ user: u })+ setSync({})},// One PUT at a time: a push asked for while one is in flight runs after it (once, however@@ -426,85 +658,144 @@ export const useStore = create((set, get) => {else if (pushing) await pushingconst res = await api('/api/data')lastCheck = Date.now()- setSync({ offline: false })+ reached()const { state, rev } = resconst S = get().S+ const { base, owed } = metaOf()// Owed to the server: a push that failed, or a change made while boot was still pulling.- const dirty = localStorage.getItem('gym_dirty') === '1' || pushPending- const sync = readSync()+ const dirty = owed || pushPending// A server from before revisions: the old rule, newer `_ts` wins outright.if (rev == null) {- localStorage.removeItem(SYNC_KEY)+ dropSync()const restored = restoredStateFor(S, state, dirty)- if (restored) persist(restored, false, false)+ if (restored) { persist(restored, false, false); confirmed(get().S) }else if (hasData(S)) await get().pushState()return}- // No marker yet — first pull on this device, or a client that just learned about+ // No base yet — first pull on this device, or a client that just learned about// revisions. The newer copy wins as before, except that a copy still owed to the// server (dirty) is merged instead of pushed over whatever is there.- if (!sync) {+ if (!base) {if (dirty && state) { mergeInto(S, state, rev); pushPending = false; await get().pushState(); return }const restored = restoredStateFor(S, state, false)- if (restored) adopt(restored, rev)+ if (restored) { adopt(restored, rev); confirmed(get().S) }else if (hasData(S)) { writeSync(rev, 0); await get().pushState() }- else writeSync(rev, state?._ts || 0)+ else { writeSync(rev, state?._ts || 0); confirmed(get().S) }return}- const serverMoved = rev !== sync.rev- const localChanged = dirty || (S._ts || 0) > (sync.ts || 0)- if (!serverMoved) { if (localChanged) await get().pushState(); return }+ const serverMoved = rev !== base.rev+ const changed = dirty || localChanged(S)+ if (!serverMoved) { if (changed) await get().pushState(); else confirmed(S); return }if (!state) { writeSync(rev, 0); if (hasData(S)) await get().pushState(); return }- if (!localChanged) { adopt(Object.assign(clone(DEF), state, { active: S.active || null }), rev); return }+ if (!changed) { adopt(Object.assign(clone(DEF), state, { active: S.active || null }), rev); confirmed(get().S); return }mergeInto(S, state, rev)pushPending = falseawait get().pushState()- } catch (e) { if (isNetworkError(e)) setSync({ offline: true }) /* keep local; the poll retries */ }+ } catch (e) { failed(e) /* keep local; the poll retries */ }finally { pulling = null }})()return pulling},+ // "Sync now": what is waiting goes, the server's copy is checked, and the answer is the+ // `sync` every screen reads — status 'ok' when the two agree.+ async syncNow() {+ if (!get().user) { setSync({}); return get().sync }+ if (pulling) await pulling+ await get().pullState()+ return get().sync+ },++ // What this device holds that the server has not seen: `owed` when anything would be lost by+ // wiping the copy now, `count` how many workouts, weigh-ins, routines and custom exercises+ // differ from the last copy the two agreed on (plus one for settings and the plan) — null+ // when the device has no record of that copy (it last agreed with the server under an older+ // version), and then only `owed` is known.+ unsyncedChanges() {+ if (!get().user || !owes()) return { owed: false, count: 0 }+ const count = countChanges(get().S, readFingerprint())+ return { owed: count !== 0, count }+ },+// Sign-in (and pairing a phone) takes the server's profile as this device's copy — the// profile is the truth for a signed-in user, whatever the timestamps say. The only thing// the device may add are the entries it logged while signed out: `ask(extras)` (a dialog,// supplied by the caller) decides whether those workouts, weigh-ins and custom exercises// are added to the profile or dropped. A profile with no state yet simply takes the- // device's data, as creating a profile always did.+ // device's data, as creating a profile always did. The same account signing in again is+ // different: see below.async adoptProfile(ask) {if (pulling) await pulling- const res = await api('/api/data') // a failure here is the caller's toast: sign-in needed the server anyway+ const sameAccount = rejoined+ let res+ try { res = await api('/api/data') }+ catch (e) { failed(e); throw e } // the caller's toast: sign-in needed the server anywayconst { state, rev } = resconst S = get().S- setSync({ offline: false })+ reached()if (!state) {- localStorage.removeItem('gym_dirty')+ markOwed(false)if (hasData(S)) { if (rev != null) writeSync(rev, 0); forceNext = true; await get().pushState() }- else if (rev != null) writeSync(rev, 0)+ else { if (rev != null) writeSync(rev, 0); confirmed(get().S) }+ await applyStash()return { adopted: false, added: false }}+ const serverCopy = Object.assign(clone(DEF), state, { active: S.active || null })+ if (sameAccount) {+ // This copy already belongs to the account: a phone paired again after its token was+ // refused, a browser signed in again after its session ended. It may hold days the server+ // never saw — new workouts, but also edits to routines and settings, which the question+ // below never covered. Merged like a conflict between two devices (the union of entries,+ // the later edit of each routine, the newer copy's settings) and pushed against the+ // server's revision. Only a copy with nothing of its own since its base takes the+ // server's as it is, so an entry deleted elsewhere meanwhile stays deleted.+ const { base, owed } = metaOf()+ if (!hasData(S) || (!owed && base && !localChanged(S))) {+ if (rev != null) adopt(serverCopy, rev)+ else { dropSync(); persist(serverCopy, false, false); markOwed(false) }+ confirmed(get().S)+ await applyStash()+ return { adopted: true, added: false, merged: false }+ }+ mergeInto(S, state, rev)+ await get().pushState()+ await applyStash()+ return { adopted: true, added: false, merged: true }+ }const extras = localExtras(S, state)const keep = (extras.workouts || extras.bodyweight || extras.customEx) && typeof ask === 'function' ? await ask(extras) : false- const serverCopy = Object.assign(clone(DEF), state, { active: S.active || null })if (keep) {const merged = Object.assign(clone(DEF), mergeStates(state, S, { prefer: 'a' }))merged.active = S.active || nullpersist(merged, false)if (rev != null) writeSync(rev, 0)- else localStorage.removeItem(SYNC_KEY)+ else dropSync()await get().pushState()+ await applyStash()return { adopted: true, added: true }}- localStorage.removeItem('gym_dirty')if (rev != null) adopt(serverCopy, rev)- else { localStorage.removeItem(SYNC_KEY); persist(serverCopy, false, false) }- setSync({ pending: false })+ else { dropSync(); persist(serverCopy, false, false); markOwed(false) }+ confirmed(get().S)+ await applyStash()return { adopted: true, added: false }},- async signOut() {- try { await get().pushState(); await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* */ }+ /* Signing out wipes this device's copy — never while it holds changes the server has not+ seen. After one more push, if anything is still owed, nothing is wiped and the result+ says so: { owed: true, count } (see unsyncedChanges), for the screen to offer a retry, an+ export, or going ahead anyway. `force` goes ahead: the owed copy is kept aside on this+ device (stashOwed) and comes back when it next reaches this server as this account. If+ even that cannot be written, nothing is wiped ({ owed, count, stashed: false }).+ Otherwise { owed: false } or { owed: true, count, stashed: true }, signed out. */+ async signOut({ force = false } = {}) {+ await settle()+ const left = get().unsyncedChanges()+ if (left.owed && !force) return { owed: true, count: left.count }+ if (left.owed && !(await stashOwed())) return { owed: true, count: left.count, stashed: false }+ try { await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* the session ends here either way */ }clearLocalSession()+ return left.owed ? { owed: true, count: left.count, stashed: true } : { owed: false }},// Mobile-only ("connect to my server" onboarding, see App.jsx's needsMobileOnboarding).@@ -515,40 +806,53 @@ export const useStore = create((set, get) => {set({ needsMobileOnboarding: false })},// Redeems the pairing code shown in the browser (Settings → "Pair the mobile app") and- // switches this device over to that account, same as signing in on the web does.+ // switches this device over to that account, same as signing in on the web does — the same+ // account pairing again merges what the phone kept (adoptProfile).async connectToServer(url, code, ask) {const user = await connect(url, code) // throws on a bad URL/expired code — caller shows it+ pairedBase = normalizeServerUrl(url)+ setSync({ server: pairedBase })get().setUser(user)await get().refreshConfig() // what this server offers (the Coach, guest mode) — see boot()await get().adoptProfile(ask)syncReminder(get().S)set({ needsMobileOnboarding: false })},- // Leaves remote mode and drops cleanly back to local-only, without losing whatever was last- // synced (signOut() already pushes before it clears).- async disconnectServer() {- await get().signOut()+ // Leaves remote mode and drops back to local-only, the way signOut does: never with changes+ // the server has not seen, unless `force` keeps them aside first. Same result as signOut;+ // the phone stays paired when that comes back owed and not stashed.+ async disconnectServer(opts) {+ const r = await get().signOut(opts)+ if (r.owed && !r.stashed) return rawait forgetRemote()+ pairedBase = null+ setSync({ server: null })get().setGuest(true)set({ ready: true })+ return r},// "Sign out everywhere": the server bumps this profile's session version, which kills every// session it has on any device — this browser included, so the app has to end up exactly- // where a normal signOut leaves it. Unlike signOut the request is NOT swallowed: if it fails- // the sessions elsewhere are all still valid, and wiping this device's copy of the data- // would sign the user out of the one place the bump didn't reach. Caller reports the error.- async signOutAll() {- await get().pushState() // never throws — stores gym_dirty and moves on when offline+ // where a normal signOut leaves it, under the same rule about changes still owed. Unlike+ // signOut the request is NOT swallowed: if it fails the sessions elsewhere are all still+ // valid, and wiping this device's copy of the data would sign the user out of the one place+ // the bump didn't reach. Caller reports the error.+ async signOutAll({ force = false } = {}) {+ await settle()+ const left = get().unsyncedChanges()+ if (left.owed && !force) return { owed: true, count: left.count }await api('/api/logout/all', { method: 'POST', body: '{}' })+ if (left.owed && !(await stashOwed())) return { owed: true, count: left.count, stashed: false }clearLocalSession()+ return left.owed ? { owed: true, count: left.count, stashed: true } : { owed: false }},// Demo build only: drop the seeded example profile back in (Settings → "Reset demo data").// Dynamic import so the generator never ships in a self-hosted bundle.async resetDemo() {const { buildDemoState } = await import('../lib/demoSeed.js')- localStorage.removeItem('gym_dirty')+ markOwed(false)persist(Object.assign(clone(DEF), buildDemoState()), false)},@@ -563,17 +867,28 @@ export const useStore = create((set, get) => {set({ coachLocal: coachDeviceSettings(await loadCoachDevice()) })if (remote?.mode === 'remote') {setRemoteAuth(remote.base, remote.token)+ pairedBase = remote.base || null+ setSync({ server: pairedBase })+ await restoreFromMirror()try {const me = await api('/api/me') // also catches a token revoked elsewhere (sign out everywhere)+ if (!me.user?.id) throw Object.assign(new Error('no user'), { status: 200, code: 'bad-response' })get().setUser(me.user)// The paired server's /api/config, the same one the web boot reads: without it the// phone never learned whether the server offers the Coach and told everyone "your// server has no Coach enabled" — with the admin looking at a green test.await get().loadConfig()await get().pullState()+ if (!get().sync.lastError) await applyStash() // only once the server really answered} catch (e) {- if (e.status === 401) { await forgetRemote(); get().setGuest(true) }- else { get().setUser(remote.user); setSync({ offline: true }) } // offline — keep going from the last-synced local copy+ // Whatever the answer — no network, a server error, a token the server no longer+ // accepts — the pairing, this copy and the account all stay, and what is owed stays+ // owed. A refused token used to unpair the phone on the spot while it went on showing+ // the account: every change after that "synced" into the app's own files (see+ // lib/api.js) and was gone on the next Disconnect. Now the screens say the server+ // refuses this phone, and pairing it again merges what it kept.+ get().setUser(remote.user || get().user)+ failed(e, { pending: owes() })}syncReminder(get().S)finishBoot()@@ -586,7 +901,16 @@ export const useStore = create((set, get) => {} else if (hasData(S)) {nativeSave(S) // first run after an update from a file-less version: seed the mirror}- get().setGuest(true)+ if (get().user) {+ // A phone that lost its pairing to a refused token under an earlier version: that boot+ // dropped the pairing file — address and token with it — but not the account, and every+ // push since "landed" on the WebView's own asset server. No other path leaves an+ // account in local mode (Disconnect and "keep it on this phone" both leave none), so+ // this is that phone. What it holds stays owed, and the screens say it has to be paired+ // again; the address is gone, so pairing asks for it.+ markOwed(true)+ failed({ status: 0, code: 'not-paired' }, { pending: true })+ } else get().setGuest(true)syncReminder(get().S)// Only a genuinely first launch — nothing chosen yet and nothing to lose either — offers// the choice. Picking local (even with no data yet) persists that choice below and this@@ -612,8 +936,10 @@ export const useStore = create((set, get) => {if (!guestAllowed(cfg)) get().setGuest(false)try {const me = await api('/api/me')+ if (!me.user?.id) throw Object.assign(new Error('no user'), { status: 200, code: 'bad-response' })get().setUser(me.user)await get().pullState()+ if (!get().sync.lastError) await applyStash() // only once the server really answered// Re-stamp the reminder's timezone on every load — keeps it correct if you're travelling,// without needing to revisit Settings.const tz = localTZ()@@ -621,10 +947,18 @@ export const useStore = create((set, get) => {get().update(s => { s.reminder = { ...s.reminder, tz } })}} catch (e) {- if (e.status === 401) get().setUser(null)- // Started without a network (a home-screen app reopened in the gym's basement): keep the- // signed-in copy and say so from the first screen, not only after the first failed push.- else if (isNetworkError(e) && get().user) setSync({ offline: true })+ // The session ended (expired, revoked, signed out everywhere): back to the sign-in+ // screen, which says so. The copy stays here with its owner, and signing in again as the+ // same account merges it (adoptProfile).+ if (e.status === 401) {+ const had = !!get().user+ get().setUser(null)+ if (had) failed(e, { pending: owes() })+ }+ // Started without a network (a home-screen app reopened in the gym's basement), or+ // behind a proxy answering for the server: keep the signed-in copy and say so from the+ // first screen, not only after the first failed push.+ else if (get().user) failed(e, { pending: owes() })}finishBoot()}diff --git a/frontend/src/store/useStore.mobile-remote.test.jsx b/frontend/src/store/useStore.mobile-remote.test.jsxnew file mode 100644index 000000000..0dbbb7d7e--- /dev/null+++ b/frontend/src/store/useStore.mobile-remote.test.jsx@@ -0,0 +1,368 @@+// @vitest-environment happy-dom++/* A paired phone whose server stops accepting it (Discord report, v1.3.8): a token expired or+ revoked by "sign out everywhere", a secret that did not survive a migration, a proxy in front+ refusing the Bearer header. It used to unpair itself silently on the next cold start while it+ went on showing the account; every change after that "synced" into Capacitor's own asset+ server (which answers any path, PUT included, with index.html and a 200), and Disconnect then+ wiped the week that only the phone had. Here the phone keeps its pairing, its account and its+ data, says the server refuses it, and pairing it again merges what it kept.++ Real modules: store/useStore.js, lib/api.js, lib/remote.js, lib/mobile.js. Mocked: the+ Capacitor plugins (an in-memory Directory.Data), and fetch, which plays the self-hosted server+ at BASE and Capacitor's local server for any other URL. */+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { syncFingerprint } from '../lib/sync-changes.js'++const h = vi.hoisted(() => {+ vi.stubEnv('VITE_MOBILE', '1') // lib/mobile.js: MOBILE = import.meta.env.VITE_MOBILE === '1'+ return { files: new Map(), server: null, calls: [] }+})++vi.mock('@capacitor/filesystem', () => ({+ Directory: { Data: 'DATA', Documents: 'DOCUMENTS', Cache: 'CACHE' },+ Encoding: { UTF8: 'utf8' },+ Filesystem: {+ readFile: async ({ path, directory }) => {+ const k = directory + '/' + path+ if (!h.files.has(k)) throw new Error('File does not exist')+ return { data: h.files.get(k) }+ },+ writeFile: async ({ path, directory, data }) => { h.files.set(directory + '/' + path, data); return { uri: 'file://' + path } },+ },+}))+vi.mock('@capacitor/local-notifications', () => ({+ LocalNotifications: { cancel: async () => {}, checkPermissions: async () => ({ display: 'granted' }), requestPermissions: async () => ({ display: 'granted' }), schedule: async () => {} },+}))+vi.mock('@capacitor/app', () => ({ App: { addListener: () => ({ remove() {} }) } }))+vi.mock('@capacitor/core', () => ({ Capacitor: { getPlatform: () => 'android', isNativePlatform: () => true }, registerPlugin: () => ({}) }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: () => {} }) } }))++const BASE = 'https://gym.example.com'+const USER = { id: 'u1', name: 'andi', admin: true }+const clone = v => JSON.parse(JSON.stringify(v))+const workout = (id, d) => ({ id, d, start: 1, entries: [] })+const routine = (id, reps) => ({ id, name: id, ex: [{ id: 'bench', sets: 2, reps }] })+const INDEX_HTML = '<!doctype html><html><head><title>openGym</title></head><body><div id="root"></div></body></html>'+const res = (status, body, type = 'application/json') => ({+ ok: status >= 200 && status < 300, status,+ headers: { get: k => (k.toLowerCase() === 'content-type' ? type : null) },+ json: async () => JSON.parse(body),+ text: async () => body,+})+const json = (status, body) => res(status, JSON.stringify(body))++function installFetch() {+ h.calls = []+ globalThis.fetch = window.fetch = vi.fn(async (url, init = {}) => {+ const method = (init.method || 'GET').toUpperCase()+ h.calls.push({ url: String(url), method, auth: init.headers?.Authorization || null, body: init.body ? JSON.parse(init.body) : null })+ if (String(url).startsWith(BASE)) return h.server(String(url).slice(BASE.length), method, init)+ // Capacitor's WebViewLocalServer: index.html and 200 for every extension-less path, any method.+ const last = String(url).split('?')[0].split('/').pop()+ return last.includes('.') ? res(404, '') : res(200, INDEX_HTML, 'text/html')+ })+}+const refusing = () => json(401, { error: 'not signed in' })+// The paired server, as api/server.js answers: a revision per document, 409 on a stale baseRev.+function serverWith(doc) {+ const srv = { doc: clone(doc), puts: [] }+ srv.handle = (path, method, init) => {+ if (path === '/api/me') return json(200, { user: USER })+ if (path === '/api/config') return json(200, { invite_only: false, allow_guest: true })+ if (path === '/api/pair/redeem') return json(200, { token: 'TOKEN-NEW', user: USER })+ if (path === '/api/data/rev') return json(200, { rev: srv.doc._rev })+ if (path === '/api/data' && method === 'GET') return json(200, { state: clone(srv.doc), rev: srv.doc._rev })+ if (path === '/api/data' && method === 'PUT') {+ const body = JSON.parse(init.body)+ srv.puts.push(body)+ if (body.baseRev != null && body.baseRev !== srv.doc._rev) return json(409, { error: 'conflict', rev: srv.doc._rev, state: clone(srv.doc) })+ srv.doc = { ...body.state, _rev: srv.doc._rev + 1 }+ delete srv.doc.active+ return json(200, { ok: true, rev: srv.doc._rev })+ }+ if (path === '/api/logout') return json(200, { ok: true })+ return json(404, { error: 'not found' })+ }+ h.server = srv.handle+ return srv+}++const readFile = name => { const v = h.files.get('DATA/' + name); return v == null ? null : JSON.parse(v) }+const serverCalls = () => h.calls.filter(c => c.url.startsWith(BASE))+const localCalls = () => h.calls.filter(c => !c.url.startsWith(BASE))+const sleep = ms => new Promise(r => setTimeout(r, ms))+const ids = xs => (xs || []).map(x => x.id)++// Server rev 5 holds w1 and the push-day routine at 10 reps; the phone is paired and in step.+const SERVER_STATE = { _ts: 1000, _rev: 5, unit: 'kg', restSec: 90, workouts: [workout('w1', '2026-09-10')], routines: [routine('push', 10)], bodyweight: [] }+let DEF+beforeAll(async () => { DEF = (await import('./useStore.js')).DEF })+// `synced`: it last agreed with the server under this version, so it knows what that copy was.+function pairedPhone({ localStorage: withLocal = true, mirror, synced = true } = {}) {+ h.files.clear()+ localStorage.clear()+ const S = { ...clone(DEF), ...clone(SERVER_STATE) }+ delete S._rev+ h.files.set('DATA/opengym-remote.json', JSON.stringify({ mode: 'remote', base: BASE, token: 'TOKEN-OLD', user: USER }))+ h.files.set('DATA/opengym-state.json', JSON.stringify(mirror || S))+ if (withLocal) {+ localStorage.setItem('gym_state_v1', JSON.stringify(S))+ localStorage.setItem('gym_user', JSON.stringify(USER))+ localStorage.setItem('gym_owner', USER.id)+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 5, ts: 1000 }))+ if (synced) localStorage.setItem('gym_synced_fp', JSON.stringify(syncFingerprint(S)))+ }+}+// What an earlier version left on a phone after the boot 401: the account, but a pairing file+// that says local, and no marker or dirty flag (the fake pushes into index.html cleared them).+function zombiePhone(local) {+ h.files.clear()+ localStorage.clear()+ localStorage.setItem('gym_user', JSON.stringify(USER))+ localStorage.setItem('gym_owner', USER.id)+ localStorage.setItem('gym_guest', '1')+ localStorage.setItem('gym_state_v1', JSON.stringify(local))+ h.files.set('DATA/opengym-remote.json', JSON.stringify({ mode: 'local' }))+ h.files.set('DATA/opengym-state.json', JSON.stringify(local))+}++// Every test boots its own store; the ones before it must not write into its files. Their+// debounced mirror write and push are flushed the way a page being hidden flushes them, then+// they are signed out so no poll of theirs runs later.+let stores = []+async function freshStore() {+ vi.resetModules()+ const { useStore } = await import('./useStore.js')+ stores.push(useStore)+ return useStore+}++beforeEach(() => installFetch())+afterEach(async () => {+ window.dispatchEvent(new Event('pagehide'))+ await sleep(20)+ for (const s of stores) s.setState({ user: null, ready: false })+ stores = []+ localStorage.clear()+})++describe('boot when the server refuses the pairing token', () => {+ it('keeps the pairing, the account and the data, and says the server refuses this phone', async () => {+ pairedPhone()+ h.server = refusing+ const useStore = await freshStore()+ await useStore.getState().boot()+ const st = useStore.getState()++ expect(readFile('opengym-remote.json')).toEqual({ mode: 'remote', base: BASE, token: 'TOKEN-OLD', user: USER })+ expect(st.user).toEqual(USER)+ expect(st.isGuest()).toBe(false)+ expect(st.sync).toMatchObject({ status: 'auth', auth: true, lastError: { status: 401, code: 'auth' }, server: BASE })+ })++ it('a change made meanwhile goes to the paired server with the token, and stays owed', async () => {+ pairedPhone()+ h.server = refusing+ const useStore = await freshStore()+ await useStore.getState().boot()+ h.calls = []++ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-15')) })+ await useStore.getState().pushState()++ expect(localCalls()).toHaveLength(0)+ expect(serverCalls()).toEqual([expect.objectContaining({ url: BASE + '/api/data', method: 'PUT', auth: 'Bearer TOKEN-OLD' })])+ expect(localStorage.getItem('gym_dirty')).toBe('1')+ expect(useStore.getState().sync).toMatchObject({ status: 'auth', pending: true, lastSynced: 0 })+ expect(useStore.getState().unsyncedChanges()).toEqual({ owed: true, count: 1 })+ })++ it('a phone that last synced under an older version knows a change is owed, not how many', async () => {+ pairedPhone({ synced: false })+ h.server = refusing+ const useStore = await freshStore()+ await useStore.getState().boot()+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-15')) })+ await useStore.getState().pushState()+ expect(useStore.getState().unsyncedChanges()).toEqual({ owed: true, count: null })+ })++ it('the next cold start asks the server again, and heals by itself once it accepts the token', async () => {+ pairedPhone()+ h.server = refusing+ let useStore = await freshStore()+ await useStore.getState().boot()+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-15')) })+ await useStore.getState().pushState()++ const srv = serverWith(SERVER_STATE) // the proxy in front was fixed+ useStore = await freshStore()+ await useStore.getState().boot()+ expect(srv.puts.at(-1)).toMatchObject({ baseRev: 5 })+ expect(ids(srv.doc.workouts)).toEqual(['w1', 'w2'])+ expect(localStorage.getItem('gym_dirty')).toBeNull()+ expect(useStore.getState().sync).toMatchObject({ status: 'ok', auth: false, pending: false })+ expect(useStore.getState().sync.lastSynced).toBeGreaterThan(0)+ })++ it('a 200 page that is not the server\'s answer is an error, not a sign-out', async () => {+ pairedPhone()+ h.server = () => res(200, INDEX_HTML, 'text/html')+ const useStore = await freshStore()+ await useStore.getState().boot()+ const st = useStore.getState()+ expect(st.user).toEqual(USER)+ expect(localStorage.getItem('gym_user')).not.toBeNull()+ expect(st.sync).toMatchObject({ status: 'error', lastError: { status: 200, code: 'bad-response' } })+ expect(readFile('opengym-remote.json')).toMatchObject({ mode: 'remote' })+ })++ it('mid-session, a refused push and a refused pull say so instead of passing in silence', async () => {+ pairedPhone()+ serverWith(SERVER_STATE)+ const useStore = await freshStore()+ await useStore.getState().boot()+ expect(useStore.getState().sync.status).toBe('ok')++ h.server = refusing+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-15')) })+ await useStore.getState().pushState()+ expect(localStorage.getItem('gym_dirty')).toBe('1')+ expect(useStore.getState().sync).toMatchObject({ status: 'auth', pending: true })+ expect(await useStore.getState().syncNow()).toMatchObject({ status: 'auth', lastError: { status: 401 } })+ })+})++describe('a phone an earlier version already unpaired', () => {+ const week = () => ({ ...clone(SERVER_STATE), _ts: 3000, _rev: undefined, restSec: 60, routines: [routine('push', 15), routine('new-plan', 8)], workouts: [workout('w1', '2026-09-10'), workout('w-week', '2026-09-18')] })++ it('is recognised at boot: its data is owed, nothing goes to the app\'s own asset server, and it asks to be paired again', async () => {+ zombiePhone(week())+ const useStore = await freshStore()+ await useStore.getState().boot()+ expect(useStore.getState().user).toEqual(USER)+ expect(useStore.getState().sync).toMatchObject({ status: 'auth', lastError: { status: 0, code: 'not-paired' }, server: null, pending: true })+ expect(localStorage.getItem('gym_dirty')).toBe('1')++ useStore.getState().update(s => { s.restSec = 45 })+ await useStore.getState().pushState()+ await useStore.getState().syncNow()+ expect(h.calls).toHaveLength(0) // not a single request, anywhere+ expect(localStorage.getItem('gym_dirty')).toBe('1')+ expect(useStore.getState().sync.status).toBe('auth')+ })++ it('pairing it again with the same account merges the week, the routine edits and the settings — no question asked', async () => {+ zombiePhone(week())+ const useStore = await freshStore()+ await useStore.getState().boot()+ const srv = serverWith(SERVER_STATE)+ const ask = vi.fn(async () => false)++ await useStore.getState().connectToServer('gym.example.com', 'ABCD2345', ask)++ expect(ask).not.toHaveBeenCalled()+ const S = useStore.getState().S+ expect(ids(S.workouts)).toEqual(['w1', 'w-week'])+ expect(S.routines.find(r => r.id === 'push').ex[0].reps).toBe(15)+ expect(ids(S.routines).sort()).toEqual(['new-plan', 'push'])+ expect(S.restSec).toBe(60)+ expect(srv.puts.at(-1).baseRev).toBe(5)+ expect(ids(srv.doc.workouts)).toEqual(['w1', 'w-week'])+ expect(useStore.getState().sync).toMatchObject({ status: 'ok', server: BASE, auth: false })+ expect(readFile('opengym-remote.json')).toMatchObject({ mode: 'remote', base: BASE, token: 'TOKEN-NEW' })+ })++ it('Disconnect does not wipe the week the server never saw', async () => {+ zombiePhone(week())+ const useStore = await freshStore()+ await useStore.getState().boot()+ await sleep(900) // the file mirror's debounce++ const r = await useStore.getState().disconnectServer()++ expect(r).toMatchObject({ owed: true })+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-week'])+ expect(localStorage.getItem('gym_state_v1')).toContain('w-week')+ await sleep(900)+ expect(ids(readFile('opengym-state.json').workouts)).toEqual(['w1', 'w-week'])+ expect(useStore.getState().user).toEqual(USER)+ expect(h.calls).toHaveLength(0)+ })+})++describe('Disconnect anyway keeps the owed changes for the next pairing', () => {+ it('stashes them in storage and in a file, wipes the phone, and merges them back when paired to the same server and account', async () => {+ pairedPhone()+ h.server = refusing+ const useStore = await freshStore()+ await useStore.getState().boot()+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-15')) })+ await useStore.getState().pushState()++ expect(await useStore.getState().disconnectServer()).toEqual({ owed: true, count: 1 })+ const r = await useStore.getState().disconnectServer({ force: true })+ expect(r).toEqual({ owed: true, count: 1, stashed: true })+ expect(useStore.getState().user).toBeNull()+ expect(useStore.getState().S.workouts).toEqual([])+ expect(readFile('opengym-remote.json')).toEqual({ mode: 'local' })+ expect(useStore.getState().sync).toMatchObject({ status: 'local', server: null })+ const stash = readFile('opengym-stash.json')+ expect(Object.keys(stash)).toEqual([BASE + '|u1'])+ expect(ids(stash[BASE + '|u1'].state.workouts)).toEqual(['w1', 'w2'])+ expect(JSON.parse(localStorage.getItem('gym_stash'))[BASE + '|u1']).toBeTruthy()++ // localStorage lost as well: the file alone brings it back.+ localStorage.removeItem('gym_stash')+ const srv = serverWith({ ...SERVER_STATE, workouts: [...SERVER_STATE.workouts, workout('w-web', '2026-09-16')], _rev: 6 })+ await useStore.getState().connectToServer('gym.example.com', 'ABCD2345', vi.fn(async () => false))++ expect(ids(srv.doc.workouts).sort()).toEqual(['w-web', 'w1', 'w2'])+ expect(ids(useStore.getState().S.workouts).sort()).toEqual(['w-web', 'w1', 'w2'])+ expect(readFile('opengym-stash.json')).toEqual({})+ expect(localStorage.getItem('gym_stash')).toBeNull()+ expect(localStorage.getItem('gym_dirty')).toBeNull()+ })++ it('a stash for another account stays where it is', async () => {+ pairedPhone()+ h.server = refusing+ const useStore = await freshStore()+ await useStore.getState().boot()+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-15')) })+ await useStore.getState().disconnectServer({ force: true })++ const srv = serverWith(SERVER_STATE)+ h.server = (path, method, init) => (path === '/api/pair/redeem' ? json(200, { token: 'T2', user: { id: 'u2', name: 'bea' } }) : srv.handle(path, method, init))+ await useStore.getState().connectToServer('gym.example.com', 'ABCD2345', vi.fn(async () => false))+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1'])+ expect(Object.keys(readFile('opengym-stash.json'))).toEqual([BASE + '|u1'])+ })+})++describe('remote-mode boot and the durable file mirror', () => {+ it('with localStorage gone, a change only the mirror holds is merged with the server copy and pushed', async () => {+ const mirror = { ...clone(SERVER_STATE), _ts: 5000, workouts: [workout('w1', '2026-09-10'), workout('w2', '2026-09-20')] }+ delete mirror._rev+ pairedPhone({ localStorage: false, mirror })+ const srv = serverWith({ ...SERVER_STATE, workouts: [...SERVER_STATE.workouts, workout('w-web', '2026-09-19')], _rev: 6 })+ const useStore = await freshStore()+ await useStore.getState().boot()+ await sleep(900)++ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-web', 'w2'])+ expect(ids(srv.doc.workouts)).toEqual(['w1', 'w-web', 'w2'])+ expect(srv.puts.at(-1).baseRev).toBe(6)+ expect(ids(readFile('opengym-state.json').workouts)).toEqual(['w1', 'w-web', 'w2'])+ })++ it('an ordinary start, mirror and storage in step, pulls as before and pushes nothing', async () => {+ pairedPhone()+ const srv = serverWith(SERVER_STATE)+ const useStore = await freshStore()+ await useStore.getState().boot()+ expect(srv.puts).toHaveLength(0)+ expect(useStore.getState().sync).toMatchObject({ status: 'ok', pending: false })+ })+})diff --git a/frontend/src/store/useStore.sync-status.test.jsx b/frontend/src/store/useStore.sync-status.test.jsxnew file mode 100644index 000000000..e262a5666--- /dev/null+++ b/frontend/src/store/useStore.sync-status.test.jsx@@ -0,0 +1,290 @@+// @vitest-environment happy-dom++/* What the store tells the screens about the server (`sync`, `syncNow`, `unsyncedChanges`), and+ the owner's rule that signing out never loses a change silently: it refuses while anything is+ owed, keeps the owed copy aside when told to go ahead anyway, and brings it back on the next+ sign-in to the same server and account. Signing in again to the account this copy already+ belongs to merges instead of asking. */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))+const { toast } = vi.hoisted(() => ({ toast: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast }) } }))++import { api } from '../lib/api.js'+import { DEF, useStore } from './useStore.js'++const clone = value => JSON.parse(JSON.stringify(value))+const workout = (id, d = '2026-09-01') => ({ id, d, start: 1, entries: [] })+const routine = (id, reps = 10) => ({ id, name: id, ex: [{ id: 'bench', sets: 3, reps }] })+const httpError = (status, data = {}) => Object.assign(new Error(data.error || 'HTTP ' + status), { status, data })+const netError = () => new TypeError('Failed to fetch')+const ids = xs => (xs || []).map(x => x.id)+const puts = () => api.mock.calls.filter(([, o]) => o?.method === 'PUT').map(([, o]) => JSON.parse(o.body))+const paths = () => api.mock.calls.map(([p, o]) => (o?.method || 'GET') + ' ' + p)+const USER = { id: 'user-1', name: 'One' }+const fresh = { offline: false, pending: false, auth: false, lastError: null, lastSynced: 0, server: null }+const signedIn = (S, extra = {}) => useStore.setState({ S, user: USER, ready: true, sync: { ...fresh }, ...extra })+// The server, in step with this device at rev 1.+const serverAt = (S, rev = 1) => ({ state: { ...clone(S), _rev: rev }, rev })++beforeEach(() => {+ localStorage.clear()+ localStorage.setItem('gym_owner', USER.id)+ api.mockReset(); toast.mockReset()+ useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh } })+})+afterEach(() => {+ vi.useRealTimers()+ localStorage.clear()+ useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh } })+})++describe('sync status', () => {+ it('ok, with the time, once a check finds this device and the server in step — and that time is kept', async () => {+ const S = { ...clone(DEF), _ts: 100, workouts: [workout('w1')] }+ signedIn(S)+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockResolvedValueOnce({ rev: 1 })+ window.dispatchEvent(new Event('online')) // the rev check the poll and a focus also run+ await new Promise(r => setTimeout(r, 10))++ expect(paths()).toEqual(['GET /api/data/rev'])+ const { sync } = useStore.getState()+ expect(sync.status).toBe('ok')+ expect(sync.lastSynced).toBeGreaterThan(0)+ expect(Number(localStorage.getItem('gym_synced_at'))).toBe(sync.lastSynced)+ })++ it('offline, error with the HTTP status, and refused — each from the failure that caused it', async () => {+ const S = { ...clone(DEF), _ts: 500, workouts: [workout('w1')] }+ signedIn(S)+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))++ api.mockRejectedValueOnce(netError())+ await useStore.getState().pushState()+ expect(useStore.getState().sync).toMatchObject({ status: 'offline', pending: true, lastError: { status: 0, code: 'network' } })++ api.mockRejectedValueOnce(httpError(500))+ await useStore.getState().pushState()+ expect(useStore.getState().sync).toMatchObject({ status: 'error', offline: false, pending: true, lastError: { status: 500, code: 'http' } })++ api.mockRejectedValueOnce(httpError(502))+ await useStore.getState().pushState()+ expect(useStore.getState().sync.lastError).toEqual({ status: 502, code: 'http' }) // a new code is news++ api.mockRejectedValueOnce(httpError(401))+ await useStore.getState().pushState()+ expect(useStore.getState().sync).toMatchObject({ status: 'auth', auth: true, pending: true, lastError: { status: 401, code: 'auth' } })+ expect(localStorage.getItem('gym_dirty')).toBe('1')++ api.mockResolvedValueOnce({ ok: true, rev: 2 })+ await useStore.getState().pushState()+ expect(useStore.getState().sync).toMatchObject({ status: 'ok', auth: false, offline: false, pending: false, lastError: null })+ })++ it('a refused rev check or pull says so and leaves the copy, the marker and the user alone', async () => {+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockRejectedValueOnce(httpError(401))+ window.dispatchEvent(new Event('online'))+ await new Promise(r => setTimeout(r, 10))+ expect(useStore.getState().sync.status).toBe('auth')+ expect(useStore.getState().user).toEqual(USER)+ expect(JSON.parse(localStorage.getItem('gym_sync'))).toEqual({ rev: 1, ts: 100 })+ })++ it('pending when a change is owed and nothing has failed yet; local without an account', () => {+ signedIn({ ...clone(DEF), _ts: 100 }, { sync: { ...fresh, pending: true } })+ useStore.getState().setUser(USER) // any update recomputes it+ expect(useStore.getState().sync.status).toBe('pending')+ useStore.getState().setUser(null)+ expect(useStore.getState().sync.status).toBe('local')+ })++ it('syncNow sends the change waiting in the debounce, checks the server, and answers with the result', async () => {+ vi.useFakeTimers()+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockImplementation(async (path, o) => (o?.method === 'PUT' ? { ok: true, rev: 2 } : { state: { ...clone(useStore.getState().S), _rev: 2 }, rev: 2 }))+ useStore.getState().update(s => { s.restSec = 30 })++ const result = await useStore.getState().syncNow()++ expect(paths()).toEqual(['PUT /api/data', 'GET /api/data'])+ expect(result).toMatchObject({ status: 'ok', pending: false })+ expect(result.lastSynced).toBeGreaterThan(0)+ })++ it('syncNow without an account answers local and asks nothing', async () => {+ expect(await useStore.getState().syncNow()).toMatchObject({ status: 'local' })+ expect(api).not.toHaveBeenCalled()+ })+})++describe('the web boot', () => {+ const boot = async me => {+ api.mockImplementation(async path => {+ if (path === '/api/config') return { allow_guest: true }+ if (path === '/api/me') return me()+ throw new Error('unexpected ' + path)+ })+ useStore.setState({ user: USER, ready: false })+ await useStore.getState().boot()+ }++ it('a session that ended goes back to sign-in, keeps the copy with its owner, and says why', async () => {+ useStore.setState({ S: { ...clone(DEF), _ts: 100, workouts: [workout('w1')] } })+ await boot(() => { throw httpError(401) })+ expect(useStore.getState().user).toBeNull()+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1'])+ expect(localStorage.getItem('gym_owner')).toBe(USER.id)+ expect(useStore.getState().sync).toMatchObject({ status: 'auth', lastError: { status: 401 } })+ useStore.getState().setGuest(true) // "Continue without account"+ expect(useStore.getState().sync.status).toBe('local')+ })++ it('a page in front that answers for the server is an error, not a sign-out', async () => {+ await boot(() => { throw Object.assign(new Error('not openGym data'), { status: 200, code: 'bad-response' }) })+ expect(useStore.getState().user).toEqual(USER)+ expect(useStore.getState().sync).toMatchObject({ status: 'error', lastError: { status: 200, code: 'bad-response' } })+ })+})++describe('signing out never loses a change silently', () => {+ const owedCopy = () => {+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockResolvedValueOnce({ rev: 1 }) // a check in step: the fingerprint of rev 1 is taken+ window.dispatchEvent(new Event('online'))+ }++ it('refuses while a change is owed, says how many, and wipes nothing', async () => {+ owedCopy()+ await new Promise(r => setTimeout(r, 10))+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-02')); s.restSec = 60 })+ api.mockReset()+ api.mockRejectedValue(netError())++ const r = await useStore.getState().signOut()++ expect(r).toEqual({ owed: true, count: 2 })+ expect(useStore.getState().user).toEqual(USER)+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w2'])+ expect(JSON.parse(localStorage.getItem('gym_state_v1')).workouts).toHaveLength(2)+ expect(paths()).toEqual(['PUT /api/data']) // the retry, and no /api/logout+ })++ it('goes ahead once the retry lands', async () => {+ owedCopy()+ await new Promise(r => setTimeout(r, 10))+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-02')) })+ api.mockReset()+ api.mockResolvedValue({ ok: true, rev: 2 })+ expect(await useStore.getState().signOut()).toEqual({ owed: false })+ expect(useStore.getState().user).toBeNull()+ expect(paths()).toEqual(['PUT /api/data', 'POST /api/logout'])+ })++ it('"sign out anyway" keeps the owed copy aside and brings it back on the next sign-in to this account', async () => {+ owedCopy()+ await new Promise(r => setTimeout(r, 10))+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-02')) })+ api.mockReset()+ api.mockRejectedValue(netError())++ const r = await useStore.getState().signOut({ force: true })+ expect(r).toEqual({ owed: true, count: 1, stashed: true })+ expect(useStore.getState().user).toBeNull()+ expect(useStore.getState().S.workouts).toEqual([])+ const stash = JSON.parse(localStorage.getItem('gym_stash'))+ expect(Object.values(stash).map(e => [e.uid, ids(e.state.workouts)])).toEqual([[USER.id, ['w1', 'w2']]])++ // Another account signs in here first: the stash is not theirs.+ api.mockReset()+ api.mockResolvedValue({ state: { ...clone(DEF), _ts: 50, workouts: [workout('b1')], _rev: 4 }, rev: 4 })+ useStore.getState().setUser({ id: 'user-2', name: 'Two' })+ await useStore.getState().adoptProfile(async () => false)+ expect(ids(useStore.getState().S.workouts)).toEqual(['b1'])+ expect(localStorage.getItem('gym_stash')).not.toBeNull()+ await useStore.getState().signOut()++ // The account comes back — the stash is merged into what the server has, and pushed.+ api.mockReset()+ api.mockImplementation(async (path, o) => (o?.method === 'PUT' ? { ok: true, rev: 3 } : { state: { ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('w-phone', '2026-09-03')], _rev: 2 }, rev: 2 }))+ useStore.getState().setUser(USER)+ await useStore.getState().adoptProfile(async () => false)++ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w2', 'w-phone'])+ expect(puts().at(-1).baseRev).toBe(2)+ expect(ids(puts().at(-1).state.workouts)).toEqual(['w1', 'w2', 'w-phone'])+ expect(localStorage.getItem('gym_stash')).toBeNull()+ })++ it('"sign out everywhere" follows the same rule, before it asks the server for anything', async () => {+ owedCopy()+ await new Promise(r => setTimeout(r, 10))+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-02')) })+ api.mockReset()+ api.mockRejectedValue(netError())+ expect(await useStore.getState().signOutAll()).toEqual({ owed: true, count: 1 })+ expect(paths()).toEqual(['PUT /api/data'])+ expect(useStore.getState().user).toEqual(USER)+ })++ it('unsyncedChanges says nothing is owed when nothing is', async () => {+ owedCopy()+ await new Promise(r => setTimeout(r, 10))+ expect(useStore.getState().unsyncedChanges()).toEqual({ owed: false, count: 0 })+ })+})++describe('signing in again to the account this copy belongs to', () => {+ // A browser whose session ended mid-week: the copy is still here with its owner and owes the+ // server a workout, a routine edit and a setting.+ const sessionEnded = () => {+ useStore.setState({ S: { ...clone(DEF), _ts: 300, restSec: 60, routines: [routine('push', 15), routine('new-plan', 8)], workouts: [workout('w1'), workout('w-week', '2026-09-18')] }, ready: true })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ localStorage.setItem('gym_dirty', '1')+ }+ const server = { ...clone(DEF), _ts: 200, restSec: 90, routines: [routine('push', 10)], workouts: [workout('w1'), workout('w-phone', '2026-09-17')], _rev: 2 }++ it('merges what it kept with what the server has, and pushes — no question asked', async () => {+ sessionEnded()+ api.mockResolvedValueOnce({ state: clone(server), rev: 2 }).mockResolvedValueOnce({ ok: true, rev: 3 })+ const ask = vi.fn(async () => false)+ useStore.getState().setUser(USER)+ const r = await useStore.getState().adoptProfile(ask)++ expect(ask).not.toHaveBeenCalled()+ expect(r).toMatchObject({ adopted: true, merged: true })+ const S = useStore.getState().S+ expect(ids(S.workouts)).toEqual(['w1', 'w-phone', 'w-week'])+ expect(ids(S.routines).sort()).toEqual(['new-plan', 'push'])+ expect(S.restSec).toBe(60)+ expect(puts()).toHaveLength(1)+ expect(puts()[0].baseRev).toBe(2)+ expect(localStorage.getItem('gym_dirty')).toBeNull()+ })++ it('a copy with nothing of its own since its revision takes the server\'s as it is', async () => {+ useStore.setState({ S: { ...clone(DEF), _ts: 100, workouts: [workout('w1'), workout('gone', '2026-09-02')] }, ready: true })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockResolvedValueOnce({ state: clone(server), rev: 2 })+ useStore.getState().setUser(USER)+ await useStore.getState().adoptProfile(async () => false)+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-phone']) // deleted elsewhere: stays deleted+ expect(puts()).toHaveLength(0)+ })++ it('a copy without an owner (a guest joining an account) still gets the question', async () => {+ localStorage.removeItem('gym_owner')+ useStore.setState({ S: { ...clone(DEF), _ts: 900, workouts: [workout('guest', '2026-09-11')] }, ready: true })+ api.mockResolvedValueOnce({ state: clone(server), rev: 2 })+ const ask = vi.fn(async () => false)+ useStore.getState().setUser(USER)+ await useStore.getState().adoptProfile(ask)+ expect(ask).toHaveBeenCalledWith({ workouts: 1, bodyweight: 0, customEx: 0 })+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-phone'])+ })+})diff --git a/frontend/src/store/useStore.sync.test.jsx b/frontend/src/store/useStore.sync.test.jsxindex b3c2a42ff..f00bb278a 100644--- a/frontend/src/store/useStore.sync.test.jsx+++ b/frontend/src/store/useStore.sync.test.jsx@@ -129,6 +129,7 @@ describe('pull against a revisioned server', () => {expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1'])expect(sync()).toEqual({ rev: 1, ts: 100 })expect(localStorage.getItem('gym_dirty')).toBeNull()+ expect(useStore.getState().sync).toMatchObject({ status: 'auth', auth: true, lastError: { status: 401 } })})})diff --git a/frontend/src/store/useStore.tabs.test.jsx b/frontend/src/store/useStore.tabs.test.jsxnew file mode 100644index 000000000..60bb6ce3b--- /dev/null+++ b/frontend/src/store/useStore.tabs.test.jsx@@ -0,0 +1,237 @@+// @vitest-environment happy-dom++/* Two tabs of one browser, one account (#283), and the other ways a client could write over+ newer server data without a 409. Each "tab" is a fresh import of the store (vi.resetModules),+ so two tabs are two closures sharing one localStorage, as in a browser. The server below+ answers like api/server.js: GET /api/data and /api/data/rev, PUT /api/data refused with the+ current document when `baseRev` is given and not the current revision. */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const h = vi.hoisted(() => ({ api: null }))+vi.mock('../lib/api.js', () => ({ api: (...a) => h.api(...a), setRemoteAuth: () => {} }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: () => {} }) } }))++const clone = v => JSON.parse(JSON.stringify(v))+const w = (id, d = '2026-09-01') => ({ id, d, start: 1, entries: [] })+const ids = st => (st?.workouts || []).map(x => x.id)+const httpError = (status, data) => Object.assign(new Error(data?.error || 'HTTP ' + status), { status, data })+const tick = (ms = 30) => new Promise(r => setTimeout(r, ms))+const saved = () => JSON.parse(localStorage.getItem('gym_state_v1'))++let tabs = []+let DEF+// A tab opened now: it loads the saved copy and its marker from storage, as a page load does.+async function openTab(user = { id: 'u1' }) {+ vi.resetModules()+ const m = await import('./useStore.js')+ DEF = m.DEF+ tabs.push(m.useStore)+ m.useStore.setState({ user, ready: true })+ return m.useStore+}++function server(doc) {+ const s = { doc: doc ? clone(doc) : null, log: [] }+ s.handler = async (path, opts = {}) => {+ const method = opts.method || 'GET'+ const body = opts.body ? JSON.parse(opts.body) : undefined+ s.log.push({ method, path, body })+ if (method === 'GET' && path === '/api/data/rev') return { rev: s.doc?._rev || 0 }+ if (method === 'GET' && path === '/api/data') return { state: s.doc ? clone(s.doc) : null, rev: s.doc?._rev || 0 }+ if (method === 'PUT' && path === '/api/data') {+ const curRev = s.doc?._rev || 0+ if (body.baseRev != null && body.baseRev !== curRev) throw httpError(409, { error: 'conflict', rev: curRev, state: s.doc ? clone(s.doc) : null })+ delete body.state.active+ body.state._rev = curRev + 1+ s.doc = body.state+ return { ok: true, ts: body.state._ts || null, rev: body.state._rev }+ }+ if (method === 'POST' && path.startsWith('/api/logout')) return { ok: true }+ throw new Error('unexpected ' + method + ' ' + path)+ }+ // Another device writes (its own conditional PUT, always current).+ s.otherDevice = (mut, ts) => { const d = clone(s.doc); mut(d); d._ts = ts; d._rev = (s.doc?._rev || 0) + 1; s.doc = d }+ s.puts = () => s.log.filter(e => e.method === 'PUT').map(e => e.body)+ h.api = s.handler+ return s+}+// Storage as a tab that last synced revision `rev` of `doc` leaves it.+const savedCopy = (doc, rev) => {+ const S = clone(doc)+ delete S._rev+ localStorage.setItem('gym_state_v1', JSON.stringify(S))+ localStorage.setItem('gym_sync', JSON.stringify({ rev, ts: S._ts }))+}++beforeEach(async () => {+ localStorage.clear()+ localStorage.setItem('gym_owner', 'u1')+ tabs = []+ DEF = (await import('./useStore.js')).DEF+})+afterEach(() => { for (const t of tabs) t.setState({ user: null, ready: false }); localStorage.clear() })++describe('a tab left open does not overwrite what another tab synced (#283)', () => {+ it('the stale tab quotes its own revision: its push is refused, merged, and the other tab\'s workout survives', async () => {+ const srv = server({ ...clone(DEF), _ts: 100, workouts: [w('w1')], _rev: 1 })+ savedCopy(srv.doc, 1)+ const A = await openTab()+ const B = await openTab()++ B.getState().update(s => { s.workouts.push(w('w2', '2026-09-02')) }) // B finishes a workout+ await B.getState().pushState()+ expect(srv.doc._rev).toBe(2)+ expect(JSON.parse(localStorage.getItem('gym_sync')).rev).toBe(2) // the shared marker moved++ A.getState().update(s => { s.restSec = 60 }) // A, untouched since, changes a setting+ await A.getState().pushState()++ expect(srv.puts().slice(-2).map(p => p.baseRev)).toEqual([1, 2]) // refused, merged, pushed again+ expect(ids(srv.doc)).toEqual(['w1', 'w2'])+ expect(srv.doc.restSec).toBe(60)+ expect(ids(A.getState().S)).toEqual(['w1', 'w2'])+ expect(ids(saved())).toEqual(['w1', 'w2'])+ })++ it('a rev check in the stale tab compares with its own revision and pulls', async () => {+ const srv = server({ ...clone(DEF), _ts: 100, workouts: [w('w1')], _rev: 1 })+ savedCopy(srv.doc, 1)+ const A = await openTab()+ const B = await openTab()+ B.getState().update(s => { s.workouts.push(w('w2', '2026-09-02')) })+ await B.getState().pushState()++ window.dispatchEvent(new Event('online')) // checkRev(true) in both tabs, like the poll or a focus+ await tick()+ expect(ids(A.getState().S)).toEqual(['w1', 'w2'])+ expect(srv.puts()).toHaveLength(1) // A adopted; nothing of its own to push+ })++ it('a full pull in the stale tab with a change of its own merges instead of pushing over', async () => {+ const srv = server({ ...clone(DEF), _ts: 100, workouts: [w('w1')], _rev: 1 })+ savedCopy(srv.doc, 1)+ const A = await openTab()+ A.getState().update(s => { s.restSec = 60 }, false) // an edit whose push has not run yet+ srv.otherDevice(d => { d.workouts.push(w('w2', '2026-09-02')) }, 200)+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 2, ts: 200 })) // written by another tab++ await A.getState().pullState()++ expect(srv.puts().map(p => p.baseRev)).toEqual([2])+ expect(ids(srv.doc)).toEqual(['w1', 'w2'])+ expect(srv.doc.restSec).toBe(60)+ })++ it('another tab\'s marker moving makes a clean tab check the server and follow', async () => {+ const srv = server({ ...clone(DEF), _ts: 100, workouts: [w('w1')], _rev: 1 })+ savedCopy(srv.doc, 1)+ const A = await openTab()+ srv.otherDevice(d => { d.workouts.push(w('w2', '2026-09-02')) }, 200)+ const marker = JSON.stringify({ rev: 2, ts: 200 })+ localStorage.setItem('gym_sync', marker)+ window.dispatchEvent(new StorageEvent('storage', { key: 'gym_sync', newValue: marker }))+ await tick()+ expect(ids(A.getState().S)).toEqual(['w1', 'w2'])+ expect(srv.log.filter(e => e.method === 'GET').map(e => e.path)).toEqual(['/api/data/rev', '/api/data'])+ })++ it('a marker at the revision the tab already has asks nothing', async () => {+ const srv = server({ ...clone(DEF), _ts: 100, workouts: [w('w1')], _rev: 1 })+ savedCopy(srv.doc, 1)+ await openTab()+ window.dispatchEvent(new StorageEvent('storage', { key: 'gym_sync', newValue: JSON.stringify({ rev: 1, ts: 100 }) }))+ await tick()+ expect(srv.log).toHaveLength(0)+ })++ it('another tab\'s failed push does not make a clean tab merge: a deletion stays deleted', async () => {+ const srv = server({ ...clone(DEF), _ts: 100, workouts: [w('w1'), w('w2', '2026-09-02')], _rev: 3 })+ savedCopy(srv.doc, 3)+ const A = await openTab()+ // Another device deletes w2; meanwhile another tab of this browser left gym_dirty behind.+ srv.otherDevice(d => { d.workouts = d.workouts.filter(x => x.id !== 'w2') }, 300)+ localStorage.setItem('gym_dirty', '1')++ await A.getState().pullState()++ expect(ids(A.getState().S)).toEqual(['w1'])+ expect(srv.puts()).toHaveLength(0)+ expect(ids(srv.doc)).toEqual(['w1'])+ })+})++describe('other ways a push could go out without a conflict check', () => {+ it('a forced push (import, reset) that fails is retried against the revision it replaced', async () => {+ const srv = server({ ...clone(DEF), _ts: 100, workouts: [w('w1')], _rev: 1 })+ savedCopy(srv.doc, 1)+ const A = await openTab()++ h.api = async () => { throw httpError(502, {}) } // the server restarting+ A.getState().replaceState({ ...clone(DEF), workouts: [w('imported')] }, true)+ await A.getState().pushState()+ expect(localStorage.getItem('gym_dirty')).toBe('1')++ h.api = srv.handler+ srv.otherDevice(d => { d.workouts.push(w('phone', '2026-09-02')) }, 150)+ A.getState().update(s => { s.restSec = 45 })+ await A.getState().pushState()++ expect(srv.puts().map(p => p.baseRev)).toEqual([1, 2]) // refused, merged, pushed+ expect(ids(srv.doc).sort()).toEqual(['imported', 'phone', 'w1'])+ })++ it('an edit on a device whose clock is behind the revision it builds on still counts as a change', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ try {+ vi.setSystemTime(4000)+ // The copy came from a phone whose clock is ahead: its stamp is 5000.+ const srv = server({ ...clone(DEF), _ts: 5000, workouts: [w('w1')], _rev: 1 })+ savedCopy(srv.doc, 1)+ const A = await openTab()+ A.getState().update(s => { s.workouts.push(w('mine', '2026-09-03')) }, false) // its push never ran+ expect(A.getState().S._ts).toBeGreaterThan(5000)+ srv.otherDevice(d => { d.restSec = 120 }, 6000)++ await A.getState().pullState()++ expect(ids(srv.doc)).toEqual(['w1', 'mine'])+ expect(srv.doc.restSec).toBe(120)+ } finally { vi.useRealTimers() }+ })++ it('a push answered by something that is not the server stays owed, keeps its marker, and merges later', async () => {+ const srv = server({ ...clone(DEF), _ts: 100, workouts: [w('w1')], _rev: 1 })+ savedCopy(srv.doc, 1)+ const A = await openTab()+ h.api = async () => { throw Object.assign(new Error('not openGym data'), { status: 200, code: 'bad-response' }) }+ A.getState().update(s => { s.workouts.push(w('local', '2026-09-03')) })+ await A.getState().pushState()+ expect(localStorage.getItem('gym_dirty')).toBe('1')+ expect(JSON.parse(localStorage.getItem('gym_sync')).rev).toBe(1)+ expect(A.getState().sync).toMatchObject({ status: 'error', pending: true, lastError: { status: 200, code: 'bad-response' } })++ srv.otherDevice(d => { d.workouts.push(w('phone', '2026-09-02')) }, 150)+ h.api = srv.handler+ await A.getState().syncNow()+ expect(ids(srv.doc)).toEqual(['w1', 'phone', 'local'])+ expect(A.getState().sync.status).toBe('ok')+ })+})++describe('routines edited on two devices', () => {+ it('a conflict keeps each routine as it was edited last, whichever copy is newer as a whole', async () => {+ const r = (id, reps) => ({ id, name: id, ex: [{ id: 'bench', sets: 3, reps }] })+ const srv = server({ ...clone(DEF), _ts: 100, routines: [r('push', 10), r('pull', 8)], _rev: 1 })+ savedCopy(srv.doc, 1)+ const A = await openTab()+ A.getState().update(s => { s.routines[0].ex[0].reps = 15 }, false) // the phone edits push day+ await tick(5)+ // then another device edits pull day and, later still, a setting: its copy is newer+ srv.otherDevice(d => { d.routines[1].ex[0].reps = 12; d.routines[1]._ts = Date.now() }, Date.now() + 1000)+ await A.getState().pushState()++ const byId = Object.fromEntries(srv.doc.routines.map(x => [x.id, x.ex[0].reps]))+ expect(byId).toEqual({ push: 15, pull: 12 })+ expect(A.getState().S.routines[0]._ts).toBeGreaterThan(0)+ })+})diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 993c0373d..749d5b76b 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -156,7 +156,9 @@ export default function Settings() {message: t('Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.'),confirmText: t('Sign out everywhere'), danger: true,onConfirm: async () => {- try { await signOutAll(); nav('/home'); toast(t('Signed out on all devices')) }+ // Refused while changes are still owed to the server: nothing was signed out or wiped,+ // and the sync banner says what is waiting.+ try { const r = await signOutAll(); if (r?.owed && !r.stashed) return; nav('/home'); toast(t('Signed out on all devices')) }catch (e) { toast(t('Could not sign out everywhere — you are still signed in.')) }},})@@ -195,7 +197,7 @@ export default function Settings() {title: t('Disconnect from your server?'),message: t('Your data is synced to your server first, then this device switches back to local-only.'),confirmText: t('Disconnect'), danger: true,- onConfirm: async () => { await disconnectServer(); nav('/home'); toast(t('Disconnected — back to local-only')) },+ onConfirm: async () => { const r = await disconnectServer(); if (r?.owed && !r.stashed) return; nav('/home'); toast(t('Disconnected — back to local-only')) },})} /></> : <><Row icon="lock" iconTint="var(--acc)" title={t('All data stays on this phone')} subtitle={t('No account, no cloud — back it up anytime with Export below.')} />@@ -212,7 +214,7 @@ export default function Settings() {{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}<Row icon="link" iconTint="var(--blue)" title={t('Pair the mobile app')} subtitle={t('Connect the openGym app on your phone to this account.')} accessory="chevron"onClick={() => useUI.getState().openSheet(close => <PairSheet close={close} />)} />- <Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} />+ <Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: async () => { const r = await signOut(); if (r?.owed && !r.stashed) return; nav('/home') } })} /><Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} /></> : webauthnOK() ? <><Row icon="sparkles" iconTint="var(--acc)" title={t('Create passkey profile')} subtitle={t('Keeps your data safe and separate per person.')} accessory="chevron" onClick={registerHere} />