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
Sync: what v1.3.9 still owed at the update keeps its setting, plan and note changes
Duarte Santos7b13e536bf00
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex 1388ffeea..0a33e5a7d 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -41,7 +41,7 @@ describe('Brazilian Portuguese locale', () => {// has to be taught is a number nobody reads. What the numbers stood for is asserted above.// If the hash fails, review the changed keys and wording before accepting a new one. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('9158547c74fd92bfe714f164605189a4679cd95c8d34724b4daa09cb36779659')+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('b76cb48dacef809fc18d7787e8daf45d86906380f4e6835c02d29994eb3aa7be')})test('does not leak European Portuguese UI terms', () => {diff --git a/frontend/src/lib/sync-legacy.js b/frontend/src/lib/sync-legacy.jsnew file mode 100644index 000000000..f9d53ac29--- /dev/null+++ b/frontend/src/lib/sync-legacy.js@@ -0,0 +1,95 @@+/* The first sync after an update from v1.3.9, when that app still owed the server a change.+ *+ * v1.3.9 stamped its workouts, routines, custom exercises and weigh-ins, but not its settings,+ * plan days, notes or removals. When another device synced meanwhile, the merge kept the other+ * device's stamped settings and undid what the old app changed offline: its rest time, its plan+ * day, its note went back. Nothing says which side changed a setting, except one thing the old+ * app left behind: the fingerprint of the copy it last agreed on with the server+ * (lib/sync-changes.js, `gym_synced_fp`), with one hash (`s`) over everything but the lists.+ *+ * Each setting the two copies hold differently was changed on one side or the other since that+ * copy (or on both). Trying every way round and hashing it the way v1.3.9 did finds the copy they+ * both started from, when exactly one way round matches: what differs from it on this device is+ * this device's change, stamped here so the merge keeps it (stampEdits). When no way round+ * matches (both sides changed the same setting, or there is no fingerprint) nothing is stamped+ * and the caller keeps the device's copy aside instead, so nothing the old app held is lost.+ *+ * Removals are left alone on purpose: v1.3.9 kept no record of them, so a workout it deleted+ * offline comes back after the merge. One tap removes it again; a wanted entry dropped by a wrong+ * guess would be gone.+ */+import { stampEdits } from './sync-merge.js'++// v1.3.9's fingerprint left these out of `s` (lib/sync-changes.js at v1.3.9).+const NOT_CONTENT_139 = new Set(['_ts', '_rev', 'active', 'workouts', 'bodyweight', 'routines', 'customEx'])+// Records v1.3.9 never changes: whatever this device holds is what the copy it agreed on held.+const KEEP_LOCAL = new Set(['deleted', 'edited', '_wid', '_wids'])+// Past this many settings that differ, the search is not worth it (2^n ways round).+const MAX_KEYS = 12++const FNV0 = 0x811c9dc5+const fnv = (h, s) => {+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0 }+ return h+}++/** v1.3.9's `s` hash of a copy: the rest of it, keys sorted, FNV-1a over the JSON. */+export function restHash139(S) {+ const rest = {}+ for (const f of Object.keys(S || {}).sort()) if (!NOT_CONTENT_139.has(f)) rest[f] = S[f]+ return fnv(FNV0, JSON.stringify(rest) ?? '').toString(36)+}++/**+ * The copy `local` and `server` both started from, as far as their settings go: per key, the+ * value of the side that did not change it. null when no way round, or more than one, matches+ * `fpS`, or too many settings differ to try.+ */+export function legacyBase(local, server, fpS) {+ if (typeof fpS !== 'string' || !local || !server) return null+ const keys = [...new Set([...Object.keys(local), ...Object.keys(server)])].filter(k => !NOT_CONTENT_139.has(k)).sort()+ // Per key: the candidates for its value in the start copy, as [value, JSON] (JSON undefined: absent).+ const opts = keys.map(k => {+ const l = local[k], lj = JSON.stringify(l)+ if (KEEP_LOCAL.has(k)) return [[l, lj]]+ const s = server[k], sj = JSON.stringify(s)+ return lj === sj ? [[l, lj]] : [[l, lj], [s, sj]]+ })+ if (opts.filter(o => o.length > 1).length > MAX_KEYS) return null+ const found = []+ const pick = []+ const walk = (i, h, first) => {+ if (found.length > 1) return+ if (i === keys.length) {+ if (fnv(h, '}').toString(36) === fpS) found.push([...pick])+ return+ }+ for (const [v, j] of opts[i]) {+ pick[i] = v+ if (j === undefined) walk(i + 1, h, first)+ else walk(i + 1, fnv(h, (first ? '' : ',') + JSON.stringify(keys[i]) + ':' + j), false)+ }+ }+ walk(0, fnv(FNV0, '{'), true)+ if (found.length !== 1) return null+ const base = {}+ keys.forEach((k, i) => { if (found[0][i] !== undefined) base[k] = found[0][i] })+ return base+}++/**+ * `local` (an old app's owed copy) ready to merge with `server`: every setting and plan day this+ * device changed since the copy `fp` was taken of is stamped at `now`. `resolved` false when that+ * could not be told and the device changed something besides its lists: the caller keeps the+ * copy aside. Returns a new object for `state`.+ */+export function liftLegacy(local, server, fp, now = Date.now()) {+ const state = JSON.parse(JSON.stringify(local))+ const fpS = fp && typeof fp === 'object' ? fp.s : null+ // Nothing besides the lists changed here: there is nothing to stamp, and nothing to lose.+ if (typeof fpS === 'string' && restHash139(local) === fpS) return { state, resolved: true }+ const base = legacyBase(local, server || {}, fpS)+ if (!base) return { state, resolved: false }+ stampEdits(base, state, now)+ return { state, resolved: true }+}diff --git a/frontend/src/lib/sync-legacy.test.js b/frontend/src/lib/sync-legacy.test.jsnew file mode 100644index 000000000..307c41663--- /dev/null+++ b/frontend/src/lib/sync-legacy.test.js@@ -0,0 +1,89 @@+/* The first merge of a copy v1.3.9 still owed the server, after another device synced+ (lib/sync-legacy.js). QA retest 2026-10-06: the old app's offline setting changes were undone. */+import { describe, expect, it } from 'vitest'+import { mergeStates, stampChange } from './sync-merge.js'+import { legacyBase, liftLegacy, restHash139 } from './sync-legacy.js'++// v1.3.9's `s` fingerprint, as that app computed it (lib/sync-changes.js at the v1.3.9 tag).+const NOT_CONTENT = new Set(['_ts', '_rev', 'active', 'workouts', 'bodyweight', 'routines', 'customEx'])+function fp139(S) {+ const rest = {}+ for (const f of Object.keys(S || {}).sort()) if (!NOT_CONTENT.has(f)) rest[f] = S[f]+ const s = JSON.stringify(rest) ?? ''+ let h = 0x811c9dc5+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0 }+ return { w: {}, b: {}, r: {}, c: {}, s: h.toString(36) }+}++const c = x => JSON.parse(JSON.stringify(x))+const T = Date.UTC(2026, 9, 6, 8)+const W = (id, t) => ({ id, d: '2026-10-0' + (1 + id.length % 5), start: t, end: t + 3600e3, entries: [{ id: 'bench', sets: [{ w: 60, r: 5 }] }] })+const base = {+ _ts: T, unit: 'kg', restSec: 90, week: { 1: 'r1' }, exNotes: { bench: 'old' }, favEx: ['squat'],+ edited: { restSec: T - 5e6 },+ workouts: [W('w1', T - 9e6), W('w2', T - 8e6)], routines: [{ id: 'r1', name: 'Push', ex: [], _ts: T - 1e7 }],+ bodyweight: [], customEx: [],+}++describe('a v1.3.9 copy owed at the update', () => {+ it('restHash139 is v1.3.9\'s fingerprint of the rest', () => {+ expect(restHash139(base)).toBe(fp139(base).s)+ })++ it('keeps the old app\'s offline setting, plan and note changes when another device synced meanwhile', () => {+ const fp = fp139(base)+ // v1.3.9 offline: rest time, a plan day and a note, no stamps+ const old = c(base)+ old.restSec = 140; old.week = { 1: 'r1', 3: 'r1' }; old.exNotes = { bench: 'new note' }; old._ts = T + 1000+ // an updated device logs a workout and changes another setting later+ const srv = c(base); srv.workouts.push(W('w3x', T + 5000)); srv.sound = false+ srv._ts = stampChange(base, srv, T + 5000)+ // before: the server's stamps won and the old app's changes went back+ const plain = mergeStates(old, srv)+ expect(plain.restSec).toBe(90)+ const { state, resolved } = liftLegacy(old, srv, fp, T + 9000)+ expect(resolved).toBe(true)+ for (const m of [mergeStates(state, srv), mergeStates(srv, state)]) {+ expect(m.restSec).toBe(140)+ expect(m.week).toEqual({ 1: 'r1', 3: 'r1' })+ expect(m.exNotes.bench).toBe('new note')+ expect(m.sound).toBe(false) // the other device's change stays too+ expect(m.workouts.map(w => w.id).sort()).toEqual(['w1', 'w2', 'w3x'])+ }+ })++ it('a setting the other device changed (and this one did not) stays the other device\'s', () => {+ const fp = fp139(base)+ const old = c(base); old.restSec = 140+ const srv = c(base); srv.exNotes = { bench: 'server note' }; srv._ts = stampChange(base, srv, T + 5000)+ const { state } = liftLegacy(old, srv, fp, T + 9000)+ const m = mergeStates(state, srv)+ expect(m.restSec).toBe(140)+ expect(m.exNotes.bench).toBe('server note')+ })++ it('both sides changed the same setting: nothing is guessed, the caller keeps the copy aside', () => {+ const fp = fp139(base)+ const old = c(base); old.restSec = 140+ const srv = c(base); srv.restSec = 60; srv._ts = stampChange(base, srv, T + 5000)+ expect(legacyBase(old, srv, fp.s)).toBe(null)+ expect(liftLegacy(old, srv, fp, T + 9000).resolved).toBe(false)+ })++ it('no fingerprint: not resolved; no setting changed here: resolved with nothing stamped', () => {+ const old = c(base); old.restSec = 140+ expect(liftLegacy(old, c(base), null).resolved).toBe(false)+ const same = c(base); same.workouts = same.workouts.slice(0, 1)+ const r = liftLegacy(same, c(base), fp139(base), T + 9000)+ expect(r.resolved).toBe(true)+ expect(r.state.edited).toEqual(base.edited)+ })++ it('never removes anything: a workout the old app deleted offline comes back', () => {+ const fp = fp139(base)+ const old = c(base); old.workouts = old.workouts.filter(w => w.id !== 'w2'); old.restSec = 140+ const srv = c(base); srv.workouts.push(W('w3x', T + 5000)); srv._ts = stampChange(base, srv, T + 5000)+ const m = mergeStates(liftLegacy(old, srv, fp, T + 9000).state, srv)+ expect(m.workouts.map(w => w.id).sort()).toEqual(['w1', 'w2', 'w3x'])+ })+})diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 1f720583b..aa6839ba4 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1987,4 +1987,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': 'أُنشئ {0} روتين على هذا الجهاز أثناء تسجيل الخروج. أضفه إلى ملفك، أو أبقِ الملف كما هو على الخادم.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': 'أُنشئت {0} روتينات على هذا الجهاز أثناء تسجيل الخروج. أضفها إلى ملفك، أو أبقِ الملف كما هو على الخادم.','This device, before signing in': 'هذا الجهاز قبل تسجيل الدخول',+ 'This device, before the update': 'هذا الجهاز قبل التحديث',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex e07275e70..d596d6335 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1954,4 +1954,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} Routine wurde auf diesem Gerät ohne Anmeldung erstellt. Zum Profil hinzufügen oder das Profil genau so lassen, wie es auf dem Server ist.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} Routinen wurden auf diesem Gerät ohne Anmeldung erstellt. Zum Profil hinzufügen oder das Profil genau so lassen, wie es auf dem Server ist.','This device, before signing in': 'Dieses Gerät, vor der Anmeldung',+ 'This device, before the update': 'Dieses Gerät, vor dem Update',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex b2cb1fe81..cd4e177f7 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} rutina se creó en este dispositivo sin iniciar sesión. Añádela a tu perfil o deja el perfil exactamente como está en el servidor.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} rutinas se crearon en este dispositivo sin iniciar sesión. Añádelas a tu perfil o deja el perfil exactamente como está en el servidor.','This device, before signing in': 'Este dispositivo, antes de iniciar sesión',+ 'This device, before the update': 'Este dispositivo, antes de la actualización',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex a5dee25b5..214af85fd 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} routine a été créée sur cet appareil sans connexion. Ajoutez-la à votre profil ou gardez le profil exactement tel qu’il est sur le serveur.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} routines ont été créées sur cet appareil sans connexion. Ajoutez-les à votre profil ou gardez le profil exactement tel qu’il est sur le serveur.','This device, before signing in': 'Cet appareil, avant la connexion',+ 'This device, before the update': 'Cet appareil, avant la mise à jour',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex a7d3fa565..eaffc857c 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} रूटीन इस डिवाइस पर बिना साइन इन किए बनाया गया। इसे अपनी प्रोफ़ाइल में जोड़ें, या प्रोफ़ाइल को ठीक वैसा ही रखें जैसा सर्वर पर है।','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} रूटीन इस डिवाइस पर बिना साइन इन किए बनाए गए। इन्हें अपनी प्रोफ़ाइल में जोड़ें, या प्रोफ़ाइल को ठीक वैसा ही रखें जैसा सर्वर पर है।','This device, before signing in': 'यह डिवाइस, साइन इन से पहले',+ 'This device, before the update': 'यह डिवाइस, अपडेट से पहले',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex ddd204f35..e69c43868 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1937,4 +1937,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} rutin készült ezen az eszközön bejelentkezés nélkül. Add hozzá a profilodhoz, vagy hagyd a profilt pontosan úgy, ahogy a szerveren van.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} rutin készült ezen az eszközön bejelentkezés nélkül. Add hozzá őket a profilodhoz, vagy hagyd a profilt pontosan úgy, ahogy a szerveren van.','This device, before signing in': 'Ez az eszköz, bejelentkezés előtt',+ 'This device, before the update': 'Ez az eszköz, a frissítés előtt',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex fcfdc0238..2e80551f5 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} routine è stata creata su questo dispositivo senza accesso. Aggiungila al tuo profilo o lascia il profilo esattamente com’è sul server.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} routine sono state create su questo dispositivo senza accesso. Aggiungile al tuo profilo o lascia il profilo esattamente com’è sul server.','This device, before signing in': 'Questo dispositivo, prima dell’accesso',+ 'This device, before the update': 'Questo dispositivo, prima dell’aggiornamento',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex a9e617091..00fdb0a03 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '로그인하지 않은 상태에서 이 기기에 루틴 {0}개가 만들어졌습니다. 프로필에 추가하거나 서버에 있는 프로필을 그대로 유지하세요.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '로그인하지 않은 상태에서 이 기기에 루틴 {0}개가 만들어졌습니다. 프로필에 추가하거나 서버에 있는 프로필을 그대로 유지하세요.','This device, before signing in': '로그인 전의 이 기기',+ 'This device, before the update': '업데이트 전의 이 기기',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex bfce601c4..46c4f6f42 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} rutyna powstała na tym urządzeniu bez logowania. Dodaj ją do profilu albo zostaw profil dokładnie taki, jaki jest na serwerze.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} rutyn powstało na tym urządzeniu bez logowania. Dodaj je do profilu albo zostaw profil dokładnie taki, jaki jest na serwerze.','This device, before signing in': 'To urządzenie, przed zalogowaniem',+ 'This device, before the update': 'To urządzenie, przed aktualizacją',}diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 6c08bb11b..0ae69b956 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} rotina foi criada neste dispositivo sem sessão iniciada. Adiciona-a ao teu perfil ou mantém o perfil exatamente como está no servidor.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} rotinas foram criadas neste dispositivo sem sessão iniciada. Adiciona-as ao teu perfil ou mantém o perfil exatamente como está no servidor.','This device, before signing in': 'Este dispositivo, antes de iniciar sessão',+ 'This device, before the update': 'Este dispositivo, antes da atualização',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 70eebec16..908f9d27e 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1938,4 +1938,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '{0} программа создана на этом устройстве без входа. Добавьте её в профиль или оставьте профиль ровно таким, как на сервере.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} программ создано на этом устройстве без входа. Добавьте их в профиль или оставьте профиль ровно таким, как на сервере.','This device, before signing in': 'Это устройство, до входа',+ 'This device, before the update': 'Это устройство, до обновления',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex d76709850..8575c47d3 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1945,4 +1945,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': 'มีการสร้างรูทีน {0} รายการบนอุปกรณ์นี้ขณะไม่ได้ลงชื่อเข้าใช้ เพิ่มลงในโปรไฟล์ของคุณ หรือคงโปรไฟล์ไว้ตามที่อยู่บนเซิร์ฟเวอร์','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': 'มีการสร้างรูทีน {0} รายการบนอุปกรณ์นี้ขณะไม่ได้ลงชื่อเข้าใช้ เพิ่มลงในโปรไฟล์ของคุณ หรือคงโปรไฟล์ไว้ตามที่อยู่บนเซิร์ฟเวอร์','This device, before signing in': 'อุปกรณ์นี้ ก่อนลงชื่อเข้าใช้',+ 'This device, before the update': 'อุปกรณ์นี้ ก่อนอัปเดต',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 1041c89c9..3178dd7e4 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': 'Bu cihazda oturum açılmadan {0} rutin oluşturuldu. Onu profiline ekle ya da profili sunucudaki hâliyle bırak.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': 'Bu cihazda oturum açılmadan {0} rutin oluşturuldu. Bunları profiline ekle ya da profili sunucudaki hâliyle bırak.','This device, before signing in': 'Bu cihaz, oturum açmadan önce',+ 'This device, before the update': 'Bu cihaz, güncellemeden önce',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 25d550390..b6856ab18 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1931,4 +1931,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': 'На цьому пристрої без входу створено програм: {0}. Додай її в профіль або лиши профіль точно таким, як на сервері.','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': 'На цьому пристрої без входу створено програм: {0}. Додай їх у профіль або лиши профіль точно таким, як на сервері.','This device, before signing in': 'Цей пристрій, до входу',+ 'This device, before the update': 'Цей пристрій, до оновлення',}diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex b684c7db7..2fba069b7 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -1927,4 +1927,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '此裝置在未登入狀態下建立了 {0} 個訓練菜單。是否將其加入你的個人檔案,或是維持伺服器上的原本紀錄?','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '此裝置在未登入狀態下建立了 {0} 個訓練菜單。是否將其加入你的個人檔案,或是維持伺服器上的原本紀錄?','This device, before signing in': '此裝置(登入前)',+ 'This device, before the update': '此裝置(更新前)',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex e4a563574..d38a18603 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1934,4 +1934,5 @@ export default {'{0} routine was made on this device while signed out. Add it to your profile, or keep the profile exactly as it is on the server.': '此设备在未登录时创建了 {0} 个训练计划。把它加入你的个人资料,或保持个人资料与服务器上的完全一致。','{0} routines were made on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '此设备在未登录时创建了 {0} 个训练计划。把它们加入你的个人资料,或保持个人资料与服务器上的完全一致。','This device, before signing in': '此设备(登录前)',+ 'This device, before the update': '此设备(更新前)',}diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 7549a4d2e..10df69d5a 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 { refillIfComplete } from '../lib/rotation.js'+import { liftLegacy } from '../lib/sync-legacy.js'import { mergeStates, localExtras, stampChange, highestStamp, stampRestore, 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'@@ -35,6 +36,9 @@ const SYNC_KEY = 'gym_sync'// Which write of the saved copy this is: a tab finds another tab's write by it (persist, joinSaved).const WID_KEY = 'gym_state_wid'const DIRTY_KEY = 'gym_dirty' // the saved copy owes the server a change+// An owed copy an older app (v1.3.9) left behind: its first sync stamps what it changed+// (lib/sync-legacy.js), holding the fingerprint that app last agreed on with the server.+const LEGACY_KEY = 'gym_legacy_owed'const SYNCED_AT_KEY = 'gym_synced_at' // when this device and the server last held the same copyconst SYNCED_FP_KEY = 'gym_synced_fp' // a fingerprint of that copy (lib/sync-changes.js)// Changes a forced sign-out or disconnect kept on this device, by server and account, until it@@ -296,6 +300,18 @@ export const useStore = create((set, get) => {// The write of the saved copy this tab last read or made, and whose copy it was (joinSaved).let seenWid = (() => { try { return localStorage.getItem(WID_KEY) } catch { return null } })()let seenOwner = (() => { try { return localStorage.getItem('gym_owner') } catch { return null } })()+ // A copy that owes the server a change and was never written with a write id was last saved by+ // an app from before this one (v1.3.9), which stamped none of its settings, plan days or notes.+ // Noted now, before this app's first save writes a write id beside it.+ try {+ if (!seenWid && seenOwner && localStorage.getItem(DIRTY_KEY) === '1' && localStorage.getItem(KEY) && !localStorage.getItem(LEGACY_KEY)) {+ let fp = null+ try { fp = JSON.parse(localStorage.getItem(SYNCED_FP_KEY)) } catch { /* no fingerprint: the copy is kept aside instead */ }+ localStorage.setItem(LEGACY_KEY, JSON.stringify({ fp, owner: seenOwner }))+ }+ } catch { /* storage refused: the first sync merges it as before */ }+ const readLegacy = () => { try { return JSON.parse(localStorage.getItem(LEGACY_KEY)) || null } catch { return null } }+ const clearLegacy = () => { try { localStorage.removeItem(LEGACY_KEY) } catch { /* the next sync tries again */ } }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 */ } }@@ -588,6 +604,16 @@ export const useStore = create((set, get) => {// happens before the push lands still sees it as unsent.const mergeInto = (local, remote, rev) => {const ts = metaOf().base?.ts || 0+ // The first merge of an older app's owed copy: what that app changed besides its lists is+ // stamped so the merge keeps it (lib/sync-legacy.js). When that cannot be told, the copy as+ // it was is kept aside before the merge, to be saved from Settings, so nothing is lost.+ const legacy = readLegacy()+ if (legacy && legacy.owner === get().user?.id) {+ const lifted = liftLegacy(local, remote, legacy.fp, Math.max(Date.now(), highestStamp(local) + 1, highestStamp(remote) + 1))+ if (!lifted.resolved) keepAside(local, t('This device, before the update'))+ local = Object.assign(clone(DEF), lifted.state)+ }+ if (legacy) clearLegacy()const merged = Object.assign(clone(DEF), mergeStates(local, remote))merged.active = carryActive(local, merged)// A pass of this app's rotation that the merge left complete (each copy finished a session of@@ -622,7 +648,10 @@ export const useStore = create((set, get) => {replaceRev = null// `stamped`: this client stamps its own changes; the server stamps only for one that does not// (api/sync-stamps.js).- const body = { state: S, stamped: true }+ // An older app's owed copy over the revision it read: the server stamps what that app changed+ // against the copy it holds, exactly as it would for that app (api/sync-stamps.js).+ const legacy = readLegacy()+ const body = { state: S, stamped: !(legacy && legacy.owner === get().user?.id) }if (asReplace != null) { body.baseRev = asReplace.rev; if (asReplace.wid) body.baseWid = asReplace.wid }else if (!force && base) { body.baseRev = base.rev; if (base.wid) body.baseWid = base.wid }try {@@ -631,6 +660,7 @@ export const useStore = create((set, get) => {// next push to, and the marker must not pretend otherwise.if (r.rev == null) dropSync()else writeSync(r.rev, S._ts, r.wid)+ if (legacy) clearLegacy()markOwed(false)toldTooLarge = falseconfirmed(S)@@ -948,14 +978,16 @@ export const useStore = create((set, get) => {// "Keep profile as is": what this device held before the sign-in leaves the screen, but not the// device. It is kept aside like a kept change (its own key, never added back on its own) and can// be saved as a backup file from Settings, in case the answer was the wrong one.- const keepDeviceCopy = async () => {- const S = get().S+ const keepAside = async (S, name) => {if (!hasData(S)) return+ const state = clone(S)const all = await readStashes()const uid = 'device-' + Date.now().toString(36)- all[stashKey(serverBase(), uid)] = { server: serverBase() || null, uid, name: t('This device, before signing in'), at: Date.now(), state: clone(S) }+ all[stashKey(serverBase(), uid)] = { server: serverBase() || null, uid, name, at: Date.now(), state }await writeStashes(all)+ set({ keptRev: get().keptRev + 1 })}+ const keepDeviceCopy = () => keepAside(get().S, t('This device, before signing in'))// 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.diff --git a/frontend/src/store/useStore.legacy-upgrade.test.jsx b/frontend/src/store/useStore.legacy-upgrade.test.jsxnew file mode 100644index 000000000..4bd085ce4--- /dev/null+++ b/frontend/src/store/useStore.legacy-upgrade.test.jsx@@ -0,0 +1,132 @@+// @vitest-environment happy-dom++/* The update from v1.3.9 while that app still owed the server a change (QA retest 2026-10-06): its+ offline setting, plan and note changes were undone on the first sync when another device had+ synced meanwhile, and pushed without stamps when none had. lib/sync-legacy.js. */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const h = vi.hoisted(() => ({ api: null }))+vi.mock('../lib/api.js', () => ({ api: (...a) => h.api(...a), setRemoteAuth: () => {} }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: () => {}, stopRest: () => {}, abandonWork: () => {} }) } }))++const clone = v => JSON.parse(JSON.stringify(v))+const T = Date.UTC(2026, 9, 6, 8)+const W = (id, t) => ({ id, d: '2026-10-01', start: t, end: t + 3600e3, entries: [] })+const OWNER = 'u1'++// v1.3.9's fingerprint (lib/sync-changes.js at the v1.3.9 tag).+const NOT_CONTENT = new Set(['_ts', '_rev', 'active', 'workouts', 'bodyweight', 'routines', 'customEx'])+const hash = v => { const s = JSON.stringify(v) ?? ''; let x = 0x811c9dc5; for (let i = 0; i < s.length; i++) { x ^= s.charCodeAt(i); x = Math.imul(x, 0x01000193) >>> 0 } return x.toString(36) }+function fp139(S) {+ const rest = {}+ for (const f of Object.keys(S).sort()) if (!NOT_CONTENT.has(f)) rest[f] = S[f]+ return { w: Object.fromEntries(S.workouts.map(w => [w.id, hash(w)])), b: {}, r: {}, c: {}, s: hash(rest) }+}++function server(doc) {+ const s = { doc: clone(doc), log: [] }+ h.api = async (path, opts = {}) => {+ const method = opts.method || 'GET'+ const body = opts.body ? JSON.parse(opts.body) : undefined+ s.log.push({ method, path, body })+ if (method === 'GET' && path === '/api/data/rev') return { rev: s.doc._rev }+ if (method === 'GET' && path === '/api/data') return { state: clone(s.doc), rev: s.doc._rev }+ if (method === 'PUT' && path === '/api/data') {+ if (body.baseRev != null && body.baseRev !== s.doc._rev) throw Object.assign(new Error('conflict'), { status: 409, data: { error: 'conflict', rev: s.doc._rev, state: clone(s.doc) } })+ body.state._rev = s.doc._rev + 1+ s.doc = body.state+ return { ok: true, rev: s.doc._rev }+ }+ throw new Error('unexpected ' + method + ' ' + path)+ }+ return s+}++let DEF+// What v1.3.9 left in the browser: its copy with offline changes, owed, the marker of the revision+// it last synced and the fingerprint of that copy. No write id: that app never wrote one.+function leaveOldCopy(base, mut) {+ const fp = fp139(base)+ const old = clone(base); delete old._rev+ mut(old)+ localStorage.setItem('gym_owner', OWNER)+ localStorage.setItem('gym_user', JSON.stringify({ id: OWNER, name: 'Ana' }))+ localStorage.setItem('gym_state_v1', JSON.stringify(old))+ localStorage.setItem('gym_sync', JSON.stringify({ rev: base._rev, ts: base._ts }))+ localStorage.setItem('gym_synced_fp', JSON.stringify(fp))+ localStorage.setItem('gym_dirty', '1')+}+async function openApp() {+ vi.resetModules()+ const m = await import('./useStore.js')+ m.useStore.setState({ user: { id: OWNER, name: 'Ana' }, ready: true })+ return m.useStore+}++beforeEach(async () => {+ localStorage.clear()+ DEF = (await import('./useStore.js')).DEF+})+afterEach(() => localStorage.clear())++const baseDoc = () => ({ ...clone(DEF), _ts: T, _rev: 3, restSec: 90, week: { 1: 'r1' }, exNotes: { bench: 'old' }, workouts: [W('w1', T - 9e6), W('w2', T - 8e6)] })++describe('the first sync after the update from v1.3.9', () => {+ it('another device synced meanwhile: the old app\'s offline rest time, plan day and note are kept', async () => {+ const base = baseDoc()+ leaveOldCopy(base, s => { s.restSec = 140; s.week = { 1: 'r1', 3: 'r1' }; s.exNotes = { bench: 'new note' }; s._ts = T + 1000 })+ // an updated device logged a workout and turned the sound off, stamped+ const srvDoc = { ...clone(base), _rev: 4, _ts: T + 5000, sound: false, edited: { sound: T + 5000 }, workouts: [...base.workouts, W('w3x', T + 5000)] }+ const srv = server(srvDoc)+ const A = await openApp()+ await A.getState().pullState()+ for (const S of [srv.doc, A.getState().S]) {+ expect(S.restSec).toBe(140)+ expect(S.week).toEqual({ 1: 'r1', 3: 'r1' })+ expect(S.exNotes.bench).toBe('new note')+ expect(S.sound).toBe(false)+ expect(S.workouts.map(w => w.id).sort()).toEqual(['w1', 'w2', 'w3x'])+ }+ expect(localStorage.getItem('gym_legacy_owed')).toBe(null)+ expect(localStorage.getItem('gym_stash')).toBe(null)+ })++ it('both sides changed the same setting: the merge decides as before, and the old copy is kept aside', async () => {+ const base = baseDoc()+ leaveOldCopy(base, s => { s.restSec = 140; s._ts = T + 1000 })+ server({ ...clone(base), _rev: 4, _ts: T + 5000, restSec: 60, edited: { restSec: T + 5000 } })+ const A = await openApp()+ await A.getState().pullState()+ await new Promise(r => setTimeout(r, 20))+ const kept = Object.values(JSON.parse(localStorage.getItem('gym_stash')) || {})+ expect(kept).toHaveLength(1)+ expect(kept[0].name).toBe('This device, before the update')+ expect(kept[0].state.restSec).toBe(140)+ })++ it('nobody synced meanwhile: the push lets the server stamp what the old app changed', async () => {+ const base = baseDoc()+ leaveOldCopy(base, s => { s.restSec = 140; s._ts = T + 1000 })+ const srv = server(base)+ const A = await openApp()+ await A.getState().pullState()+ const put = srv.log.find(x => x.method === 'PUT')+ expect(put.body.stamped).toBe(false)+ expect(put.body.baseRev).toBe(3)+ expect(localStorage.getItem('gym_legacy_owed')).toBe(null)+ // and from here on this app stamps its own changes+ A.getState().update(s => { s.restSec = 150 })+ await A.getState().pushState()+ expect(srv.log.filter(x => x.method === 'PUT').at(-1).body.stamped).toBe(true)+ })++ it('a copy this app wrote is never taken for an old app\'s', async () => {+ const base = baseDoc()+ leaveOldCopy(base, s => { s.restSec = 140 })+ localStorage.setItem('gym_state_wid', 'abc')+ const srv = server(base)+ const A = await openApp()+ await A.getState().pullState()+ expect(srv.log.find(x => x.method === 'PUT').body.stamped).toBe(true)+ })+})