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.

Sync: another account signing in on a copy that still owes the first keeps those changes aside for it instead of wiping them

Duarte Santos39ffe00ff9ef
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index fe7eb3e12..e325981e5 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -132,6 +132,7 @@ export const useStore = create((set, get) => {
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)
+ let keeping = null // phone: the file write of what keepForPrevious set aside, until it lands
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 } }
@@ -494,6 +495,26 @@ export const useStore = create((set, get) => {
}
return ok || empty
}
+ // A different account signing in on a copy that still owes its own: the copy goes, as it always
+ // has — it must not be pushed into the new account — but what it owed is kept aside first, the
+ // way a forced sign-out keeps it, for when that account comes back. Written to localStorage
+ // right here, since setUser wipes the copy straight after; on a phone the file follows, and
+ // pairing waits for it (`keeping`) before it goes on.
+ const keepForPrevious = uid => {
+ const S = get().S
+ if (!owes() || !hasData(S)) return
+ const server = serverBase()
+ const key = stashKey(server, uid)
+ let all = {}
+ try { all = JSON.parse(localStorage.getItem(STASH_KEY)) || {} } catch { /* none */ }
+ const prev = all[key]?.state
+ const state = prev ? mergeStates(S, prev) : clone(S)
+ state.active = S.active || prev?.active || null
+ const entry = { server: server || null, uid, name: get().user?.id === uid ? get().user.name || '' : '', at: Date.now(), state }
+ all[key] = entry
+ try { localStorage.setItem(STASH_KEY, JSON.stringify(all)) } catch { /* full — the file may still take it */ }
+ if (MOBILE) keeping = readStashes().then(f => writeStashes({ ...f, [key]: entry })).catch(() => {})
+ }
const stashOwed = async () => {
const user = get().user
if (!user) return true
@@ -615,12 +636,14 @@ export const useStore = create((set, get) => {
// The local copy belongs to whoever last signed in here. When a session expires or is
// 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
+ // carry the in-progress workout along) — what it still owed its own account is kept aside
+ // for that account first (keepForPrevious). A proper sign-out clears the owner, so a guest's
// 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.id
if (owner && owner !== u.id) {
+ keepForPrevious(owner)
forgetSync()
localStorage.removeItem(KEY)
persist(clone(DEF), false)
@@ -818,9 +841,12 @@ export const useStore = create((set, get) => {
// 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
+ // The account first, the address after: a copy another account still owed is kept aside
+ // for it under the server it belongs to, not the one being paired.
+ get().setUser(user)
+ if (keeping) { await keeping; keeping = null }
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)
diff --git a/frontend/src/store/useStore.mobile-remote.test.jsx b/frontend/src/store/useStore.mobile-remote.test.jsx
index b5bb60dc9..0281ed19e 100644
--- a/frontend/src/store/useStore.mobile-remote.test.jsx
+++ b/frontend/src/store/useStore.mobile-remote.test.jsx
@@ -341,6 +341,42 @@ describe('Disconnect anyway keeps the owed changes for the next pairing', () =>
})
})
+describe('another account paired on a phone that still owes the first', () => {
+ it('keeps the first account\'s changes aside under its own server, and gives them back when it pairs again', 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()
+
+ const srv = serverWith(SERVER_STATE)
+ const OTHER = 'https://other.example.com'
+ const bea = { id: 'u2', name: 'bea' }
+ h.server = (path, method, init) => (path === '/api/pair/redeem' ? json(200, { token: 'T2', user: bea }) : srv.handle(path, method, init))
+ const prevFetch = globalThis.fetch
+ globalThis.fetch = window.fetch = vi.fn(async (url, init = {}) => {
+ h.calls.push({ url: String(url), method: (init.method || 'GET').toUpperCase(), auth: init.headers?.Authorization || null })
+ return String(url).startsWith(OTHER) ? h.server(String(url).slice(OTHER.length), (init.method || 'GET').toUpperCase(), init) : prevFetch(url, init)
+ })
+ await useStore.getState().connectToServer('other.example.com', 'ABCD2345', vi.fn(async () => false))
+
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1']) // bea's copy is her server's
+ expect(ids(srv.doc.workouts)).toEqual(['w1']) // and nothing of andi's went there
+ const stash = readFile('opengym-stash.json')
+ expect(Object.keys(stash)).toEqual([BASE + '|u1']) // keyed by andi's server, not bea's
+ expect(ids(stash[BASE + '|u1'].state.workouts)).toEqual(['w1', 'w2'])
+ expect(stash[BASE + '|u1'].name).toBe('andi')
+
+ installFetch()
+ const home = serverWith(SERVER_STATE)
+ await useStore.getState().connectToServer('gym.example.com', 'ABCD2345', vi.fn(async () => false))
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w2'])
+ expect(ids(home.doc.workouts)).toEqual(['w1', 'w2'])
+ expect(readFile('opengym-stash.json')).toEqual({})
+ })
+})
+
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')] }
diff --git a/frontend/src/store/useStore.sync-status.test.jsx b/frontend/src/store/useStore.sync-status.test.jsx
index 8c4ec7cf9..2b8167662 100644
--- a/frontend/src/store/useStore.sync-status.test.jsx
+++ b/frontend/src/store/useStore.sync-status.test.jsx
@@ -288,3 +288,40 @@ describe('signing in again to the account this copy belongs to', () => {
expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-phone'])
})
})
+
+describe('another account signing in on a copy that still owes the first', () => {
+ const twosServer = async (path, o) => (o?.method === 'PUT' ? { ok: true, rev: 5 } : { state: { ...clone(DEF), _ts: 50, workouts: [workout('b1')], _rev: 4 }, rev: 4 })
+
+ it('keeps what the first account was owed aside for it — nothing of it goes into the new account — and gives it back when that account returns', async () => {
+ signedIn({ ...clone(DEF), _ts: 300, workouts: [workout('w1'), workout('w-week', '2026-09-18')] })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))
+ localStorage.setItem('gym_dirty', '1')
+
+ api.mockImplementation(twosServer)
+ useStore.getState().setUser({ id: 'user-2', name: 'Two' })
+ await useStore.getState().adoptProfile(async () => false)
+
+ expect(ids(useStore.getState().S.workouts)).toEqual(['b1'])
+ expect(puts()).toHaveLength(0)
+ expect(await useStore.getState().keptChanges()).toEqual([{ server: location.origin, uid: USER.id, name: 'One', at: expect.any(Number) }])
+ expect(await useStore.getState().signOut()).toEqual({ owed: false })
+
+ api.mockReset()
+ api.mockImplementation(async (path, o) => (o?.method === 'PUT' ? { ok: true, rev: 3 } : { state: { ...clone(DEF), _ts: 200, workouts: [workout('w1')], _rev: 2 }, rev: 2 }))
+ useStore.getState().setUser(USER)
+ await useStore.getState().adoptProfile(async () => false)
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w-week'])
+ expect(ids(puts().at(-1).state.workouts)).toEqual(['w1', 'w-week'])
+ expect(await useStore.getState().keptChanges()).toEqual([])
+ })
+
+ it('a copy that owes nothing is replaced as before, with nothing kept', async () => {
+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))
+ api.mockImplementation(twosServer)
+ useStore.getState().setUser({ id: 'user-2', name: 'Two' })
+ await useStore.getState().adoptProfile(async () => false)
+ expect(ids(useStore.getState().S.workouts)).toEqual(['b1'])
+ expect(await useStore.getState().keptChanges()).toEqual([])
+ })
+})