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: a second tab never carries one owner's copy into another's
Duarte Santos17e10b85cd5a
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 537910acf..b8ac68806 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -36,6 +36,9 @@ const KEY = 'gym_state_v1'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'+// Whose copy that write was: the owner (gym_owner) the writing tab held, '' for a guest's. A tab+// joins only a copy written under the owner it holds itself (joinSaved, syncFromSaved).+const WID_OWNER_KEY = 'gym_state_owner'const DIRTY_KEY = 'gym_dirty' // the saved copy owes the server a change// An owed copy an older app (v1.3.9) left behind: its first sync stamps what it changed// (lib/sync-legacy.js), holding the fingerprint that app last agreed on with the server.@@ -301,6 +304,11 @@ export const useStore = create((set, get) => {// 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 } })()+ // Another tab signed in or out under this one (the gym_owner storage event below): what this+ // tab holds is no copy of the new owner's, so it writes nothing until it has taken that owner's+ // saved copy as it is (takeSaved).+ let handedOver = false+ const staleUid = 'device-tab-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6)// A copy that owes the server a change and was never written with a write id was last saved by// an app from before this one (v1.3.9), which stamped none of its settings, plan days or notes.// Noted now, before this app's first save writes a write id beside it.@@ -479,6 +487,17 @@ export const useStore = create((set, get) => {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 } }+ // The owner the saved copy was written under; null for a copy saved before this was recorded.+ const readWidOwner = () => { try { return localStorage.getItem(WID_OWNER_KEY) } catch { return null } }+ // The saved copy is the one this tab may join: written under the owner this tab holds. QA+ // 2026-10-06: a sign-out (or another account signing in) wrote its wiped copy while the owner+ // key still named the previous account, a second tab joined its whole in-memory copy into it,+ // and the next guest, or the next profile created there, got the previous account's history.+ const savedIsMine = () => {+ if (readOwner() !== seenOwner) return false+ const tag = readWidOwner()+ return tag === null || tag === (seenOwner || '')+ }const readSaved = () => {try { const raw = localStorage.getItem(KEY); return raw ? Object.assign(clone(DEF), JSON.parse(raw)) : null } catch { return null }}@@ -491,7 +510,7 @@ export const useStore = create((set, get) => {// `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+ if (readWid() === seenWid || !savedIsMine()) return nullconst theirs = readSaved()if (!theirs) return nullconst touched = JSON.stringify(prev?.active ?? null) !== JSON.stringify(S?.active ?? null)@@ -499,7 +518,21 @@ export const useStore = create((set, get) => {return sameCopy(merged, S) ? null : merged}+ // A tab whose owner changed under it (another tab signed in or out) does not write: its copy is+ // not the new owner's, and written, it went into that owner's copy, settings and all, and on to+ // the server (QA 2026-10-06). Once the new owner's copy is saved it takes that copy as it is.+ // What it was asked to save was made on the empty copy it holds meanwhile, never on the previous+ // owner's: that small change is kept aside, as "Keep profile as is" keeps a device's copy.+ const refuseStale = S => {+ if (!handedOver) return false+ takeSaved()+ clearTimeout(pushTm)+ pushTm = null+ if (hasData(S)) keepAside(S, t('This device, before signing in'), staleUid).catch(() => {})+ return true+ }const persist = (S, push = true, stamp = true) => {+ if (refuseStale(S)) returnconst { base, owed } = metaOf() // the copy being replaced; the new one stands where it stoodconst joined = joinSaved(S, get()?.S)if (joined) S = joined@@ -520,6 +553,7 @@ 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))+ localStorage.setItem(WID_OWNER_KEY, seenOwner || '')const wid = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)localStorage.setItem(WID_KEY, wid)seenWid = wid@@ -719,23 +753,28 @@ export const useStore = create((set, get) => {window.addEventListener('pagehide', flush) // Safari kills the home-screen app without a visibilitychange at times// The owner check in setUser only runs in the tab that signs in. Another tab of the same- // browser still holding the previous profile would keep writing that profile's data over the- // shared copy and push it under the new session's cookie — so it drops the profile, and- // whoever signs in there passes the same check. The owner key is written last on both a- // sign-in and a sign-out, so on a new owner the copy in storage is already the wiped one; with- // no owner (a sign-out) this tab falls back to defaults rather than read the key at all — the- // previous profile's data must not stay here whichever key's event lands first.+ // browser still holding the previous profile, or a guest's copy, would keep writing it over the+ // shared copy and push it under the new session's cookie, or join it into the new owner's copy+ // the moment that one is saved (QA 2026-10-06: a guest tab left open put its workout, routine+ // and default settings into the account after "Keep profile as is"). So any tab whose owner+ // changes under it drops what it holds, signed in or not, and takes the new owner's copy as it+ // is once that is saved (takeSaved); until then it writes nothing (refuseStale). Whoever signs in+ // there passes the same check. The owner key goes first on both a sign-in and a sign-out, so+ // this runs before the new owner's copy reaches this tab.window.addEventListener('storage', e => {if (e.key !== 'gym_owner') return- const user = get().user- if (!user || e.newValue === user.id) return+ const owner = readOwner()+ if (owner === seenOwner) returnclearTimeout(pushTm)pushTm = null- const S = e.newValue ? loadState() : freshState()- meta.set(S, e.newValue ? { base: readStoredSync(), owed: storedOwed() } : { base: null, owed: false })+ const S = restartedState(get().S)+ meta.set(S, { base: null, owed: false })seenWid = readWid()- seenOwner = readOwner()- set({ user: null, S })+ seenOwner = owner+ handedOver = true+ const user = get().user+ set({ ...(user && user.id !== owner ? { user: null } : {}), S })+ takeSaved()})// 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@@ -757,9 +796,28 @@ export const useStore = create((set, get) => {// 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.+ // A tab the owner changed under takes the new owner's saved copy as it is, with where it stands+ // with the server: it has no changes of its own to join, only the previous owner's copy, or a+ // guest's, which must not go into it.+ const takeSaved = () => {+ if (!handedOver) return false+ // Only a copy known to be written under the new owner: one saved before the owner was+ // recorded beside it is most likely the guest's copy the sign-in is still asking about.+ if (readOwner() !== seenOwner || readWidOwner() !== (seenOwner || '')) return false+ const theirs = readSaved()+ if (!theirs) return false+ const S = sanitizeAccent(theirs)+ seenWid = readWid()+ handedOver = false+ meta.set(S, { base: readStoredSync(), owed: storedOwed() })+ registerCustom(S.customEx)+ set({ S })+ return true+ }const syncFromSaved = () => {+ if (handedOver) { takeSaved(); return }const wid = readWid()- if (wid === seenWid || readOwner() !== seenOwner) return+ if (wid === seenWid || !savedIsMine()) returnconst theirs = readSaved()if (!theirs) returnconst mine = get().S@@ -802,7 +860,8 @@ export const useStore = create((set, get) => {}// 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.+ // goes before the wiped copy is written: another tab must learn that the copy is nobody's before+ // it sees the new copy, or it joins its own copy of the account into it (QA 2026-10-06).const clearLocalSession = () => {const hadMedia = referencedHashes(get().S).size > 0get().setUser(null)@@ -810,11 +869,12 @@ export const useStore = create((set, get) => {forgetSync()releaseAdopt() // the copy it was about is gonelocalStorage.removeItem(KEY)- // Signed out, this device is nobody's: the sign-in screen is in the instance's language.- persist(freshState(), false)localStorage.removeItem('gym_owner_name')localStorage.removeItem('gym_owner')seenOwner = null // a guest's tab now: it joins what other signed-out tabs save (as setUser)+ handedOver = false+ // Signed out, this device is nobody's: the sign-in screen is in the instance's language.+ persist(freshState(), false)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@@ -979,11 +1039,11 @@ export const useStore = create((set, get) => {// "Keep profile as is": what this device held before the sign-in leaves the screen, but not the// device. It is kept aside like a kept change (its own key, never added back on its own) and can// be saved as a backup file from Settings, in case the answer was the wrong one.- const keepAside = async (S, name) => {+ const keepAside = async (S, name, keepUid) => {if (!hasData(S)) returnconst state = clone(S)const all = await readStashes()- const uid = 'device-' + Date.now().toString(36)+ const uid = keepUid || 'device-' + Date.now().toString(36)all[stashKey(serverBase(), uid)] = { server: serverBase() || null, uid, name, at: Date.now(), state }await writeStashes(all)set({ keptRev: get().keptRev + 1 })@@ -1149,6 +1209,7 @@ export const useStore = create((set, get) => {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)) returntry { if (!owner) localStorage.setItem('gym_owner', who) } catch { /* setUser writes it again */ }+ seenOwner = readOwner()persist(sanitizeAccent(Object.assign(clone(DEF), saved)), false, false)dropSync()markOwed(true)@@ -1400,6 +1461,11 @@ export const useStore = create((set, get) => {keepForPrevious(owner)forgetSync()localStorage.removeItem(KEY)+ // The new owner before the new copy, as on a sign-out: another tab still holding the+ // previous account's copy must not join it into this one (QA 2026-10-06).+ localStorage.setItem('gym_owner_name', u.name || '')+ localStorage.setItem('gym_owner', u.id)+ seenOwner = u.idpersist(restartedState(get().S), false)setSync({ pending: false, lastSynced: 0, lastError: null })}@@ -1412,6 +1478,7 @@ export const useStore = create((set, get) => {// sign-in saves under the new owner, and a tab still comparing against the old one took// no part until it had saved itself, then wrote its copy over theirs (joinSaved).seenOwner = u.id+ handedOver = falselocalStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest')logoutOwed(false) // this sign-in's cookie replaced the one a failed sign-out left behind// The file follows at once, as the new account's: until then it holds the previous one's.diff --git a/frontend/src/store/useStore.restore.test.jsx b/frontend/src/store/useStore.restore.test.jsxindex 1748e65e1..74b0ec755 100644--- a/frontend/src/store/useStore.restore.test.jsx+++ b/frontend/src/store/useStore.restore.test.jsx@@ -225,10 +225,12 @@ describe('signing in as a different profile', () => {useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')], active }, true) // arms a pushapi.mockResolvedValue({})- // B's setUser in the other tab: it wiped the copy, wrote defaults, then recorded the owner.- // B's own data only lands there after its pull — this tab never re-reads it.- localStorage.setItem('gym_state_v1', JSON.stringify({ ...clone(DEF), _ts: 30 }))+ // B's setUser in the other tab: it wiped the copy, recorded the owner, then wrote defaults+ // under B. B's own data only lands there after its pull.+ localStorage.removeItem('gym_state_v1')localStorage.setItem('gym_owner', 'B')+ localStorage.setItem('gym_state_v1', JSON.stringify({ ...clone(DEF), _ts: 30 }))+ localStorage.setItem('gym_state_owner', 'B')window.dispatchEvent(new StorageEvent('storage', { key: 'gym_owner', oldValue: 'A', newValue: 'B' }))expect(useStore.getState().user).toBeNull()@@ -267,9 +269,10 @@ describe('signing in as a different profile', () => {expect(hasData(useStore.getState().S)).toBe(false)})- // The listener above reacts to the owner key alone, so the wiped copy has to be in storage- // before the owner is removed — the same order setUser uses when it records a new owner.- it('signing out removes the owner only after the wiped copy is written', async () => {+ // The previous copy leaves storage first, then the owner, and only then is the wiped copy+ // written: a tab that sees the wiped copy already knows it is nobody's, and does not join the+ // account's copy it holds into it (QA 2026-10-06; the old order, owner last, leaked it).+ it('signing out removes the old copy, then the owner, then writes the wiped copy', async () => {useStore.getState().setUser({ id: 'A', name: 'A' })useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')] })api.mockResolvedValue({})@@ -290,9 +293,10 @@ describe('signing in as a different profile', () => {expect(globalThis.localStorage).toBe(real)expect(writes).toContain('removeItem gym_owner')- expect(writes.lastIndexOf('removeItem gym_owner')).toBeGreaterThan(writes.lastIndexOf('setItem gym_state_v1'))+ expect(writes.lastIndexOf('removeItem gym_owner')).toBeLessThan(writes.lastIndexOf('setItem gym_state_v1'))expect(writes.lastIndexOf('removeItem gym_owner')).toBeGreaterThan(writes.lastIndexOf('removeItem gym_state_v1'))expect(localStorage.getItem('gym_owner')).toBeNull()+ expect(localStorage.getItem('gym_state_owner')).toBe('')expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines).toEqual([])})diff --git a/frontend/src/store/useStore.tabs-owner.test.jsx b/frontend/src/store/useStore.tabs-owner.test.jsxnew file mode 100644index 000000000..bc332b8c8--- /dev/null+++ b/frontend/src/store/useStore.tabs-owner.test.jsx@@ -0,0 +1,211 @@+// @vitest-environment happy-dom++/* A second tab of the same browser while the owner of the copy changes in the first (QA round 2,+ 2026-10-06). The sign-out wrote its wiped copy while the owner key still named the account, so+ the idle tab joined its whole copy of the account into it: the next guest saw it, and the next+ profile created there uploaded it. A device-link sign-in to another account did the same. And a+ guest tab left open put its workout, routine and default settings into the account after "Keep+ profile as is". Each "tab" is a fresh import of the store sharing one localStorage; the browser's+ storage events are replayed in the order the writes happened, as the browser delivers them. */+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 routine = id => ({ id, name: id, exercises: [] })+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 saved = () => JSON.parse(localStorage.getItem('gym_state_v1') || 'null')++let DEF+let OWNER = 'o0'++/* The browser's storage events, per tab. Each tab's 'storage' listeners are kept apart (openTab),+ and every write is told to every other tab at once, while the writer goes on: the other tab sees+ storage as it is at that write, which is when the browser's event reaches a quick tab. A tab in+ the middle of its own action (act) or handler hears of writes once it is done. */+let tabs = []+let writer = null+const realSet = Storage.prototype.setItem+const realRemove = Storage.prototype.removeItem+const pump = () => {+ for (let again = true; again;) {+ again = false+ for (const t of tabs) {+ if (t.busy || !t.inbox.length) continue+ const ev = t.inbox.shift()+ const prev = writer+ writer = t; t.busy+++ try { for (const l of t.ls) l(new StorageEvent('storage', ev)) } finally { t.busy--; writer = prev }+ again = true+ }+ }+}+const emit = (key, newValue) => {+ for (const t of tabs) if (t !== writer) t.inbox.push({ key, newValue })+ pump()+}+beforeEach(() => {+ Storage.prototype.setItem = function (k, v) { realSet.call(this, k, v); emit(k, String(v)) }+ Storage.prototype.removeItem = function (k) { realRemove.call(this, k); emit(k, null) }+})+afterEach(() => {+ Storage.prototype.setItem = realSet+ Storage.prototype.removeItem = realRemove+})+// `fn` run as tab `t`: its writes are the ones the others hear of.+async function act(t, fn) {+ const tab = tabs.find(x => x.store === t)+ tab.busy++; writer = tab+ try { return await fn() } finally { tab.busy--; writer = null; pump() }+}++async function openTab(user) {+ vi.resetModules()+ const tab = { store: null, ls: [], inbox: [], busy: 0 }+ const add = window.addEventListener+ window.addEventListener = function (type, l, o) { if (type === 'storage') tab.ls.push(l); else add.call(this, type, l, o) }+ try {+ const m = await import('./useStore.js')+ DEF = m.DEF+ tab.store = m.useStore+ } finally { window.addEventListener = add }+ tabs.push(tab)+ tab.store.setState({ user: user ?? null, ready: true })+ return tab.store+}++function server(doc) {+ const s = { doc: doc ? clone(doc) : null }+ h.api = async (path, opts = {}) => {+ const method = opts.method || 'GET'+ const body = opts.body ? JSON.parse(opts.body) : undefined+ 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 account = () => ({+ ...clone(DEF), _ts: 100, restSec: 120, accent: 'sky',+ workouts: [w('x1'), w('x2', '2026-09-02'), w('x3', '2026-09-03')],+ routines: [routine('xr')], bodyweight: [{ d: '2026-09-01', w: 80, t: 1 }],+})+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 = 'o' + (Number(OWNER.slice(1)) + 1)+ DEF = (await import('./useStore.js')).DEF+})+afterEach(() => {+ for (const t of tabs) t.store.setState({ user: null, ready: false })+ tabs = []+ localStorage.clear()+})++describe('a second tab while the first one changes owner', () => {+ it('sign-out with a second tab open leaves nothing of the account in the browser', async () => {+ DEF = (await import('./useStore.js')).DEF+ const srv = server({ ...account(), _rev: 1 })+ localStorage.setItem('gym_owner', OWNER)+ savedCopy(srv.doc, 1)+ const A = await openTab({ id: OWNER, name: 'Xavi' })+ const B = await openTab({ id: OWNER, name: 'Xavi' })+ expect(ids(B.getState().S)).toEqual(['x1', 'x2', 'x3'])++ const r = await act(A, () => A.getState().signOut())+ expect(r.owed).toBe(false)++ expect(ids(saved())).toEqual([])+ expect(saved().routines).toEqual([])+ expect(saved().bodyweight).toEqual([])+ expect(ids(B.getState().S)).toEqual([])+ expect(B.getState().user).toBeNull()+ // The next guest here, in either tab or a new one, starts empty.+ const G = await openTab(null)+ expect(ids(G.getState().S)).toEqual([])+ await act(B, () => B.getState().update(s => { s.restSec = 45 }))+ expect(ids(saved())).toEqual([])+ expect(saved().routines).toEqual([])+ })++ it('a device-link sign-in to another account with a second tab open copies nothing of the old account', async () => {+ DEF = (await import('./useStore.js')).DEF+ const srv = server({ ...account(), _rev: 1 })+ localStorage.setItem('gym_owner', OWNER)+ savedCopy(srv.doc, 1)+ const A = await openTab({ id: OWNER, name: 'Xavi' })+ const B = await openTab({ id: OWNER, name: 'Xavi' })+ const yan = { ...clone(DEF), _ts: 50, workouts: [w('yW1', '2026-09-05')], _rev: 4 }+ srv.doc = yan // the server now answers as Yan's account++ await act(A, () => A.getState().setUser({ id: 'Y-' + OWNER, name: 'Yan' }, { adopt: true }))+ // The question counts nothing of Xavi's as this device's own work.+ const pre = JSON.parse(localStorage.getItem('gym_adopt')).pre+ expect(pre.workouts || []).toEqual([])+ expect(pre.routines || []).toEqual([])+ expect(ids(saved())).toEqual([])+ expect(ids(B.getState().S)).toEqual([])++ await act(A, () => A.getState().adoptProfile(async () => false)) // "Keep profile as is"+ expect(ids(srv.doc)).toEqual(['yW1'])+ expect(srv.doc.routines || []).toEqual([])+ expect(ids(saved())).toEqual(['yW1'])+ await act(B, () => B.getState().update(s => { s.bodyweight = [...(s.bodyweight || []), { d: '2026-09-06', w: 70, t: Date.now() }] }))+ await act(A, () => A.getState().pushState())+ expect(ids(srv.doc)).toEqual(['yW1'])+ expect(srv.doc.routines || []).toEqual([])+ expect((srv.doc.bodyweight || []).some(e => e.w === 80)).toBe(false)+ })++ it('a guest tab left open after "Keep profile as is" puts none of the guest copy into the account', async () => {+ DEF = (await import('./useStore.js')).DEF+ const srv = server({ ...account(), _rev: 3 })+ localStorage.setItem('gym_state_v1', JSON.stringify({+ ...clone(DEF), _ts: Date.now(), restSec: 90, accent: 'lime',+ workouts: [w('gW1', '2026-09-04')], routines: [routine('Guest Routine')],+ }))+ const A = await openTab(null)+ const B = await openTab(null)++ await act(A, () => A.getState().setUser({ id: OWNER, name: 'Xavi' }, { adopt: true }))+ // B, a guest until now, holds nothing while the question is open and writes nothing.+ expect(ids(B.getState().S)).toEqual([])+ await act(B, () => B.getState().update(s => { s.bodyweight = [{ d: '2026-09-06', w: 60, t: Date.now() }] }))+ expect(ids(saved())).toEqual(['gW1']) // still the guest copy the question is about++ await act(A, () => A.getState().adoptProfile(async () => false)) // "Keep profile as is"+ expect(ids(srv.doc)).toEqual(['x1', 'x2', 'x3'])+ // B now holds the account's copy as it is, and its next change joins the account normally.+ expect(ids(B.getState().S)).toEqual(['x1', 'x2', 'x3'])+ expect(B.getState().S.restSec).toBe(120)+ await act(B, () => B.getState().update(s => { s.bodyweight = [...(s.bodyweight || []), { d: '2026-09-07', w: 81, t: Date.now() }] }))+ A.setState({ ready: true })+ await act(A, () => A.getState().pushState())+ expect(ids(srv.doc)).toEqual(['x1', 'x2', 'x3'])+ expect((srv.doc.routines || []).map(r => r.id)).toEqual(['xr'])+ expect(srv.doc.restSec).toBe(120)+ expect(srv.doc.accent).toBe('sky')+ expect(srv.doc.bodyweight.map(e => e.w).sort()).toEqual([80, 81])+ // The weigh-in B logged in the moment it held no copy is kept aside, not lost.+ const stash = JSON.parse(localStorage.getItem('gym_stash') || '{}')+ expect(Object.values(stash).some(e => (e.state.bodyweight || []).some(b => b.w === 60))).toBe(true)+ })+})