Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Phone: the file mirror is only ever taken back for its own account, and merged — never pushed over the server's copy

Duarte Santos79f6f108fe4c
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index b708c6f12..e3fef7504 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -74,7 +74,8 @@ Where the phone keeps things, in case you ever need them by hand:
- `opengym-state.json` in the app's private data directory — the durable copy of everything
on the phone, written after every change (not reachable without a rooted phone or `adb`
- on a debug build).
+ on a debug build). `opengym-state-owner.json` beside it says which account that copy
+ belongs to: a paired phone only ever takes the file back for that account.
- `opengym-stash.json`, same directory — changes kept by "Disconnect anyway" or by another
account pairing, waiting for their server and account.
- `Documents/opengym-backup-YYYY-MM-DD.json` — only with Settings → **Auto-backup on
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index e325981e5..6d874088f 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -29,6 +29,9 @@ const SYNCED_FP_KEY = 'gym_synced_fp' // a fingerprint of that copy (lib/sync-c
// 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'
+// Mobile build: whose copy the file mirror (lib/mobile.js, opengym-state.json) holds, and which
+// one — { owner, ts }, written after it (saveMirror). A device fact, so never inside S.
+const MIRROR_OWNER_FILE = 'opengym-state-owner.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 often
export const DEF = {
@@ -133,6 +136,7 @@ export const useStore = create((set, get) => {
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)
let keeping = null // phone: the file write of what keepForPrevious set aside, until it lands
+ let mirrorQ = Promise.resolve() // phone: the file mirror's writes, one after the other (saveMirror)
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 } }
@@ -232,11 +236,28 @@ export const useStore = create((set, get) => {
initReminderSync(() => get().S)
+ // Mobile build: the file mirror, and beside it whose copy it is and which one (its `_ts`) —
+ // restoreFromMirror takes the file back only for that account, and only while the two agree,
+ // so a mirror write that failed, or a kill between the two writes, leaves a file that is never
+ // taken. One write at a time, each of the copy in the store when its turn comes: a slow write
+ // can never land after a later one.
+ const saveMirror = () => (mirrorQ = mirrorQ.then(async () => {
+ const S = get().S
+ let owner = null
+ try { owner = localStorage.getItem('gym_owner') } catch { /* unknown — the file is then nobody's */ }
+ await nativeSave(S)
+ await writeJsonFile(MIRROR_OWNER_FILE, { owner, ts: S._ts || 0 })
+ }).catch(() => {}))
// Mobile build: mirror the state into a file in the app's data directory (survives WebView
// storage eviction) and keep the native reminder schedule in step with the weekly plan.
- const nativePersist = () => {
+ // `now` skips the wait and returns the write, for a copy that replaced the last one wholesale.
+ const nativePersist = (now = false) => {
clearTimeout(saveTm)
- saveTm = setTimeout(() => { saveTm = null; nativeSave(get().S); syncReminder(get().S) }, 800)
+ saveTm = null
+ const write = () => { saveTm = null; syncReminder(get().S); return saveMirror() }
+ if (now) return write()
+ saveTm = setTimeout(write, 800)
+ return null
}
// `_ts` is when this device last changed the data — it decides which copy wins on the next
@@ -273,7 +294,10 @@ export const useStore = create((set, get) => {
meta.set(S, { base, owed: owed || !saved })
if (!saved) saveOwed(true)
set({ S })
- if (MOBILE) nativePersist()
+ // A copy that replaces the last one wholesale and keeps an older stamp — adopted from the
+ // server — goes to the file at once. Until it does, the file holds the copy it replaced,
+ // which looks newer, and a start in between would take that one back (restoreFromMirror).
+ if (MOBILE) nativePersist(!stamp)
if (push && get().user) {
// Before boot has pulled, the copy in hand may be older than the server's: a push now
// would carry it with a stale (or no) baseRev. It waits for finishBoot.
@@ -396,12 +420,7 @@ export const useStore = create((set, get) => {
// same applies to the file mirror — backgrounding is often the last thing before the OS
// kills the app.
const flush = () => {
- if (MOBILE && saveTm) {
- clearTimeout(saveTm)
- saveTm = null
- nativeSave(get().S)
- syncReminder(get().S)
- }
+ if (MOBILE && saveTm) nativePersist(true)
if (pushTm) {
clearTimeout(pushTm)
pushTm = null
@@ -470,6 +489,10 @@ export const useStore = create((set, get) => {
persist(clone(DEF), false)
localStorage.removeItem('gym_owner')
setSync({ offline: false, auth: false, lastError: null, pending: false, lastSynced: 0 })
+ // On a phone the file is wiped with it, now rather than after the usual wait: a start in
+ // between would open in local mode on the signed-out account's data, since that boot takes
+ // the file whenever storage holds nothing.
+ return MOBILE ? nativePersist(true) : null
}
/* The changes a forced sign-out or disconnect keeps, so that no change is ever lost silently.
@@ -544,7 +567,7 @@ export const useStore = create((set, get) => {
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
+ if (MOBILE) await nativePersist(true) // the durable copy holds it before the stash goes
await get().pushState()
for (const k of keys) delete all[k]
await writeStashes(all)
@@ -552,12 +575,24 @@ export const useStore = create((set, get) => {
// 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 () => {
+ // and may not have sent — it is taken, and owed. Only the paired account's own, though, and
+ // only the copy the owner file says was written (saveMirror): one another account left there,
+ // or one the file never finished replacing, is not this account's latest — taken, it used to
+ // be pushed into whichever account was paired now. And it goes without the revision storage
+ // quotes, so the pull merges it with the server's copy (its first-sync path): the file can
+ // still hold a copy the server has since moved past, and a merge brings back at most what was
+ // deleted meanwhile, where a push with a matching baseRev dropped the other side's work.
+ const restoreFromMirror = async remote => {
const saved = await nativeLoad()
if (!saved || (saved._ts || 0) <= (get().S._ts || 0)) return
+ const of = await readJsonFile(MIRROR_OWNER_FILE)
+ const who = remote?.user?.id || null
+ let owner = null
+ try { owner = localStorage.getItem('gym_owner') } catch { /* evicted along with the copy */ }
+ if (!who || of?.owner !== who || (owner && owner !== who) || of.ts !== (saved._ts || 0)) return
+ try { if (!owner) localStorage.setItem('gym_owner', who) } catch { /* setUser writes it again */ }
persist(Object.assign(clone(DEF), saved), false, false)
+ dropSync()
markOwed(true)
}
@@ -642,7 +677,8 @@ export const useStore = create((set, get) => {
// phone paired again, a browser signed in again — is remembered for adoptProfile.
const owner = localStorage.getItem('gym_owner')
rejoined = owner === u.id
- if (owner && owner !== u.id) {
+ const other = !!owner && owner !== u.id
+ if (other) {
keepForPrevious(owner)
forgetSync()
localStorage.removeItem(KEY)
@@ -651,6 +687,8 @@ export const useStore = create((set, get) => {
}
localStorage.setItem('gym_owner', u.id)
localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest')
+ // The file follows at once, as the new account's: until then it holds the previous one's.
+ if (other && MOBILE) nativePersist(true)
} else { rejoined = false; localStorage.removeItem('gym_user') }
set({ user: u })
setSync({})
@@ -825,7 +863,7 @@ export const useStore = create((set, get) => {
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()
+ await clearLocalSession()
return left.owed ? { owed: true, count: left.count, stashed: true } : { owed: false }
},
@@ -849,7 +887,7 @@ export const useStore = create((set, get) => {
setSync({ server: pairedBase })
await get().refreshConfig() // what this server offers (the Coach, guest mode) — see boot()
await get().adoptProfile(ask)
- syncReminder(get().S)
+ await nativePersist(true) // the file holds this account's copy before anything else can happen
set({ needsMobileOnboarding: false })
},
// Leaves remote mode and drops back to local-only, the way signOut does: never with changes
@@ -878,7 +916,7 @@ export const useStore = create((set, get) => {
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()
+ await clearLocalSession()
return left.owed ? { owed: true, count: left.count, stashed: true } : { owed: false }
},
@@ -903,7 +941,7 @@ export const useStore = create((set, get) => {
setRemoteAuth(remote.base, remote.token)
pairedBase = remote.base || null
setSync({ server: pairedBase })
- await restoreFromMirror()
+ await restoreFromMirror(remote)
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' })
@@ -936,7 +974,7 @@ export const useStore = create((set, get) => {
if (saved && (!hasData(S) || (saved._ts || 0) >= (S._ts || 0))) {
persist(Object.assign(clone(DEF), saved), false, false)
} else if (hasData(S)) {
- nativeSave(S) // first run after an update from a file-less version: seed the mirror
+ nativePersist(true) // first run after an update from a file-less version: seed the mirror
}
if (get().user) {
// A phone that lost its pairing to a refused token under an earlier version: that boot
diff --git a/frontend/src/store/useStore.mobile-remote.test.jsx b/frontend/src/store/useStore.mobile-remote.test.jsx
index 0281ed19e..b3bd2836f 100644
--- a/frontend/src/store/useStore.mobile-remote.test.jsx
+++ b/frontend/src/store/useStore.mobile-remote.test.jsx
@@ -16,7 +16,8 @@ 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: [] }
+ // `refuse`: file names whose writes fail, like a full disk.
+ return { files: new Map(), server: null, calls: [], refuse: new Set() }
})
vi.mock('@capacitor/filesystem', () => ({
@@ -28,7 +29,11 @@ vi.mock('@capacitor/filesystem', () => ({
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 } },
+ writeFile: async ({ path, directory, data }) => {
+ if (h.refuse.has(path)) throw new Error('No space left on device')
+ h.files.set(directory + '/' + path, data)
+ return { uri: 'file://' + path }
+ },
},
}))
vi.mock('@capacitor/local-notifications', () => ({
@@ -106,6 +111,7 @@ function pairedPhone({ localStorage: withLocal = true, mirror, synced = true } =
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))
+ h.files.set('DATA/opengym-state-owner.json', JSON.stringify({ owner: USER.id, ts: (mirror || S)._ts }))
if (withLocal) {
localStorage.setItem('gym_state_v1', JSON.stringify(S))
localStorage.setItem('gym_user', JSON.stringify(USER))
@@ -138,7 +144,7 @@ async function freshStore() {
return useStore
}
-beforeEach(() => installFetch())
+beforeEach(() => { installFetch(); h.refuse.clear() })
afterEach(async () => {
window.dispatchEvent(new Event('pagehide'))
await sleep(20)
@@ -325,6 +331,23 @@ describe('Disconnect anyway keeps the owed changes for the next pairing', () =>
expect(localStorage.getItem('gym_dirty')).toBeNull()
})
+ it('killed straight after, the next start is local and empty: the account\'s copy is in the stash, not back on the screen', 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()
+ await sleep(900)
+ expect(await useStore.getState().disconnectServer({ force: true })).toMatchObject({ stashed: true })
+
+ useStore = await freshStore()
+ await useStore.getState().boot()
+ expect(useStore.getState().user).toBeNull()
+ expect(useStore.getState().S.workouts).toEqual([])
+ expect(ids(readFile('opengym-stash.json')[BASE + '|u1'].state.workouts)).toEqual(['w1', 'w2'])
+ })
+
it('a stash for another account stays where it is', async () => {
pairedPhone()
h.server = refusing
@@ -401,6 +424,133 @@ describe('remote-mode boot and the durable file mirror', () => {
expect(srv.puts).toHaveLength(0)
expect(useStore.getState().sync).toMatchObject({ status: 'ok', pending: false })
})
+
+ it('with storage behind the mirror (a save it refused), the mirror\'s change is merged with the server copy, not pushed over it', async () => {
+ const mirror = { ...clone(SERVER_STATE), _ts: 5000, workouts: [workout('w1', '2026-09-10'), workout('w2', '2026-09-20')] }
+ delete mirror._rev
+ pairedPhone({ 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()
+
+ expect(ids(srv.doc.workouts)).toEqual(['w1', 'w-web', 'w2'])
+ expect(srv.puts.at(-1).baseRev).toBe(6)
+ })
+})
+
+/* The mirror is only ever the copy of the account the phone is paired with, as it last stood.
+ Whatever replaces the copy wholesale — another account paired, the server's copy adopted —
+ used to reach the file only 800 ms later, and an adopted copy keeps the server's older `_ts`:
+ a start in between found the file "newer", took the copy it held, and pushed it over the
+ server's with a baseRev that matched. Here the app is killed straight after each of those, or
+ the file cannot be written at all, and the next cold start puts nothing back. */
+describe('the file mirror never brings back a copy that is not this account\'s latest', () => {
+ const BEA = { id: 'u2', name: 'bea' }
+ // Bea's account on the same server: her own document, and the pairing code that is hers.
+ const beaServer = () => {
+ const srv = serverWith({ _ts: 500, _rev: 3, unit: 'kg', workouts: [workout('b1', '2026-09-01')], routines: [], bodyweight: [] })
+ h.server = (path, method, init) => (path === '/api/me' || path === '/api/pair/redeem' ? json(200, { token: 'T2', user: BEA }) : srv.handle(path, method, init))
+ return srv
+ }
+ // Andi logs a workout on the paired phone; it reaches his server and the file.
+ const andiLogged = async () => {
+ pairedPhone()
+ serverWith(SERVER_STATE)
+ const useStore = await freshStore()
+ await useStore.getState().boot()
+ useStore.getState().update(s => { s.workouts.push(workout('a-secret', '2026-09-21')) })
+ await useStore.getState().pushState()
+ await sleep(900)
+ expect(ids(readFile('opengym-state.json').workouts)).toEqual(['w1', 'a-secret'])
+ return useStore
+ }
+
+ it('another account paired, then the app killed at once: the next start keeps her copy, and nothing of his reaches her account', async () => {
+ let useStore = await andiLogged()
+ const bea = beaServer()
+ await useStore.getState().connectToServer('gym.example.com', 'ABCD2345', vi.fn(async () => false))
+ expect(ids(useStore.getState().S.workouts)).toEqual(['b1'])
+
+ useStore = await freshStore()
+ await useStore.getState().boot()
+ expect(ids(useStore.getState().S.workouts)).toEqual(['b1'])
+ expect(ids(bea.doc.workouts)).toEqual(['b1'])
+ expect(bea.puts).toHaveLength(0)
+ })
+
+ it('another account paired while the file cannot be written: his copy left in it is never taken for hers', async () => {
+ let useStore = await andiLogged()
+ const bea = beaServer()
+ h.refuse.add('opengym-state.json')
+ await useStore.getState().connectToServer('gym.example.com', 'ABCD2345', vi.fn(async () => false))
+ await sleep(900)
+ expect(ids(readFile('opengym-state.json').workouts)).toEqual(['w1', 'a-secret'])
+
+ useStore = await freshStore()
+ await useStore.getState().boot()
+ expect(ids(useStore.getState().S.workouts)).toEqual(['b1'])
+ expect(ids(bea.doc.workouts)).toEqual(['b1'])
+ expect(bea.puts).toHaveLength(0)
+ })
+
+ it('a phone that kept its own workouts out of the account does not push them in on the next start', async () => {
+ h.files.clear()
+ localStorage.clear()
+ const local = { ...clone(DEF), _ts: Date.now(), workouts: [workout('mine', '2026-09-20')] }
+ 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))
+ let 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).toHaveBeenCalled()
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1'])
+
+ useStore = await freshStore()
+ await useStore.getState().boot()
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1'])
+ expect(ids(srv.doc.workouts)).toEqual(['w1'])
+ expect(srv.puts).toHaveLength(0)
+ })
+
+ // The phone's clock runs ahead: its copy says 3000, while the newer revision the server holds
+ // was written by a device whose clock says 2000. The pull adopts that revision as it is.
+ const clockAhead = () => {
+ const mine = { ...clone(DEF), ...clone(SERVER_STATE), _ts: 3000 }
+ delete mine._rev
+ pairedPhone({ mirror: mine })
+ localStorage.setItem('gym_state_v1', JSON.stringify(mine))
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 5, ts: 3000 }))
+ return serverWith({ ...SERVER_STATE, _ts: 2000, _rev: 6, workouts: [...SERVER_STATE.workouts, workout('w-other', '2026-09-19')] })
+ }
+
+ it('a copy adopted from the server with an older clock stays adopted after a kill straight after', async () => {
+ const srv = clockAhead()
+ let useStore = await freshStore()
+ await useStore.getState().boot()
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-other'])
+
+ useStore = await freshStore()
+ await useStore.getState().boot()
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-other'])
+ expect(ids(srv.doc.workouts)).toEqual(['w1', 'w-other'])
+ expect(srv.puts).toHaveLength(0)
+ })
+
+ it('with the file not writable at all, the copy before the adopt is merged at most — never pushed over the other device\'s work', async () => {
+ const srv = clockAhead()
+ h.refuse.add('opengym-state.json')
+ h.refuse.add('opengym-state-owner.json')
+ let useStore = await freshStore()
+ await useStore.getState().boot()
+
+ useStore = await freshStore()
+ await useStore.getState().boot()
+ expect(ids(srv.doc.workouts)).toEqual(['w1', 'w-other'])
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-other'])
+ })
})
describe('a token the server renews', () => {