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: a conflict keeps each routine as it was edited last, and a device can count what the server has not seen
Duarte Santos4bce870be8a6
diff --git a/frontend/src/lib/sync-changes.js b/frontend/src/lib/sync-changes.jsnew file mode 100644index 000000000..046d6c535--- /dev/null+++ b/frontend/src/lib/sync-changes.js@@ -0,0 +1,65 @@+/* How much of this device's copy the server has not seen yet.+ *+ * Signing out and disconnecting refuse to wipe a copy that still owes the server something, and+ * say how much ("3 changes are not on your server"). The store keeps a small fingerprint of the+ * last copy this device and the server agreed on — one hash per workout, weigh-in, routine and+ * custom exercise, one for everything else (settings, the week plan, working weights, notes) —+ * and counts what differs from it. It is a count of things touched, not a diff: two edits to the+ * same workout are one change, and a changed setting and a changed plan are one change together.+ */++const list = v => (Array.isArray(v) ? v : [])++// FNV-1a over the JSON text: cheap, stable across runs, and plenty to tell an entry that is the+// same from one that was edited.+function hash(v) {+ const s = JSON.stringify(v) ?? ''+ let h = 0x811c9dc5+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0 }+ return h.toString(36)+}++const workoutKey = w => (w?.id != null ? w.id : `${w?.d}|${w?.start}`)+// The lists counted entry by entry, keyed the way lib/sync-merge.js unions them.+const LISTS = {+ w: ['workouts', workoutKey],+ b: ['bodyweight', e => e?.d],+ r: ['routines', r => r?.id],+ c: ['customEx', e => e?.id],+}+// Not content: the stamp and the revision say when, not what; the running workout never syncs.+const NOT_CONTENT = new Set(['_ts', '_rev', 'active', ...Object.values(LISTS).map(([f]) => f)])++/** A fingerprint of `S`: per-entry hashes of the counted lists, one hash (`s`) for the rest. */+export function syncFingerprint(S) {+ const fp = {}+ for (const [k, [field, key]] of Object.entries(LISTS)) {+ fp[k] = {}+ for (const x of list(S?.[field])) {+ const id = key(x)+ if (id != null) fp[k][id] = hash(x)+ }+ }+ const rest = {}+ for (const f of Object.keys(S || {}).sort()) if (!NOT_CONTENT.has(f)) rest[f] = S[f]+ fp.s = hash(rest)+ return fp+}++/**+ * How many entries of `S` were added, edited or removed since the copy `fp` was taken of, plus+ * one when anything else changed. null when there is no fingerprint to compare with — the device+ * last agreed with the server before it kept one, so it cannot say how much is waiting.+ */+export function countChanges(S, fp) {+ if (!fp || typeof fp !== 'object') return null+ const now = syncFingerprint(S)+ let n = now.s !== fp.s ? 1 : 0+ for (const k of Object.keys(LISTS)) {+ const a = now[k] || {}+ const b = fp[k] || {}+ for (const id of Object.keys(a)) if (a[id] !== b[id]) n+++ for (const id of Object.keys(b)) if (!(id in a)) n+++ }+ return n+}diff --git a/frontend/src/lib/sync-changes.test.js b/frontend/src/lib/sync-changes.test.jsnew file mode 100644index 000000000..3f24a7563--- /dev/null+++ b/frontend/src/lib/sync-changes.test.js@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest'+import { countChanges, syncFingerprint } from './sync-changes.js'++const workout = (id, d = '2026-09-01') => ({ id, d, start: 1, entries: [] })+const state = (over = {}) => ({+ _ts: 100, unit: 'kg', restSec: 90, week: { 1: ['r1'] },+ workouts: [workout('w1'), workout('w2', '2026-09-02')],+ bodyweight: [{ d: '2026-09-01', kg: 80 }],+ routines: [{ id: 'r1', name: 'Push', ex: [] }],+ customEx: [], exWeights: { sq: { w: 100 } }, ...over,+})+const clone = v => JSON.parse(JSON.stringify(v))++describe('counting what the server has not seen', () => {+ it('nothing, when the copy is the one the server has', () => {+ const S = state()+ expect(countChanges(clone(S), syncFingerprint(S))).toBe(0)+ })++ it('one per added, edited or removed entry', () => {+ const fp = syncFingerprint(state())+ const S = state()+ S.workouts.push(workout('w3', '2026-09-03')) // added+ S.workouts[0].entries.push({ ex: 'bench', sets: [] }) // edited+ S.bodyweight = [] // removed+ S.routines[0].name = 'Push A' // edited+ expect(countChanges(S, fp)).toBe(4)+ })++ it('settings, the plan and working weights count as one change together', () => {+ const fp = syncFingerprint(state())+ expect(countChanges(state({ restSec: 60, week: {}, exWeights: {} }), fp)).toBe(1)+ })++ it('the stamp, the revision and the running workout are not changes', () => {+ const fp = syncFingerprint(state())+ expect(countChanges(state({ _ts: 999, _rev: 7, active: { id: 'running' } }), fp)).toBe(0)+ })++ it('unknown without a fingerprint to compare with', () => {+ expect(countChanges(state(), null)).toBeNull()+ })+})diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 3f0ca79c1..1e4b1704f 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -8,8 +8,10 @@** Rules, by field:* - scalars and settings, `week`, `dayPlan`, `wc`, `reminder`, …: from the copy with the newer `_ts`- * - workouts, routines, customEx, equipProfiles, gymCards: union by id, the newer copy's version- * of an id that both have; workouts sorted by day and start like every other writer+ * - workouts, customEx, equipProfiles, gymCards: union by id, the newer copy's version of an+ * id that both have; workouts sorted by day and start like every other writer+ * - routines: union by id in the newer copy's order; of an id that both have, the version+ * edited last by its own `_ts` (stampRoutines), the newer copy's on a tie* - bodyweight: union by day, the later-edited (`t`) entry of a day that both have* - favEx: ordered set union, the newer copy first* - exWeights: union by exercise, the better `w` for that exercise — larger for an ordinary@@ -88,6 +90,17 @@ export function mergeStates(a, b, { prefer } = {}) {for (const f of ['routines', 'customEx', 'equipProfiles', 'gymCards']) {if (list(n[f]).length || list(o[f]).length) out[f] = unionById(n[f], o[f]).map(clone)}+ // A routine edited on both sides keeps the version edited last. Taking the newer copy's+ // version dropped a plan edit made on one device whenever the other had since logged a set or+ // flipped a setting — its whole copy was newer, its version of that routine was not. `prefer`+ // (sign-in) keeps the preferred side's plan as it is.+ if (!prefer && out.routines) {+ const other = new Map(list(o.routines).filter(r => r?.id != null).map(r => [r.id, r]))+ out.routines = out.routines.map(r => {+ const alt = r?.id != null && other.get(r.id)+ return alt && (alt._ts || 0) > (r._ts || 0) ? clone(alt) : r+ })+ }out.bodyweight = mergeBodyweight(n.bodyweight, o.bodyweight).map(clone)if (list(n.favEx).length || list(o.favEx).length) out.favEx = [...new Set([...list(n.favEx), ...list(o.favEx)])]out.exWeights = clone(mergeExWeights(n.exWeights, o.exWeights))@@ -99,6 +112,23 @@ export function mergeStates(a, b, { prefer } = {}) {return out}+const sameRoutine = (a, b) => JSON.stringify({ ...a, _ts: 0 }) === JSON.stringify({ ...b, _ts: 0 })++/**+ * Stamps `_ts` on every routine of `next` that is new or differs from its version in `prev` — the+ * edit time mergeStates needs to keep the routine edited last. The store runs it on every change+ * (useStore update), so no screen that edits a plan has to remember to. Mutates and returns `next`.+ */+export function stampRoutines(prev = [], next = [], now = Date.now()) {+ const before = new Map(list(prev).filter(r => r?.id != null).map(r => [r.id, r]))+ for (const r of list(next)) {+ if (!r || r.id == null) continue+ const old = before.get(r.id)+ if (!old || (old !== r && !sameRoutine(old, r))) r._ts = now+ }+ return next+}+// What `local` holds that `server` does not: the workouts and weigh-ins a device logged while it// was signed out, and the custom exercises they use. Sign-in asks about these before the server's// profile replaces the local copy; zero of each means there is nothing to ask about.diff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.jsindex 62c6a6fbe..613483c0b 100644--- a/frontend/src/lib/sync-merge.test.js+++ b/frontend/src/lib/sync-merge.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { localExtras, mergeBodyweight, mergeStates, newerOf, unionById } from './sync-merge.js'+import { localExtras, mergeBodyweight, mergeStates, newerOf, stampRoutines, unionById } from './sync-merge.js'const workout = (id, d = '2026-09-01', start = 1) => ({ id, d, start, entries: [] })const routine = (id, name = id) => ({ id, name, ex: [] })@@ -151,3 +151,51 @@ describe('sign-in adoption helpers', () => {expect(mergeStates(server, local).unit).toBe('kg') // without prefer the newer copy decides})})++// A conflict used to hand every routine both sides had to the copy whose WHOLE state was newer.+// The phone edits the push day, then the desktop toggles a setting: the desktop's copy is newer,+// and the phone's edit was gone. Each routine now carries its own edit time.+describe('routines keep the version edited last', () => {+ const r = (id, reps, ts) => ({ id, name: id, ex: [{ id: 'bench', sets: 3, reps }], ...(ts != null ? { _ts: ts } : {}) })++ it('the older copy\'s routine wins when it was edited after the newer copy\'s', () => {+ const phone = base({ _ts: 100, routines: [r('push', 15, 90), r('pull', 8, 10)] })+ const desk = base({ _ts: 200, restSec: 60, routines: [r('push', 10, 20), r('pull', 12, 150)] })+ const m = mergeStates(phone, desk)+ expect(m.restSec).toBe(60) // settings: the newer copy+ expect(m.routines.find(x => x.id === 'push').ex[0].reps).toBe(15) // edited later on the phone+ expect(m.routines.find(x => x.id === 'pull').ex[0].reps).toBe(12) // edited later on the desk+ expect(ids(m.routines)).toEqual(['push', 'pull']) // the newer copy's order+ expect(mergeStates(desk, phone).routines).toEqual(m.routines)+ })++ it('without stamps, or on a tie, the newer copy\'s version stays', () => {+ const a = base({ _ts: 100, routines: [r('push', 15)] })+ const b = base({ _ts: 200, routines: [r('push', 10)] })+ expect(mergeStates(a, b).routines[0].ex[0].reps).toBe(10)+ const c = base({ _ts: 100, routines: [r('push', 15, 50)] })+ const d = base({ _ts: 200, routines: [r('push', 10, 50)] })+ expect(mergeStates(c, d).routines[0].ex[0].reps).toBe(10)+ })++ it('sign-in (prefer) keeps the preferred side\'s plan whatever the stamps say', () => {+ const server = base({ _ts: 100, routines: [r('push', 10, 10)] })+ const device = base({ _ts: 200, routines: [r('push', 15, 90)] })+ expect(mergeStates(server, device, { prefer: 'a' }).routines[0].ex[0].reps).toBe(10)+ })++ it('stampRoutines stamps a new or edited routine and leaves the rest alone', () => {+ const prev = [r('push', 10, 5), r('pull', 8, 6), r('legs', 5, 7)]+ const next = JSON.parse(JSON.stringify(prev))+ next[0].ex[0].reps = 12 // edited+ next.push(r('core', 20)) // new+ next.splice(2, 1) // legs deleted+ stampRoutines(prev, next, 1000)+ expect(next.map(x => x._ts)).toEqual([1000, 6, 1000])+ // the stamp alone is not an edit: a routine that only carries a different _ts keeps it+ const again = JSON.parse(JSON.stringify(next))+ again[1]._ts = 99+ stampRoutines(next, again, 2000)+ expect(again.map(x => x._ts)).toEqual([1000, 99, 1000])+ })+})