Skip to content

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.

Undo: a change another device made before it saw the swipe survives the Undo, and a routine put back keeps its edit time

Duarte Santosc305dd4dd3e3
diff --git a/api/sync-stamps.js b/api/sync-stamps.js
index 6f3017b46..7c0ae5c60 100644
--- a/api/sync-stamps.js
+++ b/api/sync-stamps.js
@@ -59,12 +59,12 @@ const capStamps = m => {
return m;
};
const OWN_MERGE = new Set([
- '_ts', '_rev', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited',
+ '_ts', '_rev', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone',
'workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx',
'exWeights', 'balanceOverrides', 'loadKind', 'plates',
]);
const PER_KEY = new Set(['week', 'dayPlan', 'exNotes', 'barWeights']);
-const ENTRY_META = new Set(['id', '_ts', '_f']);
+const ENTRY_META = new Set(['id', '_ts', '_f', '_u']);
const ENTRY_LISTS = ['routines', 'customEx', 'equipProfiles', 'gymCards', 'workouts'];
// Whether removal record `v` replaces `cur`: the later stamp, and on a tie the add-back.
@@ -125,9 +125,24 @@ export function stampEntry(old, x, now) {
if ((k in old) !== (k in x) || !same(old[k], x[k])) f[k] = now;
}
if (Object.keys(f).length) x._f = f; else delete x._f;
+ const u = settleMarks(x._u, f, now);
+ if (u) x._u = u; else delete x._u;
return x;
}
-const sameEntry = (a, b) => same({ ...a, _ts: 0, _f: 0 }, { ...b, _ts: 0, _f: 0 });
+// An Undo's markers (`_u`, sync-merge.js "Undo"): completed with this edit's stamp, or dropped
+// once their field moved on.
+function settleMarks(marks, stamps, now) {
+ if (!isMap(marks)) return null;
+ const out = {};
+ for (const [k, m] of Object.entries(marks)) {
+ if (!Array.isArray(m)) continue;
+ const at = Number(stamps?.[k]) || 0;
+ if (m.length === 2 && at === now) out[k] = [Number(m[0]) || 0, Number(m[1]) || 0, now];
+ else if (m.length === 3 && at > 0 && Number(m[2]) === at) out[k] = m;
+ }
+ return Object.keys(out).length ? out : null;
+}
+const sameEntry = (a, b) => same({ ...a, _ts: 0, _f: 0, _u: 0 }, { ...b, _ts: 0, _f: 0, _u: 0 });
// Step 2: what a writer that does not stamp changed against the copy it read, stamped at `now`.
function stampUnstamped(cur, next, sent, now) {
diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js
index 59e8d048b..2134a2c90 100644
--- a/frontend/src/lib/sync-merge.js
+++ b/frontend/src/lib/sync-merge.js
@@ -219,10 +219,95 @@ const isMap = v => !!v && typeof v === 'object' && !Array.isArray(v)
// photo to a rename. Each edit now records, per field, when it changed it (`_f`, stampEntry), and
// the merge takes every field from the side that changed it last (mergeEntry). A field neither
// side stamped follows the version edited last, as before.
-const ENTRY_META = new Set(['id', '_ts', '_f'])
+const ENTRY_META = new Set(['id', '_ts', '_f', '_u'])
const fieldTime = (x, k) => Number(x?._f?.[k]) || 0
const sameJSON = (x, y) => JSON.stringify(x) === JSON.stringify(y)
+// ---- Undo ---------------------------------------------------------------------------------------
+//
+// An Undo that puts a field back exactly as it was before one change (a swipe's removal) is itself
+// a change, stamped after the removal so it beats it on every device that already took the
+// removal. But it also beat a change another device made to the same field before the removal
+// and never saw: a set count edited offline in the routine whose exercise was swiped away and put
+// back, a loop reordered offline while one routine was taken out of it and put back. The Undo
+// meant "as if nothing happened", and that edit was lost.
+//
+// So such an Undo marks the field with what it undid: `[base, del, at]`, the field's stamp before
+// the removal, the removal's stamp and the Undo's own (in an entry's `_u`, per field; in the
+// copy's `undone`, per setting or plan day, as `edited` is). A merge then lets the other side's
+// value win when its stamp falls strictly between `base` and `del`: a change made after the value
+// the Undo put back, and before the removal it took back, which this device never saw. The value
+// that wins is stamped just after the Undo, so every copy settles on it. A removal or edit seen
+// after the removal (a stamp from `del` on) still loses to the Undo, as before.
+
+// The marker of field `k` (`marks` is `_u` or `undone`) when it still describes the value stamped `at`.
+const undoOf = (marks, k, at) => {
+ const u = isMap(marks) ? marks[k] : null
+ return Array.isArray(u) && u.length === 3 && at > 0 && Number(u[2]) === at ? u : null
+}
+// Between two stamps of one field, `x` (marked `ux`) and `y` (marked `uy`): which side's value
+// stays ('x', 'y' or '' on a tie) and the stamp it carries. See above.
+function undoPick(tx, ux, ty, uy) {
+ if (tx > ty) return ux && ty > Number(ux[0]) && ty < Number(ux[1]) ? ['y', tx + 1] : ['x', tx]
+ if (ty > tx) return uy && tx > Number(uy[0]) && tx < Number(uy[1]) ? ['x', ty + 1] : ['y', ty]
+ return ['', tx]
+}
+// `marks` brought up to date with `stamps` after a change stamped `now`: a pending marker
+// (`[base, del]`, set by the Undo itself) of a field this change stamped gets `now`; one whose field
+// has moved on since is dropped. Returns the markers left, or null.
+function settleMarks(marks, stamps, now) {
+ if (!isMap(marks)) return null
+ const out = {}
+ for (const [k, m] of Object.entries(marks)) {
+ if (!Array.isArray(m)) continue
+ const at = Number(stamps?.[k]) || 0
+ if (m.length === 2 && at === now) out[k] = [Number(m[0]) || 0, Number(m[1]) || 0, now]
+ else if (m.length === 3 && at > 0 && Number(m[2]) === at) out[k] = m
+ }
+ return Object.keys(out).length ? out : null
+}
+
+/**
+ * What an Undo needs to mark what it put back (see above), taken right after the change it may
+ * undo: for every stamped setting or plan day that change moved, its stamp before and after, and
+ * its value before. `before` and `after` are the copies around the change.
+ */
+export function undoMarks(before, after) {
+ const eb = isMap(before?.edited) ? before.edited : {}, ea = isMap(after?.edited) ? after.edited : {}
+ const out = {}
+ for (const [k, at] of Object.entries(ea)) {
+ if (Number(at) === Number(eb[k] || 0)) continue
+ out[k] = [Number(eb[k]) || 0, Number(at) || 0, JSON.stringify(editedValue(before, k) ?? null)]
+ }
+ return out
+}
+const editedValue = (S, k) => {
+ const dot = k.indexOf('.')
+ return dot < 0 ? S?.[k] : (isMap(S?.[k.slice(0, dot)]) ? S[k.slice(0, dot)][k.slice(dot + 1)] : undefined)
+}
+/**
+ * In an Undo's draft `s`, after it put things back: marks every setting and plan day of `marks`
+ * (undoMarks) that is now exactly what it was before the change, and that nothing changed since.
+ */
+export function markUndone(s, marks) {
+ if (!s || !isMap(marks)) return s
+ const ed = isMap(s.edited) ? s.edited : {}
+ for (const [k, [base, del, was]] of Object.entries(marks)) {
+ if ((Number(ed[k]) || 0) !== del || JSON.stringify(editedValue(s, k) ?? null) !== was) continue
+ s.undone = { ...(isMap(s.undone) ? s.undone : {}), [k]: [base, del] }
+ }
+ return s
+}
+/**
+ * The same for one field `k` of an entry `x` in an Undo's draft: `base` and `del` are the field's
+ * stamps before and after the change it undid. Only when nothing changed the field since.
+ */
+export function markEntryUndone(x, k, base, del) {
+ if (!x || typeof x !== 'object' || !(del > 0) || fieldTime(x, k) !== del) return x
+ x._u = { ...(isMap(x._u) ? x._u : {}), [k]: [Number(base) || 0, del] }
+ return x
+}
+
/**
* Stamps `x`, the new version of an entry whose previous version is `old`, as edited at `now`:
* its `_ts`, and in `_f` every field that differs from `old`. A new entry gets its `_ts` only.
@@ -238,6 +323,8 @@ export function stampEntry(old, x, now) {
if ((k in old) !== (k in x) || !sameJSON(old[k], x[k])) f[k] = now
}
if (Object.keys(f).length) x._f = f; else delete x._f
+ const u = settleMarks(x._u, f, now)
+ if (u) x._u = u; else delete x._u
return x
}
@@ -248,14 +335,22 @@ export function stampEntry(old, x, now) {
export function mergeEntry(a, b) {
const [n, o] = (Number(b?._ts) || 0) > (Number(a?._ts) || 0) ? [b, a] : [a, b]
const out = clone(n)
- for (const k of new Set([...Object.keys(n), ...Object.keys(o)])) {
- if (ENTRY_META.has(k)) continue
- if (fieldTime(o, k) > fieldTime(n, k)) { if (k in o) out[k] = clone(o[k]); else delete out[k] }
- }
const f = { ...(isMap(o._f) ? o._f : {}) }
for (const [k, v] of Object.entries(isMap(n._f) ? n._f : {})) if (!((Number(f[k]) || 0) > (Number(v) || 0))) f[k] = v
+ const u = {}
+ let bumped = 0
+ for (const k of new Set([...Object.keys(n), ...Object.keys(o), ...Object.keys(f)])) {
+ if (ENTRY_META.has(k)) continue
+ const tn = fieldTime(n, k), to = fieldTime(o, k)
+ const [side, at] = undoPick(tn, undoOf(n._u, k, tn), to, undoOf(o._u, k, to))
+ if (side === 'y') { if (k in o) out[k] = clone(o[k]); else delete out[k] }
+ if (at > Math.max(tn, to)) { f[k] = at; bumped = Math.max(bumped, at) }
+ const kept = side === 'y' ? undoOf(o._u, k, at) : side === 'x' ? undoOf(n._u, k, at) : undoOf(n._u, k, at) || undoOf(o._u, k, at)
+ if (kept) u[k] = clone(kept)
+ }
if (Object.keys(f).length) out._f = f; else delete out._f
- const ts = Math.max(Number(a?._ts) || 0, Number(b?._ts) || 0)
+ if (Object.keys(u).length) out._u = u; else delete out._u
+ const ts = Math.max(Number(a?._ts) || 0, Number(b?._ts) || 0, bumped)
if (ts) out._ts = ts
return out
}
@@ -375,6 +470,7 @@ export function sinceReset(S, at, ids) {
// 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.undone
delete out.unitSet
return out
}
@@ -504,7 +600,7 @@ 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',
+ '_ts', '_rev', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone',
'workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx',
'exWeights', 'balanceOverrides', 'loadKind', 'plates',
])
@@ -549,6 +645,12 @@ export function stampEdits(prev, next, now = Date.now()) {
}
next.edited = ed
}
+ // An Undo's markers (see "Undo" above): completed with this change's stamp, or dropped once
+ // their setting moved on.
+ if ('undone' in next) {
+ const u = settleMarks(next.undone, ed, now)
+ if (u) next.undone = u; else delete next.undone
+ }
return next
}
@@ -566,10 +668,14 @@ export function mergeEdits(a, b) {
*/
function applyEdits(out, n, o) {
const en = isMap(n.edited) ? n.edited : {}, eo = isMap(o.edited) ? o.edited : {}
+ const bumps = {}
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
+ // An Undo's marker can hand the field to the side whose stamp is older (see "Undo" above).
+ const [side, at] = undoPick(tn, undoOf(n.undone, k, tn), to, undoOf(o.undone, k, to))
+ if (at > Math.max(tn, to)) bumps[k] = at
+ const src = side === 'y' ? o : n
const dot = k.indexOf('.')
if (dot < 0) {
if (OWN_MERGE.has(k) || PER_KEY.has(k)) continue
@@ -582,6 +688,7 @@ function applyEdits(out, n, o) {
const into = isMap(out[f]) ? out[f] : (out[f] = {})
if (s in from) into[s] = clone(from[s]); else delete into[s]
}
+ return bumps
}
// `prefer` names the side whose settings, plan and per-exercise config win regardless of `_ts`:
@@ -717,9 +824,17 @@ export function mergeStates(a0, b0, { 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 bumps = applyEdits(out, n, o)
const edited = mergeEdits(n.edited, o.edited)
- if (edited) out.edited = edited; else delete out.edited
+ if (edited) { Object.assign(edited, bumps); out.edited = edited } else delete out.edited
+ // An Undo's markers that still describe the merged stamp of their setting.
+ const undone = {}
+ for (const k of new Set([...Object.keys(isMap(n.undone) ? n.undone : {}), ...Object.keys(isMap(o.undone) ? o.undone : {})])) {
+ const at = Number(edited?.[k]) || 0
+ const m = undoOf(n.undone, k, at) || undoOf(o.undone, k, at)
+ if (m && !(k in bumps)) undone[k] = clone(m)
+ }
+ if (Object.keys(undone).length) out.undone = undone; else delete out.undone
}
if (deleted) out.deleted = deleted; else delete out.deleted
out._ts = Math.max(a._ts || 0, b._ts || 0)
@@ -850,7 +965,14 @@ export function stampChange(prev, next, wall = Date.now()) {
const old = bwBefore.get(e.d)
if (!old || old.t !== e.t) e.t = Math.max(Number(e.t) || 0, now)
}
- stampRoutines(prev?.routines, next.routines, now)
+ // A routine put back by an Undo keeps the edit time it had: what puts it back is the add-back
+ // on record (stampDeletions), not an edit of it. Stamped as edited now, it was the newer version
+ // to an older app's merge (v1.3.9 keeps a routine whole, by `_ts`), and a rename made there
+ // offline was lost to the Undo. Only a routine removed after its last edit counts.
+ const gone = isMap(prev?.deleted?.routines) ? prev.deleted.routines : {}
+ const putBack = r => Number(gone[r.id]) > 0 && Number(r._ts) > 0 && Number(r._ts) < Number(gone[r.id]) &&
+ !list(prev?.routines).some(x => x?.id === r.id)
+ stampRoutines(prev?.routines, next.routines, now, putBack)
stampCustomEx(prev?.customEx, next.customEx, now)
stampEntries(prev?.equipProfiles, next.equipProfiles, now)
stampEntries(prev?.gymCards, next.gymCards, now)
@@ -859,24 +981,25 @@ export function stampChange(prev, next, wall = Date.now()) {
return now
}
-const sameRoutine = (a, b) => JSON.stringify({ ...a, _ts: 0, _f: 0 }) === JSON.stringify({ ...b, _ts: 0, _f: 0 })
+const sameRoutine = (a, b) => JSON.stringify({ ...a, _ts: 0, _f: 0, _u: 0 }) === JSON.stringify({ ...b, _ts: 0, _f: 0, _u: 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()) {
+export function stampRoutines(prev = [], next = [], now = Date.now(), putBack = () => false) {
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 && putBack(r)) continue
if (!old || (old !== r && !sameRoutine(old, r))) stampEntry(old, r, now)
}
return next
}
-const sameEntry = (a, b) => JSON.stringify({ ...a, _ts: 0, _f: 0 }) === JSON.stringify({ ...b, _ts: 0, _f: 0 })
+const sameEntry = (a, b) => JSON.stringify({ ...a, _ts: 0, _f: 0, _u: 0 }) === JSON.stringify({ ...b, _ts: 0, _f: 0, _u: 0 })
/**
* Stamps `_ts` on every custom exercise of `next` that is new or differs from its version in
diff --git a/frontend/src/lib/sync-stamps-parity.test.js b/frontend/src/lib/sync-stamps-parity.test.js
index b6ae92e36..d9aa7e8e6 100644
--- a/frontend/src/lib/sync-stamps-parity.test.js
+++ b/frontend/src/lib/sync-stamps-parity.test.js
@@ -20,8 +20,8 @@ describe('api/sync-stamps.js matches sync-merge.js', () => {
expect(S.mergeEdits(ea, eb)).toEqual(mergeEdits(ea, eb))
const doc = { _ts: n(), edited: ea, deleted: a, routines: [{ id: 'r', _ts: n(), _f: { name: n() } }], plates: { kg: { _ts: n() } } }
expect(S.highestStamp(doc)).toBe(highestStamp(doc))
- const old = { id: 'r', name: 'A', ex: [1], _f: { ex: 5 } }
- const x = { id: 'r', name: R() < 0.5 ? 'A' : 'B', ex: [1, R() < 0.5 ? 2 : 1] }
+ const old = { id: 'r', name: 'A', ex: [1], _f: { ex: 5 }, ...(R() < 0.5 ? { _u: { ex: [1, 5, 5] } } : {}) }
+ const x = { id: 'r', name: R() < 0.5 ? 'A' : 'B', ex: [1, R() < 0.5 ? 2 : 1], ...(R() < 0.3 ? { _u: { name: [0, 4], ex: [1, 5, 5] } } : {}) }
expect(S.stampEntry(clone(old), clone(x), 99)).toEqual(stampEntry(clone(old), clone(x), 99))
}
})
diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsx
index 8ad1577a2..03b0b5395 100644
--- a/frontend/src/views/Plan.jsx
+++ b/frontend/src/views/Plan.jsx
@@ -21,6 +21,7 @@ import { MOBILE } from '../lib/mobile.js'
import { coachAvailable } from '../lib/coach.js'
import { queueOf, queueView } from '../lib/queue.js'
import { deriveSessionName } from '../lib/session-merge.js'
+import { markUndone, undoMarks } from '../lib/sync-merge.js'
import {
scheduleModeOf, queueRecovery, rotationIds, saveRotation, startNewPass, startPass, stopPass,
chooseRotation, chooseFixedWeek,
@@ -43,13 +44,17 @@ export function deleteRoutineWithUndo(id) {
const st = useStore.getState()
const snap = routineSnapshot(st.S, id)
if (!snap) return false
+ const before = st.S
st.update(s => { deleteRoutine(s, id) })
+ // What the removal moved (weekdays, reschedules, the loop), for the Undo to mark as put back:
+ // a change another device made to one of them before it saw the removal then still wins.
+ snap.marks = undoMarks(before, useStore.getState().S)
useUI.getState().toast(t('“{0}” gone.', snap.routine.name), { action: t('Undo'), onAction: () => undoDeleteRoutine(snap) })
return true
}
export function undoDeleteRoutine(snap) {
let ok = false
- useStore.getState().update(s => { ok = restoreRoutine(s, snap) })
+ useStore.getState().update(s => { ok = restoreRoutine(s, snap); if (ok && snap.marks) markUndone(s, snap.marks) })
// False when a sync brought it back first (another device's Undo, or its later edit).
if (!ok) useUI.getState().toast(t('It’s already back.'))
return ok
@@ -68,13 +73,14 @@ export function takeOutOfLoop(id, setSeq, seq, label) {
setSeq(seq.filter(x => x !== id))
const after = useStore.getState().S
const mark = loopMark(after)
+ const marks = undoMarks(before, after)
const name = before.routines.find(r => r.id === id)?.name ?? id
- useUI.getState().toast(t('“{0}” is out of the loop.', name), { action: t('Undo'), onAction: () => undoTakeOut({ id, at, label, snap, mark }) })
+ useUI.getState().toast(t('“{0}” is out of the loop.', name), { action: t('Undo'), onAction: () => undoTakeOut({ id, at, label, snap, mark, marks }) })
return true
}
// What the loop looked like right after a removal: the saved loop, the pass and the mode switch.
const loopMark = S => JSON.stringify([S.rotation ?? null, S.queue ?? null, S.scheduleMode ?? null])
-export function undoTakeOut({ id, at, label, snap, mark }) {
+export function undoTakeOut({ id, at, label, snap, mark, marks }) {
if (!useStore.getState().S.routines.some(r => r.id === id)) {
useUI.getState().toast(t('Too late, that one’s gone'))
return false
@@ -85,6 +91,8 @@ export function undoTakeOut({ id, at, label, snap, mark }) {
s.queue = snap.queue
const pins = Object.entries(snap.dayPlan).filter(([iso]) => s.dayPlan?.[iso] == null)
if (pins.length) s.dayPlan = { ...(s.dayPlan || {}), ...Object.fromEntries(pins) }
+ // Put back exactly: a reorder another device made before it saw the removal still wins.
+ if (marks) markUndone(s, marks)
return
}
// Only a loop that is still this app's and still running gets a pass written. After "Fixed
diff --git a/frontend/src/views/Plan.undo-sync.test.jsx b/frontend/src/views/Plan.undo-sync.test.jsx
index 8b6e61ddd..74a1754f0 100644
--- a/frontend/src/views/Plan.undo-sync.test.jsx
+++ b/frontend/src/views/Plan.undo-sync.test.jsx
@@ -45,7 +45,9 @@ describe('Undo after a removal the other device has already pulled', () => {
const here = S()
const back = here.routines.find(r => r.id === 'b')
expect(back).toBeTruthy()
- expect(back._ts).toBeGreaterThan(deleted.deleted.routines.b)
+ // It keeps the edit time it had: the add-back on record puts it back, not an edit of it (an
+ // older app keeps the routine edited last as a whole, and a rename there would lose to it).
+ expect(back._ts).toBe(900)
expect(here.deleted.routines.b).toBeLessThan(0) // marked as added back
for (const m of [mergeStates(here, other), mergeStates(other, here)]) {
expect(ids(m.routines)).toEqual(['a', 'b', 'c'])
diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx
index 86b03f8c5..a6f2bbcb9 100644
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@ -16,6 +16,7 @@ import SwipeRow from '../components/SwipeRow.jsx'
import { workoutControls } from '../lib/workout-controls.js'
import { copyRoutine, deleteRoutine, replaceSlotExercise } from '../lib/routines.js'
import { planPrintHTML, printPlan } from '../lib/plan-share.js'
+import { markEntryUndone } from '../lib/sync-merge.js'
import { MOBILE, printHtml } from '../lib/mobile.js'
import { speedUnitOf } from '../lib/speed.js'
import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js'
@@ -330,24 +331,29 @@ export function removeRoutineExercise(routineId, i) {
const slot = routine?.ex?.[i]
if (!slot) return false
const before = structuredClone(routine.ex)
+ const base = Number(routine._f?.ex) || 0
st.update(s => {
const ex = s.routines.find(x => x.id === routineId)?.ex
if (!ex) return
ex.splice(i, 1); cleanupSg(ex)
})
- const after = JSON.stringify(useStore.getState().S.routines.find(x => x.id === routineId)?.ex)
+ const now = useStore.getState().S.routines.find(x => x.id === routineId)
+ const after = JSON.stringify(now?.ex)
+ const del = Number(now?._f?.ex) || 0
useUI.getState().toast(t('“{0}” left the routine.', exerciseNameText(exOr(slot.id))),
- { action: t('Undo'), onAction: () => undoRemoveRoutineExercise({ routineId, i, before, after }) })
+ { action: t('Undo'), onAction: () => undoRemoveRoutineExercise({ routineId, i, before, after, base, del }) })
return true
}
-export function undoRemoveRoutineExercise({ routineId, i, before, after }) {
+export function undoRemoveRoutineExercise({ routineId, i, before, after, base, del }) {
if (!useStore.getState().S.routines.some(x => x.id === routineId)) {
useUI.getState().toast(t('Too late, that one’s gone'))
return false
}
useStore.getState().update(s => {
const routine = s.routines.find(x => x.id === routineId)
- if (JSON.stringify(routine.ex) === after) { routine.ex = structuredClone(before); return }
+ // Put back exactly, so a change another device made to these exercises before it saw the
+ // removal still wins (lib/sync-merge.js, "Undo").
+ if (JSON.stringify(routine.ex) === after) { routine.ex = structuredClone(before); if (del) markEntryUndone(routine, 'ex', base, del); return }
routine.ex.splice(Math.min(i, routine.ex.length), 0, structuredClone(before[i]))
cleanupSg(routine.ex)
})
diff --git a/frontend/src/views/undo-concurrent.test.jsx b/frontend/src/views/undo-concurrent.test.jsx
new file mode 100644
index 000000000..84e2e9c54
--- /dev/null
+++ b/frontend/src/views/undo-concurrent.test.jsx
@@ -0,0 +1,141 @@
+// @vitest-environment happy-dom
+// RC review 2026-10-07: an Undo after a swipe beat a change another device made, offline, to the
+// same list before it saw the removal: a routine's set count (exercise swiped out of the routine
+// and put back), a reorder of the loop (a routine swiped out of it and put back), and with an
+// older app (v1.3.9) a rename of the routine swiped away in Plan and put back. Undo means "as if
+// nothing happened", so that change has to survive, on every device, in either merge order.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn(), useParams: () => ({}) }))
+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), beacon: vi.fn(), appBase: () => '/' }))
+vi.mock('../components/Media.jsx', () => ({ Thumb: () => null }))
+vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
+
+import { DEF, useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { deleteRoutineWithUndo, takeOutOfLoop } from './Plan.jsx'
+import { removeRoutineExercise } from './RoutineEdit.jsx'
+import { mergeStates, stampChange } from '../lib/sync-merge.js'
+import { saveRotation } from '../lib/rotation.js'
+import { stampPut } from '../../../api/sync-stamps.js'
+
+const clone = v => JSON.parse(JSON.stringify(v))
+const S = () => useStore.getState().S
+const undo = () => useUI.getState().runToastAction()
+const change = (prev, fn, wall) => { const next = clone(prev); fn(next); next._ts = stampChange(prev, next, wall); return next }
+const T0 = Date.now() - 3_600_000
+const ex = (id, sets) => ({ id, sets, reps: 8, weight: 40 })
+const shared = () => {
+ const base = Object.assign(clone(DEF), {
+ _ts: T0 - 10_000,
+ routines: [
+ { id: 'a', name: 'Push', _ts: T0 - 10_000, ex: [ex('0025', 3), ex('0198', 3), ex('0586', 3)] },
+ { id: 'b', name: 'Pull', _ts: T0 - 10_000, ex: [ex('0586', 3)] },
+ { id: 'c', name: 'Legs', _ts: T0 - 10_000, ex: [ex('0198', 5)] },
+ ],
+ week: { 1: ['a', 'b'], 3: ['b'], 5: ['c'] },
+ })
+ // one stamped change, so the copy carries a record of edits like any copy from this version
+ return change(base, s => { s.restSec = 100 }, T0 - 9_000)
+}
+const both = (x, y) => [mergeStates(x, y), mergeStates(y, x)]
+
+beforeEach(() => { localStorage.clear(); useStore.setState({ S: shared(), user: null }) })
+afterEach(() => { localStorage.clear() })
+
+describe('Undo of an exercise swiped out of a routine', () => {
+ it('a set count changed offline on another device before it saw the removal survives', () => {
+ const base = S()
+ const other = change(base, s => { s.routines[0].ex[2].sets = 6 }, T0) // offline, before the swipe
+ removeRoutineExercise('a', 0)
+ const removed = clone(S()) // what the server got
+ undo()
+ const here = S()
+ expect(here.routines[0].ex.map(e => e.id)).toEqual(['0025', '0198', '0586'])
+ for (const m of both(here, other)) {
+ expect(m.routines[0].ex.map(e => `${e.id}x${e.sets}`)).toEqual(['0025x3', '0198x3', '0586x6'])
+ // and every copy settles on it, the one still holding the removal included
+ for (const n of both(m, removed)) expect(n.routines[0].ex.map(e => `${e.id}x${e.sets}`)).toEqual(['0025x3', '0198x3', '0586x6'])
+ for (const n of both(m, here)) expect(n.routines[0].ex.map(e => `${e.id}x${e.sets}`)).toEqual(['0025x3', '0198x3', '0586x6'])
+ }
+ for (const m of both(mergeStates(here, removed), other)) expect(m.routines[0].ex[2].sets).toBe(6)
+ })
+ it('a change made after the other device saw the removal still loses to the Undo', () => {
+ removeRoutineExercise('a', 0)
+ const removed = clone(S())
+ const other = change(removed, s => { s.routines[0].ex[1].sets = 9 }, Date.now()) // on the list without it
+ undo()
+ for (const m of both(S(), other)) expect(m.routines[0].ex.map(e => `${e.id}x${e.sets}`)).toEqual(['0025x3', '0198x3', '0586x3'])
+ })
+ it('an Undo after another edit of the routine puts the exercise back without claiming the rest', () => {
+ removeRoutineExercise('a', 0)
+ useStore.getState().update(s => { s.routines[0].ex[0].sets = 4 })
+ undo()
+ expect(S().routines[0].ex.map(e => `${e.id}x${e.sets}`)).toEqual(['0025x3', '0198x4', '0586x3'])
+ expect(S().routines[0]._u).toBeUndefined()
+ })
+})
+
+describe('Undo of a routine swiped out of the loop', () => {
+ const loop = s => s.queue?.ids?.join(',')
+ const setSeq = ids => useStore.getState().update(s => { saveRotation(s, ids, 'Loop') })
+ beforeEach(() => {
+ useStore.getState().update(s => { s.scheduleMode = 'rotation'; saveRotation(s, ['a', 'b', 'c'], 'Loop') })
+ })
+ it('a reorder made offline on another device before it saw the removal survives', () => {
+ const base = clone(S())
+ const other = change(base, s => { const ids = ['c', 'a', 'b']; s.rotation = { ...s.rotation, sequence: ids }; s.queue = { ...s.queue, ids } }, Date.now() - 1000)
+ expect(takeOutOfLoop('b', setSeq, ['a', 'b', 'c'], 'Loop')).toBe(true)
+ const removed = clone(S())
+ undo()
+ expect(loop(S())).toBe('a,b,c')
+ for (const m of both(S(), other)) {
+ expect(loop(m)).toBe('c,a,b')
+ expect(m.rotation.sequence.join(',')).toBe('c,a,b')
+ for (const n of both(m, removed)) expect(loop(n)).toBe('c,a,b')
+ }
+ })
+})
+
+describe('Undo of a routine swiped away in Plan, with an older app (v1.3.9) on the account', () => {
+ // v1.3.9's merge keeps a routine whole, the version with the later `_ts`, and stamps nothing
+ // but `_ts` (lib/sync-merge.js of v1.3.9).
+ const v139Merge = (local, server) => {
+ const n = (server._ts || 0) > (local._ts || 0) ? server : local, o = n === local ? server : local
+ const out = clone(n)
+ const other = new Map(o.routines.map(r => [r.id, r]))
+ out.routines = [...n.routines, ...o.routines.filter(r => !n.routines.some(x => x.id === r.id))]
+ .map(r => { const alt = other.get(r.id); return clone(alt && (alt._ts || 0) > (r._ts || 0) ? alt : r) })
+ out._ts = Math.max(local._ts || 0, server._ts || 0)
+ return out
+ }
+ it('a rename made there offline before the removal survives the Undo', () => {
+ const base = S()
+ const old = clone(base)
+ old.routines[1].name = 'Pull heavy'; old.routines[1]._ts = T0; old._ts = T0 // v1.3.9, offline
+ deleteRoutineWithUndo('b')
+ undo()
+ const server = clone(S())
+ // v1.3.9 comes back: 409, its merge, its push over that revision
+ const pushed = v139Merge(old, server)
+ stampPut(server, pushed, { overRead: true, stamped: false, now: Date.now() + 1 })
+ expect(pushed.routines.find(r => r.id === 'b').name).toBe('Pull heavy')
+ for (const m of both(S(), pushed)) {
+ expect(m.routines.map(r => r.id)).toEqual(['a', 'b', 'c'])
+ expect(m.routines.find(r => r.id === 'b').name).toBe('Pull heavy')
+ expect(m.week[3]).toEqual(['b'])
+ }
+ })
+ it('a weekday another device changed before it saw the removal survives the Undo', () => {
+ const other = change(S(), s => { s.week[3] = ['b', 'c'] }, Date.now() - 1000)
+ deleteRoutineWithUndo('b')
+ const removed = clone(S())
+ undo()
+ for (const m of both(S(), other)) {
+ expect(m.week[3]).toEqual(['b', 'c'])
+ expect(m.week[1]).toEqual(['a', 'b'])
+ for (const n of both(m, removed)) expect(n.routines.map(r => r.id)).toEqual(['a', 'b', 'c'])
+ }
+ })
+})