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.

Follow-up to #203: an edited workout replaces the saved one by id on every device, through the sync the app now has

Duarte Santos7122b69fcf52
diff --git a/frontend/src/lib/session-edit.js b/frontend/src/lib/session-edit.js
index cf1da0f6f..67668a2e8 100644
--- a/frontend/src/lib/session-edit.js
+++ b/frontend/src/lib/session-edit.js
@@ -1,147 +1,120 @@
+// Editing a workout that is already in history (#143): its exercises, sets and notes.
+//
+// The editor is the ordinary workout screen working on a copy in S.active (`editingWorkoutId`
+// says whose), so a reload, a closed tab or an offline spell keeps the draft, and the saved
+// record stays exactly as it was until Save. When the session happened — its day, start and
+// length — is not edited here: WorkoutDetail has its own rows for that (lib/workout-date.js).
+//
+// Save replaces the record by id. Getting that replacement onto every device is the sync's job,
+// not this file's: the record is stamped with the time of the edit (stampWorkout), and a conflict
+// between two copies keeps the version edited last (lib/sync-merge.js). So the edit replaces the
+// old copy wherever it is, is never joined by it as a duplicate, and an older copy cannot come
+// back over it on a 409.
import { buildCompletedWorkout } from './finish-workout.js'
import { beatsWeight } from './exercises.js'
import { bestWeightForEntry, workoutVolume } from './history.js'
import { hasCompletedWork } from './workout-model.js'
+import { stampWorkout } from './sync-merge.js'
+import { legacySyncKey, rebuildPrHistory } from './workout-date.js'
const clone = value => structuredClone(value)
-const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
-const byDayStart = (a, b) => a.d === b.d ? (a.start || 0) - (b.start || 0) : a.d < b.d ? -1 : 1
+const list = v => (Array.isArray(v) ? v : [])
-// A saved-workout edit is an ordinary persisted active draft. The history record stays byte for
-// byte unchanged until Save, so reload, cancel and an offline spell cannot lose the original.
-export function editCompletedSession(state, workoutId) {
+// Which record the editor works on. A workout logged before ids existed is keyed by its day and
+// start, the way the sync keys it; Save freezes that key as its id (as a date move does), so the
+// other device's untouched copy is still recognised as the same record.
+const keyOf = w => (w?.id != null ? w.id : legacySyncKey(w))
+
+// The best load one workout logged for an exercise, across every occurrence of it.
+function bestIn(workout, id) {
+ let best = 0
+ for (const e of list(workout?.entries)) {
+ if (e?.id !== id) continue
+ const w = bestWeightForEntry(e)
+ if (beatsWeight(id, w, best)) best = w
+ }
+ return best
+}
+
+/**
+ * Opens the editor on a saved workout: a copy of it becomes S.active. `ref` is the workout or its
+ * id. Throws while another session is running, or when the workout is gone.
+ */
+export function editCompletedSession(state, ref) {
if (state.active) throw new Error('Finish the current workout first.')
- const original = state.workouts.find(workout => workout.id === workoutId)
- if (!original) throw new Error('This workout is no longer available.')
+ const key = ref && typeof ref === 'object' ? keyOf(ref) : ref
+ const original = key == null ? null : list(state.workouts).find(w => keyOf(w) === key)
+ if (!original) throw new Error('Workout deleted')
const active = clone(original)
- active.entries = clone(original.entries)
active.cur = 0
- active.editingWorkoutId = original.id
- active.editingOriginal = clone(original)
- for (const key of ['vol', 'prs']) delete active[key]
+ active.editingWorkoutId = key
+ // Worked out again on Save, from the edited sets.
+ for (const k of ['vol', 'prs', '_ts']) delete active[k]
state.active = active
return active
}
-// Refresh the record-derived caches that can become stale when a correction lowers or removes a
-// set. PRs are historical: each workout is compared only with sessions before it.
-export function rebuildHistoryDerived(state, exerciseIds) {
- const ids = new Set(exerciseIds)
- const best = new Map()
- for (const workout of [...state.workouts].sort(byDayStart)) {
- const existing = (workout.prs || []).filter(id => !ids.has(id))
- for (const id of ids) {
- let weight = 0
- for (const entry of workout.entries.filter(entry => entry.id === id)) {
- const entryWeight = bestWeightForEntry(entry)
- if (beatsWeight(id, entryWeight, weight)) weight = entryWeight
- }
- const previous = best.get(id) || 0
- if (beatsWeight(id, weight, previous)) existing.push(id)
- if (beatsWeight(id, weight, previous)) best.set(id, weight)
- }
- workout.prs = [...new Set(existing)]
- }
- for (const id of ids) {
- const candidates = state.workouts.flatMap(workout => workout.entries
- .filter(entry => entry.id === id)
- .map(entry => ({ w: bestWeightForEntry(entry), d: workout.d })))
- .filter(value => value.w > 0)
- let bestCandidate = null
- for (const candidate of candidates) {
- if (!bestCandidate || beatsWeight(id, candidate.w, bestCandidate.w)) bestCandidate = candidate
- }
- if (bestCandidate) state.exWeights[id] = bestCandidate
- else delete state.exWeights[id]
- }
-}
-
-export function saveWorkoutEdit(state) {
+/**
+ * Saves the editor into history and closes it. Returns the saved record.
+ *
+ * The record is the one history holds now, not the one the editor opened: another device may have
+ * moved it or corrected its note meanwhile, and what the editor does not edit stays as that left
+ * it. The sets are the editor's — the edit saved last wins, as it does between devices. A record
+ * deleted meanwhile (the deletion already reached this device) is not brought back behind the
+ * person's back: Save throws, and the draft stays open to keep editing or drop.
+ */
+export function saveWorkoutEdit(state, now = Date.now()) {
const active = state.active
- const original = active?.editingOriginal
- const index = state.workouts.findIndex(workout => workout.id === active?.editingWorkoutId)
+ const key = active?.editingWorkoutId
+ const index = key == null ? -1 : list(state.workouts).findIndex(w => keyOf(w) === key)
if (index < 0) throw new Error('This workout was deleted on another device. Your edits are still here.')
- if (!original || !same(state.workouts[index], original)) {
- throw new Error('This workout changed on another device. Your edits are still here.')
- }
+ const current = state.workouts[index]
const updated = buildCompletedWorkout(active, {
- end: original.end,
- prs: original.prs || [],
+ end: current.end,
+ prs: current.prs || [],
snapshotFor: entry => entry.muscleSnapshot,
})
- updated.start = original.start
- updated.d = original.d
-
// Carry occurrence metadata opaquely, by order rather than exercise id: the same exercise may
- // appear twice. Canonical completed-entry fields win, while live-only prescription data stays
- // out of history just as it does after an ordinary workout.
+ // appear twice. Canonical completed-entry fields win, while live-only prescription data (the
+ // plan's explanation, the "carried over" marker) stays out of history as it does after an
+ // ordinary workout.
const logged = active.entries.filter(entry => entry.sets.some(hasCompletedWork))
- updated.entries = updated.entries.map((entry, index) => {
- const merged = { ...clone(logged[index]), ...entry }
+ updated.entries = updated.entries.map((entry, i) => {
+ const merged = { ...clone(logged[i]), ...entry }
delete merged.plan
- for (const key of ['note', 'notePin', 'noProg', 'muscleSnapshot']) if (!(key in entry)) delete merged[key]
+ delete merged.carried
+ for (const k of ['note', 'notePin', 'noProg', 'muscleSnapshot', 'rid', 'planned']) if (!(k in entry)) delete merged[k]
return merged
})
- const record = { ...original, ...updated, vol: workoutVolume(updated) }
- for (const key of ['note', 'excludeFromProgression']) if (!(key in updated)) delete record[key]
+ const record = { ...current, ...updated, id: key, d: current.d, start: current.start, end: current.end }
+ for (const k of ['note', 'excludeFromProgression']) if (!(k in updated)) delete record[k]
+ record.vol = workoutVolume(record)
+ stampWorkout(record, now)
state.workouts[index] = record
- rebuildHistoryDerived(state, [...original.entries, ...active.entries].map(entry => entry.id))
- state.active = null
- return record
-}
-// The editor dirties the device state as its draft changes. If another device changes the source
-// record meanwhile, make that remote record the visible original before the normal state merge;
-// Save will then detect it instead of silently replacing it with the stale copy held at edit start.
-export function prepareLocalStateForEditMerge(local, remote, pending = []) {
- const next = clone(local)
- const receipts = Array.isArray(pending) ? pending : (pending?.id ? [pending] : [])
- const active = local?.active
- const activeEdit = active?.editingWorkoutId
- ? { id: active.editingWorkoutId, original: active.editingOriginal, saved: active, activeDraft: true }
- : null
- const edits = [...(activeEdit ? [activeEdit] : []), ...receipts.filter(edit => edit.id !== activeEdit?.id)]
- let blocked = false
- let occupied = !!active
- const affectedExerciseIds = new Set()
- for (const edit of edits) {
- const { id, original } = edit || {}
- if (!id || !original) continue
- const current = next.workouts?.find(workout => workout.id === id)
- const remoteRecord = remote?.workouts?.find(workout => workout.id === id)
- const saved = edit.saved || (!same(current, original) ? current : null)
- if (remoteRecord && same(remoteRecord, original)) continue
+ // Badges are a claim about the sessions before each one. The edited session can earn one it now
+ // leads with, and a later one loses its own if the edit raised the bar above it — the same
+ // asymmetric rule a date move follows, so imported history never sprouts trophies.
+ const touched = [...new Set([...list(current.entries), ...record.entries].map(e => e?.id).filter(id => id != null))]
+ state.workouts = rebuildPrHistory(state.workouts, touched, record)
+ const saved = state.workouts.find(w => keyOf(w) === key)
- // The server changed or deleted the source record. Its canonical record wins this merge. A
- // saved local correction becomes an editor draft when the active slot is free; otherwise its
- // receipt remains in localStorage and the caller stops before retrying the PUT.
- next.workouts = next.workouts.filter(workout => workout.id !== id)
- if (remoteRecord) next.workouts.push(clone(remoteRecord))
- if (!edit.activeDraft && saved) {
- if (!occupied) {
- next.active = clone(saved)
- next.active.entries = clone(saved.entries)
- next.active.cur = 0
- next.active.editingWorkoutId = id
- next.active.editingOriginal = clone(remoteRecord || original)
- for (const key of ['vol', 'prs']) delete next.active[key]
- occupied = true
- } else blocked = true
- }
- // The saved correction may already have lowered this cache locally. Once it is moved back to
- // a draft (or held in its receipt), the remote document owns derived state again.
- for (const exerciseId of new Set([...(original.entries || []), ...(current?.entries || []), ...(remoteRecord?.entries || [])].map(entry => entry.id))) {
- affectedExerciseIds.add(exerciseId)
- if (remote?.exWeights?.[exerciseId]) next.exWeights[exerciseId] = clone(remote.exWeights[exerciseId])
- else delete next.exWeights[exerciseId]
+ // The kept working weight of an exercise is lowered only when it came from this session and the
+ // edit took it away — a typed 1000 corrected to 100. Then it is the best set left in history, or
+ // gone. One confirmed anywhere else ("Tracked — next time starts at…") is left as it is.
+ for (const id of touched) {
+ const kept = state.exWeights?.[id]
+ const before = bestIn(current, id)
+ if (!kept || !(kept.w > 0) || kept.w !== before || !beatsWeight(id, before, bestIn(saved, id))) continue
+ let best = null
+ for (const w of state.workouts) {
+ const top = bestIn(w, id)
+ if (beatsWeight(id, top, best?.w || 0)) best = { w: top, d: w.d }
}
+ if (best) state.exWeights[id] = best
+ else delete state.exWeights[id]
}
- return { state: next, blocked, affectedExerciseIds: [...affectedExerciseIds] }
-}
-
-export const localStateForEditMerge = (local, remote, pending) => {
- const prepared = prepareLocalStateForEditMerge(local, remote, pending)
- rebuildHistoryDerived(prepared.state, prepared.affectedExerciseIds)
- return prepared.state
+ state.active = null
+ return saved
}
diff --git a/frontend/src/lib/session-edit.test.js b/frontend/src/lib/session-edit.test.js
index 16b6ee3ed..9d33c4612 100644
--- a/frontend/src/lib/session-edit.test.js
+++ b/frontend/src/lib/session-edit.test.js
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
-import { editCompletedSession, localStateForEditMerge, saveWorkoutEdit } from './session-edit.js'
+import { editCompletedSession, saveWorkoutEdit } from './session-edit.js'
+import { mergeStates } from './sync-merge.js'
const entry = (w, id = '0025') => ({ id, sets: [{ w, r: 5, done: true }], target: { mode: 'reps' } })
const fixture = () => ({
@@ -36,30 +37,46 @@ describe('saved workout editing', () => {
expect(saved.entries[1]).not.toHaveProperty('plan')
})
- it('rebuilds best weights and historical PR flags after lowering or deleting record work', () => {
+ it('rebuilds best weights and PR flags after lowering record work', () => {
const state = fixture()
state.workouts.push({ id: 'later', d: '2026-09-02', start: 3000, end: 4000, entries: [entry(30)], prs: [] })
state.exWeights['0025'] = { w: 40, d: '2026-09-01' }
editCompletedSession(state, 'workout')
state.active.entries[0].sets[0].w = 20
saveWorkoutEdit(state)
+ // The kept 40 came from this very session, and the edit took it away.
expect(state.exWeights['0025']).toEqual({ w: 30, d: '2026-09-02' })
+ // Still the first 20 ever. The later 30 never had a badge, and a session that was not
+ // edited is never handed one (the rule a date move follows too, lib/workout-date.js).
expect(state.workouts[0].prs).toEqual(['0025'])
- expect(state.workouts[1].prs).toEqual(['0025'])
+ expect(state.workouts[1].prs).toEqual([])
+ })
+
+ it('takes a badge from a later session the edit raised the bar above, and leaves a kept load from elsewhere', () => {
+ const state = fixture()
+ state.workouts[0].prs = []
+ state.workouts.push({ id: 'later', d: '2026-09-02', start: 3000, end: 4000, entries: [entry(50)], prs: ['0025'] })
+ state.exWeights['0025'] = { w: 55, d: '2026-09-03' } // confirmed in the top-weight sheet
+ editCompletedSession(state, 'workout')
+ state.active.entries[0].sets[0].w = 60
+ saveWorkoutEdit(state)
+ expect(state.workouts.map(w => w.prs)).toEqual([['0025'], []])
+ expect(state.exWeights['0025']).toEqual({ w: 55, d: '2026-09-03' })
})
it('keeps assisted-machine records ordered by less help after an edit', () => {
const state = fixture()
state.workouts[0].entries = [entry(30, '0017')]
state.workouts[0].prs = ['0017']
- state.workouts.push({ id: 'later', d: '2026-09-02', start: 3000, end: 4000, entries: [entry(25, '0017')], prs: [] })
- state.exWeights['0017'] = { w: 30, d: '2026-09-01' }
+ state.workouts.push({ id: 'later', d: '2026-09-02', start: 3000, end: 4000, entries: [entry(25, '0017')], prs: ['0017'] })
+ state.exWeights['0017'] = { w: 25, d: '2026-09-02' }
editCompletedSession(state, 'workout')
state.active.entries[0].sets[0].w = 20
saveWorkoutEdit(state)
- expect(state.exWeights['0017']).toEqual({ w: 20, d: '2026-09-01' })
- expect(state.workouts[0].prs).toEqual(['0017'])
- expect(state.workouts[1].prs).toEqual([])
+ // 20 kg of help is less than the later 25: the edited session leads and the later one no
+ // longer does. Less help is a better kept load, so there is nothing to lower.
+ expect(state.workouts.map(w => w.prs)).toEqual([['0017'], []])
+ expect(state.exWeights['0017']).toEqual({ w: 25, d: '2026-09-02' })
})
it('preserves repeated occurrences, combined-routine ownership and per-side fields', () => {
@@ -94,45 +111,65 @@ describe('saved workout editing', () => {
expect(saved.vol).toBe(80)
})
- it('keeps the draft when the original is missing or changed remotely', () => {
+ it('keeps the draft when the workout was deleted meanwhile', () => {
const deleted = fixture()
editCompletedSession(deleted, 'workout')
+ deleted.active.entries[0].sets[0].w = 50
deleted.workouts = []
expect(() => saveWorkoutEdit(deleted)).toThrow('deleted on another device')
expect(deleted.active.editingWorkoutId).toBe('workout')
+ expect(deleted.active.entries[0].sets[0].w).toBe(50)
+ expect(deleted.workouts).toEqual([])
+ })
+
+ // Another device moved the workout or corrected its note while this one edited its sets. What
+ // the editor does not edit stays as the other device left it; the sets are the editor's.
+ it('saves over the record as history holds it now, keeping what the editor does not edit', () => {
+ const state = fixture()
+ editCompletedSession(state, 'workout')
+ state.active.entries[0].sets[0].w = 50
+ Object.assign(state.workouts[0], { d: '2026-08-20', start: 500, end: 1500, note: 'from phone' })
+ state.active.note = 'from phone'
+ const saved = saveWorkoutEdit(state)
+ expect(saved).toMatchObject({ id: 'workout', d: '2026-08-20', start: 500, end: 1500, note: 'from phone' })
+ expect(saved.entries[0].sets[0].w).toBe(50)
+ })
- const changed = fixture()
- editCompletedSession(changed, 'workout')
- changed.workouts[0].note = 'remote'
- expect(() => saveWorkoutEdit(changed)).toThrow('changed on another device')
- expect(changed.active.editingWorkoutId).toBe('workout')
+ it('stamps the edit, and the edit replaces the old copy by id in a merge whichever copy is newer', () => {
+ const state = fixture()
+ editCompletedSession(state, 'workout')
+ state.active.entries[0].sets[0].w = 50
+ const saved = saveWorkoutEdit(state, 1234)
+ expect(saved._ts).toBe(1234)
+ const phone = { ...fixture(), _ts: 9999 }
+ for (const merged of [mergeStates({ ...state, _ts: 1234 }, phone), mergeStates(phone, { ...state, _ts: 1234 })]) {
+ expect(merged.workouts).toHaveLength(1)
+ expect(merged.workouts[0].entries[0].sets[0].w).toBe(50)
+ }
})
- it('feeds a remotely changed or deleted original into the current revision merge', () => {
- const local = fixture()
- editCompletedSession(local, 'workout')
- local.active.entries[0].sets[0].w = 50
- const remote = fixture()
- remote.workouts[0].note = 'from phone'
- remote.exWeights['0025'] = { w: 40, d: '2026-09-01' }
- expect(localStateForEditMerge(local, remote).workouts[0].note).toBe('from phone')
- expect(localStateForEditMerge(local, { ...remote, workouts: [] }).workouts).toEqual([])
- expect(local.active.entries[0].sets[0].w).toBe(50)
+ it('opens and saves a workout logged before ids, freezing its old key as its id', () => {
+ const state = fixture()
+ delete state.workouts[0].id
+ state.workouts.push({ d: '2026-09-02', start: 3000, end: 4000, entries: [entry(30)], prs: [] })
+ editCompletedSession(state, state.workouts[1])
+ expect(state.active.editingWorkoutId).toBe('2026-09-02|3000')
+ state.active.entries[0].sets[0].w = 35
+ const saved = saveWorkoutEdit(state)
+ expect(saved).toMatchObject({ id: '2026-09-02|3000', d: '2026-09-02', start: 3000 })
+ expect(state.workouts[0]).not.toHaveProperty('id')
+ expect(state.workouts[0].entries[0].sets[0].w).toBe(40)
+ const other = { ...fixture(), _ts: 9999, workouts: [state.workouts[0], { d: '2026-09-02', start: 3000, end: 4000, entries: [entry(30)], prs: [] }] }
+ expect(mergeStates(other, { ...state, _ts: 1 }).workouts.map(w => w.entries[0].sets[0].w)).toEqual([40, 35])
})
- it('restores a locally saved correction as a draft when its first push conflicts', () => {
- const local = fixture()
- editCompletedSession(local, 'workout')
- const original = structuredClone(local.active.editingOriginal)
- local.active.entries[0].sets[0].w = 50
- saveWorkoutEdit(local)
- const remote = fixture()
- remote.workouts[0].note = 'from phone'
- remote.exWeights['0025'] = { w: 40, d: '2026-09-01' }
- const merged = localStateForEditMerge(local, remote, { id: 'workout', original })
- expect(merged.workouts[0].note).toBe('from phone')
- expect(merged.active.entries[0].sets[0].w).toBe(50)
- expect(merged.active.editingOriginal).toEqual(remote.workouts[0])
- expect(merged.exWeights['0025'].w).toBe(40)
+ it('keeps only the loads, not the marks the live session used, and no prescription explanation', () => {
+ const state = fixture()
+ editCompletedSession(state, 'workout')
+ state.active.entries[0].sets[0] = { w: 45, r: 5, done: true, weightOrigin: 'manual' }
+ state.active.entries[0].plan = { kind: 'hold' }
+ state.active.entries[0].carried = true
+ const saved = saveWorkoutEdit(state)
+ expect(JSON.stringify(saved)).not.toMatch(/weightOrigin|"plan"|carried|editingWorkoutId/)
})
})
diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js
index 17238ccb8..75430fced 100644
--- a/frontend/src/lib/sync-merge.js
+++ b/frontend/src/lib/sync-merge.js
@@ -1,5 +1,3 @@
-import { bestWeightForEntry } from './history.js'
-
/* Two copies of the account state, one merged copy.
*
* The server refuses a push over a document the device never saw (PUT /api/data with a stale
@@ -10,16 +8,22 @@ import { bestWeightForEntry } from './history.js'
*
* Rules, by field:
* - scalars and settings, `week`, `dayPlan`, `wc`, `reminder`, …: from the copy with the newer `_ts`
- * - 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
+ * - customEx, equipProfiles, gymCards: union by id, the newer copy's version of an id that
+ * both have
+ * - workouts: union by id; of an id that both have, the version edited last by its own `_ts`
+ * (stampWorkout — a workout changed after it was logged: its sets edited, moved to another
+ * day, its length or note corrected), the newer copy's on a tie; 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, normally the larger `w`; when the winning side changed an
- * existing workout, affected exercises are rebuilt from that side and the merged history so
- * a deliberate history correction can lower a stale cached best. Assistance machines use
- * their smaller-is-better ordering; exNotes and barWeights remain key unions.
+ * - exWeights: union by exercise, the better `w` for that exercise — larger for an ordinary
+ * lift, smaller on an assistance machine (a PR logged on the other device must not be
+ * forgotten, whichever way it runs). An exercise in a workout whose edited version was kept
+ * is the exception: the edit may have taken away the set the kept weight came from, so it
+ * is the best of the merged history and of the editing copy's own, and the other copy's
+ * can no longer bring a corrected typo back. exNotes, barWeights: key union
* - `_ts`: the later of the two; `_rev` dropped (the server sets it); `active` left to the caller
*
* Known limit: with no record of what each side deleted, an entry removed on one device inside
@@ -28,6 +32,7 @@ import { bestWeightForEntry } from './history.js'
* would close it.
*/
import { beatsWeight } from './exercises.js'
+import { bestWeightForEntry } from './history.js'
const clone = o => JSON.parse(JSON.stringify(o))
const list = v => (Array.isArray(v) ? v : [])
@@ -71,28 +76,41 @@ export function mergeBodyweight(a = [], b = []) {
// harder setting and taking the larger would hand back the help the other device just dropped
// (issue #232). `beatsWeight` knows which way round each exercise runs; the date breaks a tie
// on an exercise where both sides moved in the same direction.
-function mergeExWeights(n = {}, o = {}, workouts = [], corrected = new Set()) {
+function mergeExWeights(n = {}, o = {}) {
const out = { ...(o || {}), ...(n || {}) }
for (const k of Object.keys(o || {})) {
if (!(n && n[k] && o[k])) continue
if (beatsWeight(k, o[k].w || 0, n[k].w || 0)) out[k] = o[k]
}
- for (const id of corrected) {
- const logged = workouts.flatMap(workout => list(workout.entries)
- .filter(entry => entry?.id === id)
- .map(entry => ({ w: bestWeightForEntry(entry), d: workout.d })))
- .filter(value => value.w > 0)
- const candidates = [...logged, ...(n?.[id]?.w > 0 ? [n[id]] : [])]
- let best = null
- for (const candidate of candidates) {
- if (!best || beatsWeight(id, candidate.w, best.w)) best = candidate
- }
- if (best) out[id] = best
- else delete out[id]
- }
return out
}
+// The kept load of an exercise that a kept workout edit touched (see mergeStates): the best set in
+// the merged history, or the editing copy's own kept load when that is better still — the other
+// copy's may be the very typo the edit corrected. `sources` are the exWeights of each copy whose
+// edit was kept. Nothing left to read removes the key, as the edit itself did.
+function correctedExWeight(id, workouts, sources) {
+ let best = null
+ const consider = c => { if (c && c.w > 0 && (!best || beatsWeight(id, c.w, best.w))) best = c }
+ for (const w of workouts) {
+ for (const e of list(w?.entries)) if (e?.id === id) consider({ w: bestWeightForEntry(e), d: w.d })
+ }
+ for (const src of sources) consider(src?.[id])
+ return best
+}
+
+/**
+ * Stamps `_ts` on a saved workout changed after it was logged — its sets edited, moved to another
+ * day or time, its length or its note corrected — the edit time mergeStates needs to keep the
+ * version edited last, the way stampRoutines does for a plan. Without it the copy that was newer
+ * as a whole decided: a phone that logged a weigh-in after the desktop corrected a workout brought
+ * the uncorrected one back on the next conflict. Mutates and returns `w`.
+ */
+export function stampWorkout(w, now = Date.now()) {
+ if (w && typeof w === 'object') w._ts = now
+ return w
+}
+
// `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.
@@ -102,14 +120,31 @@ export function mergeStates(a, b, { prefer } = {}) {
const n = prefer === 'a' ? a : prefer === 'b' ? b : newerOf(a, b)
const o = n === a ? b : a
const out = clone(n)
- out.workouts = unionById(n.workouts, o.workouts, workoutKey).map(clone).sort(byDayStart)
- const olderWorkouts = new Map(list(o.workouts).map(workout => [workoutKey(workout), workout]))
- const corrected = new Set()
- for (const workout of list(n.workouts)) {
- const older = olderWorkouts.get(workoutKey(workout))
- if (!older || JSON.stringify(workout.entries) === JSON.stringify(older.entries)) continue
- for (const entry of [...list(workout.entries), ...list(older.entries)]) if (entry?.id != null) corrected.add(entry.id)
+ out.workouts = unionById(n.workouts, o.workouts, workoutKey).map(clone)
+ // A workout edited after it was logged keeps the version edited last, whichever copy is newer
+ // as a whole — the same rule as a routine's. `editedBy` notes, per exercise, the copies whose
+ // edit of its sets was kept, for the kept loads below. `prefer` (sign-in) keeps the preferred
+ // side's version as it is.
+ const editedBy = new Map()
+ if (!prefer) {
+ const mine = new Set(list(n.workouts).map(workoutKey))
+ const other = new Map(list(o.workouts).map(w => [workoutKey(w), w]))
+ out.workouts = out.workouts.map(w => {
+ const key = workoutKey(w)
+ const alt = mine.has(key) ? other.get(key) : null
+ if (!alt) return w
+ const [kept, lost, by] = (alt._ts || 0) > (w._ts || 0) ? [clone(alt), w, o] : [w, alt, n]
+ if ((kept._ts || 0) > (lost._ts || 0) && JSON.stringify(kept.entries) !== JSON.stringify(lost.entries)) {
+ for (const e of [...list(kept.entries), ...list(lost.entries)]) {
+ if (e?.id == null) continue
+ if (!editedBy.has(e.id)) editedBy.set(e.id, new Set())
+ editedBy.get(e.id).add(by.exWeights)
+ }
+ }
+ return kept
+ })
}
+ out.workouts.sort(byDayStart)
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)
}
@@ -126,7 +161,12 @@ export function mergeStates(a, b, { 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)])]
- out.exWeights = clone(mergeExWeights(n.exWeights, o.exWeights, out.workouts, corrected))
+ out.exWeights = clone(mergeExWeights(n.exWeights, o.exWeights))
+ for (const [id, sources] of editedBy) {
+ const kept = correctedExWeight(id, out.workouts, sources)
+ if (kept) out.exWeights[id] = clone(kept)
+ else delete out.exWeights[id]
+ }
for (const f of ['exNotes', 'barWeights']) {
if (n[f] || o[f]) out[f] = clone({ ...(o[f] || {}), ...(n[f] || {}) })
}
diff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.js
index abba992ef..8c5e4423b 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, stampRoutines, unionById } from './sync-merge.js'
+import { localExtras, mergeBodyweight, mergeStates, newerOf, stampRoutines, stampWorkout, unionById } from './sync-merge.js'
import { retimeWorkout } from './workout-date.js'
const workout = (id, d = '2026-09-01', start = 1) => ({ id, d, start, entries: [] })
@@ -81,18 +81,79 @@ describe('mergeStates', () => {
expect(m.barWeights).toEqual({ sq: 20, dl: 15 })
})
- it('does not resurrect a cached best lowered by the winning workout correction', () => {
- const set = w => ({ id: 'sq', target: { mode: 'reps' }, sets: [{ w, r: 5, done: true }] })
- const older = base({ _ts: 100, workouts: [{ ...workout('w1'), entries: [set(100)] }], exWeights: { sq: { w: 100, d: '2026-09-01' } } })
- const corrected = base({ _ts: 200, workouts: [{ ...workout('w1'), entries: [set(80)] }], exWeights: { sq: { w: 80, d: '2026-09-01' } } })
- expect(mergeStates(corrected, older).exWeights.sq).toEqual({ w: 80, d: '2026-09-01' })
- })
+ // A workout edited after it was logged is stamped with the time of the edit (stampWorkout).
+ // Whichever copy is newer as a whole, the edited version replaces the old one by id, and the
+ // old one can no longer come back over it.
+ describe('a workout edited after it was logged', () => {
+ const set = (w, id = 'sq') => ({ id, target: { mode: 'reps' }, sets: [{ w, r: 5, done: true }] })
+ const logged = (entries, over = {}) => ({ ...workout('w1'), entries, ...over })
+
+ it('keeps the edit when the other copy is newer as a whole but still has the old version', () => {
+ const edited = base({ _ts: 100, workouts: [stampWorkout(logged([set(80)]), 100)] })
+ const stale = base({ _ts: 200, workouts: [logged([set(100)])], bodyweight: [{ d: '2026-09-02', w: 80, t: 200 }] })
+ for (const m of [mergeStates(edited, stale), mergeStates(stale, edited)]) {
+ expect(m.workouts).toHaveLength(1)
+ expect(m.workouts[0].entries[0].sets[0].w).toBe(80)
+ expect(m.bodyweight).toHaveLength(1) // the newer copy's own change is kept too
+ }
+ })
+
+ it('keeps the later of two edits of the same workout, the newer copy\'s on a tie', () => {
+ const a = base({ _ts: 300, workouts: [stampWorkout(logged([set(80)]), 150)] })
+ const b = base({ _ts: 100, workouts: [stampWorkout(logged([set(90)]), 250)] })
+ expect(mergeStates(a, b).workouts[0].entries[0].sets[0].w).toBe(90)
+ expect(mergeStates(b, a).workouts[0].entries[0].sets[0].w).toBe(90)
+ const tie = base({ _ts: 100, workouts: [stampWorkout(logged([set(70)]), 250)] })
+ expect(mergeStates(b, { ...tie, _ts: 50 }).workouts[0].entries[0].sets[0].w).toBe(90)
+ })
+
+ it('a date move replaces the other copy by id too', () => {
+ const moved = retimeWorkout(logged([set(80)]), '2026-08-20', '07:00')
+ stampWorkout(moved, 100)
+ const m = mergeStates(base({ _ts: 100, workouts: [moved] }), base({ _ts: 200, workouts: [logged([set(80)])] }))
+ expect(m.workouts).toHaveLength(1)
+ expect(m.workouts[0].d).toBe('2026-08-20')
+ })
+
+ it('an edit of a workout the other copy deleted brings it back, edited', () => {
+ const edited = base({ _ts: 100, workouts: [stampWorkout(logged([set(80)]), 100)] })
+ const deleted = base({ _ts: 200, workouts: [] })
+ expect(mergeStates(deleted, edited).workouts.map(w => w.entries[0].sets[0].w)).toEqual([80])
+ })
+
+ it('sign-in keeps the preferred side\'s version as it is', () => {
+ const server = base({ _ts: 100, workouts: [logged([set(100)])] })
+ const device = base({ _ts: 50, workouts: [stampWorkout(logged([set(80)]), 300)] })
+ expect(mergeStates(server, device, { prefer: 'a' }).workouts[0].entries[0].sets[0].w).toBe(100)
+ })
+
+ // The kept load may be the typo the edit corrected: the other copy's must not bring it back.
+ it('does not resurrect a kept load the edit took away, from either side', () => {
+ const edited = base({ _ts: 100, workouts: [stampWorkout(logged([set(80)]), 100)], exWeights: { sq: { w: 80, d: '2026-09-01' } } })
+ const stale = base({ _ts: 200, workouts: [logged([set(1000)])], exWeights: { sq: { w: 1000, d: '2026-09-01' } } })
+ expect(mergeStates(edited, stale).exWeights.sq).toEqual({ w: 80, d: '2026-09-01' })
+ expect(mergeStates(stale, edited).exWeights.sq).toEqual({ w: 80, d: '2026-09-01' })
+ })
+
+ it('keeps a heavier set the other copy logged since, and its own kept load when that is better', () => {
+ const edited = base({ _ts: 100, workouts: [stampWorkout(logged([set(80)]), 100)], exWeights: { sq: { w: 85, d: '2026-08-01' } } })
+ const other = base({ _ts: 200, workouts: [logged([set(1000)]), { ...workout('w2', '2026-09-03'), entries: [set(90)] }], exWeights: { sq: { w: 1000, d: '2026-09-01' } } })
+ expect(mergeStates(other, edited).exWeights.sq).toEqual({ w: 90, d: '2026-09-03' })
+ const noLater = base({ _ts: 200, workouts: [logged([set(1000)])], exWeights: { sq: { w: 1000, d: '2026-09-01' } } })
+ expect(mergeStates(noLater, edited).exWeights.sq).toEqual({ w: 85, d: '2026-08-01' })
+ })
+
+ it('keeps assisted-machine kept loads ordered by less help', () => {
+ const edited = base({ _ts: 100, workouts: [stampWorkout(logged([set(20, '0017')]), 100)], exWeights: { '0017': { w: 20, d: '2026-09-01' } } })
+ const stale = base({ _ts: 200, workouts: [logged([set(30, '0017')])], exWeights: { '0017': { w: 30, d: '2026-09-01' } } })
+ expect(mergeStates(stale, edited).exWeights['0017']).toEqual({ w: 20, d: '2026-09-01' })
+ })
- it('keeps assisted-machine correction caches ordered by less help', () => {
- const set = w => ({ id: '0017', target: { mode: 'reps' }, sets: [{ w, r: 5, done: true }] })
- const older = base({ _ts: 100, workouts: [{ ...workout('w1'), entries: [set(30)] }], exWeights: { '0017': { w: 30, d: '2026-09-01' } } })
- const corrected = base({ _ts: 200, workouts: [{ ...workout('w1'), entries: [set(20)] }], exWeights: { '0017': { w: 20, d: '2026-09-01' } } })
- expect(mergeStates(corrected, older).exWeights['0017']).toEqual({ w: 20, d: '2026-09-01' })
+ it('leaves the kept loads alone when only the date, the length or the note changed', () => {
+ const moved = stampWorkout(logged([set(80)], { note: 'moved' }), 100)
+ const other = base({ _ts: 200, workouts: [logged([set(80)])], exWeights: { sq: { w: 120, d: '2026-08-01' } } })
+ expect(mergeStates(other, base({ _ts: 100, workouts: [moved], exWeights: {} })).exWeights.sq).toEqual({ w: 120, d: '2026-08-01' })
+ })
})
it('is commutative on the union fields and idempotent', () => {
diff --git a/frontend/src/lib/workout-date.js b/frontend/src/lib/workout-date.js
index 5db110c1d..ce06dc68e 100644
--- a/frontend/src/lib/workout-date.js
+++ b/frontend/src/lib/workout-date.js
@@ -10,6 +10,7 @@
import { insertChronological, backfillStart } from './backfill.js'
import { bestWeightForEntry } from './history.js'
import { beatsWeight } from './exercises.js'
+import { stampWorkout } from './sync-merge.js'
// Before ids existed a workout was keyed for sync by its day and start time
// (`workoutKey` in sync-merge.js). That is exactly what this edit changes, so moving such a
@@ -83,11 +84,15 @@ export function rebuildPrHistory(workouts, exerciseIds, moved = null) {
// The history after a workout has been moved: the old copy is gone, the moved one sits where
// its new date and start time put it, and every exercise it touches has its badges rebuilt.
// Returns the new array, or `null` when there is nothing to move. The caller stores it.
-export function moveWorkout(workouts, ref, iso, time) {
+//
+// The moved workout carries the time of the move (stampWorkout): a conflict with a copy that
+// still holds it where it was keeps the version edited last, not whichever copy is newer as a
+// whole — a phone that logged a weigh-in since would otherwise put it back.
+export function moveWorkout(workouts, ref, iso, time, now = Date.now()) {
const list = Array.isArray(workouts) ? workouts : []
const current = list.find(w => sameWorkout(w, ref))
if (!current) return null
- const moved = retimeWorkout(current, iso, time)
+ const moved = stampWorkout(retimeWorkout(current, iso, time), now)
const filed = insertChronological(list.filter(w => w !== current), moved)
return rebuildPrHistory(filed, (current.entries || []).map(e => e.id), moved)
}
diff --git a/frontend/src/lib/workout-date.test.js b/frontend/src/lib/workout-date.test.js
index 978b44a5e..db90b25e4 100644
--- a/frontend/src/lib/workout-date.test.js
+++ b/frontend/src/lib/workout-date.test.js
@@ -208,6 +208,12 @@ describe('moveWorkout', () => {
expect(out.map(x => x.id)).toEqual(['a', 'c', 'b'])
expect(moveWorkout(list(), { id: 'c' }, '2026-01-05', '21:00').map(x => x.id)).toEqual(['a', 'b', 'c'])
})
+ it('stamps the moved workout with the time of the move, and only that one', () => {
+ const list = [w('a', '2026-01-01', '18:00', 60), w('b', '2026-01-05', '18:00', 60)]
+ const out = moveWorkout(list, list[1], '2025-12-20', '07:00', 4242)
+ expect(out.find(x => x.id === 'b')._ts).toBe(4242)
+ expect(out.find(x => x.id === 'a')).not.toHaveProperty('_ts')
+ })
it('returns null when the workout is not there', () => {
expect(moveWorkout(list(), { id: 'zz' }, '2026-01-03', '07:00')).toBe(null)
expect(moveWorkout(undefined, { id: 'a' }, '2026-01-03', '07:00')).toBe(null)
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index d515d3d1a..3755e5b38 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1341,7 +1341,6 @@ export default {
"Don't save": 'Nicht speichern',
'Keep editing': 'Weiter bearbeiten',
'This workout was deleted on another device. Your edits are still here.': 'Dieses Training wurde auf einem anderen Gerät gelöscht. Deine Änderungen sind noch hier.',
- 'This workout changed on another device. Your edits are still here.': 'Dieses Training wurde auf einem anderen Gerät geändert. Deine Änderungen sind noch hier.',
'Close editor': 'Editor schließen',
'Editing a saved workout. Date and duration stay unchanged.': 'Du bearbeitest ein gespeichertes Training. Datum und Dauer bleiben unverändert.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 475cde863..1b082a4f1 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": 'No guardar',
'Keep editing': 'Seguir editando',
'This workout was deleted on another device. Your edits are still here.': 'Este entrenamiento se eliminó en otro dispositivo. Tus cambios siguen aquí.',
- 'This workout changed on another device. Your edits are still here.': 'Este entrenamiento cambió en otro dispositivo. Tus cambios siguen aquí.',
'Close editor': 'Cerrar editor',
'Editing a saved workout. Date and duration stay unchanged.': 'Estás editando un entrenamiento guardado. La fecha y la duración no cambian.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index cfce3bc2d..801889f60 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": 'Ne pas enregistrer',
'Keep editing': 'Continuer la modification',
'This workout was deleted on another device. Your edits are still here.': 'Cet entraînement a été supprimé sur un autre appareil. Vos modifications sont toujours ici.',
- 'This workout changed on another device. Your edits are still here.': 'Cet entraînement a été modifié sur un autre appareil. Vos modifications sont toujours ici.',
'Close editor': 'Fermer l’éditeur',
'Editing a saved workout. Date and duration stay unchanged.': 'Vous modifiez un entraînement enregistré. La date et la durée restent inchangées.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index eb8f1e901..2dd675854 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": 'न सहेजें',
'Keep editing': 'संपादन जारी रखें',
'This workout was deleted on another device. Your edits are still here.': 'यह वर्कआउट दूसरे डिवाइस पर मिटा दिया गया। आपके बदलाव अभी भी यहाँ हैं।',
- 'This workout changed on another device. Your edits are still here.': 'यह वर्कआउट दूसरे डिवाइस पर बदला गया। आपके बदलाव अभी भी यहाँ हैं।',
'Close editor': 'संपादक बंद करें',
'Editing a saved workout. Date and duration stay unchanged.': 'आप सहेजा हुआ वर्कआउट संपादित कर रहे हैं। तारीख और अवधि नहीं बदलेंगी।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 9e2895ac3..536b05ee1 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1324,7 +1324,6 @@ export default {
"Don't save": 'Ne mentse',
'Keep editing': 'Szerkesztés folytatása',
'This workout was deleted on another device. Your edits are still here.': 'Ezt az edzést egy másik eszközön törölték. A módosításaid továbbra is itt vannak.',
- 'This workout changed on another device. Your edits are still here.': 'Ezt az edzést egy másik eszközön módosították. A módosításaid továbbra is itt vannak.',
'Close editor': 'Szerkesztő bezárása',
'Editing a saved workout. Date and duration stay unchanged.': 'Mentett edzést szerkesztesz. A dátum és az időtartam változatlan marad.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 3960d1eee..72ef43ab1 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": 'Non salvare',
'Keep editing': 'Continua a modificare',
'This workout was deleted on another device. Your edits are still here.': 'Questo allenamento è stato eliminato su un altro dispositivo. Le tue modifiche sono ancora qui.',
- 'This workout changed on another device. Your edits are still here.': 'Questo allenamento è stato modificato su un altro dispositivo. Le tue modifiche sono ancora qui.',
'Close editor': 'Chiudi editor',
'Editing a saved workout. Date and duration stay unchanged.': 'Stai modificando un allenamento salvato. Data e durata rimangono invariate.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 2bf902bc3..31564a971 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": '저장하지 않기',
'Keep editing': '계속 편집',
'This workout was deleted on another device. Your edits are still here.': '이 운동은 다른 기기에서 삭제되었습니다. 편집 내용은 여기에 남아 있습니다.',
- 'This workout changed on another device. Your edits are still here.': '이 운동은 다른 기기에서 변경되었습니다. 편집 내용은 여기에 남아 있습니다.',
'Close editor': '편집기 닫기',
'Editing a saved workout. Date and duration stay unchanged.': '저장된 운동을 편집 중입니다. 날짜와 시간은 변경되지 않습니다.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 0dd47d633..77fb4eb8b 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": 'Nie zapisuj',
'Keep editing': 'Kontynuuj edycję',
'This workout was deleted on another device. Your edits are still here.': 'Ten trening usunięto na innym urządzeniu. Twoje zmiany nadal są tutaj.',
- 'This workout changed on another device. Your edits are still here.': 'Ten trening zmieniono na innym urządzeniu. Twoje zmiany nadal są tutaj.',
'Close editor': 'Zamknij edytor',
'Editing a saved workout. Date and duration stay unchanged.': 'Edytujesz zapisany trening. Data i czas trwania pozostaną bez zmian.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index dec0b40eb..f62db230c 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -728,7 +728,6 @@ export const PT_BR_OVERRIDES = {
"Don't save": 'Não salvar',
'Keep editing': 'Continuar editando',
'This workout was deleted on another device. Your edits are still here.': 'Este treino foi excluído em outro dispositivo. Suas alterações continuam aqui.',
- 'This workout changed on another device. Your edits are still here.': 'Este treino foi alterado em outro dispositivo. Suas alterações continuam aqui.',
'Close editor': 'Fechar editor',
'Editing a saved workout. Date and duration stay unchanged.': 'Você está editando um treino salvo. A data e a duração permanecem iguais.',
}
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 724de4172..5555c3d15 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": 'Não guardar',
'Keep editing': 'Continuar a editar',
'This workout was deleted on another device. Your edits are still here.': 'Este treino foi eliminado noutro dispositivo. As tuas alterações continuam aqui.',
- 'This workout changed on another device. Your edits are still here.': 'Este treino foi alterado noutro dispositivo. As tuas alterações continuam aqui.',
'Close editor': 'Fechar editor',
'Editing a saved workout. Date and duration stay unchanged.': 'Estás a editar um treino guardado. A data e a duração permanecem inalteradas.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 3ea97ed4c..f3ee77ec7 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": 'Не сохранять',
'Keep editing': 'Продолжить редактирование',
'This workout was deleted on another device. Your edits are still here.': 'Эта тренировка удалена на другом устройстве. Ваши изменения всё ещё здесь.',
- 'This workout changed on another device. Your edits are still here.': 'Эта тренировка изменена на другом устройстве. Ваши изменения всё ещё здесь.',
'Close editor': 'Закрыть редактор',
'Editing a saved workout. Date and duration stay unchanged.': 'Вы редактируете сохранённую тренировку. Дата и длительность не изменятся.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index e38e1b9d5..9d6e681e4 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1332,7 +1332,6 @@ export default {
"Don't save": 'ไม่บันทึก',
'Keep editing': 'แก้ไขต่อ',
'This workout was deleted on another device. Your edits are still here.': 'การออกกำลังกายนี้ถูกลบในอุปกรณ์อื่น การแก้ไขของคุณยังอยู่ที่นี่',
- 'This workout changed on another device. Your edits are still here.': 'การออกกำลังกายนี้ถูกเปลี่ยนในอุปกรณ์อื่น การแก้ไขของคุณยังอยู่ที่นี่',
'Close editor': 'ปิดตัวแก้ไข',
'Editing a saved workout. Date and duration stay unchanged.': 'กำลังแก้ไขการออกกำลังกายที่บันทึกไว้ วันที่และระยะเวลาจะไม่เปลี่ยน',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index c0b3f0923..52d232c62 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": 'Kaydetme',
'Keep editing': 'Düzenlemeye devam et',
'This workout was deleted on another device. Your edits are still here.': 'Bu antrenman başka bir cihazda silindi. Düzenlemelerin hâlâ burada.',
- 'This workout changed on another device. Your edits are still here.': 'Bu antrenman başka bir cihazda değiştirildi. Düzenlemelerin hâlâ burada.',
'Close editor': 'Düzenleyiciyi kapat',
'Editing a saved workout. Date and duration stay unchanged.': 'Kayıtlı bir antrenmanı düzenliyorsun. Tarih ve süre değişmeden kalır.',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index ce312131c..dd600b984 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1321,7 +1321,6 @@ export default {
"Don't save": '不保存',
'Keep editing': '继续编辑',
'This workout was deleted on another device. Your edits are still here.': '此训练已在另一台设备上删除。你的编辑仍保留在这里。',
- 'This workout changed on another device. Your edits are still here.': '此训练已在另一台设备上更改。你的编辑仍保留在这里。',
'Close editor': '关闭编辑器',
'Editing a saved workout. Date and duration stay unchanged.': '正在编辑已保存的训练。日期和时长保持不变。',
}
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 9e24e0f32..40fa9e575 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -40,6 +40,7 @@ import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'
import { moveWorkout, sameWorkout, startTimeOf } from './lib/workout-date.js'
import { editCompletedSession } from './lib/session-edit.js'
+import { stampWorkout } from './lib/sync-merge.js'
const S = () => useStore.getState().S
const update = (...a) => useStore.getState().update(...a)
@@ -1727,11 +1728,16 @@ function WorkoutDetail({ w, close }) {
// The session note is editable here rather than only at the finish sheet: what you want to
// record about a session is often clearer once you have looked at what you actually did.
const [note, setNote] = useState(w.note || '')
+ // A note written here is an edit of the saved workout, stamped for the sync to keep it over an
+ // older copy of the same workout (stampWorkout) — and only when it changed, since a stamp
+ // outranks what another device wrote since.
const saveNote = () => update(s => {
- const rec = s.workouts.find(x => x.id === w.id)
+ const rec = s.workouts.find(x => sameWorkout(x, w))
if (!rec) return
const text = note.trim().slice(0, NOTE_MAX)
+ if (text === (rec.note || '')) return
if (text) rec.note = text; else delete rec.note
+ stampWorkout(rec)
})
// onBlur alone loses the note: Escape, the Android back gesture and swipe-to-dismiss all
// close the sheet without ever moving focus out of the textarea. Flush on unmount too. The
@@ -1744,9 +1750,10 @@ function WorkoutDetail({ w, close }) {
const text = latest.current.trim().slice(0, NOTE_MAX)
if (text === initial.current) return
update(s => {
- const rec = s.workouts.find(x => x.id === w.id)
- if (!rec) return // deleted from this very sheet
+ const rec = s.workouts.find(x => sameWorkout(x, w))
+ if (!rec || text === (rec.note || '')) return // deleted from this very sheet, or already saved
if (text) rec.note = text; else delete rec.note
+ stampWorkout(rec)
})
}, [])
// A combined session's entries carry a `rid`; group them into per-routine sections in merge
@@ -1793,8 +1800,12 @@ function WorkoutDetail({ w, close }) {
onFocus={onNoteFocus} onChange={e => setNote(e.target.value)} onBlur={saveNote} />
<div style={{ height: 14 }} />
{st.active && <p className="small muted">{t('Finish the current workout first.')}</p>}
+ {/* The editor starts from the record as it is, so a note typed here goes in first — the same
+ flush the date row does, and the unmount hook then has nothing left to write over it. */}
<Button icon="pencil" disabled={!!st.active} onClick={() => {
- try { update(state => editCompletedSession(state, w.id)); close(); nav('/workout') }
+ saveNote()
+ initial.current = latest.current.trim().slice(0, NOTE_MAX)
+ try { update(state => { editCompletedSession(state, w) }); close(); nav('/workout') }
catch (error) { toast(t(error.message)) }
}}>{t('Edit workout')}</Button>
<div style={{ height: 8 }} />
diff --git a/frontend/src/store/useStore.sync.test.jsx b/frontend/src/store/useStore.sync.test.jsx
index f00bb278a..0b5856853 100644
--- a/frontend/src/store/useStore.sync.test.jsx
+++ b/frontend/src/store/useStore.sync.test.jsx
@@ -12,6 +12,7 @@ vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast }) } }))
import { api } from '../lib/api.js'
import { DEF, useStore } from './useStore.js'
+import { editCompletedSession } from '../lib/session-edit.js'
const clone = value => JSON.parse(JSON.stringify(value))
const routine = id => ({ id, name: id, ex: [] })
@@ -325,3 +326,100 @@ describe('ordering', () => {
expect(gets()).toHaveLength(3)
})
})
+
+/* A workout edited after it was logged (lib/session-edit.js), on its way between devices. The
+ edit is an ordinary change of the copy — owed, pushed, merged on a 409 — and carries the time
+ of the edit, so the merge keeps it over the old version by id, whichever copy is newer as a
+ whole (lib/sync-merge.js). */
+describe('an edited workout between devices', () => {
+ const lift = w => ({ id: 'sq', target: { mode: 'reps' }, sets: [{ w, r: 5, done: true }] })
+ const logged = (w = 40) => ({ ...workout('w1'), end: 2, entries: [lift(w)], prs: [] })
+ const weightsIn = state => state.workouts.map(x => [x.id, x.entries[0]?.sets[0]?.w])
+ const edit = w => {
+ useStore.getState().update(s => { editCompletedSession(s, 'w1') })
+ useStore.getState().update(s => { s.active.entries[0].sets[0].w = w })
+ return useStore.getState().saveHistoryEdit()
+ }
+
+ it('an edit saved offline reaches the server with the next push, over a server that moved meanwhile', async () => {
+ vi.useFakeTimers()
+ signedIn({ ...clone(DEF), _ts: 100, workouts: [logged()] })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))
+ api.mockRejectedValueOnce(new TypeError('Failed to fetch'))
+
+ edit(50)
+ await useStore.getState().pushState()
+ expect(localStorage.getItem('gym_dirty')).toBe('1')
+ expect(useStore.getState().S.active).toBeNull()
+
+ // Meanwhile a phone logged another workout. Its copy is newer as a whole and still holds
+ // the workout as it was before the edit.
+ const phone = { ...clone(DEF), _ts: Date.now() + 60000, workouts: [logged(), { ...workout('w2', '2026-09-02'), entries: [lift(45)] }], _rev: 2 }
+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: phone }))
+ api.mockResolvedValueOnce({ ok: true, rev: 3 })
+ await useStore.getState().pushState()
+
+ expect(weightsIn(puts().at(-1).state)).toEqual([['w1', 50], ['w2', 45]])
+ expect(puts().at(-1).baseRev).toBe(2)
+ expect(weightsIn(useStore.getState().S)).toEqual([['w1', 50], ['w2', 45]])
+ expect(localStorage.getItem('gym_dirty')).toBeNull()
+ })
+
+ it('edited on one device while another still holds the old copy: the edit replaces it there too', async () => {
+ // The other device: the old copy, and a setting changed after the edit was made elsewhere.
+ signedIn({ ...clone(DEF), _ts: Date.now() + 60000, workouts: [logged()], restSec: 75 })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))
+ const edited = { ...logged(50), _ts: Date.now() }
+ const server = { ...clone(DEF), _ts: Date.now(), workouts: [edited], _rev: 2 }
+
+ // Its push meets the edit on the server.
+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: server }))
+ api.mockResolvedValueOnce({ ok: true, rev: 3 })
+ await useStore.getState().pushState()
+ expect(weightsIn(puts().at(-1).state)).toEqual([['w1', 50]])
+ expect(puts().at(-1).state.restSec).toBe(75)
+
+ // And a pull that finds both sides changed merges the same way.
+ useStore.getState().update(s => { s.workouts = [logged()]; s.restSec = 60 }, false)
+ api.mockResolvedValueOnce({ state: { ...server, _rev: 4 }, rev: 4 })
+ api.mockResolvedValueOnce({ ok: true, rev: 5 })
+ await useStore.getState().pullState()
+ expect(weightsIn(useStore.getState().S)).toEqual([['w1', 50]])
+ expect(useStore.getState().S.restSec).toBe(60)
+ })
+
+ it('an edit of a workout another device deleted: kept as a draft when the deletion arrived first', async () => {
+ vi.useFakeTimers()
+ signedIn({ ...clone(DEF), _ts: 100, workouts: [logged()] })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))
+ api.mockResolvedValueOnce({ ok: true, rev: 2 })
+ useStore.getState().update(s => { editCompletedSession(s, 'w1') })
+ useStore.getState().update(s => { s.active.entries[0].sets[0].w = 50 })
+ await useStore.getState().pushState() // the draft is where the server has it: nothing owed
+
+ // The phone deletes the workout; this device learns of it while its editor is open.
+ api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: Date.now() + 60000, workouts: [], _rev: 3 }, rev: 3 })
+ await useStore.getState().pullState()
+ expect(useStore.getState().S.workouts).toEqual([])
+
+ expect(() => useStore.getState().saveHistoryEdit()).toThrow('deleted on another device')
+ expect(useStore.getState().S.active.entries[0].sets[0].w).toBe(50)
+ expect(useStore.getState().S.workouts).toEqual([])
+ useStore.getState().discardHistoryEdit()
+ expect(useStore.getState().S.active).toBeNull()
+ })
+
+ it('an edit of a workout another device deleted: saved first, it comes back edited rather than lost', async () => {
+ vi.useFakeTimers()
+ signedIn({ ...clone(DEF), _ts: 100, workouts: [logged()] })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))
+ edit(50)
+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: { ...clone(DEF), _ts: Date.now() + 60000, workouts: [], _rev: 2 } }))
+ api.mockResolvedValueOnce({ ok: true, rev: 3 })
+
+ await useStore.getState().pushState()
+
+ expect(weightsIn(puts().at(-1).state)).toEqual([['w1', 50]])
+ expect(weightsIn(useStore.getState().S)).toEqual([['w1', 50]])
+ })
+})
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index e1c7dd286..07fbf898f 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -1101,6 +1101,8 @@ function ActiveWorkout() {
<SwipeCards index={unitIdx} count={units.length} revision={A}
timerKey={timer && `${timer.endsAt}:${timer.forIdx ?? ''}`} workKey={work?.endsAt}
onNavigate={navigateUnit} renderPreview={direction => {
+ // The card slid in shows what the card itself will: in the editor, no hold to start
+ // and no plates to load.
const adjacent = units[unitIdx + direction] || []
if (!adjacent.length) return null
return adjacent.length > 1 ? (
@@ -1108,10 +1110,10 @@ function ActiveWorkout() {
<div className="ss-hd"><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</div>
{adjacent.map((idx, k) => <div key={idx} className="ss-ex">
{k > 0 && <div className="ss-amp">+</div>}
- <ExerciseBlock entryIdx={idx} compact />
+ <ExerciseBlock entryIdx={idx} compact editing={editing} />
</div>)}
</div>
- ) : <ExerciseBlock entryIdx={adjacent[0]} />
+ ) : <ExerciseBlock entryIdx={adjacent[0]} editing={editing} />
}}>
{isSuperset ? (
<div className="ss-card">
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx
index 6d2a5cb45..b8cec5786 100644
--- a/frontend/src/views/Workout.test.jsx
+++ b/frontend/src/views/Workout.test.jsx
@@ -227,7 +227,7 @@ it('edits a saved set without running live completion, rest or success feedback'
await mount([exercise('plain-bench', [false], {
plan: { policy: 'linear', kind: 'first', why: ['Nothing logged yet — this session sets the baseline.'] },
})], 0, {
- active: { editingWorkoutId: 'saved', editingOriginal: { id: 'saved' } },
+ active: { editingWorkoutId: 'saved' },
})
await toggleSet(0)
expect(mocks.S.active.entries[0].sets[0].done).toBe(true)