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
Tabs: two tabs of one browser keep each other's changes, running workout and owed state
Duarte Santosa05afffd254d
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 69ff4188b..73041180a 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -32,6 +32,8 @@ const KEY = 'gym_state_v1'// 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'+// Which write of the saved copy this is: a tab finds another tab's write by it (persist, joinSaved).+const WID_KEY = 'gym_state_wid'const DIRTY_KEY = 'gym_dirty' // the saved copy owes the server a changeconst SYNCED_AT_KEY = 'gym_synced_at' // when this device and the server last held the same copyconst SYNCED_FP_KEY = 'gym_synced_fp' // a fingerprint of that copy (lib/sync-changes.js)@@ -291,6 +293,9 @@ export const useStore = create((set, get) => {let fpOf = null // the copy the stored fingerprint was last taken of (confirmed)let keeping = null // phone: the file write of what keepForPrevious set aside, until it landslet mirrorQ = Promise.resolve() // phone: the file mirror's writes, one after the other (saveMirror)+ // The write of the saved copy this tab last read or made, and whose copy it was (joinSaved).+ let seenWid = (() => { try { return localStorage.getItem(WID_KEY) } catch { return null } })()+ let seenOwner = (() => { try { return localStorage.getItem('gym_owner') } catch { return null } })()const readAdopt = () => { try { return JSON.parse(localStorage.getItem(ADOPT_KEY)) || null } catch { return null } }const writeAdopt = v => { try { if (v) localStorage.setItem(ADOPT_KEY, JSON.stringify(v)); else localStorage.removeItem(ADOPT_KEY) } catch { /* the hold in memory still stands */ } }@@ -434,9 +439,44 @@ export const useStore = create((set, get) => {// 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.+ /* Two tabs of one browser share the saved copy, and each writes its own copy over it whole. A+ change one tab saved and had not pushed (offline, the server down, a guest who never pushes)+ was gone as soon as the other tab saved anything, or the closed tab's finished workout was:+ no trace in storage, on the server or in the count of changes owed. And a second tab's pull+ wrote its `active: null` over the workout running in the first. So every write of the saved+ copy carries a write id (WID_KEY). A tab that finds another tab's write there joins that copy+ into its own first, the way two devices merge (joinSaved), and a tab told of one by the+ browser (the storage event below) takes it into memory straight away. The running workout+ belongs to the browser, not the tab: it is the saved copy's unless this change touched it. */+ const sameCopy = (a, b) => JSON.stringify({ ...a, _ts: 0 }) === JSON.stringify({ ...b, _ts: 0 })+ const readWid = () => { try { return localStorage.getItem(WID_KEY) } catch { return null } }+ const readOwner = () => { try { return localStorage.getItem('gym_owner') } catch { return null } }+ const readSaved = () => {+ try { const raw = localStorage.getItem(KEY); return raw ? Object.assign(clone(DEF), JSON.parse(raw)) : null } catch { return null }+ }+ // Another tab's copy joined into `mine`; `touched` when this change set the running workout.+ const joinTabs = (mine, theirs, touched) => {+ const merged = Object.assign(clone(DEF), mergeStates(mine, theirs))+ merged.active = touched ? carryActive(mine, merged) : carryActive(theirs, merged)+ return merged+ }+ // `S` with what another tab saved since this one last read or wrote the copy; null when there is+ // nothing to join (the same write, no saved copy, or a copy another account's sign-in replaced).+ const joinSaved = (S, prev) => {+ if (readWid() === seenWid || readOwner() !== seenOwner) return null+ const theirs = readSaved()+ if (!theirs) return null+ const touched = JSON.stringify(prev?.active ?? null) !== JSON.stringify(S?.active ?? null)+ const merged = joinTabs(S, theirs, touched)+ return sameCopy(merged, S) ? null : merged+ }+const persist = (S, push = true, stamp = true) => {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, Number(S._ts) || 0)+ const joined = joinSaved(S, get()?.S)+ if (joined) S = joined+ // A join holds another tab's changes, which this copy then owes the server too.+ if (stamp || joined) S._ts = Math.max(Date.now(), (base?.ts || 0) + 1, Number(S._ts) || 0)// Every copy that enters the store — an edit, a pull, an adoption, a restored backup — has its// custom exercises marked as such (#378): one stored without the flag by an older plan import// goes out with it on the next push, without a stamp of its own (healCustomEx).@@ -452,6 +492,10 @@ export const useStore = create((set, get) => {// copy's, which costs one merge at worst — never a newer one, which would lose data.saveMarker(base)localStorage.setItem(KEY, JSON.stringify(S))+ const wid = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)+ localStorage.setItem(WID_KEY, wid)+ seenWid = wid+ seenOwner = readOwner()toldNoRoom = false} catch (e) {saved = false@@ -462,7 +506,7 @@ export const useStore = create((set, get) => {.catch(() => {})}}- meta.set(S, { base, owed: owed || !saved })+ meta.set(S, { base, owed: owed || !saved || (!!joined && storedOwed()) })if (!saved) saveOwed(true)set({ S })// A copy that replaces the last one wholesale and keeps an older stamp — adopted from the@@ -644,6 +688,8 @@ export const useStore = create((set, get) => {pushTm = nullconst S = e.newValue ? loadState() : freshState()meta.set(S, e.newValue ? { base: readStoredSync(), owed: storedOwed() } : { base: null, owed: false })+ seenWid = readWid()+ seenOwner = readOwner()set({ user: null, S })})// Another tab of this browser synced — its marker moved to a revision this tab's copy does not@@ -662,11 +708,39 @@ export const useStore = create((set, get) => {checkRev(true)})+ // Another tab saved: its copy joins this one's at once, so this tab shows it and never writes+ // over it. When the saved copy holds everything this tab has, this tab takes it as it is, with+ // where it stands with the server (its marker and dirty flag); otherwise the join is saved and+ // pushed like any change.+ const syncFromSaved = () => {+ const wid = readWid()+ if (wid === seenWid || readOwner() !== seenOwner) return+ const theirs = readSaved()+ if (!theirs) return+ const mine = get().S+ const merged = joinTabs(mine, theirs, false)+ seenWid = wid+ if (sameCopy(merged, mine)) return+ if (sameCopy(merged, theirs)) {+ merged._ts = Math.max(Number(theirs._ts) || 0, Number(mine._ts) || 0)+ meta.set(merged, { base: readStoredSync(), owed: storedOwed() })+ registerCustom(merged.customEx)+ set({ S: merged })+ return+ }+ persist(merged, true)+ }+ window.addEventListener('storage', e => {+ if (e.key !== WID_KEY || !e.newValue || e.newValue === seenWid) return+ syncFromSaved()+ })+// 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. Then the photos and videos// still waiting get one more try (lib/media-owed.js, at most a minute): they are owed exactly// like a change is.const settle = async () => {+ syncFromSaved() // what another tab of this browser saved and has not sent counts tooif (pulling) await pullingawait get().pushState() // never throws — an owed copy stays owed when it does not landwhile (pushing) await pushing@@ -750,6 +824,7 @@ export const useStore = create((set, get) => {// Photos or videos that never reached that account's server count as owed on their own, even on// a copy with no workouts or routines yet — the custom exercise they belong to is all there is.const keepForPrevious = uid => {+ syncFromSaved()const S = get().Sif (!(owes() && hasData(S)) && !pendingRefCount(S)) returnconst server = serverBase()diff --git a/frontend/src/store/useStore.tabs-join.test.jsx b/frontend/src/store/useStore.tabs-join.test.jsxnew file mode 100644index 000000000..6bbdd3bde--- /dev/null+++ b/frontend/src/store/useStore.tabs-join.test.jsx@@ -0,0 +1,144 @@+// @vitest-environment happy-dom++/* Two tabs of one browser share the saved copy. Each used to write its whole in-memory copy over+ it, so a change one tab saved and had not pushed (offline, the server down, a guest) was lost+ the moment the other tab saved anything; a second tab's pull wrote `active: null` over the+ workout running in the first; and a sign-out in one tab decided from its own stale copy and+ wiped what the other tab owed. (QA 2026-10-06, also in v1.3.9.) Each "tab" is a fresh import of+ the store sharing one localStorage, as in the other tab tests. */+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: () => {}, stopRest: () => {}, abandonWork: () => {} }) } }))++const clone = v => JSON.parse(JSON.stringify(v))+const w = (id, d = '2026-09-01') => ({ id, d, start: 1, end: 2, entries: [] })+const ids = st => (st?.workouts || []).map(x => x.id).sort()+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+// Tabs of earlier tests still listen on the same window; each test is another account, so they+// take no part (a tab joins only copies of the account it last saw).+let OWNER = 'u0'+async function openTab(user = { id: OWNER }) {+ vi.resetModules()+ const m = await import('./useStore.js')+ DEF = m.DEF+ tabs.push(m.useStore)+ m.useStore.setState({ user, ready: true })+ return m.useStore+}+// The browser telling the other tabs that this one saved (it never tells the tab that wrote).+const announce = () => window.dispatchEvent(new StorageEvent('storage', { key: 'gym_state_wid', newValue: localStorage.getItem('gym_state_wid') }))++function server(doc) {+ const s = { doc: doc ? clone(doc) : null, log: [], offline: false }+ h.api = async (path, opts = {}) => {+ if (s.offline) throw new TypeError('Failed to fetch')+ 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: clone(s.doc) })+ delete body.state.active+ body.state._rev = curRev + 1+ s.doc = body.state+ return { ok: true, rev: body.state._rev }+ }+ if (method === 'POST' && path.startsWith('/api/logout')) return { ok: true }+ throw new Error('unexpected ' + method + ' ' + path)+ }+ return s+}+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()+ OWNER = 'u' + (Number(OWNER.slice(1)) + 1)+ localStorage.setItem('gym_owner', OWNER)+ tabs = []+ DEF = (await import('./useStore.js')).DEF+})+afterEach(() => { for (const t of tabs) t.setState({ user: null, ready: false }); localStorage.clear() })++describe('two tabs of one browser keep each other\'s changes', () => {+ it('offline: a workout finished in a tab that is then closed survives the other tab\'s next change, and reaches the server', 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()+ srv.offline = true+ B.getState().update(s => { s.workouts.push(w('w2', '2026-09-02')); s.bodyweight = [{ d: '2026-09-02', w: 77.7, t: Date.now() }] })+ await B.getState().pushState() // fails: offline+ B.setState({ user: null, ready: false }) // the tab is closed (no event reaches A in time)+ A.getState().update(s => { s.restSec = 45 })+ expect(ids(saved())).toEqual(['w1', 'w2'])+ expect(saved().bodyweight.map(e => e.w)).toEqual([77.7])+ expect(saved().restSec).toBe(45)+ srv.offline = false+ await A.getState().pushState()+ expect(ids(srv.doc)).toEqual(['w1', 'w2'])+ expect(srv.doc.bodyweight.map(e => e.w)).toEqual([77.7])+ })++ it('guests: what one tab logged survives the other tab\'s setting change', async () => {+ localStorage.removeItem('gym_owner')+ localStorage.setItem('gym_state_v1', JSON.stringify({ ...clone(DEF), _ts: 100, workouts: [w('g1')] }))+ const A = await openTab(null)+ const B = await openTab(null)+ A.getState().update(s => { s.workouts.push(w('g2', '2026-09-03')) })+ B.getState().update(s => { s.restSec = 120 })+ expect(ids(saved())).toEqual(['g1', 'g2'])+ expect(saved().restSec).toBe(120)+ })++ it('a second tab\'s pull keeps the workout running in the first', 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()+ A.getState().update(s => { s.active = { id: 'run1', start: Date.now(), entries: [{ id: 'bench', sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] }] } })+ // another device writes; B (no change of its own) pulls and adopts the server's copy+ srv.doc = { ...clone(srv.doc), workouts: [w('w1'), w('wX', '2026-09-04')], _rev: 2, _ts: 300 }+ await B.getState().pullState()+ expect(saved().active?.id).toBe('run1')+ expect(saved().active.entries[0].sets).toHaveLength(2)+ expect(ids(saved())).toEqual(['w1', 'wX'])+ })++ it('the other tab takes a saved change into memory as soon as the browser says so', 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')) }, false)+ announce()+ expect(ids(A.getState().S)).toEqual(['w1', 'w2'])+ })++ it('sign-out in one tab counts, and keeps, what the other tab finished offline', 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()+ srv.offline = true+ B.getState().update(s => { s.workouts.push(w('w2', '2026-09-02')) })+ await B.getState().pushState()+ srv.offline = false // only tab B's push failed; A is online when it signs out+ const r = await A.getState().signOut()+ // A's last push carried B's workout before the wipe (or, had it failed, the sign-out would say it is owed)+ expect(r.owed).toBe(false)+ expect(ids(srv.doc)).toEqual(['w1', 'w2'])+ })+})diff --git a/frontend/src/views/RoutineEdit.drag.test.jsx b/frontend/src/views/RoutineEdit.drag.test.jsxindex 85aa830ed..f22d71cfc 100644--- a/frontend/src/views/RoutineEdit.drag.test.jsx+++ b/frontend/src/views/RoutineEdit.drag.test.jsx@@ -151,7 +151,8 @@ describe('routine long-press reorder', () => {expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines[0].ex.map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])expect(localStorage.getItem('gym_state_v1')).not.toBe(before)- expect(writes).toHaveBeenCalledTimes(1)+ // one save of the copy (beside it the write id other tabs read, useStore persist)+ expect(writes.mock.calls.filter(([k]) => k === 'gym_state_v1')).toHaveLength(1)})it('suppresses the compatibility click after a successful changed drop', () => {