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: the order of the routines is stamped, so a reorder survives another device's later change
Duarte Santos95503f8f94f2
diff --git a/api/sync-stamps.js b/api/sync-stamps.jsindex 7c0ae5c60..d441d7441 100644--- a/api/sync-stamps.js+++ b/api/sync-stamps.js@@ -59,7 +59,7 @@ const capStamps = m => {return m;};const OWN_MERGE = new Set([- '_ts', '_rev', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone',+ '_ts', '_rev', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder','workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx','exWeights', 'balanceOverrides', 'loadKind', 'plates',]);@@ -191,6 +191,12 @@ function stampUnstamped(cur, next, sent, now) {else if (!moved(k)) ed[k] = now;}}+ // The order of the routines (sync-merge.js ORDER_KEY), the same way: a reorder is stamped, an+ // older copy's order of routines another device reordered since is put back as stored.+ if (Array.isArray(next.routines) && orderMoved(cur.routines, next.routines)) {+ if (stale(ORDER_KEY)) next.routines = inOrderOf(cur.routines, next.routines);+ else if (!moved(ORDER_KEY)) ed[ORDER_KEY] = now;+ }if (Object.keys(ed).length) next.edited = ed;// Entries edited without stamps of their own: a routine, a custom exercise, a profile, a card,// a workout whose content changed. The same rule per field: one the stored entry changed (`_f`)@@ -221,6 +227,32 @@ function stampUnstamped(cur, next, sent, now) {}}+const ORDER_KEY = 'routineOrder';+/** Whether two lists hold the routines both have in a different order (sync-merge.js orderMoved). */+export function orderMoved(a, b) {+ const ida = list(a).map(r => r?.id).filter(id => id != null), idb = list(b).map(r => r?.id).filter(id => id != null);+ const inA = new Set(ida), inB = new Set(idb);+ return JSON.stringify(ida.filter(id => inB.has(id))) !== JSON.stringify(idb.filter(id => inA.has(id)));+}+// `xs` with the routines `order` also has in its order, each other one after its nearest earlier+// neighbour in `xs` (sync-merge.js unionByNeighbours).+function inOrderOf(order, xs) {+ const by = new Map(list(xs).filter(x => x?.id != null).map(x => [x.id, x]));+ const out = list(order).filter(x => x?.id != null && by.has(x.id)).map(x => by.get(x.id));+ const at = new Set(out.map(x => x.id));+ let prev = null;+ for (const x of list(xs)) {+ if (x?.id == null) { out.push(x); continue; }+ if (!at.has(x.id)) {+ const i = prev == null ? -1 : out.findIndex(y => y?.id === prev);+ out.splice(i + 1, 0, x);+ at.add(x.id);+ }+ prev = x.id;+ }+ return out;+}+// Step 0, for a writer that does not stamp: what it left out because it does not know it comes// back from the stored copy. An app from before a field existed rebuilds what it edits from the// fields it knows: v1.3.9's exercise sheet saved a routine's exercise as sets, reps and weight,diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex fd6ad4ffd..f601f8be3 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -600,12 +600,21 @@ function applyDeletions(S, deleted) {// a rotation pass refilled on the phone survives a setting flipped on the desktop. Fields with a// merge of their own are not stamped here; a field nobody stamped follows the newer copy, as before.const OWN_MERGE = new Set([- '_ts', '_rev', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone',+ '_ts', '_rev', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder','workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx','exWeights', 'balanceOverrides', 'loadKind', 'plates',])// Stamped per key instead of whole: one day of the plan, one exercise's note or bar.const PER_KEY = new Set(['week', 'dayPlan', 'exNotes', 'barWeights'])+// The order of the routines, as the list shows them, is a choice of its own (`edited.routineOrder`):+// a reorder on one device was lost to the other's whole copy whenever that one was newer.+export const ORDER_KEY = 'routineOrder'+// Whether two lists hold the routines both have in a different order (added or removed ones aside).+export function orderMoved(a, b) {+ const ida = list(a).map(r => r?.id).filter(id => id != null), idb = list(b).map(r => r?.id).filter(id => id != null)+ const inA = new Set(ida), inB = new Set(idb)+ return JSON.stringify(ida.filter(id => inB.has(id))) !== JSON.stringify(idb.filter(id => inA.has(id)))+}// A per-key stamp of a key neither copy holds any more is dropped after this long.const EDIT_KEEP_MS = 180 * 86400000const same = (x, y) => JSON.stringify(x) === JSON.stringify(y)@@ -629,6 +638,7 @@ export function stampEdits(prev, next, now = Date.now()) {}} else if (p !== n && !same(p, n)) { ed[k] = now; touched = true }}+ if (prev && prev.routines !== next.routines && orderMoved(prev.routines, next.routines)) { ed[ORDER_KEY] = now; touched = true }// An own accent colour is one choice made in two fields: picking a new colour while the own// colour is already on changes only accentCustom, and a preset picked earlier on another device// then kept `accent` and won (QA 2026-10-06). Either one changed to an own colour stamps both.@@ -771,6 +781,13 @@ export function mergeStates(a0, b0, { prefer } = {}) {for (const f of ['routines', 'customEx', 'equipProfiles', 'gymCards']) {if (list(n[f]).length || list(o[f]).length) out[f] = (f === 'routines' ? unionByNeighbours : unionById)(n[f], o[f]).map(clone)}+ // The routines in the order chosen last (`edited.routineOrder`), the newer copy's without a+ // stamp to tell; one only the other copy has still goes next to its neighbour there. Each entry+ // is still the newer copy's version here, merged with the other's below.+ if (!prefer && out.routines && (Number(o.edited?.[ORDER_KEY]) || 0) > (Number(n.edited?.[ORDER_KEY]) || 0)) {+ const mine = new Map(list(n.routines).filter(r => r?.id != null).map(r => [r.id, r]))+ out.routines = unionByNeighbours(o.routines, n.routines).map(r => clone(r?.id != null && mine.has(r.id) ? mine.get(r.id) : r))+ }// 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`@@ -898,6 +915,7 @@ export function stampRestore(next, others = [], now = Date.now()) {for (const f of PER_KEY) {for (const S of [next, ...others]) for (const s of Object.keys(isMap(S?.[f]) ? S[f] : {})) ed[`${f}.${s}`] = now}+ ed[ORDER_KEY] = nownext.edited = edfor (const f of ['routines', 'customEx']) for (const x of list(next[f])) if (x && typeof x === 'object') x._ts = nowreturn nextdiff --git a/frontend/src/lib/sync-routine-order.test.js b/frontend/src/lib/sync-routine-order.test.jsnew file mode 100644index 000000000..62db5d1ca--- /dev/null+++ b/frontend/src/lib/sync-routine-order.test.js@@ -0,0 +1,64 @@+/* RC review 2026-10-07: the order of the routines was not stamped. A reorder on one device was lost+ to the other device's copy whenever that one was newer as a whole (a weigh-in logged later), so+ the list jumped back. The order is now a choice of its own (`edited.routineOrder`), merged like+ a setting; a routine only one copy has still goes next to its neighbour there. The server stamps+ it for a writer that does not (api/sync-stamps.js), and keeps a newer order from an older copy. */+import { describe, expect, it } from 'vitest'+import { mergeStates, orderMoved, stampChange } from './sync-merge.js'+import * as S from '../../../api/sync-stamps.js'++const clone = v => JSON.parse(JSON.stringify(v))+const T = 1_800_000_000_000+const r = id => ({ id, name: id, ex: [], _ts: T - 1000 })+const ids = s => s.routines.map(x => x.id).join(',')+const change = (prev, fn, wall) => { const n = clone(prev); fn(n); n._ts = stampChange(prev, n, wall); return n }+const base = () => ({ _ts: T, unit: 'kg', workouts: [], routines: [r('a'), r('b'), r('c')], edited: { restSec: T } })+const reorder = order => s => { s.routines = order.map(id => s.routines.find(x => x.id === id)) }++describe('the order of the routines', () => {+ it('a reorder survives the other device\'s later, unrelated change, in either merge order', () => {+ const A = change(base(), reorder(['c', 'a', 'b']), T + 1000)+ const B = change(base(), s => { s.restSec = 45 }, T + 5000)+ for (const m of [mergeStates(A, B), mergeStates(B, A)]) {+ expect(ids(m)).toBe('c,a,b')+ expect(m.restSec).toBe(45)+ }+ })+ it('the order chosen last wins', () => {+ const A = change(base(), reorder(['c', 'a', 'b']), T + 1000)+ const B = change(base(), reorder(['b', 'a', 'c']), T + 2000)+ for (const m of [mergeStates(A, B), mergeStates(B, A)]) expect(ids(m)).toBe('b,a,c')+ })+ it('a routine only the other copy has goes next to its neighbour there, and both edits of an entry are kept', () => {+ const A = change(base(), reorder(['c', 'a', 'b']), T + 1000)+ const B = change(base(), s => { s.routines.splice(1, 0, { id: 'n', name: 'New', ex: [] }); s.routines[0].name = 'A2' }, T + 5000)+ for (const m of [mergeStates(A, B), mergeStates(B, A)]) {+ expect(ids(m)).toBe('c,a,n,b')+ expect(m.routines.find(x => x.id === 'a').name).toBe('A2')+ }+ })+ it('adding or removing a routine is no reorder', () => {+ expect(orderMoved([r('a'), r('b')], [r('a'), r('x'), r('b')])).toBe(false)+ expect(orderMoved([r('a'), r('b'), r('c')], [r('a'), r('c')])).toBe(false)+ expect(orderMoved([r('a'), r('b')], [r('b'), r('a')])).toBe(true)+ expect(change(base(), s => { s.routines.push(r('d')) }, T + 1).edited.routineOrder).toBeUndefined()+ for (const [a, b] of [[[r('a'), r('b')], [r('b'), r('a'), r('z')]], [[r('a')], [r('a')]]]) expect(S.orderMoved(a, b)).toBe(orderMoved(a, b))+ })+})++describe('the server and a writer that does not stamp', () => {+ it('its reorder is stamped, and holds against a phone that reconnects with an older change', () => {+ const cur = base()+ const old = clone(cur); old.routines = ['b', 'c', 'a'].map(id => old.routines.find(x => x.id === id)); old._ts = T + 3000+ S.stampPut(cur, old, { overRead: true, now: T + 3000 })+ expect(old.edited.routineOrder).toBeGreaterThanOrEqual(T + 3000)+ const phone = change(cur, s => { s.restSec = 30 }, T + 9000)+ for (const m of [mergeStates(phone, old), mergeStates(old, phone)]) expect(ids(m)).toBe('b,c,a')+ })+ it('an older copy\'s order does not undo a reorder made since', () => {+ const cur = change(base(), reorder(['c', 'b', 'a']), T + 1000)+ const old = clone(base()); old.routines.push({ id: 'z', name: 'z', ex: [] }); old._ts = T + 9000 // its own new routine, older order+ S.stampPut(cur, old, { overRead: true, now: T + 9000 })+ expect(ids(old)).toBe('c,z,b,a') // its new one next to the routine it followed there+ })+})