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
Pairing and signing in no longer overwrite the profile while their question is open; a unit conversion, a reset and a backup import hold across devices
Duarte Santos771184c988d9
diff --git a/frontend/src/components/Passkeys.jsx b/frontend/src/components/Passkeys.jsxindex cf110620a..9e868d162 100644--- a/frontend/src/components/Passkeys.jsx+++ b/frontend/src/components/Passkeys.jsx@@ -294,7 +294,9 @@ export function DeviceLinkRedeemSheet({ close }) {const st = useStore.getState()useStore.setState({ linkCode: null })const same = st.user?.id === r.user.id- st.setUser(r.user)+ // Another profile: its question decides what becomes of this copy, and nothing syncs+ // before it is answered (adoptProfile).+ st.setUser(r.user, same ? undefined : { adopt: { alwaysAsk: true } })close()if (same) { toast(t('Passkey added')); return }// Signed in by now whatever happens next: a pull that fails is the sync banner's to saydiff --git a/frontend/src/components/Passkeys.test.jsx b/frontend/src/components/Passkeys.test.jsxindex c63644138..d1f387f3b 100644--- a/frontend/src/components/Passkeys.test.jsx+++ b/frontend/src/components/Passkeys.test.jsx@@ -396,7 +396,7 @@ describe('the other device: redeeming a code', () => {expect(mocks.createPasskey).toHaveBeenCalledWith({ challenge: 'xyz' })expect(mocks.calls.at(-1).path).toBe('/api/device-link/verify')expect(mocks.calls.at(-1).body).toMatchObject({ code: 'K7WQ-2MZP-4HXA', cid: 'link-cid', credential: { id: 'new-key' } })- expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u1', name: 'Ana', admin: false })+ expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u1', name: 'Ana', admin: false }, { adopt: { alwaysAsk: true } })// What this device logged goes into that profile only when asked, even into an empty one.expect(mocks.adoptProfile).toHaveBeenCalledWith(mocks.askAddDeviceData, { alwaysAsk: true })expect(mocks.store.linkCode).toBeNull()diff --git a/frontend/src/components/PasswordAuth.jsx b/frontend/src/components/PasswordAuth.jsxindex 2932e85bc..b0e75892b 100644--- a/frontend/src/components/PasswordAuth.jsx+++ b/frontend/src/components/PasswordAuth.jsx@@ -73,7 +73,7 @@ const dismissed = e => e?.name === 'NotAllowedError' || e?.name === 'AbortError'// merges what this device kept for it (adoptProfile).async function signedIn(u, close) {const st = useStore.getState()- st.setUser(u)+ st.setUser(u, { adopt: true })close()await st.adoptProfile(askAddDeviceData)toast(t('Welcome back, {0}', u.name))diff --git a/frontend/src/components/PasswordAuth.test.jsx b/frontend/src/components/PasswordAuth.test.jsxindex 11c49fd87..1e7428229 100644--- a/frontend/src/components/PasswordAuth.test.jsx+++ b/frontend/src/components/PasswordAuth.test.jsx@@ -119,7 +119,7 @@ describe('PasswordSignInSheet', () => {type(name, ' Ana '); type(pw, 'correct horse battery')await submit(host)expect(mocks.passwordLogin).toHaveBeenCalledWith('Ana', 'correct horse battery')- expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u1', name: 'Ana' })+ expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u1', name: 'Ana' }, { adopt: true }) // nothing syncs until the question is answeredexpect(close).toHaveBeenCalled()expect(mocks.adoptProfile).toHaveBeenCalled()expect(mocks.toast).toHaveBeenCalledWith('Welcome back, Ana')@@ -176,7 +176,7 @@ describe('PasswordSignInSheet', () => {type(field, ' [email protected] '); type(byPlaceholder(host, 'Password'), 'correct horse battery')await submit(host)expect(mocks.passwordLogin).toHaveBeenCalledWith('[email protected]', 'correct horse battery')- expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u1', name: 'Ana' })+ expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u1', name: 'Ana' }, { adopt: true })})it('a reset code is redeemed with the e-mail too', async () => {diff --git a/frontend/src/components/ServerSync.jsx b/frontend/src/components/ServerSync.jsxindex d7e7885f4..8a8b75d7f 100644--- a/frontend/src/components/ServerSync.jsx+++ b/frontend/src/components/ServerSync.jsx@@ -129,7 +129,7 @@ export async function passkeySignIn() {const st = useStore.getState()try {const u = await passkeyLogin()- st.setUser(u)+ st.setUser(u, { adopt: true })await st.adoptProfile(askAddDeviceData)toast(t('Welcome back, {0}', u.name))} catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Sign-in failed')) }diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex b3dc90899..ebd2b5f4f 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -65,5 +65,8 @@ describe('Brazilian Portuguese locale', () => {expect(ptBR['Sign-in e-mail']).toBe('E-mail de login')for (const key of ['Name or e-mail', 'Sign in with “{0}” instead of your name', '“{0}” is saved, but signs in only once this profile has a password.', 'Type it at “Sign in with password” instead of your profile name. Nothing is ever sent to it — a forgotten password is still reset by your admin.'])expect(key in PT_BR_OVERRIDES, key).toBe(true)+ // So is the backup import's warning about the server's workouts: pt-PT says cópia and registado.+ for (const key of ['The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.', 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.', 'Replace anyway', 'Merge them in'])+ expect(key in PT_BR_OVERRIDES, key).toBe(true)})})diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 0af4d7d27..646fffd47 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -34,6 +34,24 @@* key is the unit, so the inventory of one unit is kept whole, as last edited* - `_ts`: the later of the two; `_rev` dropped (the server sets it); `active` left to the caller*+ * Two rules come before all of these:+ *+ * - Units. Every weight in a copy is in its `unit`, so two copies in different units are never+ * merged number by number: one is brought into the other's unit first (sameUnit). The unit+ * that stays is the one chosen last — `unitSet.at`, stamped by a unit switch — or, with no+ * stamp to tell, the newer copy's; with `prefer`, the preferred side's. A switch that only+ * changed the label (`unitSet.convert === false`: the numbers were in the new unit all along)+ * relabels the other copy instead of converting it. A copy converted to lb on one device used+ * to meet the other device's kg copy and come back as kg with lb numbers under it.+ * - Reset. "Reset everything" stamps the empty copy with `resetAt`. A copy that has not seen that+ * reset (an older or no `resetAt`) contributes only what was made after it: workouts finished+ * or edited later (`_ts`, else `end`, else `start`), routines and custom exercises edited later+ * (`_ts`), weigh-ins entered later (`t`), stamped settings set later — and the reset copy's+ * settings and plan win whatever the `_ts`. Everything else from before the reset stays+ * deleted (sinceReset). Before, a device with an unsent change got the 409, merged, and its+ * union brought the whole wiped profile back. Not with `prefer`: a sign-in adds what a device+ * logged signed out, which is not a copy of this account's history.+ ** Known limit: with no record of what each side deleted, an entry removed on one device inside* the conflict window comes back from the other. The window is a few seconds now (the store pulls* on resume and every push is conditional), and a resurrected entry beats a lost one. Tombstones@@ -41,6 +59,7 @@*/import { beatsWeight } from './exercises.js'import { bestWeightForEntry } from './history.js'+import { convertStateUnit, convertBodyWeight } from './units.js'const clone = o => JSON.parse(JSON.stringify(o))const list = v => (Array.isArray(v) ? v : [])@@ -168,15 +187,82 @@ export function mergeStampedMap(newer, older, prefer) {return out}+const unitOf = S => (S?.unit === 'lb' ? 'lb' : 'kg')+const unitStamp = S => Number(S?.unitSet?.at) || 0++/**+ * `follow` in the unit of `lead`: converted, or only relabelled when `lead`'s last switch kept the+ * numbers (see the file's header). Returns `follow` itself when the units already agree.+ */+export function inUnitOf(follow, lead) {+ const to = unitOf(lead)+ if (!follow || unitOf(follow) === to) return follow+ if (lead?.unitSet?.convert === false) return { ...follow, unit: to }+ return convertStateUnit({ ...follow, unit: unitOf(follow) }, to)+}++/** When the entries of a copy were made — what sinceReset holds against a reset. */+const workoutTime = w => Number(w?._ts) || Number(w?.end) || Number(w?.start) || 0++/**+ * What a copy that has not seen a reset still contributes after it (see the file's header): only+ * the entries made after `at`. The kept loads are those of the workouts that remain.+ */+export function sinceReset(S, at) {+ const after = v => (Number(v) || 0) > at+ const out = clone(S)+ out.workouts = list(S.workouts).filter(w => w && after(workoutTime(w)))+ out.routines = list(S.routines).filter(r => r && after(r._ts))+ out.customEx = list(S.customEx).filter(c => c && after(c._ts))+ out.bodyweight = list(S.bodyweight).filter(e => e && after(e.t))+ // No time of their own: taken for what they were before the reset, which cleared them.+ out.equipProfiles = []+ out.gymCards = []+ out.favEx = []+ out.exNotes = {}+ out.barWeights = {}+ for (const f of ['balanceOverrides', 'loadKind', 'plates']) {+ out[f] = Object.fromEntries(Object.entries(isMap(S[f]) ? S[f] : {}).filter(([, v]) => after(stampOf(v))))+ }+ const ex = {}+ for (const w of out.workouts) {+ for (const e of list(w.entries)) {+ if (e?.id == null) continue+ const wt = bestWeightForEntry(e)+ if (wt > 0 && (!ex[e.id] || beatsWeight(e.id, wt, ex[e.id].w))) ex[e.id] = { w: wt, d: w.d }+ }+ }+ out.exWeights = ex+ return out+}+// `prefer` names the side whose settings, plan and per-exercise config win regardless of `_ts`:// on sign-in the server's profile is the truth and the device only contributes the entries it// logged while signed out. Without it the newer copy decides, as for a conflict between devices.-export function mergeStates(a, b, { prefer } = {}) {- if (!a) return b ? clone(b) : b- if (!b) return clone(a)- const n = prefer === 'a' ? a : prefer === 'b' ? b : newerOf(a, b)+export function mergeStates(a0, b0, { prefer } = {}) {+ if (!a0) return b0 ? clone(b0) : b0+ if (!b0) return clone(a0)+ let a = a0, b = b0+ // A reset seen by one copy only: the other keeps what was made after it, and the reset copy+ // decides the rest (the file's header).+ let side = prefer === 'a' || prefer === 'b' ? prefer : newerOf(a, b) === a ? 'a' : 'b'+ if (!prefer) {+ const ra = Number(a.resetAt) || 0, rb = Number(b.resetAt) || 0+ if (ra > rb) { b = sinceReset(b, ra); side = 'a' }+ else if (rb > ra) { a = sinceReset(a, rb); side = 'b' }+ }+ // One unit before anything is compared.+ let lead = null+ if (unitOf(a) !== unitOf(b)) {+ lead = prefer || unitStamp(a) === unitStamp(b) ? (side === 'a' ? a : b) : unitStamp(a) > unitStamp(b) ? a : b+ if (lead === a) b = inUnitOf(b, a); else a = inUnitOf(a, b)+ }+ const n = side === 'a' ? a : bconst o = n === a ? b : aconst out = clone(n)+ // The unit is the lead's by now; so is the record of choosing it.+ const unitBy = lead || (unitStamp(a) >= unitStamp(b) ? a : b)+ if (unitBy.unitSet) out.unitSet = clone(unitBy.unitSet)out.workouts = unionById(n.workouts, o.workouts, workoutKey).map(clone)// A workout edited after it was logged keeps the version edited last, whichever copy is newer// as a whole — the same rule as a routine's. `editedBy` notes, per exercise, the copies whose@@ -299,13 +385,20 @@ export function stampCustomEx(prev = [], next = [], now = Date.now()) {// What `local` holds that `server` does not: the workouts and weigh-ins a device logged while it// was signed out, and the custom exercises they use. Sign-in asks about these before the server's// profile replaces the local copy; zero of each means there is nothing to ask about.+// A weigh-in on a day the server has one too counts when it differs and was entered later — the+// one "Add them" keeps (mergeBodyweight). Counted only on days the server lacked, a weigh-in+// made on the phone on a day the profile already had one was dropped without the question ever+// being asked. Weights are compared in the server's unit.export function localExtras(local, server) {const have = new Set(list(server?.workouts).map(workoutKey))- const days = new Set(list(server?.bodyweight).map(e => e?.d))+ const days = new Map(list(server?.bodyweight).filter(e => e && e.d != null).map(e => [e.d, e]))const ex = new Set(list(server?.customEx).map(e => e?.id))+ const from = unitOf(local), to = unitOf(server)+ const differs = (mine, theirs) =>+ (Number(mine.t) || 0) > (Number(theirs.t) || 0) && Number(convertBodyWeight(mine.w, from, to)) !== Number(theirs.w)return {workouts: list(local?.workouts).filter(w => !have.has(workoutKey(w))).length,- bodyweight: list(local?.bodyweight).filter(e => e && e.d != null && !days.has(e.d)).length,+ bodyweight: list(local?.bodyweight).filter(e => e && e.d != null && (!days.has(e.d) || differs(e, days.get(e.d)))).length,customEx: list(local?.customEx).filter(e => e && !ex.has(e.id)).length}}diff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.jsindex 8385f6fd0..561de3982 100644--- a/frontend/src/lib/sync-merge.test.js+++ b/frontend/src/lib/sync-merge.test.js@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'-import { localExtras, mergeBodyweight, mergeStampedMap, mergeStates, newerOf, stampCustomEx, stampRoutines, stampWorkout, unionById } from './sync-merge.js'+import { localExtras, mergeBodyweight, mergeStampedMap, mergeStates, newerOf, sinceReset, stampCustomEx, stampRoutines, stampWorkout, unionById } from './sync-merge.js'+import { convertBodyWeight, convertStateUnit, convertWeight } from './units.js'import { retimeWorkout } from './workout-date.js'import { inventoryFor, loadKindFor, withLoadKind, withPlatePairs, withStandardPlates } from './plates.js'@@ -233,7 +234,9 @@ describe('sign-in adoption helpers', () => {const server = { _ts: 100, unit: 'lb', restSec: 60, workouts: [{ id: 'w1', d: '2026-09-01' }], bodyweight: [{ d: '2026-09-01', w: 80, t: 1 }], routines: [{ id: 'r1', name: 'A' }], week: { 1: ['r1'] } }const local = { _ts: 900, unit: 'kg', restSec: 90, workouts: [{ id: 'w9', d: '2026-09-11' }], bodyweight: [{ d: '2026-09-11', w: 81, t: 2 }, { d: '2026-09-01', w: 79, t: 9 }], routines: [{ id: 'rg', name: 'Guest' }], customEx: [{ id: 'c1', name: 'x' }], week: { 2: ['rg'] } }it('localExtras counts what the device has that the server does not', () => {- expect(localExtras(local, server)).toEqual({ workouts: 1, bodyweight: 1, customEx: 1 })+ // the new day, and 09-01: the device's weigh-in of a day the server has too, entered later+ // and different (79 kg is 174.2 lb, not the server's 80 lb)+ expect(localExtras(local, server)).toEqual({ workouts: 1, bodyweight: 2, customEx: 1 })expect(localExtras(server, server)).toEqual({ workouts: 0, bodyweight: 0, customEx: 0 })expect(localExtras(null, server)).toEqual({ workouts: 0, bodyweight: 0, customEx: 0 })})@@ -243,8 +246,9 @@ describe('sign-in adoption helpers', () => {expect(m.workouts.map(w => w.id)).toEqual(['w1', 'w9'])expect(m.routines.map(r => r.id).sort()).toEqual(['r1', 'rg'])expect(m.customEx.map(e => e.id)).toEqual(['c1'])- // the weigh-in both sides have for the same day: the later `t` wins, as between devices- expect(m.bodyweight.find(e => e.d === '2026-09-01').w).toBe(79)+ // the weigh-in both sides have for the same day: the later `t` wins, as between devices —+ // in the profile's unit (79 kg)+ expect(m.bodyweight.find(e => e.d === '2026-09-01').w).toBe(174.2)expect(mergeStates(server, local).unit).toBe('kg') // without prefer the newer copy decides})})@@ -455,3 +459,118 @@ describe('custom exercises keep the version edited last', () => {expect(again.map(c => c._ts)).toEqual([1000, 6, 1000])})})+++// QA, v1.3.9 (t9): a copy converted to lb met the other device's kg copy, and the merge compared+// the numbers as they were — the server ended in kg with lb numbers in it.+describe('two copies in different units', () => {+ const lifted = (id, w) => ({ id, d: '2026-09-20', start: 1, end: 2, entries: [{ id: '0025', sets: [{ w, r: 5, done: true }] }] })+ const kg = base({ _ts: 300, workouts: [lifted('w1', 60), lifted('w-kg', 70)], bodyweight: [{ d: '2026-09-27', w: 81, t: 300 }], exWeights: { '0025': { w: 55, d: '2026-09-20' } } })+ const lb = { ...convertStateUnit(base({ _ts: 200, workouts: [lifted('w1', 60)], exWeights: { '0025': { w: 55, d: '2026-09-20' } } }), 'lb'), unitSet: { at: 200, convert: true } }++ it('the unit chosen last stays, and the other copy is converted into it before anything is compared', () => {+ for (const m of [mergeStates(kg, lb), mergeStates(lb, kg)]) {+ expect(m.unit).toBe('lb')+ expect(m.unitSet).toEqual({ at: 200, convert: true })+ expect(m.workouts.find(w => w.id === 'w-kg').entries[0].sets[0].w).toBe(convertWeight(70, 'kg', 'lb'))+ expect(m.workouts.find(w => w.id === 'w1').entries[0].sets[0].w).toBe(convertWeight(60, 'kg', 'lb'))+ expect(m.bodyweight[0].w).toBe(convertBodyWeight(81, 'kg', 'lb'))+ // the kept load is compared in one unit: 70 kg lifted since beats the 55 kg in both copies+ expect(m.exWeights['0025'].w).toBe(convertWeight(55, 'kg', 'lb'))+ }+ })++ it('with no switch stamped on either side, the newer copy\'s unit stays', () => {+ const old = { ...convertStateUnit(base({ _ts: 100, workouts: [lifted('w1', 60)] }), 'lb') }+ const m = mergeStates(old, kg)+ expect(m.unit).toBe('kg')+ expect(m.workouts.find(w => w.id === 'w1').entries[0].sets[0].w).toBe(60)+ })++ it('a label-only switch relabels the other copy instead of converting it', () => {+ const relabelled = { ...base({ _ts: 200 }), unit: 'lb', unitSet: { at: 200, convert: false } }+ const m = mergeStates(kg, relabelled)+ expect(m.unit).toBe('lb')+ expect(m.workouts.find(w => w.id === 'w-kg').entries[0].sets[0].w).toBe(70)+ expect(m.bodyweight[0].w).toBe(81)+ })++ it('with prefer (sign-in), the preferred side\'s unit stays', () => {+ const m = mergeStates(lb, kg, { prefer: 'a' })+ expect(m.unit).toBe('lb')+ expect(m.workouts.find(w => w.id === 'w-kg').entries[0].sets[0].w).toBe(convertWeight(70, 'kg', 'lb'))+ })+})++// QA, v1.3.9 (t8): "Reset everything" on one device; another pushed a change of its own, got the+// 409, merged, and the union brought the whole wiped profile back.+describe('a reset holds against a copy that has not seen it', () => {+ const R = 5000+ const reset = base({ _ts: R, resetAt: R, restSec: 90 })+ const w = (id, end, extra = {}) => ({ id, d: '2026-09-01', start: end - 10, end, entries: [{ id: '0025', sets: [{ w: 100, r: 5, done: true }] }], ...extra })+ const stale = base({+ _ts: 6000, restSec: 45,+ workouts: [w('old', 1000), w('new', 5500), w('old-edited', 1000, { _ts: 5600 }), w('backfilled', 1000, { _ts: 5700 })],+ routines: [{ id: 'r-old', name: 'old', ex: [], _ts: 100 }, { id: 'r-new', name: 'new', ex: [], _ts: 5800 }, { id: 'r-unstamped', name: 'x', ex: [] }],+ bodyweight: [{ d: '2026-08-01', w: 80, t: 100 }, { d: '2026-09-27', w: 81, t: 5900 }],+ customEx: [{ id: 'c-old', n: 'old', _ts: 100 }, { id: 'c-new', n: 'new', _ts: 5900 }],+ favEx: ['0025'], exNotes: { '0025': 'seat 4' }, gymCards: [{ id: 'g1', value: '123' }],+ exWeights: { '0025': { w: 140, d: '2026-08-01' }, '0100': { w: 30, d: '2026-08-01' } },+ loadKind: { '0025': { kind: 'single', _ts: 100 }, '0100': { kind: 'pairs', _ts: 5900 } },+ })++ it('keeps only what the other copy made after the reset, whichever copy is newer', () => {+ for (const m of [mergeStates(reset, stale), mergeStates(stale, reset)]) {+ expect(ids(m.workouts).sort()).toEqual(['backfilled', 'new', 'old-edited'])+ expect(ids(m.routines)).toEqual(['r-new'])+ expect(m.bodyweight.map(e => e.d)).toEqual(['2026-09-27'])+ expect(ids(m.customEx)).toEqual(['c-new'])+ expect(m.favEx || []).toEqual([])+ expect(m.exNotes || {}).toEqual({})+ expect(m.gymCards || []).toEqual([])+ expect(Object.keys(m.loadKind)).toEqual(['0100'])+ // the kept loads are those of the workouts that remain, not the ones from before the reset+ expect(m.exWeights).toEqual({ '0025': { w: 100, d: '2026-09-01' } })+ expect(m.restSec).toBe(90) // the reset copy's settings, though the other is newer+ expect(m.resetAt).toBe(R)+ expect(m._ts).toBe(6000)+ }+ })++ it('two copies that both saw the reset merge as usual', () => {+ const after = { ...stale, resetAt: R }+ expect(ids(mergeStates(reset, after).workouts)).toHaveLength(4)+ })++ it('a later reset wins over an earlier one', () => {+ const later = base({ _ts: 9000, resetAt: 9000 })+ expect(mergeStates({ ...stale, resetAt: R }, later).workouts).toEqual([])+ })++ it('not on sign-in: the device\'s own entries are not a copy of the account\'s history', () => {+ const m = mergeStates(reset, stale, { prefer: 'a' })+ expect(ids(m.workouts)).toHaveLength(4)+ })++ it('sinceReset leaves the copy it reads alone', () => {+ const before = JSON.stringify(stale)+ sinceReset(stale, R)+ expect(JSON.stringify(stale)).toBe(before)+ })+})++// QA, v1.3.9: a weigh-in logged on the phone on a day the profile already had one was dropped on+// pairing without the question being asked.+describe('localExtras and the weigh-ins of a day both copies have', () => {+ const server = { unit: 'kg', workouts: [], bodyweight: [{ d: '2026-09-27', w: 80, t: 100 }] }+ it('counts a same-day weigh-in that differs and was entered later', () => {+ expect(localExtras({ unit: 'kg', bodyweight: [{ d: '2026-09-27', w: 81.5, t: 200 }] }, server).bodyweight).toBe(1)+ })+ it('not the same reading, nor one the server\'s later entry replaced', () => {+ expect(localExtras({ unit: 'kg', bodyweight: [{ d: '2026-09-27', w: 80, t: 200 }] }, server).bodyweight).toBe(0)+ expect(localExtras({ unit: 'kg', bodyweight: [{ d: '2026-09-27', w: 82, t: 50 }] }, server).bodyweight).toBe(0)+ })+ it('compares in the server\'s unit', () => {+ expect(localExtras({ unit: 'lb', bodyweight: [{ d: '2026-09-27', w: convertBodyWeight(80, 'kg', 'lb'), t: 200 }] }, server).bodyweight).toBe(0)+ })+})diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 7d9f786ff..f38e837ca 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1675,4 +1675,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'ستُحذف معه أيضًا الصور أو مقاطع الفيديو المرفقة ({0}).','Its photo or video moves to the new workout.': 'تنتقل الصورة أو الفيديو المرفق إلى التمرين الجديد.','Its {0} photos or videos move to the new workout.': 'تنتقل الصور أو مقاطع الفيديو المرفقة ({0}) إلى التمرين الجديد.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'على الخادم تمرين واحد ليس في هذه النسخة الاحتياطية، سُجّل بعد إنشائها أو على جهاز آخر. الاستبدال يحذفه.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'على الخادم {0} تمارين ليست في هذه النسخة الاحتياطية، سُجّلت بعد إنشائها أو على جهاز آخر. الاستبدال يحذفها.',+ 'Replace anyway': 'استبدال على أي حال',+ 'Merge them in': 'دمجها',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 0449b6cfd..516ca97d6 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1642,4 +1642,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'Die {0} Fotos oder Videos darin werden mitgelöscht.','Its photo or video moves to the new workout.': 'Das Foto oder Video kommt ins neue Training mit.','Its {0} photos or videos move to the new workout.': 'Die {0} Fotos oder Videos kommen ins neue Training mit.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'Auf dem Server ist 1 Training, das nicht in diesem Backup ist – seither oder auf einem anderen Gerät erfasst. Ersetzen löscht es.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'Auf dem Server sind {0} Trainings, die nicht in diesem Backup sind – seither oder auf einem anderen Gerät erfasst. Ersetzen löscht sie.',+ 'Replace anyway': 'Trotzdem ersetzen',+ 'Merge them in': 'Zusammenführen',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 3bc562441..7e5315243 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'Sus {0} fotos o vídeos también se eliminan.','Its photo or video moves to the new workout.': 'Su foto o vídeo pasa al nuevo entrenamiento.','Its {0} photos or videos move to the new workout.': 'Sus {0} fotos o vídeos pasan al nuevo entrenamiento.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'El servidor tiene 1 entrenamiento que no está en esta copia, registrado después de hacerla o en otro dispositivo. Reemplazar lo elimina.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'El servidor tiene {0} entrenamientos que no están en esta copia, registrados después de hacerla o en otro dispositivo. Reemplazar los elimina.',+ 'Replace anyway': 'Reemplazar igualmente',+ 'Merge them in': 'Combinarlos',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 647074d36..83bd95723 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'Ses {0} photos ou vidéos sont supprimées avec elle.','Its photo or video moves to the new workout.': 'Sa photo ou vidéo passe à la nouvelle séance.','Its {0} photos or videos move to the new workout.': 'Ses {0} photos ou vidéos passent à la nouvelle séance.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'Le serveur a 1 séance absente de cette sauvegarde, enregistrée depuis ou sur un autre appareil. Remplacer la supprime.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'Le serveur a {0} séances absentes de cette sauvegarde, enregistrées depuis ou sur un autre appareil. Remplacer les supprime.',+ 'Replace anyway': 'Remplacer quand même',+ 'Merge them in': 'Les fusionner',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 5c187e8bd..0197e233b 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'इसकी {0} फ़ोटो या वीडियो भी इसके साथ हट जाएँगी।','Its photo or video moves to the new workout.': 'इसकी फ़ोटो या वीडियो नए वर्कआउट में चली जाएगी।','Its {0} photos or videos move to the new workout.': 'इसकी {0} फ़ोटो या वीडियो नए वर्कआउट में चली जाएँगी।',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'सर्वर पर 1 वर्कआउट है जो इस बैकअप में नहीं है — बैकअप के बाद या किसी दूसरे डिवाइस पर दर्ज। बदलने से वह हट जाएगा।',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'सर्वर पर {0} वर्कआउट हैं जो इस बैकअप में नहीं हैं — बैकअप के बाद या किसी दूसरे डिवाइस पर दर्ज। बदलने से वे हट जाएँगे।',+ 'Replace anyway': 'फिर भी बदलें',+ 'Merge them in': 'उन्हें मिलाएँ',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex d4de29b62..3e2b736b3 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1625,4 +1625,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'Vele együtt törlődnek a hozzá tartozó fotók és videók is ({0}).','Its photo or video moves to the new workout.': 'A hozzá tartozó fotó vagy videó átkerül az új edzéshez.','Its {0} photos or videos move to the new workout.': 'A hozzá tartozó fotók és videók ({0}) átkerülnek az új edzéshez.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'A szerveren van 1 edzés, amely nincs ebben a mentésben – azóta vagy egy másik eszközön rögzítették. A csere törli.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'A szerveren {0} edzés van, amely nincs ebben a mentésben – azóta vagy egy másik eszközön rögzítették. A csere törli őket.',+ 'Replace anyway': 'Csere mégis',+ 'Merge them in': 'Összefésülés',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex e48ba98af..458dbaeaf 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'Anche le sue {0} foto o video vengono eliminati.','Its photo or video moves to the new workout.': 'La sua foto o il suo video passa al nuovo allenamento.','Its {0} photos or videos move to the new workout.': 'Le sue {0} foto o video passano al nuovo allenamento.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'Sul server c’è 1 allenamento che non è in questo backup, registrato dopo o su un altro dispositivo. Sostituire lo elimina.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'Sul server ci sono {0} allenamenti che non sono in questo backup, registrati dopo o su un altro dispositivo. Sostituire li elimina.',+ 'Replace anyway': 'Sostituisci comunque',+ 'Merge them in': 'Uniscili',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 6b430aee7..62957311c 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': '첨부된 사진·동영상 {0}개도 함께 삭제됩니다.','Its photo or video moves to the new workout.': '첨부된 사진·동영상은 새 운동으로 옮겨집니다.','Its {0} photos or videos move to the new workout.': '첨부된 사진·동영상 {0}개는 새 운동으로 옮겨집니다.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': '서버에 이 백업에 없는 운동이 1개 있습니다. 백업 이후 또는 다른 기기에서 기록된 것입니다. 바꾸면 삭제됩니다.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': '서버에 이 백업에 없는 운동이 {0}개 있습니다. 백업 이후 또는 다른 기기에서 기록된 것입니다. 바꾸면 삭제됩니다.',+ 'Replace anyway': '그래도 바꾸기',+ 'Merge them in': '합치기',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 41e5b177d..4a09a4c09 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'Zdjęcia lub filmy ({0}) też zostaną usunięte.','Its photo or video moves to the new workout.': 'Zdjęcie lub film przejdzie do nowego treningu.','Its {0} photos or videos move to the new workout.': 'Zdjęcia lub filmy ({0}) przejdą do nowego treningu.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'Na serwerze jest 1 trening, którego nie ma w tej kopii – zapisany później lub na innym urządzeniu. Zastąpienie go usunie.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'Na serwerze jest {0} treningów, których nie ma w tej kopii – zapisanych później lub na innym urządzeniu. Zastąpienie je usunie.',+ 'Replace anyway': 'Zastąp mimo to',+ 'Merge them in': 'Scal je',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 8c733fde9..0007173a8 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -967,6 +967,10 @@ export const PT_BR_OVERRIDES = {'A progress photo or a form-check video, kept with this workout.': 'Uma foto de progresso ou um vídeo para conferir a técnica, salvos com este treino.','Its photo or video is deleted with it.': 'A foto ou o vídeo dele também é excluído.','Its {0} photos or videos are deleted with it.': 'As {0} fotos ou vídeos dele também são excluídos.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'O servidor tem 1 treino que não está neste backup, registrado depois dele ou em outro dispositivo. Substituir exclui esse treino.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'O servidor tem {0} treinos que não estão neste backup, registrados depois dele ou em outro dispositivo. Substituir exclui esses treinos.',+ 'Replace anyway': 'Substituir mesmo assim',+ 'Merge them in': 'Juntar os treinos',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex b87bd0b62..58dc11929 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'As {0} fotos ou vídeos dele também são eliminados.','Its photo or video moves to the new workout.': 'A foto ou o vídeo dele passa para o novo treino.','Its {0} photos or videos move to the new workout.': 'As {0} fotos ou vídeos dele passam para o novo treino.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'O servidor tem 1 treino que não está nesta cópia, registado depois dela ou noutro dispositivo. Substituir elimina-o.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'O servidor tem {0} treinos que não estão nesta cópia, registados depois dela ou noutro dispositivo. Substituir elimina-os.',+ 'Replace anyway': 'Substituir mesmo assim',+ 'Merge them in': 'Juntá-los',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 6e9b3d6e7..feac9d508 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'Фото и видео ({0}) тоже будут удалены.','Its photo or video moves to the new workout.': 'Фото или видео перейдёт в новую тренировку.','Its {0} photos or videos move to the new workout.': 'Фото и видео ({0}) перейдут в новую тренировку.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'На сервере есть 1 тренировка, которой нет в этой копии: записана позже или на другом устройстве. Замена её удалит.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'На сервере есть тренировки, которых нет в этой копии ({0}): записаны позже или на другом устройстве. Замена их удалит.',+ 'Replace anyway': 'Всё равно заменить',+ 'Merge them in': 'Объединить',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 217fbafe5..048b97864 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1633,4 +1633,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'รูปภาพหรือวิดีโอที่แนบไว้ {0} รายการจะถูกลบไปด้วย','Its photo or video moves to the new workout.': 'รูปภาพหรือวิดีโอที่แนบไว้จะย้ายไปยังการออกกำลังกายใหม่','Its {0} photos or videos move to the new workout.': 'รูปภาพหรือวิดีโอที่แนบไว้ {0} รายการจะย้ายไปยังการออกกำลังกายใหม่',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'เซิร์ฟเวอร์มีการออกกำลังกาย 1 รายการที่ไม่อยู่ในข้อมูลสำรองนี้ บันทึกหลังจากนั้นหรือบนอุปกรณ์อื่น การแทนที่จะลบรายการนั้น',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'เซิร์ฟเวอร์มีการออกกำลังกาย {0} รายการที่ไม่อยู่ในข้อมูลสำรองนี้ บันทึกหลังจากนั้นหรือบนอุปกรณ์อื่น การแทนที่จะลบรายการเหล่านั้น',+ 'Replace anyway': 'แทนที่ต่อไป',+ 'Merge them in': 'รวมเข้าด้วยกัน',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 74debd884..8fb2df291 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': '{0} fotoğrafı veya videosu da onunla birlikte silinir.','Its photo or video moves to the new workout.': 'Fotoğrafı veya videosu yeni antrenmana taşınır.','Its {0} photos or videos move to the new workout.': '{0} fotoğrafı veya videosu yeni antrenmana taşınır.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'Sunucuda bu yedekte olmayan 1 antrenman var; yedekten sonra ya da başka bir cihazda kaydedilmiş. Değiştirmek onu siler.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'Sunucuda bu yedekte olmayan {0} antrenman var; yedekten sonra ya da başka bir cihazda kaydedilmiş. Değiştirmek onları siler.',+ 'Replace anyway': 'Yine de değiştir',+ 'Merge them in': 'Birleştir',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 954d92698..50da3dd07 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1619,4 +1619,8 @@ export default {'Its {0} photos or videos are deleted with it.': 'Фото й відео ({0}) теж буде видалено.','Its photo or video moves to the new workout.': 'Фото чи відео перейде до нового тренування.','Its {0} photos or videos move to the new workout.': 'Фото й відео ({0}) перейдуть до нового тренування.',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': 'На сервері є 1 тренування, якого немає в цій копії: записане пізніше або на іншому пристрої. Заміна його видалить.',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': 'На сервері є тренування, яких немає в цій копії ({0}): записані пізніше або на іншому пристрої. Заміна їх видалить.',+ 'Replace anyway': 'Однаково замінити',+ 'Merge them in': 'Об’єднати',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 2c2241e52..2fe8d22ca 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1622,4 +1622,8 @@ export default {'Its {0} photos or videos are deleted with it.': '其中的 {0} 个照片或视频也会一并删除。','Its photo or video moves to the new workout.': '其中的照片或视频会移到新的训练中。','Its {0} photos or videos move to the new workout.': '其中的 {0} 个照片或视频会移到新的训练中。',+ 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.': '服务器上有 1 次训练不在此备份中,是备份之后或在其他设备上记录的。替换会删除它。',+ 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.': '服务器上有 {0} 次训练不在此备份中,是备份之后或在其他设备上记录的。替换会删除它们。',+ 'Replace anyway': '仍然替换',+ 'Merge them in': '合并进来',}diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex 355020a87..20f8ef58d 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -2635,6 +2635,9 @@ function doFinishWorkout() {w.vol = workoutVolume(w)update(s => {if (past) {+ // Its start and end are in the past; the stamp says when it was logged, which is what a+ // merge after a reset elsewhere asks of it (lib/sync-merge.js sinceReset).+ stampWorkout(w)s.workouts = completeBackfill(s.workouts, A, w)} else {w.entries.forEach(e => {diff --git a/frontend/src/store/useStore.adopt-hold.test.jsx b/frontend/src/store/useStore.adopt-hold.test.jsxnew file mode 100644index 000000000..8a15eef10--- /dev/null+++ b/frontend/src/store/useStore.adopt-hold.test.jsx@@ -0,0 +1,220 @@+// @vitest-environment happy-dom++/* QA, v1.3.9 (Android): a phone in local mode, one workout on it, paired with an account that+ has twelve. While "Add this device's workouts?" was open, the poll pulled, took the phone's+ newer copy for the account's and pushed it: the server held one workout. "Keep profile as is"+ then adopted the copy read before the question, with its old revision, and the eleven were+ gone for good; closing the app with the question open did the same on the next start.++ Now nothing syncs between the pairing and the answer, the answer is applied to the server's+ copy as it is when the question closes, and a start with the question still open asks it again.++ Real modules: store/useStore.js, lib/api.js, lib/remote.js, lib/mobile.js. Mocked: the Capacitor+ plugins (an in-memory Directory.Data), the question sheet, and fetch, which plays the server. */+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++const h = vi.hoisted(() => {+ vi.stubEnv('VITE_MOBILE', '1')+ return { files: new Map(), server: null, calls: [], ask: null }+})++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: () => {} }) } }))+// The question a resumed adoption asks (useStore resumeAdoption): the sign-in's own sheet.+vi.mock('../sheets.jsx', () => ({ askAddDeviceData: extras => h.ask(extras) }))++const BASE = 'https://gym.example.com'+const USER = { id: 'u1', name: 'andi' }+const clone = v => JSON.parse(JSON.stringify(v))+const workout = (id, d) => ({ id, d, start: 1, end: 2, entries: [] })+const res = (status, body) => ({+ ok: status >= 200 && status < 300, status,+ headers: { get: k => (k.toLowerCase() === 'content-type' ? 'application/json' : null) },+ json: async () => JSON.parse(body),+ text: async () => body,+})+const json = (status, body) => res(status, JSON.stringify(body))+const sleep = ms => new Promise(r => setTimeout(r, ms))+const ids = xs => (xs || []).map(x => x.id)+const deferred = () => { let resolve; const p = new Promise(r => { resolve = r }); return { p, resolve } }++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 })+ if (String(url).startsWith(BASE)) return h.server(String(url).slice(BASE.length), method, init)+ return res(404, '{}')+ })+}+function serverWith(doc) {+ const srv = { doc: clone(doc), puts: [] }+ h.server = (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', 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 })+ }+ return json(404, { error: 'not found' })+ }+ return srv+}++// The account: twelve workouts at rev 5. The phone: local mode, one workout of its own, newer.+const TWELVE = Array.from({ length: 12 }, (_, i) => workout('s' + i, `2026-09-${String(i + 1).padStart(2, '0')}`))+const SERVER = { _ts: 1000, _rev: 5, unit: 'kg', workouts: TWELVE, routines: [], bodyweight: [] }+let DEF+beforeAll(async () => { DEF = (await import('./useStore.js')).DEF })+function localPhone() {+ h.files.clear()+ localStorage.clear()+ const S = { ...clone(DEF), _ts: 5000, workouts: [workout('phone-1', '2026-09-20')] }+ h.files.set('DATA/opengym-remote.json', JSON.stringify({ mode: 'local' }))+ h.files.set('DATA/opengym-state.json', JSON.stringify(S))+ localStorage.setItem('gym_state_v1', JSON.stringify(S))+ localStorage.setItem('gym_guest', '1')+}++let stores = []+async function freshStore() {+ vi.resetModules()+ const { useStore } = await import('./useStore.js')+ stores.push(useStore)+ return useStore+}+// Everything that used to start a sync while the question was open: the poll's check on a+// resume, a pull, a push, a change on its debounce.+async function everySyncTrigger(useStore) {+ window.dispatchEvent(new Event('focus'))+ await useStore.getState().pullState()+ await useStore.getState().pushState()+ useStore.getState().update(s => { s.restSec = 75 })+ await sleep(1700)+}++beforeEach(() => { installFetch(); h.ask = null })+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('pairing a phone: nothing syncs while the question is open', () => {+ it('a pull, a push, the poll and a debounced change in the window write nothing, and Keep leaves all twelve', async () => {+ localPhone()+ const srv = serverWith(SERVER)+ const useStore = await freshStore()+ await useStore.getState().boot()+ const answer = deferred()+ const ask = vi.fn(() => answer.p)+ const pairing = useStore.getState().connectToServer('gym.example.com', 'ABCD2345', ask)+ while (!ask.mock.calls.length) await sleep(5)++ await everySyncTrigger(useStore)+ expect(srv.puts).toHaveLength(0)+ expect(ids(srv.doc.workouts)).toHaveLength(12)++ answer.resolve(false) // Keep profile as is+ await pairing+ expect(srv.puts).toHaveLength(0)+ expect(ids(srv.doc.workouts)).toHaveLength(12)+ expect(ids(useStore.getState().S.workouts)).toEqual(ids(TWELVE))+ expect(localStorage.getItem('gym_adopt')).toBeNull()+ // and sync is back: the next change goes to the server as usual+ useStore.getState().update(s => { s.workouts.push(workout('after', '2026-09-25')) })+ await useStore.getState().pushState()+ expect(srv.puts.at(-1).baseRev).toBe(5)+ expect(ids(srv.doc.workouts)).toHaveLength(13)+ })++ it('Keep takes the server\'s copy as it is when the question closes, not as it was when it opened', async () => {+ localPhone()+ const srv = serverWith(SERVER)+ const useStore = await freshStore()+ await useStore.getState().boot()+ const answer = deferred()+ const ask = vi.fn(() => answer.p)+ const pairing = useStore.getState().connectToServer('gym.example.com', 'ABCD2345', ask)+ while (!ask.mock.calls.length) await sleep(5)+ // another device logs a workout meanwhile+ srv.doc = { ...srv.doc, workouts: [...srv.doc.workouts, workout('web-new', '2026-09-26')], _ts: 6000, _rev: 6 }++ answer.resolve(false)+ await pairing+ expect(ids(useStore.getState().S.workouts)).toContain('web-new')+ expect(JSON.parse(localStorage.getItem('gym_sync')).rev).toBe(6)+ expect(srv.puts).toHaveLength(0)+ })++ it('Add them merges into the server\'s current copy and pushes against its revision', async () => {+ localPhone()+ const srv = serverWith(SERVER)+ const useStore = await freshStore()+ await useStore.getState().boot()+ const answer = deferred()+ const ask = vi.fn(() => answer.p)+ const pairing = useStore.getState().connectToServer('gym.example.com', 'ABCD2345', ask)+ while (!ask.mock.calls.length) await sleep(5)+ srv.doc = { ...srv.doc, workouts: [...srv.doc.workouts, workout('web-new', '2026-09-26')], _ts: 6000, _rev: 6 }++ answer.resolve(true)+ await pairing+ expect(srv.puts).toHaveLength(1)+ expect(srv.puts[0].baseRev).toBe(6)+ expect(ids(srv.doc.workouts).sort()).toEqual([...ids(TWELVE), 'phone-1', 'web-new'].sort())+ })++ it('closed with the question open, the next start asks again and pushes nothing before the answer', async () => {+ localPhone()+ const srv = serverWith(SERVER)+ let useStore = await freshStore()+ await useStore.getState().boot()+ const first = vi.fn(() => new Promise(() => {})) // never answered: the app is killed+ useStore.getState().connectToServer('gym.example.com', 'ABCD2345', first)+ while (!first.mock.calls.length) await sleep(5)+ await sleep(900) // the file mirror's debounce, as on a phone that stayed open a moment+ for (const s of stores) s.setState({ user: null, ready: false })++ const answer = deferred()+ h.ask = vi.fn(() => answer.p)+ useStore = await freshStore()+ await useStore.getState().boot()+ while (!h.ask.mock.calls.length) await sleep(5)+ expect(h.ask).toHaveBeenCalledWith(expect.objectContaining({ workouts: 1 }))+ await everySyncTrigger(useStore)+ expect(srv.puts).toHaveLength(0)++ answer.resolve(false)+ while (localStorage.getItem('gym_adopt')) await sleep(5)+ await sleep(20)+ expect(srv.puts).toHaveLength(0)+ expect(ids(srv.doc.workouts)).toHaveLength(12)+ expect(ids(useStore.getState().S.workouts)).toEqual(ids(TWELVE))+ })+})diff --git a/frontend/src/store/useStore.adopt.test.jsx b/frontend/src/store/useStore.adopt.test.jsxindex 1f7c535f0..540b2d1f9 100644--- a/frontend/src/store/useStore.adopt.test.jsx+++ b/frontend/src/store/useStore.adopt.test.jsx@@ -39,7 +39,7 @@ describe('adoptProfile — sign-in takes the server profile', () => {expect(S.unit).toBe('lb'); expect(S.restSec).toBe(60)expect(S.workouts.map(w => w.id)).toEqual(['w1'])expect(S.routines.map(x => x.id)).toEqual(['r1'])- expect(S.active).toEqual({ id: 'running' }) // the in-progress session stays with the device+ expect(S.active).toMatchObject({ id: 'running' }) // the in-progress session stays with the deviceexpect(puts()).toHaveLength(0)expect(sync()).toEqual({ rev: 4, ts: 100 })expect(r).toEqual({ adopted: true, added: false })@@ -48,6 +48,7 @@ describe('adoptProfile — sign-in takes the server profile', () => {it('adds the device\'s entries to the profile when asked to, keeping the profile\'s settings and plan', async () => {signedIn(clone(guest))api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 }) // read again once answeredapi.mockResolvedValueOnce({ ok: true, rev: 5 })await useStore.getState().adoptProfile(async () => true)const S = useStore.getState().S@@ -207,3 +208,71 @@ describe('revision check on resume', () => {expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1'])})})++// QA, v1.3.9: the sign-in's question was open while a pull ran, and the device's copy — newer by+// its stamp — was pushed over the profile. The web sign-ins hold sync just the same.+describe('web sign-in: nothing syncs while the question is open', () => {+ it('no pull, push or revision check before the answer; Keep takes the server copy as it is then', async () => {+ signedIn(clone(guest), { user: null })+ useStore.getState().setUser({ id: 'user-1' }, { adopt: true })+ expect(JSON.parse(localStorage.getItem('gym_adopt'))).toMatchObject({ uid: 'user-1', rejoined: false })+ let answer+ const ask = vi.fn(() => new Promise(r => { answer = r }))+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ const done = useStore.getState().adoptProfile(ask)+ await vi.waitFor(() => expect(ask).toHaveBeenCalled())++ await useStore.getState().pullState()+ await useStore.getState().pushState()+ window.dispatchEvent(new Event('online'))+ await new Promise(r => setTimeout(r, 10))+ expect(paths()).toEqual(['/api/data'])++ // another device wrote while the question was open+ api.mockResolvedValueOnce({ state: { ...clone(server), _ts: 200, workouts: [workout('w1'), workout('w-other', '2026-09-20')], _rev: 5 }, rev: 5 })+ answer(false)+ await done+ expect(puts()).toHaveLength(0)+ expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'w-other'])+ expect(sync().rev).toBe(5)+ expect(localStorage.getItem('gym_adopt')).toBeNull()+ })++ it('a sign-in whose adoption could not reach the server keeps sync held and asks again on the next check', async () => {+ signedIn(clone(guest), { user: null })+ useStore.getState().setUser({ id: 'user-1' }, { adopt: true })+ api.mockRejectedValueOnce(netErr())+ await expect(useStore.getState().adoptProfile(vi.fn())).rejects.toThrow()+ await useStore.getState().pullState()+ expect(puts()).toHaveLength(0)+ expect(paths()).toEqual(['/api/data'])+ // back online: the check runs the adoption again, question and all+ const ask = vi.fn(async () => false)+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ await useStore.getState().resumeAdoption(ask)+ expect(ask).toHaveBeenCalledWith({ workouts: 1, bodyweight: 0, customEx: 0 })+ expect(puts()).toHaveLength(0)+ expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1'])+ expect(localStorage.getItem('gym_adopt')).toBeNull()+ })+})++// QA, v1.3.9: "Back online — synced with the server" after switching accounts — the push the+// previous account could not make offline was announced by the next account's first push.+describe('the back-online toast belongs to the account that was offline', () => {+ it('is not said after another account signs in', async () => {+ localStorage.setItem('gym_owner', 'user-1')+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ useStore.getState().update(s => { s.restSec = 75 })+ api.mockRejectedValueOnce(netErr())+ await useStore.getState().pushState()+ expect(useStore.getState().sync.offline).toBe(true)++ useStore.getState().setUser({ id: 'user-2', name: 'Two' })+ useStore.getState().update(s => { s.workouts.push(workout('w-two')) })+ api.mockResolvedValueOnce({ ok: true, rev: 1 })+ await useStore.getState().pushState()+ await new Promise(r => setTimeout(r, 10))+ expect(toast).not.toHaveBeenCalledWith('Back online — synced with the server.')+ })+})diff --git a/frontend/src/store/useStore.import-check.test.jsx b/frontend/src/store/useStore.import-check.test.jsxnew file mode 100644index 000000000..91032e7f3--- /dev/null+++ b/frontend/src/store/useStore.import-check.test.jsx@@ -0,0 +1,69 @@+// @vitest-environment happy-dom++/* QA, v1.3.9: importing a backup replaced the server copy outright, and a workout another device+ had synced meanwhile was gone. The import stays a deliberate replace, but the server is asked+ first: what it holds that the backup does not is said in the confirm, with the choice to merge+ it in (views/Settings.jsx doImport). */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn() }) } }))++import { api } from '../lib/api.js'+import { DEF, useStore } from './useStore.js'++const clone = v => JSON.parse(JSON.stringify(v))+const ids = xs => (xs || []).map(x => x.id)+const workout = (id, d = '2026-09-20') => ({ id, d, start: 1, end: 2, entries: [] })+const puts = () => api.mock.calls.filter(([, o]) => o?.method === 'PUT').map(([, o]) => JSON.parse(o.body))+const signedIn = (S, rev) => {+ localStorage.setItem('gym_sync', JSON.stringify({ rev, ts: S._ts }))+ useStore.setState({ S, user: { id: 'u1' }, ready: true, sync: { offline: false, pending: false, lastSynced: 0 } })+}+const BACKUP = { ...clone(DEF), _ts: 50, restSec: 120, workouts: [workout('w1'), workout('w2')] }+const SERVER = { ...clone(DEF), _ts: 300, restSec: 60, workouts: [workout('w1'), workout('w2'), workout('elsewhere', '2026-09-26')], _rev: 7 }++beforeEach(() => { localStorage.clear(); api.mockReset() })+afterEach(() => { localStorage.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })++describe('importing a backup over a profile that moved on', () => {+ it('names the workouts on the server that the backup lacks', async () => {+ signedIn({ ...clone(DEF), _ts: 200, workouts: [workout('w1')] }, 6)+ api.mockResolvedValueOnce({ state: clone(SERVER), rev: 7 })+ const c = await useStore.getState().importConflict(BACKUP)+ expect(c).toMatchObject({ workouts: 1, rev: 7 })+ })++ it('nothing to say when the backup has everything, when signed out, or when the server cannot be asked', async () => {+ signedIn(clone(DEF), 6)+ api.mockResolvedValueOnce({ state: clone(BACKUP), rev: 7 })+ expect(await useStore.getState().importConflict(BACKUP)).toBeNull()+ api.mockRejectedValueOnce(new TypeError('Failed to fetch'))+ expect(await useStore.getState().importConflict(BACKUP)).toBeNull()+ useStore.setState({ user: null })+ expect(await useStore.getState().importConflict(BACKUP)).toBeNull()+ })++ it('"Merge them in" keeps the backup\'s settings and every workout of both, pushed against the server\'s revision', async () => {+ signedIn({ ...clone(DEF), _ts: 200, workouts: [workout('w1')] }, 6)+ api.mockResolvedValueOnce({ state: clone(SERVER), rev: 7 })+ const c = await useStore.getState().importConflict(BACKUP)+ api.mockResolvedValueOnce({ ok: true, rev: 8 })+ useStore.getState().importBackup(BACKUP, { mergeWith: c })+ await useStore.getState().pushState()+ const put = puts().at(-1)+ expect(put.baseRev).toBe(7)+ expect(ids(put.state.workouts)).toEqual(['w1', 'w2', 'elsewhere'])+ expect(put.state.restSec).toBe(120)+ })++ it('"Replace anyway" is the replace it always was', async () => {+ signedIn({ ...clone(DEF), _ts: 200, workouts: [workout('w1')] }, 6)+ api.mockResolvedValueOnce({ ok: true, rev: 8 })+ useStore.getState().importBackup(BACKUP)+ await useStore.getState().pushState()+ const put = puts().at(-1)+ expect(put.baseRev).toBeUndefined()+ expect(ids(put.state.workouts)).toEqual(['w1', 'w2'])+ })+})diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 3e5fe6e04..ea3f6d0ce 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -8,6 +8,7 @@ import { rememberDefaultLang } from '../lib/default-lang.js'import { guestAllowed } from '../lib/guest.js'import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'import { mergeStates, localExtras, stampRoutines, stampCustomEx } from '../lib/sync-merge.js'+import { convertStateUnit } from '../lib/units.js'import { pendingRefCount, settleMedia, loadPending } from '../lib/media-owed.js'import { referencedHashes } from '../lib/media-refs.js'import { mediaStore, mediaStoreInUse } from '../lib/media-store.js'@@ -42,6 +43,13 @@ const STASH_FILE = 'opengym-stash.json'// boot sends the logout again instead of asking /api/me, which would sign the browser straight// back in with no passkey or password. Any sign-in replaces the cookie and clears the mark.const LOGOUT_OWED_KEY = 'gym_logout_owed'+// A sign-in (or a phone's pairing) whose question about this device's own entries has not been+// answered yet (adoptProfile): { uid, rejoined, alwaysAsk }. Until it is, nothing syncs — the copy+// on this device may still be a guest's, and a pull or push in that window used to send it over the+// account's profile (QA, v1.3.9: a phone's one workout replaced the twelve on the server while the+// question was open). Kept in storage so an app killed with the question open asks it again on+// the next start instead of pushing the copy it still holds.+const ADOPT_KEY = 'gym_adopt'// Reads the mark with no argument, sets or clears it with one. Storage that cannot be read owes nothing.function logoutOwed(on) {try {@@ -55,6 +63,10 @@ function logoutOwed(on) {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+const AUTO_BACKUP_SOON_MS = 2000 // several photos picked at once make one backup+// Which photos and videos each workout holds, as one string to compare.+const workoutMediaKey = S => (Array.isArray(S?.workouts) ? S.workouts : [])+ .map(w => (Array.isArray(w?.media) ? w.media.map(m => m?.hash || '').join(',') : '')).join('|')export const DEF = {unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, soundOnSilent: false, timerFlash: false, timedSetOvertime: false, keepAwake: true, lang: 'en',theme: 'dark', accent: 'lime', body: 'male', targetW: null,@@ -230,12 +242,22 @@ 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 backupTm = null // phone: the auto-backup after workout media changed, on its debounce+ let adoptHold = false // a sign-in's adoption has not decided yet: no pull, no push (ADOPT_KEY)+ let adoptClaimed = false // a sign-in is on its way to adoptProfile: nothing else starts one+ let adopting = null // the adoptProfile in flightlet 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 onelet 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)+ 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 */ } }+ // The adoption owed by the account signed in now, if there is one.+ const adoptOwed = () => { const m = readAdopt(); const u = get()?.user; return m && u && m.uid === u.id ? m : null }+ // The question is answered: sync as usual from here.+ const releaseAdopt = () => { adoptHold = false; adoptClaimed = false; writeAdopt(null) }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 } }@@ -423,6 +445,9 @@ export const useStore = create((set, get) => {if (!get().user || !get().ready || document.visibilityState === 'hidden') returnif (!force && Date.now() - lastCheck < CHECK_MIN_MS) returnlastCheck = Date.now()+ // A sign-in still deciding what becomes of this copy: no check of its own. One whose+ // adoption could not reach the server tries again here, question and all.+ if (adoptHold) { if (!adopting && !adoptClaimed && adoptOwed()) get().resumeAdoption(); return }if (pulling) return pullingconst { base } = metaOf()if (!base || owes()) return get().pullState()@@ -454,11 +479,19 @@ export const useStore = create((set, get) => {const mergeInto = (local, remote, rev) => {const ts = metaOf().base?.ts || 0const merged = Object.assign(clone(DEF), mergeStates(local, remote))- merged.active = local.active || null+ merged.active = carryActive(local, merged)persist(merged, false)if (rev == null) dropSync()else writeSync(rev, ts)}+ // The workout running on this device, carried from its copy into the one replacing it — in that+ // copy's unit: a merge or a pull can bring the other device's switch to lb along, and a session+ // left in kg would then log kg numbers under an lb label.+ const carryActive = (from, to) => {+ const a = from?.active || null+ const fu = from?.unit || 'kg', tu = to?.unit || 'kg'+ return !a || fu === tu ? a : convertStateUnit({ unit: fu, active: a }, tu).active+ }// 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); markOwed(false) }@@ -576,6 +609,7 @@ export const useStore = create((set, get) => {// that replaces it descends from no revision and owes nothing.const forgetSync = () => {meta.set(get().S, { base: null, owed: false })+ offlineChanges = false // a push the previous account owed is not this one's to announcetry { for (const k of [SYNC_KEY, DIRTY_KEY, SYNCED_AT_KEY, SYNCED_FP_KEY]) localStorage.removeItem(k) } catch { /* nothing to keep */ }fpOf = null}@@ -587,6 +621,7 @@ export const useStore = create((set, get) => {get().setUser(null)localStorage.removeItem('gym_guest')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)@@ -710,6 +745,101 @@ export const useStore = create((set, get) => {await writeStashes(all)}+ // adoptProfile's work (see there). Every way out answers the question — releaseAdopt — before+ // the decision is written and pushed; only a server that could not be reached leaves it owed.+ const runAdopt = async (ask, { alwaysAsk = false } = {}) => {+ if (pulling) await pulling+ // An adoption resumed after a restart is the sign-in's own: whether this copy already belonged+ // to the account was decided then — boot's sign-in sees the owner that sign-in wrote.+ const owedMark = adoptOwed()+ const sameAccount = owedMark ? !!owedMark.rejoined : rejoined+ if (owedMark?.alwaysAsk) alwaysAsk = true+ let res+ try { res = await api('/api/data') }+ catch (e) {+ failed(e)+ // Nothing decided: with a sign-in that marked it, sync stays held and the next check asks+ // again (checkRev); a bare call has nothing to hold for.+ if (!owedMark) releaseAdopt()+ throw e // the caller's toast: sign-in needed the server anyway+ }+ let { state, rev } = res+ reached()+ let asked = false+ const askAbout = async extras => {+ if (!(extras.workouts || extras.bodyweight || extras.customEx) || typeof ask !== 'function') return false+ asked = true+ return !!(await ask(extras))+ }+ // The question can stay open for minutes: what is applied is the server's copy once it+ // closes. Unreachable by then, the copy read before it stands — its revision is older than+ // the server's, so the next pull still brings in what changed.+ const reread = async () => {+ if (!asked) return+ try { const r = await api('/api/data'); if (r && r.state) ({ state, rev } = r) } catch { /* the first read */ }+ }+ const takeServer = () => {+ const copy = Object.assign(clone(DEF), state)+ copy.active = carryActive(get().S, copy)+ if (rev != null) adopt(copy, rev)+ else { dropSync(); persist(copy, false, false); markOwed(false) }+ confirmed(get().S)+ }+ const S0 = get().S+ if (!state) {+ const push = hasData(S0) && (!alwaysAsk || sameAccount || await askAbout(localExtras(S0, null)))+ releaseAdopt()+ if (hasData(get().S) && !push) {+ takeServer()+ await applyStash()+ return { adopted: true, added: false }+ }+ markOwed(false)+ if (push) { if (rev != null) writeSync(rev, 0); forceNext = true; await get().pushState() }+ else { if (rev != null) writeSync(rev, 0); confirmed(get().S) }+ await applyStash()+ return { adopted: false, added: false }+ }+ 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.+ releaseAdopt()+ const S = get().S+ const { base, owed } = metaOf()+ if (!hasData(S) || (!owed && base && !localChanged(S))) {+ takeServer()+ 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 keep = await askAbout(localExtras(S0, state))+ await reread()+ releaseAdopt()+ if (keep) {+ const S = get().S+ const merged = Object.assign(clone(DEF), mergeStates(state, S, { prefer: 'a' }))+ merged.active = carryActive(S, merged)+ persist(merged, false)+ if (rev != null) writeSync(rev, 0)+ else dropSync()+ await get().pushState()+ await applyStash()+ return { adopted: true, added: true }+ }+ takeServer()+ await applyStash()+ return { adopted: true, added: false }+ }+// 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. Only the paired account's own, though, and@@ -740,6 +870,7 @@ export const useStore = create((set, get) => {if (referencedHashes(S0).size) loadPending()meta.set(S0, { base: readStoredSync(), owed: storedOwed() })const user0 = (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })()+ adoptHold = !!user0 && readAdopt()?.uid === user0.idconst 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)@@ -774,6 +905,12 @@ export const useStore = create((set, get) => {stampRoutines(prev.routines, S.routines)stampCustomEx(prev.customEx, S.customEx)persist(S, push)+ // A photo or video added to (or taken off) a workout is a change worth the day's backup too:+ // the one finishing wrote went before the finish screen's pictures (autoBackupNow).+ if (MOBILE && S.autoBackup && workoutMediaKey(prev) !== workoutMediaKey(S)) {+ clearTimeout(backupTm)+ backupTm = setTimeout(() => { backupTm = null; get().autoBackupNow() }, AUTO_BACKUP_SOON_MS)+ }},// An edit of a saved workout (lib/session-edit.js) is saved or dropped like any other change:// the store's own sync takes it to the server, and a conflict on the way is settled by@@ -791,6 +928,57 @@ export const useStore = create((set, get) => {get().update(S => { removed = deleteEditedWorkout(S) })return removed},+ // Settings → unit. `convert` walks every stored weight into the new unit (lib/units.js); off,+ // only the label changes. Either way the choice is stamped (`unitSet`), so a merge with a+ // copy still in the old unit brings that copy over rather than mixing the two (lib/sync-merge.js),+ // and a conversion goes to the server at once, as an ordinary conditional push: another device+ // still logging in the old unit meets it on its very next push, and a copy it pushed first is+ // converted before it is merged in.+ setUnit(to, { convert = true } = {}) {+ const S0 = get().S+ if ((S0.unit || 'kg') === to) return null+ const S = clone(convert ? convertStateUnit(S0, to) : { ...S0, unit: to })+ S.unitSet = { at: Date.now(), convert }+ persist(S, true)+ return convert && get().ready ? get().pushState() : null+ },+ // Settings → Reset everything: the empty copy, stamped with when (`resetAt`). Pushed as a+ // replace, and the stamp is what makes it hold: a device that has not seen the reset and+ // still pushes a change of its own gets the 409, and its merge keeps only what that device+ // made after the reset instead of bringing the whole profile back (lib/sync-merge.js).+ resetEverything() {+ const S = clone(DEF)+ S.resetAt = Date.now()+ get().replaceState(S, !!get().user)+ },+ // Before a backup replaces this copy (Settings → Import): the workouts the server holds that the+ // backup does not — logged since it was made, or on another device meanwhile. The import is a+ // deliberate replace and deletes them from the profile; the confirm says so and offers to merge+ // them in instead (importBackup). null when there are none, when nobody is signed in, or when+ // the server cannot be asked — the replace then goes as it always has.+ async importConflict(backup) {+ if (!get().user) return null+ let res+ try { res = await api('/api/data') } catch { return null }+ const state = res?.state+ if (!state) return null+ const key = w => (w?.id != null ? w.id : `${w?.d}|${w?.start}`)+ const inBackup = new Set((Array.isArray(backup?.workouts) ? backup.workouts : []).map(key))+ const workouts = (Array.isArray(state.workouts) ? state.workouts : []).filter(w => w && !inBackup.has(key(w))).length+ return workouts ? { workouts, state, rev: res.rev } : null+ },+ // A backup in place of this copy. With `mergeWith` — importConflict's answer — the server's copy+ // is merged in instead of replaced: the backup's settings and plan, every entry of both+ // (mergeStates with the backup preferred, in the backup's unit), pushed against that revision+ // like any other change, so a workout logged meanwhile elsewhere is not lost either.+ importBackup(backup, { mergeWith } = {}) {+ const next = Object.assign(clone(DEF), backup)+ if (!mergeWith?.state || !get().user) { get().replaceState(next, !!get().user); return }+ const merged = Object.assign(clone(DEF), mergeStates(next, mergeWith.state, { prefer: 'a' }))+ merged.active = next.active || null+ persist(merged, true)+ if (mergeWith.rev != null) writeSync(mergeWith.rev, 0)+ },// A replace that is meant to reach the server (backup import, reset) is a deliberate// overwrite, not a change to merge: the push it arms goes without a baseRev.replaceState(S, push = false) { if (push) forceNext = true; persist(clone(S), push) },@@ -833,7 +1021,9 @@ export const useStore = create((set, get) => {return configFetch},- setUser(u) {+ // `adopt` (a sign-in, a pairing — { alwaysAsk } for a device link): adoptProfile follows and+ // decides what becomes of this copy; until it has, nothing is pulled or pushed (ADOPT_KEY).+ setUser(u, { adopt } = {}) {if (u) {// 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@@ -845,6 +1035,20 @@ export const useStore = create((set, get) => {const owner = localStorage.getItem('gym_owner')rejoined = owner === u.idconst other = !!owner && owner !== u.id+ // The hold goes on before anything else can run: a poll, a resume, a debounced push.+ if (adopt) {+ adoptHold = true+ adoptClaimed = true+ clearTimeout(pushTm)+ pushTm = null+ writeAdopt({ uid: u.id, rejoined, alwaysAsk: !!adopt.alwaysAsk })+ } else {+ // Boot signing the account back in: an adoption it still owes holds sync until it is+ // answered (resumeAdoption); one another account left behind is void.+ const m = readAdopt()+ if (m && m.uid !== u.id) writeAdopt(null)+ adoptHold = !!m && m.uid === u.id+ }if (other) {keepForPrevious(owner)forgetSync()@@ -865,7 +1069,7 @@ export const useStore = create((set, get) => {// nothing on this path waits for the answer. A copy that has the key was made for a// session and is already the right answer, Coach or no Coach.if (get().config && !('coach' in get().config)) get().refreshConfig()- } else { rejoined = false; localStorage.removeItem('gym_user') }+ } else { rejoined = false; adoptHold = false; adoptClaimed = false; localStorage.removeItem('gym_user') }set({ user: u })setSync({})},@@ -877,6 +1081,7 @@ export const useStore = create((set, get) => {if (!get().user) returnclearTimeout(pushTm)pushTm = null+ if (adoptHold) return // the sign-in has not decided what this copy is yet (adoptProfile)if (pushing) { pushAgain = true; return pushing.then(() => pushing) }pushing = doPush().finally(() => {pushing = null@@ -888,6 +1093,7 @@ export const useStore = create((set, get) => {// in the debounce goes first — the server's answer is then the one that already includes it,// and the push itself is what catches a conflict.async pullState() {+ if (adoptHold) return // as pushState: adoptProfile reads the server itselfif (pulling) return pullingpulling = (async () => {try {@@ -924,7 +1130,7 @@ export const useStore = create((set, get) => {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 (!changed) { adopt(Object.assign(clone(DEF), state, { active: S.active || null }), rev); confirmed(get().S); return }+ if (!changed) { const next = Object.assign(clone(DEF), state); next.active = carryActive(S, next); adopt(next, rev); confirmed(get().S); return }mergeInto(S, state, rev)pushPending = falseawait get().pushState()@@ -989,70 +1195,32 @@ export const useStore = create((set, get) => {// the code chooses it — so what a guest logged here is not moved into it unasked, not even// into one with no state yet, where it would otherwise go without a word. Declined, this// device takes that empty profile as it is, the way it takes a profile that has state.- async adoptProfile(ask, { alwaysAsk = false } = {}) {- if (pulling) await pulling- 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 anyway- const { state, rev } = res- const S = get().S- reached()- const askAbout = async extras =>- (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 (!state) {- const push = hasData(S) && (!alwaysAsk || sameAccount || await askAbout(localExtras(S, null)))- if (hasData(S) && !push) {- if (rev != null) adopt(serverCopy, rev)- else { dropSync(); persist(serverCopy, false, false); markOwed(false) }- confirmed(get().S)- await applyStash()- return { adopted: true, added: false }- }- markOwed(false)- if (push) { if (rev != null) writeSync(rev, 0); forceNext = true; await get().pushState() }- else { if (rev != null) writeSync(rev, 0); confirmed(get().S) }- await applyStash()- return { adopted: false, added: false }- }- 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 keep = await askAbout(localExtras(S, state))- if (keep) {- const merged = Object.assign(clone(DEF), mergeStates(state, S, { prefer: 'a' }))- merged.active = S.active || null- persist(merged, false)- if (rev != null) writeSync(rev, 0)- else dropSync()- await get().pushState()- await applyStash()- return { adopted: true, added: true }- }- if (rev != null) adopt(serverCopy, rev)- else { dropSync(); persist(serverCopy, false, false); markOwed(false) }- confirmed(get().S)- await applyStash()- return { adopted: true, added: false }+ //+ // Nothing syncs from the sign-in until the answer is in (setUser's `adopt`, ADOPT_KEY): a poll or+ // a resume pull in the meantime took the device's copy for a newer one of the account's and+ // pushed it over the profile. And the answer is applied to the server's copy as it is once the+ // question closes, not as it was when it opened — another device may have written meanwhile.+ // Calls made while one is running get that one.+ adoptProfile(ask, opts = {}) {+ if (adopting) return adopting+ adoptHold = true+ adoptClaimed = false+ adopting = runAdopt(ask, opts).finally(() => { adopting = null })+ return adopting+ },+ // The adoption a sign-in still owes — the app was closed with its question open, or the server+ // could not be reached for it: asked again, with the sign-in's own question.+ async resumeAdoption(ask) {+ const m = adoptOwed()+ if (!m) { if (adoptHold && !adopting && !adoptClaimed) releaseAdopt(); return null }+ if (adopting) return adopting+ try {+ if (typeof ask !== 'function') ask = (await import('../sheets.jsx')).askAddDeviceData+ const r = await get().adoptProfile(ask, { alwaysAsk: !!m.alwaysAsk })+ // A phone whose pairing ended here: what connectToServer does after its own adoption.+ if (MOBILE) { await nativePersist(true); if (get().needsMobileOnboarding) set({ needsMobileOnboarding: false }) }+ return r+ } catch { return null }},/* Signing out wipes this device's copy — never while it holds changes the server has not@@ -1088,7 +1256,7 @@ export const useStore = create((set, get) => {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)+ get().setUser(user, { adopt: true })if (keeping) { await keeping; keeping = null }pairedBase = normalizeServerUrl(url)setSync({ server: pairedBase })@@ -1162,6 +1330,14 @@ export const useStore = create((set, get) => {// 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()+ // Closed with the pairing's question still open: asked again, and nothing is pulled+ // or pushed until it is answered — this copy may still be the one from before pairing.+ if (adoptOwed()) {+ syncReminder(get().S)+ finishBoot()+ get().resumeAdoption()+ return+ }await get().pullState()if (!get().sync.lastError) await applyStash() // only once the server really answered} catch (e) {@@ -1233,6 +1409,9 @@ export const useStore = create((set, get) => {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)+ // Closed with the sign-in's question still open: asked again once the app is up (see the+ // phone's boot above).+ if (adoptOwed()) { finishBoot(); get().resumeAdoption(); return }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,diff --git a/frontend/src/store/useStore.media-backup.test.jsx b/frontend/src/store/useStore.media-backup.test.jsxnew file mode 100644index 000000000..f25024614--- /dev/null+++ b/frontend/src/store/useStore.media-backup.test.jsx@@ -0,0 +1,68 @@+// @vitest-environment happy-dom++/* QA, v1.3.9: the phone's auto-backup is written when a workout is finished — before the finish+ screen offers to add its photos and videos, so the day's backup never had them. A change to a+ workout's media now writes it again, once for a batch picked together. */+import { afterEach, describe, expect, it, vi } from 'vitest'++const h = vi.hoisted(() => {+ vi.stubEnv('VITE_MOBILE', '1')+ return { files: new Map() }+})+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 } },+ readdir: async () => ({ files: [] }),+ deleteFile: async () => {},+ },+}))+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: () => {} }) } }))++import { DEF, useStore } from './useStore.js'+import { addWorkoutMedia, removeWorkoutMedia } from '../lib/workout-media.js'++const clone = v => JSON.parse(JSON.stringify(v))+const sleep = ms => new Promise(r => setTimeout(r, ms))+const W = { id: 'w1', d: '2026-09-27', start: 1, end: 2, entries: [] }+const ref = c => ({ kind: 'image', hash: c.repeat(64), mime: 'image/webp', size: 3, width: 8, height: 6, at: 1 })+const backups = () => [...h.files].filter(([k]) => k.startsWith('DOCUMENTS/')).map(([, v]) => JSON.parse(v))++afterEach(() => { h.files.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })++describe('auto-backup and a workout\'s photos and videos', () => {+ it('a photo added after finishing is in the day\'s backup, one write for two picked together', async () => {+ useStore.setState({ S: { ...clone(DEF), autoBackup: true, workouts: [clone(W)] }, ready: true })+ useStore.getState().update(s => { addWorkoutMedia(s, W, ref('a')) })+ useStore.getState().update(s => { addWorkoutMedia(s, W, ref('b')) })+ await sleep(2300)+ const all = backups()+ expect(all).toHaveLength(1)+ expect(all[0].workouts[0].media.map(m => m.hash)).toEqual(['a'.repeat(64), 'b'.repeat(64)])++ h.files.clear()+ useStore.getState().update(s => { removeWorkoutMedia(s, W, 'a'.repeat(64)) })+ await sleep(2300)+ expect(backups()[0].workouts[0].media.map(m => m.hash)).toEqual(['b'.repeat(64)])+ })++ it('nothing written for other changes, or with the setting off', async () => {+ useStore.setState({ S: { ...clone(DEF), autoBackup: true, workouts: [clone(W)] }, ready: true })+ useStore.getState().update(s => { s.restSec = 60 })+ useStore.setState({ S: { ...clone(DEF), autoBackup: false, workouts: [clone(W)] } })+ useStore.getState().update(s => { addWorkoutMedia(s, W, ref('a')) })+ await sleep(2300)+ expect(backups()).toHaveLength(0)+ })+})diff --git a/frontend/src/store/useStore.plan-sync.test.jsx b/frontend/src/store/useStore.plan-sync.test.jsxindex 42667a9c7..f2a6158bb 100644--- a/frontend/src/store/useStore.plan-sync.test.jsx+++ b/frontend/src/store/useStore.plan-sync.test.jsx@@ -18,7 +18,7 @@ import { api } from '../lib/api.js'import { DEF, useStore } from './useStore.js'import { buildCombinedEntries } from '../lib/session-merge.js'import { buildCompletedWorkout } from '../lib/finish-workout.js'-import { convertStateUnit, convertWeight } from '../lib/units.js'+import { convertWeight } from '../lib/units.js'import { isWarmupRow } from '../lib/workout-model.js'const BENCH = '0025' // barbell bench press — loaded, 2.5 kg step@@ -148,7 +148,7 @@ describe('converting the numbers to lb', () => {useStore.setState({ S, user: null, ready: true })// What Settings → Units → "Convert the numbers" does.- useStore.getState().replaceState(convertStateUnit(useStore.getState().S, 'lb'))+ useStore.getState().setUnit('lb')const lb = useStore.getState().Sexpect(lb.workouts[0].entries[0].planned.weight).toBe(benchOf(lb).weight)expect(benchOf(lb).weight).toBe(convertWeight(100, 'kg', 'lb'))diff --git a/frontend/src/store/useStore.reset-sync.test.jsx b/frontend/src/store/useStore.reset-sync.test.jsxnew file mode 100644index 000000000..e08905bd0--- /dev/null+++ b/frontend/src/store/useStore.reset-sync.test.jsx@@ -0,0 +1,70 @@+// @vitest-environment happy-dom++/* QA, v1.3.9 (t8): "Reset everything" on one device was undone by the next device that pushed a+ change of its own — its push got the 409, the merge took the union, and the wiped profile was+ back. The reset now carries its time (`resetAt`) and a merge with a copy that has not seen it+ keeps only what that copy made after it (lib/sync-merge.js). */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn() }) } }))++import { api } from '../lib/api.js'+import { DEF, useStore } from './useStore.js'++const clone = v => JSON.parse(JSON.stringify(v))+const ids = xs => (xs || []).map(x => x.id)+const workout = (id, end) => ({ id, d: '2026-09-20', start: end - 1000, end, entries: [] })+const puts = () => api.mock.calls.filter(([, o]) => o?.method === 'PUT').map(([, o]) => JSON.parse(o.body))+const conflict = (state, rev) => Object.assign(new Error('conflict'), { status: 409, data: { state, rev } })+const signedIn = (S, rev) => {+ localStorage.setItem('gym_sync', JSON.stringify({ rev, ts: S._ts }))+ useStore.setState({ S, user: { id: 'u1' }, ready: true, sync: { offline: false, pending: false, lastSynced: 0 } })+}+const PROFILE = { ...clone(DEF), _ts: 100, workouts: [workout('w1', 50), workout('w2', 60)], routines: [{ id: 'r1', name: 'A', ex: [], _ts: 10 }], bodyweight: [{ d: '2026-09-01', w: 80, t: 10 }] }++beforeEach(() => { localStorage.clear(); api.mockReset() })+afterEach(() => { localStorage.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })++describe('Reset everything', () => {+ it('replaces the server copy with the empty one, stamped with when', async () => {+ signedIn(clone(PROFILE), 3)+ api.mockResolvedValueOnce({ ok: true, rev: 4 })+ const before = Date.now()+ useStore.getState().resetEverything()+ await useStore.getState().pushState()+ const [put] = puts()+ expect(put.baseRev).toBeUndefined()+ expect(put.state.workouts).toEqual([])+ expect(put.state.resetAt).toBeGreaterThanOrEqual(before)+ })++ it('a device that has not seen it and pushes a change from before keeps the reset, not the old profile', async () => {+ signedIn(clone(PROFILE), 3)+ useStore.getState().update(s => { s.restSec = 45 }) // a change made before the reset, unsent+ const resetAt = Date.now() + 1000+ const serverReset = { ...clone(DEF), _ts: resetAt, resetAt, _rev: 4 }+ api.mockRejectedValueOnce(conflict(serverReset, 4))+ api.mockResolvedValueOnce({ ok: true, rev: 5 })+ await useStore.getState().pushState()++ const put = puts().at(-1)+ expect(put.baseRev).toBe(4)+ expect(put.state.workouts).toEqual([])+ expect(put.state.routines).toEqual([])+ expect(put.state.bodyweight).toEqual([])+ expect(put.state.resetAt).toBe(resetAt)+ expect(useStore.getState().S.workouts).toEqual([])+ })++ it('what that device logged after the reset is kept', async () => {+ const resetAt = Date.now() - 60000+ signedIn(clone(PROFILE), 3)+ useStore.getState().update(s => { s.workouts.push(workout('after', Date.now())) })+ const serverReset = { ...clone(DEF), _ts: resetAt, resetAt, _rev: 4 }+ api.mockRejectedValueOnce(conflict(serverReset, 4))+ api.mockResolvedValueOnce({ ok: true, rev: 5 })+ await useStore.getState().pushState()+ expect(ids(puts().at(-1).state.workouts)).toEqual(['after'])+ })+})diff --git a/frontend/src/store/useStore.unit-sync.test.jsx b/frontend/src/store/useStore.unit-sync.test.jsxnew file mode 100644index 000000000..63fcd5c00--- /dev/null+++ b/frontend/src/store/useStore.unit-sync.test.jsx@@ -0,0 +1,97 @@+// @vitest-environment happy-dom++/* QA, v1.3.9 (t9): Settings → kg to lb → "Convert the numbers" on one device while another,+ still in kg, logs a weigh-in. The conversion was not pushed, and the merge knew nothing of+ units: the server ended in kg with the numbers back in kg — and the kept loads still in lb under+ the kg label (55 kg became 121.5 kg). Now the conversion goes to the server at once, and a merge+ brings a copy in the other unit over before anything is compared (lib/sync-merge.js). */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn() }) } }))++import { api } from '../lib/api.js'+import { DEF, useStore } from './useStore.js'+import { convertBodyWeight, convertStateUnit, convertWeight } from '../lib/units.js'++const clone = v => JSON.parse(JSON.stringify(v))+const TODAY = '2026-09-27'+const workout = (id, w) => ({ id, d: '2026-09-20', start: 1, end: 2, entries: [{ id: '0025', sets: [{ w, r: 5, done: true }] }] })+const puts = () => api.mock.calls.filter(([, o]) => o?.method === 'PUT').map(([, o]) => JSON.parse(o.body))+const conflict = (state, rev) => Object.assign(new Error('conflict'), { status: 409, data: { state, rev } })+const signedIn = (S, rev) => {+ localStorage.setItem('gym_sync', JSON.stringify({ rev, ts: S._ts }))+ useStore.setState({ S, user: { id: 'u1' }, ready: true, sync: { offline: false, pending: false, lastSynced: 0 } })+}+// The profile both devices started from: rev 1, in kg.+const KG = { ...clone(DEF), _ts: 100, unit: 'kg', workouts: [workout('w1', 60)], bodyweight: [{ d: '2026-09-20', w: 80, t: 50 }], exWeights: { '0025': { w: 55, d: '2026-09-20' } } }++beforeEach(() => { localStorage.clear(); api.mockReset() })+afterEach(() => { localStorage.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })++describe('converting the unit while another device logs in the old one', () => {+ it('the converting device pushes at once, and a kg copy that landed first is converted before the merge', async () => {+ signedIn(clone(KG), 1)+ // the other device's weigh-in, in kg, reached the server first (rev 2)+ const serverKg = { ...clone(KG), _ts: 300, bodyweight: [...KG.bodyweight, { d: TODAY, w: 81, t: 300 }], _rev: 2 }+ api.mockRejectedValueOnce(conflict(serverKg, 2))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })++ await useStore.getState().setUnit('lb')++ const [first, second] = puts()+ expect(first.baseRev).toBe(1) // an ordinary conditional push, straight away+ expect(first.state.unit).toBe('lb')+ expect(second.baseRev).toBe(2)+ const S = second.state+ expect(S.unit).toBe('lb')+ expect(S.bodyweight.find(b => b.d === TODAY).w).toBe(convertBodyWeight(81, 'kg', 'lb'))+ expect(S.bodyweight.find(b => b.d === '2026-09-20').w).toBe(convertBodyWeight(80, 'kg', 'lb'))+ expect(S.workouts[0].entries[0].sets[0].w).toBe(convertWeight(60, 'kg', 'lb'))+ expect(S.exWeights['0025'].w).toBe(convertWeight(55, 'kg', 'lb'))+ expect(useStore.getState().S.unit).toBe('lb')+ })++ it('the device still in kg merges the converted profile into lb, its own weigh-in converted with it', async () => {+ signedIn(clone(KG), 1)+ // the other device converted and pushed (rev 2); this one logs a weigh-in in kg on rev 1+ const serverLb = { ...convertStateUnit(clone(KG), 'lb'), _ts: 200, unitSet: { at: 200, convert: true }, _rev: 2 }+ useStore.getState().update(s => { s.bodyweight.push({ d: TODAY, w: 81, t: Date.now() }) })+ api.mockRejectedValueOnce(conflict(serverLb, 2))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })+ await useStore.getState().pushState()++ const S = puts().at(-1).state+ expect(puts().at(-1).baseRev).toBe(2)+ expect(S.unit).toBe('lb') // the later choice holds+ expect(S.bodyweight.find(b => b.d === TODAY).w).toBe(convertBodyWeight(81, 'kg', 'lb'))+ expect(S.workouts[0].entries[0].sets[0].w).toBe(convertWeight(60, 'kg', 'lb'))+ // never the lb number under a kg label, nor the kg number under an lb one+ expect(S.exWeights['0025'].w).toBe(convertWeight(55, 'kg', 'lb'))+ expect(useStore.getState().S.unit).toBe('lb')+ })++ it('a running workout on the device still in kg comes over in lb with the merge', async () => {+ const active = { id: 'run', d: TODAY, start: 5, entries: [{ id: '0025', sets: [{ w: 100, r: 5 }] }] }+ signedIn({ ...clone(KG), active }, 1)+ const serverLb = { ...convertStateUnit(clone(KG), 'lb'), _ts: 200, unitSet: { at: 200, convert: true }, _rev: 2 }+ useStore.getState().update(s => { s.restSec = 75 })+ api.mockRejectedValueOnce(conflict(serverLb, 2))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })+ await useStore.getState().pushState()+ expect(useStore.getState().S.active.entries[0].sets[0].w).toBe(convertWeight(100, 'kg', 'lb'))+ })++ it('"Keep the numbers, change the label" relabels the other copy instead of converting it', async () => {+ signedIn(clone(KG), 1)+ const serverLb = { ...clone(KG), unit: 'lb', _ts: 200, unitSet: { at: 200, convert: false }, _rev: 2 }+ useStore.getState().update(s => { s.bodyweight.push({ d: TODAY, w: 180, t: Date.now() }) })+ api.mockRejectedValueOnce(conflict(serverLb, 2))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })+ await useStore.getState().pushState()+ const S = puts().at(-1).state+ expect(S.unit).toBe('lb')+ expect(S.bodyweight.find(b => b.d === TODAY).w).toBe(180)+ expect(S.exWeights['0025'].w).toBe(55)+ })+})diff --git a/frontend/src/views/Login.jsx b/frontend/src/views/Login.jsxindex 39eaa5c0f..0429b07f9 100644--- a/frontend/src/views/Login.jsx+++ b/frontend/src/views/Login.jsx@@ -72,7 +72,7 @@ export default function Login() {const pwOn = passwordOn(config)const register = () => useUI.getState().openSheet(close => <RegisterSheet close={close} />)const signIn = async () => {- try { const u = await passkeyLogin(); setUser(u); await adoptProfile(askAddDeviceData); useUI.getState().toast(t('Welcome back, {0}', u.name)) }+ try { const u = await passkeyLogin(); setUser(u, { adopt: true }); await adoptProfile(askAddDeviceData); useUI.getState().toast(t('Welcome back, {0}', u.name)) }catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || t('Sign-in failed')) }}const head = <>diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex b83fe942e..7ff047a8f 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -2,7 +2,6 @@ import { useEffect, useRef, useState, forwardRef, useSyncExternalStore } from 'rimport { useNavigate } from 'react-router-dom'import { useStore, DEF, hasData } from '../store/useStore.js'import { workoutControls } from '../lib/workout-controls.js'-import { convertStateUnit } from '../lib/units.js'import { speedUnitOf } from '../lib/speed.js'import { copyText } from '../lib/clipboard.js'import { useUI } from '../store/useUI.js'@@ -48,7 +47,7 @@ export default function Settings() {const passkeys = usePasskeys(!!user && !MOBILE && !DEMO)const [credsV, setCredsV] = useState(0)const credsChanged = () => { passkeys.load(); setCredsV(v => v + 1) }- const { update, replaceState, setUser, pullState, pushState, resetDemo } = useStore()+ const { update, importConflict, importBackup, setUnit, resetEverything: resetAll, setUser, pullState, pushState, resetDemo } = useStore()const toast = useUI(s => s.toast)const fileRef = useRef(null)const importRef = useRef(null)@@ -63,8 +62,8 @@ export default function Settings() {title: t('Convert to {0}?', v),subtitle: t('Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?', S.unit),items: [- { icon: 'shuffle', label: t('Convert the numbers'), onClick: () => replaceState(convertStateUnit(useStore.getState().S, v)) },- { icon: 'pencil', label: t('Keep the numbers, change the label'), onClick: () => update(s => { s.unit = v }) },+ { icon: 'shuffle', label: t('Convert the numbers'), onClick: () => setUnit(v) },+ { icon: 'pencil', label: t('Keep the numbers, change the label'), onClick: () => setUnit(v, { convert: false }) },],})}@@ -187,16 +186,36 @@ export default function Settings() {const { readBackupFile } = await import('../lib/backup-media.js')read = await readBackupFile(f)} catch (e) { toast(t('Import failed: {0}', e.message)); return }+ const apply = async mergeWith => {+ if (read.files.length) {+ const { storeBackupMedia } = await import('../lib/backup-media.js')+ await storeBackupMedia(read.files, { limits: limitsFrom(useStore.getState().config) })+ }+ importBackup(read.state, { mergeWith })+ toast(t('Backup imported'))+ }+ // Signed in, the server is asked first: a workout logged since the backup was made, or on+ // another device meanwhile, would be deleted from the profile by the replace — said, with the+ // choice to merge those in instead (useStore importConflict / importBackup).+ const conflict = await importConflict(read.state)+ if (conflict) {+ const n = conflict.workouts+ menuSheet({+ title: t('Import backup?'),+ subtitle: t(n === 1+ ? 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.'+ : 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.', n),+ items: [+ { icon: 'trash', label: t('Replace anyway'), danger: true, onClick: () => apply(null) },+ { icon: 'shuffle', label: t('Merge them in'), onClick: () => apply(conflict) },+ { icon: 'xmark', label: t('Cancel'), onClick: () => {} },+ ],+ })+ return+ }confirmSheet({title: t('Import backup?'), message: t('This replaces all current data with the backup file.'), confirmText: t('Import'), danger: true,- onConfirm: async () => {- if (read.files.length) {- const { storeBackupMedia } = await import('../lib/backup-media.js')- await storeBackupMedia(read.files, { limits: limitsFrom(useStore.getState().config) })- }- replaceState(Object.assign(JSON.parse(JSON.stringify(DEF)), read.state), true)- toast(t('Backup imported'))- }+ onConfirm: () => apply(null)})}// Whether any custom exercise has a photo or video: the rows about them only show then.@@ -244,7 +263,7 @@ export default function Settings() {onConfirm: () => {if (user) api('/api/coach/forget', { method: 'POST', body: '{}' }).catch(() => {})if (coachLocal?.mode === 'byok') forgetCoach().catch(() => {})- replaceState(JSON.parse(JSON.stringify(DEF)), true)+ resetAll()nav('/home'); toast(t('All data reset'))clearMediaAfterReset(!!user).catch(() => {})},diff --git a/frontend/src/views/Settings.media.test.jsx b/frontend/src/views/Settings.media.test.jsxindex 1a04cb90b..1e380fd55 100644--- a/frontend/src/views/Settings.media.test.jsx+++ b/frontend/src/views/Settings.media.test.jsx@@ -17,6 +17,10 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = trueconst mocks = vi.hoisted(() => {const state = { S: null, user: null, config: null, sync: { status: 'ok' }, stashed: new Set() }state.replaceState = vi.fn()+ state.importBackup = vi.fn()+ state.resetEverything = vi.fn()+ state.menuSheet = vi.fn()+ state.conflict = nullstate.pushState = vi.fn(async () => {})state.confirmSheet = vi.fn()state.api = vi.fn(() => Promise.resolve({ ok: true }))@@ -30,7 +34,8 @@ const mocks = vi.hoisted(() => {update: vi.fn(), replaceState: state.replaceState, setUser: vi.fn(), pullState: vi.fn(), pushState: state.pushState,signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),syncNow: vi.fn(), unsyncedChanges: () => ({ owed: false, count: 0 }), keptChanges: state.keptChanges,- stashedMediaHashes: async () => state.stashed+ stashedMediaHashes: async () => state.stashed,+ importConflict: async () => state.conflict, importBackup: state.importBackup, resetEverything: state.resetEverything})return state})@@ -56,7 +61,7 @@ vi.mock('../lib/coach-api.js', () => ({ forgetCoach: vi.fn(() => Promise.resolvevi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))vi.mock('../sheets.jsx', () => ({starterPlanSheet: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a), importFromApp: vi.fn(),- importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(), askAddDeviceData: vi.fn(),+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: (...a) => mocks.menuSheet(...a), askAddDeviceData: vi.fn(),}))globalThis.__APP_VERSION__ ??= 'test'@@ -85,7 +90,8 @@ beforeEach(async () => {mocks.config = nullmocks.sync = { status: 'ok' }mocks.stashed = new Set()- for (const f of [mocks.replaceState, mocks.pushState, mocks.confirmSheet, mocks.api, mocks.toast]) f.mockClear()+ mocks.conflict = null+ for (const f of [mocks.replaceState, mocks.importBackup, mocks.resetEverything, mocks.menuSheet, mocks.pushState, mocks.confirmSheet, mocks.api, mocks.toast]) f.mockClear()host = document.createElement('div')document.body.appendChild(host)root = createRoot(host)@@ -173,9 +179,30 @@ describe('Settings — photos and videos', () => {expect(await media.has(HASH)).toBe(false) // nothing before the confirmawait act(async () => { await mocks.confirmSheet.mock.calls[0][0].onConfirm() })expect(await media.get(HASH)).toMatchObject({ mime: 'image/jpeg', pending: true })- expect(mocks.replaceState).toHaveBeenCalledTimes(1)- expect(mocks.replaceState.mock.calls[0][0].customEx[0].media.hash).toBe(HASH)- expect(mocks.replaceState.mock.calls[0][1]).toBe(true)+ expect(mocks.importBackup).toHaveBeenCalledTimes(1)+ expect(mocks.importBackup.mock.calls[0][0].customEx[0].media.hash).toBe(HASH)+ expect(mocks.importBackup.mock.calls[0][1]).toEqual({ mergeWith: null }) // the replace+ })++ // QA, v1.3.9: the import replaced a workout another device had synced meanwhile, unsaid.+ it('importing over a server that has workouts the backup lacks says how many, and can merge them in', async () => {+ mocks.user = { id: 'u1', name: 'Ana' }+ mocks.conflict = { workouts: 2, state: { workouts: [] }, rev: 9 }+ const S = stateWithPhoto()+ await mount()+ const input = host.querySelector('input[type="file"][accept^=".json"]')+ Object.defineProperty(input, 'files', { value: [new File([JSON.stringify(S)], 'backup.json')], configurable: true })+ act(() => { input.dispatchEvent(new Event('change', { bubbles: true })) })+ await until(() => mocks.menuSheet.mock.calls.length > 0)+ expect(mocks.confirmSheet).not.toHaveBeenCalled()+ const sheet = mocks.menuSheet.mock.calls[0][0]+ expect(sheet.subtitle).toBe('The server has 2 workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.')+ expect(sheet.items.map(i => i.label)).toEqual(['Replace anyway', 'Merge them in', 'Cancel'])+ await act(async () => { await sheet.items[1].onClick() })+ expect(mocks.importBackup).toHaveBeenCalledTimes(1)+ expect(mocks.importBackup.mock.calls[0][1]).toEqual({ mergeWith: mocks.conflict })+ await act(async () => { await sheet.items[0].onClick() })+ expect(mocks.importBackup.mock.calls[1][1]).toEqual({ mergeWith: null })})it('Reset, signed in: pushes, asks the server to sweep, and keeps only what a stash refers to', async () => {diff --git a/frontend/src/views/Settings.reset.test.jsx b/frontend/src/views/Settings.reset.test.jsxindex 8b9b17112..73007d4fc 100644--- a/frontend/src/views/Settings.reset.test.jsx+++ b/frontend/src/views/Settings.reset.test.jsx@@ -13,6 +13,7 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = trueconst mocks = vi.hoisted(() => {const state = { S: null, user: null, coachLocal: null }state.replaceState = vi.fn()+ state.resetEverything = vi.fn()state.confirmSheet = vi.fn()state.forgetCoach = vi.fn(() => Promise.resolve({ ok: true }))state.api = vi.fn(() => Promise.resolve({ ok: true }))@@ -26,7 +27,7 @@ const mocks = vi.hoisted(() => {mut(next)state.S = next},- replaceState: state.replaceState, setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),+ replaceState: state.replaceState, resetEverything: state.resetEverything, setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),})return state@@ -67,6 +68,7 @@ beforeEach(() => {mocks.user = nullmocks.coachLocal = nullmocks.replaceState.mockClear()+ mocks.resetEverything.mockClear()mocks.confirmSheet.mockClear()mocks.forgetCoach.mockClear()mocks.api.mockClear()@@ -96,8 +98,8 @@ describe('Settings — reset everything', () => {expect(dialog.title).toBe('Reset everything?')expect(dialog.message).toBe('Deletes your plan, workouts and body weight on this device. This cannot be undone.')act(() => { dialog.onConfirm() })- expect(mocks.replaceState).toHaveBeenCalledTimes(1)- expect(mocks.replaceState.mock.calls[0]).toEqual([{ reminder: { time: '17:30' }, workouts: [] }, true])+ // the store's reset: the empty copy, stamped (useStore resetEverything)+ expect(mocks.resetEverything).toHaveBeenCalledTimes(1)expect(serverForgetCalls()).toHaveLength(0)expect(mocks.forgetCoach).not.toHaveBeenCalled()expect(mocks.toast).toHaveBeenCalledWith('All data reset')@@ -112,8 +114,7 @@ describe('Settings — reset everything', () => {expect(serverForgetCalls()).toHaveLength(1)expect(serverForgetCalls()[0][1]).toEqual({ method: 'POST', body: '{}' })expect(mocks.forgetCoach).not.toHaveBeenCalled() // no device Coach here- expect(mocks.replaceState).toHaveBeenCalledTimes(1)- expect(mocks.replaceState.mock.calls[0][1]).toBe(true)+ expect(mocks.resetEverything).toHaveBeenCalledTimes(1)expect(mocks.toast).toHaveBeenCalledWith('All data reset')})@@ -124,7 +125,7 @@ describe('Settings — reset everything', () => {const dialog = openDialog()await act(async () => { dialog.onConfirm(); await Promise.resolve() })expect(serverForgetCalls()).toHaveLength(1)- expect(mocks.replaceState).toHaveBeenCalledTimes(1)+ expect(mocks.resetEverything).toHaveBeenCalledTimes(1)expect(mocks.toast).toHaveBeenCalledWith('All data reset')})@@ -137,7 +138,7 @@ describe('Settings — reset everything', () => {act(() => { dialog.onConfirm() })expect(serverForgetCalls()).toHaveLength(1)expect(mocks.forgetCoach).toHaveBeenCalledTimes(1)- expect(mocks.replaceState).toHaveBeenCalledTimes(1)+ expect(mocks.resetEverything).toHaveBeenCalledTimes(1)expect(mocks.toast).toHaveBeenCalledWith('All data reset')})@@ -148,6 +149,6 @@ describe('Settings — reset everything', () => {act(() => { dialog.onConfirm() })expect(serverForgetCalls()).toHaveLength(0)expect(mocks.forgetCoach).toHaveBeenCalledTimes(1)- expect(mocks.replaceState).toHaveBeenCalledTimes(1)+ expect(mocks.resetEverything).toHaveBeenCalledTimes(1)})})