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: deletions stay deleted, each setting keeps its last change
Duarte Santos618e2b3e4c8c
diff --git a/frontend/src/lib/sync-changes.js b/frontend/src/lib/sync-changes.jsindex 046d6c535..2957d8afb 100644--- a/frontend/src/lib/sync-changes.js+++ b/frontend/src/lib/sync-changes.js@@ -27,8 +27,9 @@ const LISTS = {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)])+// Not content: the stamps and the revision say when, not what (`deleted` and `edited` go with a+// change the lists or the rest already count); the running workout never syncs.+const NOT_CONTENT = new Set(['_ts', '_rev', 'active', 'deleted', 'edited', ...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) {diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 23f9efa58..073ed1212 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -7,7 +7,10 @@* entries and lets the newer copy decide everything that has no natural union.** Rules, by field:- * - scalars and settings, `week`, `dayPlan`, `wc`, `reminder`, …: from the copy with the newer `_ts`+ * - scalars and settings, `week`, `dayPlan`, `wc`, `reminder`, `queue`, `rotation`, …: each from+ * the copy that changed it last by its own stamp in `edited` (stampEdits; `week`, `dayPlan`,+ * exNotes and barWeights per day or per exercise), from the copy with the newer `_ts` when+ * neither side stamped it or on a tie* - equipProfiles, gymCards: union by id, the newer copy's version of an id that both have* - customEx: union by id; of an id that both have, the version edited last by its own `_ts`* (stampCustomEx), the newer copy's on a tie — a photo or link added on one device must not@@ -59,10 +62,10 @@* `prefer`: a sign-in adds what a device logged signed out, which is not a copy of this* account's history.*- * Known limit: with no record of what each side deleted, an entry removed on one device inside- * the conflict window comes back from the other. The window is a few seconds now (the store pulls- * on resume and every push is conditional), and a resurrected entry beats a lost one. Tombstones- * would close it.+ * After all of these, removals: an entry either copy records in `deleted` (stampDeletions) as+ * removed after it was last edited is left out, whatever the other copy still holds. Without it a+ * device that came back online after any time away brought back every workout, routine, custom+ * exercise, weigh-in or favourite the other device had removed meanwhile.*/import { beatsWeight } from './exercises.js'import { bestWeightForEntry } from './history.js'@@ -289,9 +292,190 @@ export function sinceReset(S, at, ids) {}}out.exWeights = ex+ // The reset copy's settings, plan and unit win whatever this copy's own stamps say (the file's+ // header): stamps from before the reset would otherwise outrank the fresh profile's defaults,+ // a unit switch made long ago would bring the old unit back over the reset's.+ delete out.edited+ delete out.unitSetreturn out}+// ---- Deletions (`deleted`) ------------------------------------------------------------------+//+// S.deleted = { workouts: { <key>: at }, routines: {…}, customEx, bodyweight, gymCards,+// equipProfiles, favEx }+//+// A positive `at` is when the entry was removed on some device; a negative one (-at) is when it+// was added back after such a removal (a favourite starred again). The store writes them on every+// change (stampDeletions, useStore update) and the merge honours them (applyDeletions): a removal+// beats any copy of the entry edited before it, so a device that was offline for a week no longer+// brings back the workout, routine or custom exercise deleted meanwhile. An edit made after the+// removal (the entry's own `_ts`, a weigh-in's `t`) keeps it, as does an add-back stamped later.+const DEL_LISTS = {+ workouts: workoutKey, routines: x => x?.id, customEx: x => x?.id, bodyweight: e => e?.d,+ gymCards: x => x?.id, equipProfiles: x => x?.id, favEx: x => x,+}+// When an entry was last edited, to hold against a removal. Entries with no time of their own+// (cards, profiles, favourites) count as older than any removal.+const DEL_TIME = {+ workouts: workoutTime, routines: x => Number(x?._ts) || 0, customEx: x => Number(x?._ts) || 0,+ bodyweight: e => Number(e?.t) || 0,+}+// Per field, the most stamps kept; past it the oldest go first.+export const DELETED_MAX = 5000+const capStamps = m => {+ const ks = Object.keys(m)+ if (ks.length <= DELETED_MAX) return m+ ks.sort((x, y) => Math.abs(m[x]) - Math.abs(m[y]))+ for (const k of ks.slice(0, ks.length - DELETED_MAX)) delete m[k]+ return m+}++/**+ * Records in `next.deleted` every entry `prev` had and `next` no longer has, at `now`, and marks+ * as added back (`-now`) any entry `next` has again whose removal was on record. Mutates and+ * returns `next`; adds no `deleted` when there is nothing to record.+ */+export function stampDeletions(prev, next, now = Date.now()) {+ if (!next || typeof next !== 'object') return next+ const del = isMap(next.deleted) ? next.deleted : {}+ let touched = false+ for (const [f, key] of Object.entries(DEL_LISTS)) {+ const before = list(prev?.[f]), after = list(next[f])+ if (before === after) continue+ const have = new Set(after.filter(x => x != null).map(x => String(key(x))))+ const m = isMap(del[f]) ? del[f] : {}+ let changed = false+ for (const x of before) {+ if (x == null) continue+ const k = String(key(x))+ if (!have.has(k)) { m[k] = now; changed = true }+ }+ for (const k of Object.keys(m)) if (m[k] > 0 && have.has(k)) { m[k] = -now; changed = true }+ if (changed) { del[f] = capStamps(m); touched = true }+ }+ if (touched) next.deleted = del+ return next+}++/** Both copies' records of removals: per entry, the later stamp. */+export function mergeDeletions(a, b) {+ const out = {}+ for (const f of Object.keys(DEL_LISTS)) {+ const x = isMap(a?.[f]) ? a[f] : {}, y = isMap(b?.[f]) ? b[f] : {}+ const m = { ...x }+ for (const [k, v] of Object.entries(y)) if (!(k in m) || Math.abs(Number(v) || 0) > Math.abs(Number(m[k]) || 0)) m[k] = v+ if (Object.keys(m).length) out[f] = capStamps(m)+ }+ return Object.keys(out).length ? out : null+}++/**+ * `S` without the entries `deleted` says were removed after they were last edited. Returns the+ * removed workouts too (their kept loads need a second look). Mutates `S`.+ */+function applyDeletions(S, deleted) {+ const gone = []+ if (!deleted) return gone+ for (const [f, key] of Object.entries(DEL_LISTS)) {+ const m = deleted[f]+ if (!isMap(m) || !Array.isArray(S[f])) continue+ const time = DEL_TIME[f] || (() => 0)+ S[f] = S[f].filter(x => {+ if (x == null) return true+ const at = Number(m[String(key(x))]) || 0+ const drop = at > 0 && at >= time(x)+ if (drop && f === 'workouts') gone.push(x)+ return !drop+ })+ }+ return gone+}++// ---- Edit stamps (`edited`) -----------------------------------------------------------------+//+// S.edited = { restSec: at, queue: at, rotation: at, 'week.3': at, 'dayPlan.2026-10-08': at, … }+//+// When each setting, and each day of the plan, was last changed on some device. The store writes+// them on every change (stampEdits, useStore update) and the merge takes each one from the copy+// that changed it last (applyEdits) rather than the whole lot from the copy that changed anything+// last: Wednesday set on an offline phone survives the weigh-in the desktop logged meanwhile, and+// 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',+ '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'])+// A per-key stamp of a key neither copy holds any more is dropped after this long.+const EDIT_KEEP_MS = 180 * 86400000+const same = (x, y) => JSON.stringify(x) === JSON.stringify(y)++/**+ * Stamps in `next.edited` every field (and every day of the plan, note, bar weight) that differs+ * from `prev`, at `now`. Mutates and returns `next`.+ */+export function stampEdits(prev, next, now = Date.now()) {+ if (!next || typeof next !== 'object') return next+ const ed = isMap(next.edited) ? next.edited : {}+ let touched = false+ for (const k of new Set([...Object.keys(prev || {}), ...Object.keys(next)])) {+ if (OWN_MERGE.has(k)) continue+ const p = prev?.[k], n = next[k]+ if (PER_KEY.has(k)) {+ const pm = isMap(p) ? p : {}, nm = isMap(n) ? n : {}+ if (p === n) continue+ for (const s of new Set([...Object.keys(pm), ...Object.keys(nm)])) {+ if ((s in pm) !== (s in nm) || !same(pm[s], nm[s])) { ed[`${k}.${s}`] = now; touched = true }+ }+ } else if (p !== n && !same(p, n)) { ed[k] = now; touched = true }+ }+ if (touched) {+ for (const [k, at] of Object.entries(ed)) {+ const dot = k.indexOf('.')+ if (dot < 0 || now - at < EDIT_KEEP_MS) continue+ const m = next[k.slice(0, dot)]+ if (!isMap(m) || !(k.slice(dot + 1) in m)) delete ed[k]+ }+ next.edited = ed+ }+ return next+}++/** Both copies' edit stamps: per key, the later one. */+function mergeEdits(a, b) {+ const x = isMap(a) ? a : {}, y = isMap(b) ? b : {}+ const out = { ...x }+ for (const [k, v] of Object.entries(y)) if (!((Number(out[k]) || 0) >= (Number(v) || 0))) out[k] = v+ return Object.keys(out).length ? out : null+}++/**+ * Into `out` (a merge built from `n`, the newer copy), every stamped field and plan day from the+ * copy that changed it last, removal included. A tie or a field nobody stamped stays as it is.+ */+function applyEdits(out, n, o) {+ const en = isMap(n.edited) ? n.edited : {}, eo = isMap(o.edited) ? o.edited : {}+ for (const k of new Set([...Object.keys(en), ...Object.keys(eo)])) {+ const tn = Number(en[k]) || 0, to = Number(eo[k]) || 0+ if (tn === to) continue+ const src = to > tn ? o : n+ const dot = k.indexOf('.')+ if (dot < 0) {+ if (OWN_MERGE.has(k) || PER_KEY.has(k)) continue+ if (k in src) out[k] = clone(src[k]); else delete out[k]+ continue+ }+ const f = k.slice(0, dot), s = k.slice(dot + 1)+ if (!PER_KEY.has(f)) continue+ const from = isMap(src[f]) ? src[f] : {}+ const into = isMap(out[f]) ? out[f] : (out[f] = {})+ if (s in from) into[s] = clone(from[s]); else delete into[s]+ }+}+// `prefer` names the side whose settings, plan and per-exercise config win regardless of `_ts`:// on sign-in the server's profile is the truth and the device only contributes the entries it// logged while signed out. Without it the newer copy decides, as for a conflict between devices.@@ -387,6 +571,19 @@ export function mergeStates(a0, b0, { prefer } = {}) {}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)])]+ // What either device removed stays removed (the `deleted` section above). A workout taken out+ // this way leaves its exercises' kept loads to be read again, as an edit of it would: from the+ // merged history and from the deleting copy's own, which already let go of what it held.+ const deleted = mergeDeletions(a.deleted, b.deleted)+ for (const w of applyDeletions(out, deleted)) {+ const k = String(workoutKey(w))+ const by = [n, o].filter(S => Number(S.deleted?.workouts?.[k]) > 0).map(S => S.exWeights)+ for (const e of list(w.entries)) {+ if (e?.id == null) continue+ if (!editedBy.has(e.id)) editedBy.set(e.id, new Set())+ for (const src of by) editedBy.get(e.id).add(src)+ }+ }out.exWeights = clone(mergeExWeights(n.exWeights, o.exWeights))for (const [id, sources] of editedBy) {const kept = correctedExWeight(id, out.workouts, sources)@@ -402,6 +599,14 @@ export function mergeStates(a0, b0, { prefer } = {}) {for (const f of ['balanceOverrides', 'loadKind', 'plates']) {if (n[f] || o[f]) out[f] = clone(mergeStampedMap(n[f], o[f], prefer))}+ // Each stamped setting and plan day from the copy that changed it last (the `edited` section+ // above). `prefer` (sign-in) keeps the preferred side's, stamps and all.+ if (!prefer) {+ applyEdits(out, n, o)+ const edited = mergeEdits(n.edited, o.edited)+ if (edited) out.edited = edited; else delete out.edited+ }+ if (deleted) out.deleted = deleted; else delete out.deletedout._ts = Math.max(a._ts || 0, b._ts || 0)if (resetAt) out.resetAt = resetAtif (resetIds) out.resetIds = resetIdsdiff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.jsindex ddff762ff..36cd7bcd3 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 { keepReset, localExtras, mergeBodyweight, mergeResetIds, mergeStampedMap, mergeStates, newerOf, resetIdsOf, RESET_ID_MAX, sinceReset, stampCustomEx, stampRoutines, stampWorkout, unionById } from './sync-merge.js'+import { keepReset, localExtras, mergeDeletions, stampDeletions, stampEdits, 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'@@ -12,6 +12,7 @@ const base = (over = {}) => ({workouts: [], routines: [], bodyweight: [], customEx: [], favEx: [], exWeights: {}, exNotes: {}, barWeights: {},equipProfiles: [], gymCards: [], _ts: 0, ...over})+const clone = o => JSON.parse(JSON.stringify(o))const ids = xs => (xs || []).map(x => x.id)describe('newerOf / unionById / mergeBodyweight', () => {@@ -661,3 +662,167 @@ describe('localExtras and the weigh-ins of a day both copies have', () => {expect(localExtras({ unit: 'lb', bodyweight: [{ d: '2026-09-27', w: convertBodyWeight(80, 'kg', 'lb'), t: 200 }] }, server).bodyweight).toBe(0)})})++describe('a removal holds against a copy that was offline', () => {+ // A removes, B was offline the whole time and logged a weigh-in later (its copy is newer).+ const W = { id: 'W', d: '2026-09-01', start: 100, end: 200, entries: [{ id: '0025', sets: [{ w: 150, r: 1, done: true }] }] }+ const both = base({+ _ts: 300, workouts: [W, workout('keep')], routines: [{ ...routine('r1'), _ts: 50 }],+ customEx: [{ id: 'c1', n: 'Sync me', _ts: 50 }], favEx: ['0025', 'c1'], gymCards: [{ id: 'g1', value: '1' }],+ bodyweight: [{ d: '2026-09-02', w: 80, t: 60 }], exWeights: { '0025': { w: 150, d: '2026-09-01' } },+ })+ const removedOnA = () => {+ const a = clone(both)+ a.workouts = a.workouts.filter(w => w.id !== 'W')+ a.routines = []+ a.customEx = []+ a.favEx = ['0025']+ a.gymCards = []+ a.bodyweight = []+ a.exWeights = {}+ a._ts = 1000+ return stampDeletions(both, a, 1000)+ }+ const offlineB = () => {+ const b = clone(both)+ b.bodyweight = [...b.bodyweight, { d: '2026-09-05', w: 79, t: 2000 }]+ b._ts = 2000+ return b+ }++ it('stamps what a change removed, and nothing when nothing was', () => {+ const a = removedOnA()+ expect(a.deleted).toEqual({+ workouts: { W: 1000 }, routines: { r1: 1000 }, customEx: { c1: 1000 },+ bodyweight: { '2026-09-02': 1000 }, gymCards: { g1: 1000 }, favEx: { c1: 1000 },+ })+ expect(stampDeletions(both, clone(both), 1000).deleted).toBeUndefined()+ })++ it('stays removed, whichever copy is newer', () => {+ for (const m of [mergeStates(removedOnA(), offlineB()), mergeStates(offlineB(), removedOnA())]) {+ expect(ids(m.workouts)).toEqual(['keep'])+ expect(m.routines).toEqual([])+ expect(m.customEx).toEqual([])+ expect(m.favEx).toEqual(['0025'])+ expect(m.gymCards).toEqual([])+ expect(m.bodyweight.map(e => e.d)).toEqual(['2026-09-05']) // B's new weigh-in is kept+ // the removed workout's PR goes with it, though B still had it as its kept load+ expect(m.exWeights['0025']).toBeUndefined()+ expect(m.deleted.workouts).toEqual({ W: 1000 })+ }+ })++ it('an edit made after the removal keeps the entry', () => {+ const b = offlineB()+ b.routines = [{ ...routine('r1', 'edited'), _ts: 1500 }]+ b.workouts = b.workouts.map(w => (w.id === 'W' ? { ...w, note: 'x', _ts: 1500 } : w))+ const m = mergeStates(removedOnA(), b)+ expect(ids(m.routines)).toEqual(['r1'])+ expect(ids(m.workouts)).toContain('W')+ })++ it('a favourite starred again after the removal comes back with it', () => {+ const a = removedOnA()+ const again = clone(a)+ again.favEx = ['0025', 'c1']+ stampDeletions(a, again, 1500)+ expect(again.deleted.favEx).toEqual({ c1: -1500 })+ expect(mergeStates(again, offlineB()).favEx.sort()).toEqual(['0025', 'c1'])+ expect(mergeDeletions(a.deleted, again.deleted).favEx).toEqual({ c1: -1500 })+ })+})++describe('settings and plan days keep the change made last', () => {+ // B, offline, sets Wednesday and the rest timer; A logs a weigh-in later and flips the sound.+ const start = () => base({ _ts: 100, week: { 1: ['r1'] }, restSec: 90, sound: true, exNotes: { '0025': 'seat 4' } })+ const onB = () => {+ const b = start()+ const next = clone(b)+ next.week[3] = ['upperB']+ next.restSec = 120+ delete next.exNotes['0025']+ next._ts = 500+ return stampEdits(b, next, 500)+ }+ const onA = () => {+ const a = start()+ const next = clone(a)+ next.sound = false+ next.bodyweight = [{ d: '2026-09-05', w: 79, t: 900 }]+ next._ts = 900+ return stampEdits(a, next, 900)+ }++ it('stamps each changed setting and plan day on its own', () => {+ expect(onB().edited).toEqual({ 'week.3': 500, restSec: 500, 'exNotes.0025': 500 })+ expect(onA().edited).toEqual({ sound: 900 }) // a weigh-in has its own merge, no stamp+ })++ it('takes each from the copy that changed it, whichever copy is newer', () => {+ for (const m of [mergeStates(onA(), onB()), mergeStates(onB(), onA())]) {+ expect(m.week).toEqual({ 1: ['r1'], 3: ['upperB'] })+ expect(m.restSec).toBe(120)+ expect(m.sound).toBe(false)+ expect(m.exNotes).toEqual({}) // a cleared note stays cleared+ expect(m.bodyweight.map(e => e.d)).toEqual(['2026-09-05'])+ expect(m.edited).toEqual({ 'week.3': 500, restSec: 500, 'exNotes.0025': 500, sound: 900 })+ }+ })++ it('a later change of the same day wins, a removal included', () => {+ const a = onA()+ const next = clone(a)+ next.week[3] = ['legs']+ next.restSec = 60+ stampEdits(a, next, 1000)+ expect(mergeStates(onB(), next).week).toEqual({ 1: ['r1'], 3: ['legs'] })+ expect(mergeStates(onB(), next).restSec).toBe(60)+ // A pulled B's Wednesday, then cleared it while B (offline again) still has it+ const seen = mergeStates(onA(), onB())+ const cleared = clone(seen)+ delete cleared.week[3]+ stampEdits(seen, cleared, 1000)+ for (const m of [mergeStates(onB(), cleared), mergeStates(cleared, onB())]) expect(m.week).toEqual({ 1: ['r1'] })+ })++ it('a rotation refill on one device survives a setting saved later on the other', () => {+ const s0 = base({ _ts: 100, queue: { ids: ['a', 'b'], since: 1, startsOn: '2026-09-01', rotationId: 'r' }, rotation: { id: 'r', sequence: ['a', 'b'] } })+ const phone = clone(s0)+ phone.queue = { ids: ['a', 'b'], since: 400, startsOn: '2026-09-06', rotationId: 'r' }+ phone._ts = 400+ stampEdits(s0, phone, 400)+ const desk = clone(s0)+ desk.restSec = 45+ desk._ts = 800+ stampEdits(s0, desk, 800)+ for (const m of [mergeStates(phone, desk), mergeStates(desk, phone)]) {+ expect(m.queue.since).toBe(400)+ expect(m.restSec).toBe(45)+ }+ })++ it('unstamped copies still follow the newer one; sign-in keeps the preferred side', () => {+ const m = mergeStates(base({ _ts: 1, restSec: 30 }), base({ _ts: 2, restSec: 60 }))+ expect(m.restSec).toBe(60)+ const signIn = mergeStates(base({ _ts: 1, restSec: 30 }), onB(), { prefer: 'a' })+ expect(signIn.restSec).toBe(30)+ })+})++describe('a reset leads the unit over a copy that switched before it', () => {+ it('the reset copy is in kg, the stale lb copy is converted into it', () => {+ const R = 5000+ const reset = base({ _ts: R, resetAt: R, unit: 'kg', resetIds: { bodyweight: ['2026-08-01|100'] } })+ const stale = base({+ _ts: 6000, unit: 'lb', unitSet: { at: 100, convert: true }, restSec: 45,+ bodyweight: [{ d: '2026-08-01', w: 176, t: 100 }, { d: '2026-09-27', w: 220, t: 5900 }],+ })+ for (const m of [mergeStates(reset, stale), mergeStates(stale, reset)]) {+ expect(m.unit).toBe('kg')+ expect(m.unitSet).toBeUndefined()+ expect(m.bodyweight).toEqual([{ d: '2026-09-27', w: convertBodyWeight(220, 'lb', 'kg'), t: 5900 }])+ expect(m.restSec).toBe(90)+ }+ })+})diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 4d4b2ee19..9030ed8be 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, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } from '../lib/sync-merge.js'+import { mergeStates, localExtras, stampRoutines, stampCustomEx, stampDeletions, stampEdits, 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'@@ -1013,8 +1013,13 @@ export const useStore = create((set, get) => {const prev = get().Sconst S = clone(prev)mut(S)- stampRoutines(prev.routines, S.routines)- stampCustomEx(prev.customEx, S.customEx)+ const now = Date.now()+ stampRoutines(prev.routines, S.routines, now)+ stampCustomEx(prev.customEx, S.customEx, now)+ // What the change removed, and which settings and plan days it touched, each with its time:+ // a conflict then keeps a removal and the setting changed last (lib/sync-merge.js).+ stampDeletions(prev, S, now)+ stampEdits(prev, S, now)persist(S, push)// 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,diff --git a/frontend/src/store/useStore.sync.test.jsx b/frontend/src/store/useStore.sync.test.jsxindex 0b5856853..37d2fbeb8 100644--- a/frontend/src/store/useStore.sync.test.jsx+++ b/frontend/src/store/useStore.sync.test.jsx@@ -423,3 +423,49 @@ describe('an edited workout between devices', () => {expect(weightsIn(useStore.getState().S)).toEqual([['w1', 50]])})})++describe('removals and settings across a conflict', () => {+ it('a workout deleted on the other device stays deleted when this one comes back with a change', async () => {+ vi.useFakeTimers()+ vi.setSystemTime(10000)+ // A deleted W through the store (update records when), then pushed.+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('W'), workout('keep')] })+ useStore.getState().update(s => { s.workouts = s.workouts.filter(w => w.id !== 'W') }, false)+ const fromA = clone(useStore.getState().S)+ expect(fromA.deleted).toEqual({ workouts: { W: 10000 } })++ // B was offline with W still there and logged a setting change later.+ vi.setSystemTime(20000)+ localStorage.clear()+ api.mockReset()+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('W'), workout('keep')] })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ useStore.getState().update(s => { s.restSec = 45 }, false)+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: { ...fromA, _rev: 2 } }))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })++ await useStore.getState().pushState()++ expect(puts().at(-1).state.workouts.map(w => w.id)).toEqual(['keep'])+ expect(puts().at(-1).state.restSec).toBe(45)+ expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['keep'])+ })++ it('a day of the plan set offline survives the other device syncing something later', async () => {+ vi.useFakeTimers()+ vi.setSystemTime(10000)+ signedIn({ ...clone(DEF), _ts: 100 })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ useStore.getState().update(s => { s.week = { ...s.week, 3: ['upperB'] } }, false)+ // the other device logged a weigh-in after it (its copy is newer as a whole)+ const other = { ...clone(DEF), _ts: 50000, bodyweight: [{ d: '2026-09-05', w: 80, t: 50000 }], _rev: 2 }+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: other }))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })++ await useStore.getState().pushState()++ const sent = puts().at(-1).state+ expect(sent.week).toEqual({ 3: ['upperB'] })+ expect(sent.bodyweight.map(e => e.d)).toEqual(['2026-09-05'])+ })+})