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
A reset names what it wiped and never goes back, so a restored backup, an old import or a device with a slow clock keep their workouts; a sign-in's question can no longer hold sync for good
Duarte Santose8977abc3306
diff --git a/api/server.js b/api/server.jsindex 2b09f209c..8493cfe2f 100644--- a/api/server.js+++ b/api/server.js@@ -2024,6 +2024,17 @@ const routes = {return json(res, 409, { error: 'conflict', rev: curRev, state: cur });}delete body.state.active; // in-progress workouts stay device-local+ // "Reset everything" stamps the profile (`resetAt`, with `resetIds`: what it wiped). The stamp+ // only moves forward: a write without it, or with an older one — a client from before it, a+ // backup restored over the profile — keeps the stored stamp. Otherwise every device that saw+ // the reset would take that copy for one older than the reset, and wipe it again on its next+ // merge (frontend/src/lib/sync-merge.js).+ const storedReset = Number(cur?.resetAt) || 0;+ if (storedReset > (Number(body.state.resetAt) || 0)) {+ body.state.resetAt = cur.resetAt;+ if (cur.resetIds && typeof cur.resetIds === 'object') body.state.resetIds = cur.resetIds;+ else delete body.state.resetIds;+ }body.state._rev = curRev + 1; // server-owned; whatever the client sent is ignoredatomicWrite(stateFile(user.id), JSON.stringify(body.state));// The stat cache cannot see this write on its own: mtime granularity is 4 ms here (ext4 ondiff --git a/api/test/server-data-reset.test.js b/api/test/server-data-reset.test.jsnew file mode 100644index 000000000..255676e35--- /dev/null+++ b/api/test/server-data-reset.test.js@@ -0,0 +1,86 @@+/* "Reset everything" stamps the profile with `resetAt` (and `resetIds`, the names it wiped). The+ stamp only moves forward on the server: a write without it, or with an older one — a client from+ before it, a backup restored over the profile — keeps the stored one, so the devices that saw+ the reset do not take the restored copy for one from before it and wipe it again. Real+ server.js in a child. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { boundPort } from './helpers.mjs';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');+const UID = 'u_reset_1';++function mintSession(uid, sv = 0) {+ const payload = `${uid}:${Date.now() + 86400000}:${sv}`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+}+const headers = () => ({ Cookie: `gymsid=${mintSession(UID)}`, 'Content-Type': 'application/json' });++async function startServer(t) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-reset-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({+ users: [{ id: UID, name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: []+ }));+ const child = spawn(process.execPath, ['server.js'], {+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }+ });+ const h = { log: '', dataDir };+ child.stdout.on('data', d => h.log += d);+ child.stderr.on('data', d => h.log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ h.port = await boundPort(child, () => h.log);+ h.api = `http://127.0.0.1:${h.port}`;+ return h;+}++test('PUT /api/data keeps the reset stamp when a write lacks it or carries an older one', async t => {+ const h = await startServer(t);+ const put = async body => {+ const r = await fetch(`${h.api}/api/data`, { method: 'PUT', headers: headers(), body: JSON.stringify(body) });+ return { status: r.status, body: await r.json() };+ };+ const onDisk = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, `state-${UID}.json`), 'utf8'));+ const ids = { workouts: ['w-old'] };++ // the reset+ let r = await put({ state: { _ts: 100, workouts: [], routines: [], resetAt: 5000, resetIds: ids } });+ assert.equal(r.status, 200);+ assert.equal(onDisk().resetAt, 5000);++ // a backup restored over it, with no stamp: its workouts land, the stamp stays+ r = await put({ state: { _ts: 50, workouts: [{ id: 'w-old', d: '2026-01-01' }], routines: [] } });+ assert.equal(r.status, 200);+ assert.deepEqual(onDisk().workouts.map(w => w.id), ['w-old']);+ assert.equal(onDisk().resetAt, 5000);+ assert.deepEqual(onDisk().resetIds, ids);++ // an older stamp does not take it back either+ r = await put({ state: { _ts: 60, workouts: [], routines: [], resetAt: 10, resetIds: { workouts: ['x'] } }, baseRev: 2 });+ assert.equal(r.status, 200);+ assert.equal(onDisk().resetAt, 5000);+ assert.deepEqual(onDisk().resetIds, ids);++ // a later reset moves it forward+ r = await put({ state: { _ts: 70, workouts: [], routines: [], resetAt: 9000, resetIds: { workouts: ['w-new'] } } });+ assert.equal(r.status, 200);+ assert.equal(onDisk().resetAt, 9000);+ assert.deepEqual(onDisk().resetIds, { workouts: ['w-new'] });+});++test('PUT /api/data: a profile never reset gets no stamp', async t => {+ const h = await startServer(t);+ const r = await fetch(`${h.api}/api/data`, { method: 'PUT', headers: headers(), body: JSON.stringify({ state: { _ts: 1, workouts: [], routines: [] } }) });+ assert.equal(r.status, 200);+ const doc = JSON.parse(fs.readFileSync(path.join(h.dataDir, `state-${UID}.json`), 'utf8'));+ assert.equal('resetAt' in doc, false);+ assert.equal('resetIds' in doc, false);+});diff --git a/frontend/src/components/ServerSync.jsx b/frontend/src/components/ServerSync.jsxindex 8a8b75d7f..07454bb17 100644--- a/frontend/src/components/ServerSync.jsx+++ b/frontend/src/components/ServerSync.jsx@@ -66,6 +66,10 @@ export function connectionView(sync, { mobile = MOBILE, online = isOnline() } =return { tone: 'ok', icon: 'cloud', line: t('All synced'), banner: null, action: null }case 'pending': // the sentence already says "tap to retry": no second word for itreturn { tone: 'wait', icon: 'reset', line: t('Waiting to sync'), banner: t('Not synced yet — tap to retry.'), action: 'retry', label: null }+ // A sign-in's question about this device's workouts is still open (useStore adoptProfile):+ // nothing syncs until it is answered, and "retry" — Sync now — asks it again.+ case 'held':+ return { tone: 'wait', icon: 'reset', line: t('Waiting for your answer about this device’s workouts'), banner: t('Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.'), action: 'retry', label: null }case 'offline':if (online) return {tone: 'off', icon: 'cloudSlash', action: 'retry',diff --git a/frontend/src/components/SyncBanner.test.jsx b/frontend/src/components/SyncBanner.test.jsxindex f768d2c4c..2fa4ec48d 100644--- a/frontend/src/components/SyncBanner.test.jsx+++ b/frontend/src/components/SyncBanner.test.jsx@@ -248,6 +248,18 @@ describe('no server at all', () => {})})+// Review of 771184c9: while a sign-in's question held sync, the screens said nothing at all.+describe('a sign-in waiting for its question', () => {+ it('says nothing syncs until it is answered, and the tap runs Sync now, which asks it', () => {+ mocks.sync = sync('held')+ render()+ expect(text()).toBe('Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.')+ expect(connectionView(sync('held')).line).toBe('Waiting for your answer about this device’s workouts')+ act(() => { button().click() })+ expect(mocks.syncNow).toHaveBeenCalled()+ })+})+describe('where it never shows', () => {it('the public demo, which has no server by design', () => {mocks.DEMO = truediff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex ebd2b5f4f..890175234 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -65,8 +65,9 @@ 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'])+ // So are the backup import's warning (pt-PT says cópia and registado) and the sign-in hold's+ // status (pt-PT says «À espera da tua resposta»).+ 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', 'Waiting for your answer about this device’s workouts', 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.'])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 646fffd47..23f9efa58 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -43,14 +43,21 @@* 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.+ * - Reset. "Reset everything" stamps the empty copy with `resetAt` and with `resetIds`: the keys+ * of every entry it wiped — workouts, routines, custom exercises, weigh-ins (day and entry+ * time), gym cards, equipment profiles, favourites, notes, bar weights and the stamped+ * settings maps — of this device's copy and of the server's (resetIdsOf). A copy that has not+ * seen that reset (an older or no `resetAt`) loses exactly those entries and keeps everything+ * else, whatever its dates say: a CSV or Apple Health import of old sessions, a device whose+ * clock runs behind, an entry with no date at all (sinceReset). Only a reset stamped before+ * `resetIds` existed falls back to judging by time. The reset copy's settings and plan win+ * whatever the `_ts`. `resetAt` only ever moves forward: the merge keeps the later one (with+ * its ids; the union of both for the same reset), with `prefer` too, and so do a replace in+ * the store and the server's PUT — a restored backup that carried no stamp would otherwise be+ * taken for a copy older than the reset and wiped again. 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@@ -201,28 +208,77 @@ export function inUnitOf(follow, lead) {return convertStateUnit({ ...follow, unit: unitOf(follow) }, to)}-/** When the entries of a copy were made — what sinceReset holds against a reset. */+/** When the entries of a copy were made — what sinceReset holds against a reset without ids. */const workoutTime = w => Number(w?._ts) || Number(w?.end) || Number(w?.start) || 0+// What a reset records of the entries it wiped (resetIds), by field: how an entry is named.+const bodyweightKey = e => `${e?.d}|${e?.t ?? ''}`+const RESET_LISTS = {+ workouts: workoutKey, routines: x => x?.id, customEx: x => x?.id, bodyweight: bodyweightKey,+ gymCards: x => x?.id, equipProfiles: x => x?.id, favEx: x => x,+}+const RESET_MAPS = ['exNotes', 'barWeights', 'balanceOverrides', 'loadKind', 'plates']+/** An entry's name in resetIds: a workout's id (or day and start), a weigh-in's day and time, … */+export const entryKey = (field, x) => String(RESET_LISTS[field](x))+// Per field, the most names a reset keeps — far more workouts than anyone logs, and a bound on+// the document all the same. Past it the oldest names go first.+export const RESET_ID_MAX = 20000+const capIds = xs => (xs.length > RESET_ID_MAX ? xs.slice(xs.length - RESET_ID_MAX) : xs)++/** Every field's names from `a` then `b`, each once, capped (see RESET_ID_MAX). */+export function mergeResetIds(a, b) {+ const out = {}+ for (const f of [...Object.keys(RESET_LISTS), ...RESET_MAPS]) {+ const xs = [...new Set([...list(a?.[f]), ...list(b?.[f])].filter(k => k != null).map(String))]+ if (xs.length) out[f] = capIds(xs)+ }+ return out+}++/** The names of every entry the given copies hold — what a reset wipes (see the file's header). */+export function resetIdsOf(...copies) {+ let out = {}+ for (const S of copies) {+ if (!S || typeof S !== 'object') continue+ const one = {}+ for (const [f, key] of Object.entries(RESET_LISTS)) one[f] = list(S[f]).filter(x => x != null).map(key)+ for (const f of RESET_MAPS) one[f] = Object.keys(isMap(S[f]) ? S[f] : {})+ out = mergeResetIds(out, one)+ }+ return out+}+/**- * 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.+ * What a copy that has not seen a reset still contributes after it (see the file's header): with+ * the reset's `ids`, everything but the entries it wiped; without (a reset from before ids were+ * kept), 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+export function sinceReset(S, at, ids) {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))))+ if (ids && typeof ids === 'object') {+ for (const [f, key] of Object.entries(RESET_LISTS)) {+ const gone = new Set(list(ids[f]).map(String))+ if (Array.isArray(S[f])) out[f] = clone(S[f].filter(x => x == null || !gone.has(String(key(x)))))+ }+ for (const f of RESET_MAPS) {+ const gone = new Set(list(ids[f]).map(String))+ if (isMap(S[f])) out[f] = clone(Object.fromEntries(Object.entries(S[f]).filter(([k]) => !gone.has(k))))+ }+ } else {+ const after = v => (Number(v) || 0) > at+ 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) {@@ -246,11 +302,15 @@ export function mergeStates(a0, b0, { prefer } = {}) {// 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'+ const ra = Number(a.resetAt) || 0, rb = Number(b.resetAt) || 0if (!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' }+ if (ra > rb) { b = sinceReset(b, ra, a.resetIds); side = 'a' }+ else if (rb > ra) { a = sinceReset(a, rb, b.resetIds); side = 'b' }}+ // The reset stamp only moves forward, with the names it wiped — with `prefer` too.+ const resetAt = Math.max(ra, rb)+ const resetIds = ra === rb ? (a0.resetIds || b0.resetIds ? mergeResetIds(a0.resetIds, b0.resetIds) : null)+ : (ra > rb ? a0 : b0).resetIds || null// One unit before anything is compared.let lead = nullif (unitOf(a) !== unitOf(b)) {@@ -343,10 +403,31 @@ export function mergeStates(a0, b0, { prefer } = {}) {if (n[f] || o[f]) out[f] = clone(mergeStampedMap(n[f], o[f], prefer))}out._ts = Math.max(a._ts || 0, b._ts || 0)+ if (resetAt) out.resetAt = resetAt+ if (resetIds) out.resetIds = resetIds+ else delete out.resetIdsdelete out._revreturn out}+/**+ * `next` replacing `cur` wholesale (a backup import, a reset) never takes the reset stamp back:+ * the later `resetAt` stays, with its names — a restored backup that carried none would otherwise+ * be taken, on every device that saw the reset, for a copy from before it and wiped again.+ * Mutates and returns `next`.+ */+export function keepReset(cur, next) {+ if (!next || typeof next !== 'object') return next+ const rc = Number(cur?.resetAt) || 0, rn = Number(next.resetAt) || 0+ if (rc > rn) {+ next.resetAt = cur.resetAt+ if (cur.resetIds) next.resetIds = clone(cur.resetIds); else delete next.resetIds+ } else if (rc && rc === rn && (cur.resetIds || next.resetIds)) {+ next.resetIds = mergeResetIds(cur.resetIds, next.resetIds)+ }+ return next+}+const sameRoutine = (a, b) => JSON.stringify({ ...a, _ts: 0 }) === JSON.stringify({ ...b, _ts: 0 })/**diff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.jsindex 561de3982..ddff762ff 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, sinceReset, stampCustomEx, stampRoutines, stampWorkout, unionById } from './sync-merge.js'+import { keepReset, localExtras, mergeBodyweight, mergeResetIds, mergeStampedMap, mergeStates, newerOf, resetIdsOf, RESET_ID_MAX, sinceReset, stampCustomEx, stampRoutines, stampWorkout, unionById } from './sync-merge.js'+import { mergeImport } from './import-csv.js'import { convertBodyWeight, convertStateUnit, convertWeight } from './units.js'import { retimeWorkout } from './workout-date.js'import { inventoryFor, loadKindFor, withLoadKind, withPlatePairs, withStandardPlates } from './plates.js'@@ -519,7 +520,7 @@ describe('a reset holds against a copy that has not seen it', () => {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', () => {+ it('without resetIds (a reset from before they were kept) keeps only what the other copy made after it, 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'])@@ -555,10 +556,96 @@ describe('a reset holds against a copy that has not seen it', () => {it('sinceReset leaves the copy it reads alone', () => {const before = JSON.stringify(stale)sinceReset(stale, R)+ sinceReset(stale, R, resetIdsOf(stale))expect(JSON.stringify(stale)).toBe(before)})})+// Review of the reset rule: judging by dates dropped a CSV import of old sessions, an Apple Health+// weigh-in history, a workout logged on a device whose clock runs behind, and anything undated.+// The reset now names what it wiped (resetIds), and only that goes.+describe('a reset names what it wiped', () => {+ const clone = v => JSON.parse(JSON.stringify(v))+ const R = Date.now()+ 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 })+ // what the profile held when it was reset — on the resetting device and on the stale one alike+ const before = base({+ _ts: R - 1000,+ workouts: [w('old', R - 5000)], routines: [{ id: 'r-old', name: 'old', ex: [], _ts: R - 5000 }],+ bodyweight: [{ d: '2026-08-01', w: 80, t: R - 5000 }], customEx: [{ id: 'c-old', n: 'old', _ts: R - 5000 }],+ favEx: ['0025'], exNotes: { '0025': 'seat 4' }, gymCards: [{ id: 'g1', value: '123' }],+ loadKind: { '0025': { kind: 'single', _ts: R - 5000 } },+ })+ const reset = base({ _ts: R, resetAt: R, resetIds: resetIdsOf(before) })++ it('drops exactly the wiped entries of a copy that has not seen the reset', () => {+ const stale = clone(before)+ stale._ts = R + 10+ for (const m of [mergeStates(reset, stale), mergeStates(stale, reset)]) {+ expect(m.workouts).toEqual([])+ expect(m.routines || []).toEqual([])+ expect(m.bodyweight).toEqual([])+ expect(m.customEx || []).toEqual([])+ expect(m.favEx || []).toEqual([])+ expect(m.exNotes || {}).toEqual({})+ expect(m.gymCards || []).toEqual([])+ expect(m.loadKind || {}).toEqual({})+ expect(m.exWeights).toEqual({})+ expect(m.resetAt).toBe(R)+ }+ })++ it('keeps a CSV import of old sessions and an old weigh-in history made on that device', () => {+ const stale = clone(before)+ mergeImport(stale, { kind: 'workouts', customEx: [], workouts: [{ ...w('iw1', Date.parse('2024-03-01')), d: '2024-03-01' }] })+ mergeImport(stale, { kind: 'bodyweight', bodyweight: [{ d: '2024-03-01', w: 80, t: Date.parse('2024-03-01') }] })+ const m = mergeStates(stale, reset)+ expect(ids(m.workouts)).toEqual(['iw1'])+ expect(m.bodyweight.map(e => e.d)).toEqual(['2024-03-01'])+ })++ it('keeps a workout logged after the reset on a device whose clock runs behind', () => {+ const stale = { ...clone(before), workouts: [...before.workouts, w('after-but-skewed', R - 60000)] }+ expect(ids(mergeStates(stale, reset).workouts)).toEqual(['after-but-skewed'])+ })++ it('keeps entries with no date or stamp at all', () => {+ const stale = { ...clone(before), workouts: [{ id: 'undated', entries: [] }], routines: [{ id: 'r-unstamped', name: 'x', ex: [] }], customEx: [{ id: 'c-unstamped', n: 'x' }] }+ const m = mergeStates(reset, stale)+ expect(ids(m.workouts)).toEqual(['undated'])+ expect(ids(m.routines)).toEqual(['r-unstamped'])+ expect(ids(m.customEx)).toEqual(['c-unstamped'])+ })++ it('the stamp only moves forward: with prefer, and with a copy that carries none', () => {+ const backup = base({ _ts: 5, workouts: [w('restored', 4)] })+ const m = mergeStates(backup, reset, { prefer: 'a' })+ expect(m.resetAt).toBe(R)+ expect(m.resetIds).toEqual(reset.resetIds)+ expect(ids(m.workouts)).toEqual(['restored'])+ // a copy restored with the stamp kept merges with one that saw the reset as usual+ const restored = { ...backup, resetAt: R, resetIds: reset.resetIds, _ts: R + 5 }+ const seen = base({ _ts: R + 1, resetAt: R, resetIds: reset.resetIds, workouts: [w('gym-today', R + 1)] })+ expect(ids(mergeStates(seen, restored).workouts).sort()).toEqual(['gym-today', 'restored'])+ })++ it('keepReset: a replace never takes the stamp back; the same reset\'s names are joined', () => {+ const cur = { resetAt: R, resetIds: { workouts: ['a'] } }+ expect(keepReset(cur, { workouts: [] })).toMatchObject({ resetAt: R, resetIds: { workouts: ['a'] } })+ expect(keepReset(cur, { resetAt: R + 1, resetIds: { workouts: ['b'] } }).resetIds).toEqual({ workouts: ['b'] })+ expect(keepReset(cur, { resetAt: R, resetIds: { workouts: ['b'] } }).resetIds).toEqual({ workouts: ['a', 'b'] })+ expect(keepReset({}, { workouts: [] })).toEqual({ workouts: [] })+ })++ it('names are joined across copies and bounded', () => {+ expect(mergeResetIds({ workouts: ['a', 'b'] }, { workouts: ['b', 'c'], routines: ['r'] })).toEqual({ workouts: ['a', 'b', 'c'], routines: ['r'] })+ const many = Array.from({ length: RESET_ID_MAX + 5 }, (_, i) => 'w' + i)+ const out = mergeResetIds({ workouts: many }, null).workouts+ expect(out).toHaveLength(RESET_ID_MAX)+ expect(out.at(-1)).toBe('w' + (RESET_ID_MAX + 4))+ })+})+// 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', () => {diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex f38e837ca..b237e6fe2 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1679,4 +1679,6 @@ export default {'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': 'دمجها',+ 'Waiting for your answer about this device’s workouts': 'بانتظار إجابتك بشأن تمارين هذا الجهاز',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'لن تتم المزامنة حتى تحدد ما إذا كانت تمارين هذا الجهاز ستُضاف إلى ملفك — اضغط للإجابة.',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 516ca97d6..c6bd7ddf6 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1646,4 +1646,6 @@ export default {'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',+ 'Waiting for your answer about this device’s workouts': 'Wartet auf deine Antwort zu den Trainings dieses Geräts',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Nichts wird synchronisiert, bis du sagst, ob die Trainings dieses Geräts in dein Profil kommen – tippe zum Antworten.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 7e5315243..7703d1c03 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1626,4 +1626,6 @@ export default {'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',+ 'Waiting for your answer about this device’s workouts': 'Esperando tu respuesta sobre los entrenamientos de este dispositivo',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'No se sincroniza nada hasta que digas si los entrenamientos de este dispositivo van a tu perfil: toca para responder.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 83bd95723..c20a60241 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1626,4 +1626,6 @@ export default {'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',+ 'Waiting for your answer about this device’s workouts': 'En attente de ta réponse sur les séances de cet appareil',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Rien ne se synchronise tant que tu n’as pas dit si les séances de cet appareil vont dans ton profil — touche pour répondre.',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 0197e233b..870bc3d2c 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1626,4 +1626,6 @@ export default {'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': 'उन्हें मिलाएँ',+ 'Waiting for your answer about this device’s workouts': 'इस डिवाइस के वर्कआउट के बारे में आपके जवाब की प्रतीक्षा है',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'जब तक आप यह नहीं बताते कि इस डिवाइस के वर्कआउट आपकी प्रोफ़ाइल में जाएँ या नहीं, कुछ भी सिंक नहीं होगा — जवाब देने के लिए टैप करें।',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 3e2b736b3..36261c7a8 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1629,4 +1629,6 @@ export default {'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',+ 'Waiting for your answer about this device’s workouts': 'Válaszra vár az eszköz edzéseiről',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Semmi sem szinkronizálódik, amíg meg nem mondod, bekerüljenek-e az eszköz edzései a profilodba – koppints a válaszhoz.',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 458dbaeaf..b01eab5f8 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1626,4 +1626,6 @@ export default {'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',+ 'Waiting for your answer about this device’s workouts': 'In attesa della tua risposta sugli allenamenti di questo dispositivo',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Non si sincronizza nulla finché non dici se gli allenamenti di questo dispositivo vanno nel tuo profilo — tocca per rispondere.',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 62957311c..087592709 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1626,4 +1626,6 @@ export default {'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': '합치기',+ 'Waiting for your answer about this device’s workouts': '이 기기의 운동에 대한 답변을 기다리는 중',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': '이 기기의 운동을 프로필에 넣을지 정할 때까지 아무것도 동기화되지 않습니다. 탭하여 답하세요.',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 4a09a4c09..e35d9fabb 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1626,4 +1626,6 @@ export default {'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',+ 'Waiting for your answer about this device’s workouts': 'Czeka na Twoją odpowiedź w sprawie treningów z tego urządzenia',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Nic się nie synchronizuje, dopóki nie zdecydujesz, czy treningi z tego urządzenia trafią do profilu – dotknij, aby odpowiedzieć.',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 0007173a8..e8b3a6566 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -971,6 +971,8 @@ export const PT_BR_OVERRIDES = {'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',+ 'Waiting for your answer about this device’s workouts': 'Aguardando sua resposta sobre os treinos deste dispositivo',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Nada é sincronizado até você dizer se os treinos deste dispositivo vão para o seu perfil — toque para responder.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 58dc11929..49e34042d 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1626,4 +1626,6 @@ export default {'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',+ 'Waiting for your answer about this device’s workouts': 'À espera da tua resposta sobre os treinos deste dispositivo',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Nada é sincronizado até dizeres se os treinos deste dispositivo vão para o teu perfil — toca para responder.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex feac9d508..2a38d0b83 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1626,4 +1626,6 @@ export default {'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': 'Объединить',+ 'Waiting for your answer about this device’s workouts': 'Ждём вашего ответа о тренировках с этого устройства',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Ничего не синхронизируется, пока вы не решите, добавлять ли тренировки с этого устройства в профиль, — нажмите, чтобы ответить.',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 048b97864..2d7fa85e5 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1637,4 +1637,6 @@ export default {'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': 'รวมเข้าด้วยกัน',+ 'Waiting for your answer about this device’s workouts': 'กำลังรอคำตอบของคุณเกี่ยวกับการออกกำลังกายในอุปกรณ์นี้',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'จะไม่มีการซิงค์จนกว่าคุณจะบอกว่าจะเพิ่มการออกกำลังกายในอุปกรณ์นี้ลงในโปรไฟล์หรือไม่ — แตะเพื่อตอบ',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 8fb2df291..cc29ca277 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1626,4 +1626,6 @@ export default {'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',+ 'Waiting for your answer about this device’s workouts': 'Bu cihazdaki antrenmanlar için yanıtın bekleniyor',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Bu cihazdaki antrenmanların profiline eklenip eklenmeyeceğini söyleyene kadar hiçbir şey eşitlenmez — yanıtlamak için dokun.',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 50da3dd07..4d159c1d4 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1623,4 +1623,6 @@ export default {'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': 'Об’єднати',+ 'Waiting for your answer about this device’s workouts': 'Чекаємо на вашу відповідь щодо тренувань із цього пристрою',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': 'Нічого не синхронізується, доки ви не вирішите, чи додавати тренування з цього пристрою до профілю, — торкніться, щоб відповісти.',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 2fe8d22ca..cc68820fc 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1626,4 +1626,6 @@ export default {'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': '合并进来',+ 'Waiting for your answer about this device’s workouts': '正在等待你对本设备训练的答复',+ 'Nothing syncs until you say whether this device’s workouts go into your profile — tap to answer.': '在你决定是否将本设备的训练加入个人资料之前,不会同步任何内容——点按以答复。',}diff --git a/frontend/src/store/useStore.adopt.test.jsx b/frontend/src/store/useStore.adopt.test.jsxindex 540b2d1f9..7a096512c 100644--- a/frontend/src/store/useStore.adopt.test.jsx+++ b/frontend/src/store/useStore.adopt.test.jsx@@ -6,8 +6,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'vi.mock('../lib/api.js', () => ({ api: vi.fn() }))-const { toast } = vi.hoisted(() => ({ toast: vi.fn() }))+const { toast, sheetAsk } = vi.hoisted(() => ({ toast: vi.fn(), sheetAsk: vi.fn() }))vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast }) } }))+// The question an adoption resumed by the store itself asks (resumeAdoption, checkRev, Sync now).+vi.mock('../sheets.jsx', () => ({ askAddDeviceData: (...a) => sheetAsk(...a) }))import { api } from '../lib/api.js'import { DEF, hasData, useStore } from './useStore.js'@@ -257,6 +259,58 @@ describe('web sign-in: nothing syncs while the question is open', () => {})})+// Review of 771184c9: the hold could outlive the session, and it held back more than the question.+describe('the sign-in hold: never stuck, and only about what the device had', () => {+ const settle = () => new Promise(r => setTimeout(r, 20))++ it('a sign-in whose adoption never started (the pairing failed on the way) runs it on the next check', async () => {+ signedIn(clone(guest), { user: null })+ useStore.getState().setUser({ id: 'user-1' }, { adopt: true })+ expect(useStore.getState().sync.status).toBe('held')+ sheetAsk.mockResolvedValueOnce(false)+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ window.dispatchEvent(new Event('online'))+ await vi.waitFor(() => expect(localStorage.getItem('gym_adopt')).toBeNull())+ await settle()+ expect(sheetAsk).toHaveBeenCalledWith({ workouts: 1, bodyweight: 0, customEx: 0 })+ expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1'])+ expect(useStore.getState().sync.status).not.toBe('held')+ })++ it('a bare adoption whose question throws lets go of the hold', async () => {+ signedIn(clone(guest))+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ await expect(useStore.getState().adoptProfile(() => { throw new Error('sheet gone') })).rejects.toThrow('sheet gone')+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ api.mockResolvedValue({ ok: true, rev: 5 })+ await useStore.getState().pullState()+ expect(paths().filter(p => p === '/api/data').length).toBeGreaterThan(1) // it pulled: not held+ api.mockReset()+ })++ it('what was logged while held is not asked about, and "Keep profile as is" keeps it; Sync now asks the question', 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()+ // held, the gym goes on: a workout logged on this device, now the account's+ useStore.getState().update(s => { s.workouts.push(workout('w-later', '2026-09-25')) })+ expect(useStore.getState().sync.status).not.toBe('ok')+ sheetAsk.mockResolvedValueOnce(false)+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ api.mockResolvedValueOnce({ ok: true, rev: 5 })+ await useStore.getState().syncNow()+ expect(sheetAsk).toHaveBeenCalledWith({ workouts: 1, bodyweight: 0, customEx: 0 }) // w9 only+ expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'w-later'])+ const put = puts().at(-1)+ expect(put.baseRev).toBe(4)+ expect(put.state.workouts.map(w => w.id)).toEqual(['w1', 'w-later'])+ expect(put.state.unit).toBe('lb') // the profile's settings+ })+})+// 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', () => {diff --git a/frontend/src/store/useStore.import-check.test.jsx b/frontend/src/store/useStore.import-check.test.jsxindex 91032e7f3..310d2358f 100644--- a/frontend/src/store/useStore.import-check.test.jsx+++ b/frontend/src/store/useStore.import-check.test.jsx@@ -57,6 +57,19 @@ describe('importing a backup over a profile that moved on', () => {expect(put.state.restSec).toBe(120)})+ // Review of 771184c9: a workout logged here and not yet sent was neither counted nor merged.+ it('counts this device\'s unsent workouts too, and "Merge them in" keeps them', async () => {+ signedIn({ ...clone(DEF), _ts: 200, workouts: [workout('w1')] }, 7)+ useStore.getState().update(s => { s.workouts.push(workout('unsent', '2026-09-27')) })+ api.mockResolvedValueOnce({ state: clone(SERVER), rev: 7 })+ const c = await useStore.getState().importConflict(BACKUP)+ expect(c).toMatchObject({ workouts: 2, local: true }) // 'elsewhere' on the server, 'unsent' here+ api.mockResolvedValueOnce({ ok: true, rev: 8 })+ useStore.getState().importBackup(BACKUP, { mergeWith: c })+ await useStore.getState().pushState()+ expect(ids(puts().at(-1).state.workouts)).toEqual(['w1', 'w2', 'elsewhere', 'unsent'])+ })+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 })diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex ea3f6d0ce..ba46ca8f2 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -7,7 +7,7 @@ import { DEMO, DEMO_SEEDED } from '../lib/demo.js'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 { mergeStates, localExtras, stampRoutines, stampCustomEx, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } 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'@@ -64,9 +64,13 @@ 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 oftenconst 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('|')+// Whether `next` has a workout photo or video that `prev` had on none of its workouts.+const workoutMediaHashes = S => (Array.isArray(S?.workouts) ? S.workouts : [])+ .flatMap(w => (Array.isArray(w?.media) ? w.media.map(m => m?.hash).filter(h => typeof h === 'string' && h) : []))+const gainedWorkoutMedia = (prev, next) => {+ const had = new Set(workoutMediaHashes(prev))+ return workoutMediaHashes(next).some(h => !had.has(h))+}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,@@ -244,7 +248,6 @@ export const useStore = create((set, get) => {let offlineChanges = false // a push failed for lack of network — the next one that lands says solet backupTm = null // phone: the auto-backup after workout media changed, on its debouncelet 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 onelet 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 one@@ -256,8 +259,10 @@ export const useStore = create((set, get) => {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 }+ // Sync held or not, and the screens told (`sync.held`, status 'held').+ const setHold = on => { adoptHold = on; if (get()?.sync) setSync({ held: on }) }// The question is answered: sync as usual from here.- const releaseAdopt = () => { adoptHold = false; adoptClaimed = false; writeAdopt(null) }+ const releaseAdopt = () => { setHold(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 } }@@ -307,13 +312,16 @@ export const useStore = create((set, get) => {'auth' the server refuses this device (a 401), or the phone has lost its pairing'offline' the server could not be reached at all (no network, DNS, a timeout)'error' it answered with a failure: 5xx, 403, 413, a page that is not openGym's+ 'held' signed in, but the question about this device's own entries is still open'pending' reachable, and a change is still waiting to reach it'ok' this device holds what the server holds`pending`: a change is owed and the last attempt did not land. `lastSynced`: when this deviceand the server last held the same copy. `lastError`: { status, code } of the failure behind'auth', 'offline' or 'error' (status 0 without an HTTP answer). `server`: the base URL thisdevice syncs with, or null on a phone that has none. */- const statusOf = (x, user) => x.auth ? 'auth' : !user ? 'local' : x.offline ? 'offline' : x.lastError ? 'error' : x.pending ? 'pending' : 'ok'+ // 'held': a sign-in's question about this device's own entries is still open (adoptProfile), and+ // nothing syncs until it is answered — said after a failed connection, which is why it is held.+ const statusOf = (x, user) => x.auth ? 'auth' : !user ? 'local' : x.offline ? 'offline' : x.lastError ? 'error' : x.held ? 'held' : x.pending ? 'pending' : 'ok'const sameError = (a, b) => (a && b ? a.status === b.status && a.code === b.code : a === b)const setSync = patch => {const cur = get().sync@@ -445,9 +453,10 @@ 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 }+ // A sign-in still deciding what becomes of this copy: no check of its own. One whose adoption+ // never ran or did not get through (no server, a pairing that failed on the way to it) runs it+ // here, question and all; one already running is left to answer.+ if (adoptHold) { if (!adopting && adoptOwed()) get().resumeAdoption(); return }if (pulling) return pullingconst { base } = metaOf()if (!base || owes()) return get().pullState()@@ -486,11 +495,12 @@ export const useStore = create((set, get) => {}// 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.+ // left in kg would then log kg numbers under an lb label. A switch that only changed the label+ // (`unitSet.convert === false`) relabels the session as it relabels the history (inUnitOf).const carryActive = (from, to) => {const a = from?.active || nullconst fu = from?.unit || 'kg', tu = to?.unit || 'kg'- return !a || fu === tu ? a : convertStateUnit({ unit: fu, active: a }, tu).active+ return !a || fu === tu ? a : inUnitOf({ unit: fu, active: a }, to).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) }@@ -821,7 +831,12 @@ export const useStore = create((set, get) => {await applyStash()return { adopted: true, added: false, merged: true }}- const keep = await askAbout(localExtras(S0, state))+ // The question is about what this copy held when the sign-in began (the marker's `pre`). What+ // was logged since — while an adoption that could not reach the server kept sync held — is+ // this account's own already: never offered as "logged while signed out", never dropped by+ // "Keep profile as is", but merged like any change of the account's.+ const pre = owedMark?.pre+ const keep = await askAbout(localExtras(pre ? splitByPre(S0, pre).before : S0, state))await reread()releaseAdopt()if (keep) {@@ -835,10 +850,44 @@ export const useStore = create((set, get) => {await applyStash()return { adopted: true, added: true }}+ const later = pre ? splitByPre(get().S, pre).later : nulltakeServer()+ if (later) {+ const S = get().S+ const merged = Object.assign(clone(DEF), mergeStates(S, later, { 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: false }}+ // A copy's workouts, weigh-ins and custom exercises split by the names a sign-in recorded when it+ // began (`pre`, see setUser): `before` holds what was there then, `later` — null when nothing+ // is — what was logged since, with the custom exercises its workouts use, in this copy's unit.+ const ADOPT_FIELDS = ['workouts', 'bodyweight', 'customEx']+ const splitByPre = (S, pre) => {+ const before = { ...S }+ const later = { _ts: S._ts, unit: S.unit, ...(S.unitSet ? { unitSet: S.unitSet } : {}) }+ let any = false+ for (const f of ADOPT_FIELDS) {+ const had = new Set(Array.isArray(pre?.[f]) ? pre[f] : [])+ const xs = Array.isArray(S[f]) ? S[f].filter(x => x != null) : []+ before[f] = xs.filter(x => had.has(entryKey(f, x)))+ later[f] = xs.filter(x => !had.has(entryKey(f, x)))+ if (later[f].length) any = true+ }+ if (!any) return { before, later: null }+ const used = new Set(later.workouts.flatMap(w => (Array.isArray(w?.entries) ? w.entries : []).map(e => e?.id)))+ later.customEx = [...later.customEx, ...before.customEx.filter(c => used.has(c.id))]+ return { before, later }+ }+ const preOf = S => {+ const ids = resetIdsOf(S)+ return Object.fromEntries(ADOPT_FIELDS.map(f => [f, ids[f] || []]))+ }// 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@@ -871,7 +920,7 @@ export const useStore = create((set, get) => {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.id- const sync0 = { offline: false, pending: storedOwed(), auth: false, lastError: null, lastSynced: (() => { try { return +localStorage.getItem(SYNCED_AT_KEY) || 0 } catch { return 0 } })(), server: serverBase() }+ const sync0 = { offline: false, pending: storedOwed(), auth: false, lastError: null, lastSynced: (() => { try { return +localStorage.getItem(SYNCED_AT_KEY) || 0 } catch { return 0 } })(), server: serverBase(), held: adoptHold }sync0.status = statusOf(sync0, user0)return {@@ -905,9 +954,10 @@ 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)) {+ // A photo or video added to a workout is a change worth the day's backup too: the one+ // finishing wrote went before the finish screen's pictures (autoBackupNow). Not a removal,+ // nor a workout deleted: the day's copy then still holds what was taken off, as a backup should.+ if (MOBILE && S.autoBackup && gainedWorkoutMedia(prev, S)) {clearTimeout(backupTm)backupTm = setTimeout(() => { backupTm = null; get().autoBackupNow() }, AUTO_BACKUP_SOON_MS)}@@ -946,10 +996,26 @@ export const useStore = create((set, get) => {// 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).+ //+ // With it goes `resetIds`, the names of every entry the reset wiped: this copy's, the earlier+ // resets' (a copy older than those too is still judged right), and the server's once it+ // answers — it may hold entries this device never pulled. A device that has not seen the+ // reset loses exactly those, and keeps whatever else it holds, whatever its dates say.+ // Resolves once the server's names are in (or could not be had).resetEverything() {+ const cur = get().Sconst S = clone(DEF)- S.resetAt = Date.now()+ S.resetAt = Math.max(Date.now(), (Number(cur.resetAt) || 0) + 1)+ S.resetIds = mergeResetIds(cur.resetIds, resetIdsOf(cur))get().replaceState(S, !!get().user)+ if (!get().user) return Promise.resolve()+ return api('/api/data').then(res => {+ const now = get().S+ if (!res?.state || now.resetAt !== S.resetAt) return+ const ids = mergeResetIds(now.resetIds, mergeResetIds(res.state.resetIds, resetIdsOf(res.state)))+ if (JSON.stringify(ids) === JSON.stringify(now.resetIds)) return+ persist(Object.assign(clone(now), { resetIds: ids }), true)+ }).catch(() => {})},// 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@@ -962,26 +1028,33 @@ export const useStore = create((set, get) => {try { res = await api('/api/data') } catch { return null }const state = res?.stateif (!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+ const key = w => entryKey('workouts', w)+ const inBackup = new Set((Array.isArray(backup?.workouts) ? backup.workouts : []).filter(Boolean).map(key))+ const server = (Array.isArray(state.workouts) ? state.workouts : []).filter(Boolean)+ const onServer = new Set(server.map(key))+ const workouts = server.filter(w => !inBackup.has(key(w))).length+ // This device's own workouts the server has not received yet go the same way, and count too.+ const mine = owes() ? (get().S.workouts || []).filter(w => w && !inBackup.has(key(w)) && !onServer.has(key(w))).length : 0+ return workouts + mine ? { workouts: workouts + mine, state, rev: res.rev, local: mine > 0 || owes() } : 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.+ // is merged in instead of replaced (with this device's changes not yet on it, when there are+ // any): the backup's settings and plan, every entry of all of them (mergeStates with the backup+ // preferred, in the backup's unit), pushed against that revision like any other change, so a+ // workout logged meanwhile elsewhere, or here, 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' }))+ const others = mergeWith.local ? mergeStates(get().S, mergeWith.state) : mergeWith.state+ const merged = keepReset(get().S, Object.assign(clone(DEF), mergeStates(next, others, { prefer: 'a' })))merged.active = next.active || nullpersist(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) },+ // overwrite, not a change to merge: the push it arms goes without a baseRev. It never takes+ // the reset stamp back (keepReset).+ replaceState(S, push = false) { if (push) forceNext = true; persist(keepReset(get().S, clone(S)), push) },// Fires after the moments where losing local data would actually hurt — a workout just// logged, a routine just edited — not on every keystroke. No-op off mobile or with the@@ -1038,10 +1111,8 @@ export const useStore = create((set, get) => {// The hold goes on before anything else can run: a poll, a resume, a debounced push.if (adopt) {adoptHold = true- adoptClaimed = trueclearTimeout(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.@@ -1056,6 +1127,9 @@ export const useStore = create((set, get) => {persist(clone(DEF), false)setSync({ pending: false, lastSynced: 0, lastError: null })}+ // The mark, with the names of what this copy holds now (`pre`) — what the question is+ // about; whatever is logged later belongs to the account (runAdopt).+ if (adopt) writeAdopt({ uid: u.id, rejoined, alwaysAsk: !!adopt.alwaysAsk, pre: preOf(get().S) })localStorage.setItem('gym_owner_name', u.name || '')localStorage.setItem('gym_owner', u.id)localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest')@@ -1069,9 +1143,9 @@ 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; adoptHold = false; adoptClaimed = false; localStorage.removeItem('gym_user') }+ } else { rejoined = false; adoptHold = false; localStorage.removeItem('gym_user') }set({ user: u })- setSync({})+ setSync({ held: adoptHold })},// One PUT at a time: a push asked for while one is in flight runs after it (once, however@@ -1144,6 +1218,8 @@ export const useStore = create((set, get) => {// `sync` every screen reads — status 'ok' when the two agree.async syncNow() {if (!get().user) { setSync({}); return get().sync }+ // Held for a sign-in's question: "Sync now" is asking it (again), and the sync follows.+ if (adoptHold) { await get().resumeAdoption(); if (adoptHold) return get().sync }if (pulling) await pullingawait get().pullState()return get().sync@@ -1203,16 +1279,20 @@ export const useStore = create((set, get) => {// 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 })+ setHold(true)+ // Whatever throws on the way (the server, the question itself): a sign-in that marked it+ // stays held, and the next check or "Sync now" runs it again; a bare call has nothing to+ // hold for and lets go.+ adopting = runAdopt(ask, opts)+ .catch(e => { if (!adoptOwed()) releaseAdopt(); throw e })+ .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 (!m) { if (adoptHold && !adopting) releaseAdopt(); return null }if (adopting) return adoptingtry {if (typeof ask !== 'function') ask = (await import('../sheets.jsx')).askAddDeviceData@@ -1335,7 +1415,9 @@ export const useStore = create((set, get) => {if (adoptOwed()) {syncReminder(get().S)finishBoot()- get().resumeAdoption()+ // The adoption applies what the pull would have (its stash included); the reminder+ // then follows the copy it settled on.+ get().resumeAdoption().then(() => syncReminder(get().S))return}await get().pullState()@@ -1409,17 +1491,24 @@ 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,// without needing to revisit Settings.- const tz = localTZ()- if (get().S.reminder?.on && get().S.reminder.tz !== tz) {- get().update(s => { s.reminder = { ...s.reminder, tz } })+ const restampTz = () => {+ const tz = localTZ()+ if (get().S.reminder?.on && get().S.reminder.tz !== tz) {+ get().update(s => { s.reminder = { ...s.reminder, tz } })+ }+ }+ // Closed with the sign-in's question still open: asked again once the app is up (see the+ // phone's boot above); the adoption applies the stash, the timezone follows its copy.+ if (adoptOwed()) {+ finishBoot()+ get().resumeAdoption().then(() => { if (!adoptHold) restampTz() })+ return}+ await get().pullState()+ if (!get().sync.lastError) await applyStash() // only once the server really answered+ restampTz()} catch (e) {// The session ended (expired, revoked, signed out everywhere): back to the sign-in// screen, which says so. The copy stays here with its owner, and signing in again as thediff --git a/frontend/src/store/useStore.media-backup.test.jsx b/frontend/src/store/useStore.media-backup.test.jsxindex f25024614..a53624ded 100644--- a/frontend/src/store/useStore.media-backup.test.jsx+++ b/frontend/src/store/useStore.media-backup.test.jsx@@ -51,10 +51,15 @@ describe('auto-backup and a workout\'s photos and videos', () => {expect(all).toHaveLength(1)expect(all[0].workouts[0].media.map(m => m.hash)).toEqual(['a'.repeat(64), 'b'.repeat(64)])- h.files.clear()+ })++ // Review of 771184c9: a removal wrote the day's backup over the copy that still had the photo.+ it('taking a photo off, or deleting the workout, leaves the day\'s backup as it was', async () => {+ useStore.setState({ S: { ...clone(DEF), autoBackup: true, workouts: [{ ...clone(W), media: [ref('a'), ref('b')] }] }, ready: true })useStore.getState().update(s => { removeWorkoutMedia(s, W, 'a'.repeat(64)) })+ useStore.getState().update(s => { s.workouts = [] })await sleep(2300)- expect(backups()[0].workouts[0].media.map(m => m.hash)).toEqual(['b'.repeat(64)])+ expect(backups()).toHaveLength(0)})it('nothing written for other changes, or with the setting off', async () => {diff --git a/frontend/src/store/useStore.reset-sync.test.jsx b/frontend/src/store/useStore.reset-sync.test.jsxindex e08905bd0..81aa5b753 100644--- a/frontend/src/store/useStore.reset-sync.test.jsx+++ b/frontend/src/store/useStore.reset-sync.test.jsx@@ -2,8 +2,10 @@/* QA, v1.3.9 (t8): "Reset everything" on one device was undone by the next device that pushed achange 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). */+ back. The reset now carries its time (`resetAt`) and the names of what it wiped (`resetIds`); a+ merge with a copy that has not seen it drops exactly those (lib/sync-merge.js). And the stamp+ only moves forward: a backup restored after the reset is not wiped again by the devices that+ saw it (review of 771184c9). */import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))@@ -11,6 +13,7 @@ vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn() }) } }import { api } from '../lib/api.js'import { DEF, useStore } from './useStore.js'+import { resetIdsOf } from '../lib/sync-merge.js'const clone = v => JSON.parse(JSON.stringify(v))const ids = xs => (xs || []).map(x => x.id)@@ -27,23 +30,28 @@ 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 () => {+ it('replaces the server copy with the empty one, stamped, naming what this copy and the server held', async () => {signedIn(clone(PROFILE), 3)+ // the server also has a workout this device never pulled+ api.mockResolvedValueOnce({ state: { ...clone(PROFILE), workouts: [...PROFILE.workouts, workout('w-elsewhere', 70)], _rev: 3 }, rev: 3 })api.mockResolvedValueOnce({ ok: true, rev: 4 })const before = Date.now()- useStore.getState().resetEverything()+ await 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)+ expect(put.state.resetIds.workouts).toEqual(['w1', 'w2', 'w-elsewhere'])+ expect(put.state.resetIds.routines).toEqual(['r1'])+ expect(put.state.resetIds.bodyweight).toEqual(['2026-09-01|10'])})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, unsentconst resetAt = Date.now() + 1000- const serverReset = { ...clone(DEF), _ts: resetAt, resetAt, _rev: 4 }+ const serverReset = { ...clone(DEF), _ts: resetAt, resetAt, resetIds: resetIdsOf(PROFILE), _rev: 4 }api.mockRejectedValueOnce(conflict(serverReset, 4))api.mockResolvedValueOnce({ ok: true, rev: 5 })await useStore.getState().pushState()@@ -57,14 +65,41 @@ describe('Reset everything', () => {expect(useStore.getState().S.workouts).toEqual([])})- it('what that device logged after the reset is kept', async () => {- const resetAt = Date.now() - 60000+ it('what that device logged after the reset is kept, whatever its clock says', async () => {+ const resetAt = Date.now() + 3600e3 // this device's clock is an hour behind the resetting onesignedIn(clone(PROFILE), 3)useStore.getState().update(s => { s.workouts.push(workout('after', Date.now())) })- const serverReset = { ...clone(DEF), _ts: resetAt, resetAt, _rev: 4 }+ const serverReset = { ...clone(DEF), _ts: resetAt, resetAt, resetIds: resetIdsOf(PROFILE), _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'])})})++describe('a backup restored after a reset', () => {+ it('the replace keeps the reset stamp, so it is not taken for a copy from before the reset', async () => {+ const T1 = Date.now() - 3600e3+ signedIn({ ...clone(DEF), _ts: T1, resetAt: T1, resetIds: resetIdsOf(PROFILE) }, 4)+ const backup = { ...clone(PROFILE), _ts: 50 } // an old backup: no stamp+ api.mockResolvedValueOnce({ ok: true, rev: 5 })+ useStore.getState().importBackup(backup)+ await useStore.getState().pushState()+ const put = puts().at(-1)+ expect(ids(put.state.workouts)).toEqual(['w1', 'w2'])+ expect(put.state.resetAt).toBe(T1)+ })++ it('a device that saw the reset keeps the restored backup when it merges its own change in', async () => {+ const T1 = Date.now() - 3600e3+ const resetIds = resetIdsOf(PROFILE)+ signedIn({ ...clone(DEF), _ts: T1, resetAt: T1, resetIds }, 4)+ useStore.getState().update(s => { s.workouts.push(workout('gym-today', Date.now())) })+ // the server after the restore on the other device: the backup's workouts, the stamp kept+ const serverAfterImport = { ...clone(PROFILE), _ts: Date.now() - 1000, resetAt: T1, resetIds, _rev: 5 }+ api.mockRejectedValueOnce(conflict(serverAfterImport, 5))+ api.mockResolvedValueOnce({ ok: true, rev: 6 })+ await useStore.getState().pushState()+ expect(ids(puts().at(-1).state.workouts).sort()).toEqual(['gym-today', 'w1', 'w2'])+ })+})diff --git a/frontend/src/store/useStore.unit-sync.test.jsx b/frontend/src/store/useStore.unit-sync.test.jsxindex 63fcd5c00..610155112 100644--- a/frontend/src/store/useStore.unit-sync.test.jsx+++ b/frontend/src/store/useStore.unit-sync.test.jsx@@ -94,4 +94,24 @@ describe('converting the unit while another device logs in the old one', () => {expect(S.bodyweight.find(b => b.d === TODAY).w).toBe(180)expect(S.exWeights['0025'].w).toBe(55)})++ // Review of 771184c9: the history was relabelled, but the running session was converted.+ it('a label-only switch elsewhere relabels the running session too, on a pull and on a merge', async () => {+ const active = { id: 'run', d: TODAY, start: 5, entries: [{ id: '0025', sets: [{ w: 100, r: 5, done: true }] }] }+ const serverLb = { ...clone(KG), unit: 'lb', _ts: 200, unitSet: { at: 150, convert: false }, _rev: 2 }+ // a pull with nothing changed here: the server's copy is adopted+ signedIn({ ...clone(KG), active }, 1)+ api.mockResolvedValueOnce({ state: clone(serverLb), rev: 2 })+ await useStore.getState().pullState()+ expect(useStore.getState().S.unit).toBe('lb')+ expect(useStore.getState().S.active.entries[0].sets[0].w).toBe(100)+ // a merge with a change of this device's own+ signedIn({ ...clone(KG), active }, 1)+ useStore.getState().update(s => { s.restSec = 75 })+ api.mockRejectedValueOnce(conflict(clone(serverLb), 2))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })+ await useStore.getState().pushState()+ expect(useStore.getState().S.unit).toBe('lb')+ expect(useStore.getState().S.active.entries[0].sets[0].w).toBe(100)+ })})