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
feat: edit completed workout entries with conflict recovery
Space-Hermes2d32606ed06a
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 6d2198472..2ed7b76bd 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -13,7 +13,7 @@ import { installViewportGuard } from './lib/viewport-guard.js'import { installChipDrag } from './lib/hchips.js'import { syncPushSubscription } from './lib/push.js'import { MOBILE } from './lib/mobile.js'-import { startFlow } from './sheets.jsx'+import { exitWorkoutEdit, startFlow } from './sheets.jsx'import Icon from './components/Icon.jsx'import TabBar from './components/TabBar.jsx'import ErrorBoundary from './components/ErrorBoundary.jsx'@@ -69,6 +69,17 @@ function Shell() {const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding)const langV = useLang() // re-renders the whole shell when the language (pack) changesuseEffect(() => { setNav(navigate) }, [navigate])+ const lastEditPath = useRef(loc.pathname)+ // Any in-app route exit, browser back included, returns to the persisted draft and asks for a+ // save decision. Reload needs no prompt because the draft itself is already in local storage.+ useEffect(() => {+ const previous = lastEditPath.current+ lastEditPath.current = loc.pathname+ if (previous !== '/workout' || !S.active?.editingWorkoutId || loc.pathname === '/workout') return+ const destination = loc.pathname + loc.search+ navigate('/workout', { replace: true })+ exitWorkoutEdit(() => navigate(destination, { replace: true }))+ }, [loc.pathname, loc.search, S.active?.editingWorkoutId, navigate])useEffect(() => { applyPrefs(S.theme, S.accent) }, [S.theme, S.accent])// 'system' needs to react live if the OS theme flips while the app is open, not just on// the next mount — a fixed 'dark'/'light' choice never re-fires this since matchMedia@@ -116,7 +127,7 @@ function Shell() {return () => window.cancelAnimationFrame(frame)}, [loc.pathname, navType])// bound to the workout, not to the route — checking Stats mid-session keeps the screen on- useWakeLock(!!S.active && S.keepAwake !== false)+ useWakeLock(!!S.active && !S.active.editingWorkoutId && S.keepAwake !== false)const authed = user || isGuestif (!ready && !authed) return (diff --git a/frontend/src/components/TabBar.jsx b/frontend/src/components/TabBar.jsxindex d33c7a2a6..c18a792cc 100644--- a/frontend/src/components/TabBar.jsx+++ b/frontend/src/components/TabBar.jsx@@ -38,7 +38,7 @@ export default function TabBar({ onStart }) {were on — the marker is kept in S.active.cur and never moves on its own (#21). */}<button className={'start' + (S.active ? ' rec' : '') + (S.active && cur === 'workout' ? ' on' : '')} onClick={startWorkout}><span className="cir"><Icon name={S.active ? (cur === 'workout' ? 'dumbbell' : 'play') : 'dumbbell'} /></span>- <span>{S.active ? (cur === 'workout' ? t('Workout') : t('Resume')) : t('Start')}</span>+ <span>{S.active ? (cur === 'workout' ? t('Workout') : S.active.editingWorkoutId ? t('Edit workout') : t('Resume')) : t('Start')}</span></button><Tab k="stats" icon="chart" to="/stats" label={t('Stats')} /><Tab k="library" icon="list" to="/library" label={t('Exercises')} />diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex f692c6095..c0b560abc 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {.sort(byCodeUnit)const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(644)+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(655)expect(inherited).toHaveLength(647)// If this fails, review the changed keys and wording before accepting a new hash. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --listdiff --git a/frontend/src/lib/session-edit.js b/frontend/src/lib/session-edit.jsnew file mode 100644index 000000000..4c036b3de--- /dev/null+++ b/frontend/src/lib/session-edit.js@@ -0,0 +1,138 @@+import { buildCompletedWorkout } from './finish-workout.js'+import { bestWeightForEntry, workoutVolume } from './history.js'+import { hasCompletedWork } from './workout-model.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++// 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) {+ 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 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]+ 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) {+ const weight = Math.max(0, ...workout.entries.filter(entry => entry.id === id).map(bestWeightForEntry))+ if (weight > (best.get(id) || 0)) existing.push(id)+ if (weight > (best.get(id) || 0)) 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)+ .sort((a, b) => b.w - a.w)+ if (candidates.length) state.exWeights[id] = candidates[0]+ else delete state.exWeights[id]+ }+}++export function saveWorkoutEdit(state) {+ const active = state.active+ const original = active?.editingOriginal+ const index = state.workouts.findIndex(workout => workout.id === active?.editingWorkoutId)+ 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 updated = buildCompletedWorkout(active, {+ end: original.end,+ prs: original.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.+ const logged = active.entries.filter(entry => entry.sets.some(hasCompletedWork))+ updated.entries = updated.entries.map((entry, index) => {+ const merged = { ...clone(logged[index]), ...entry }+ delete merged.plan+ for (const key of ['note', 'notePin', 'noProg', 'muscleSnapshot']) if (!(key in entry)) delete merged[key]+ return merged+ })+ const record = { ...original, ...updated, vol: workoutVolume(updated) }+ for (const key of ['note', 'excludeFromProgression']) if (!(key in updated)) delete record[key]+ 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++ // 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]+ }+ }+ 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+}diff --git a/frontend/src/lib/session-edit.test.js b/frontend/src/lib/session-edit.test.jsnew file mode 100644index 000000000..798c46612--- /dev/null+++ b/frontend/src/lib/session-edit.test.js@@ -0,0 +1,124 @@+import { describe, expect, it } from 'vitest'+import { editCompletedSession, localStateForEditMerge, saveWorkoutEdit } from './session-edit.js'++const entry = (w, id = '0025') => ({ id, sets: [{ w, r: 5, done: true }], target: { mode: 'reps' } })+const fixture = () => ({+ active: null,+ exWeights: {},+ routines: [{ id: 'routine', ex: [] }],+ workouts: [{ id: 'workout', d: '2026-09-01', start: 1000, end: 2000, entries: [entry(40)], note: 'old', prs: ['0025'] }],+})++describe('saved workout editing', () => {+ it('keeps history unchanged until Save, survives reload and preserves its identity, clock and templates', () => {+ const state = fixture(), history = structuredClone(state.workouts), routines = structuredClone(state.routines)+ editCompletedSession(state, 'workout')+ state.active.entries[0].sets[0].w = 80+ state.active.note = ''+ expect(state.workouts).toEqual(history)+ const reloaded = JSON.parse(JSON.stringify(state))+ const saved = saveWorkoutEdit(reloaded)+ expect(saved).toMatchObject({ id: 'workout', d: '2026-09-01', start: 1000, end: 2000, vol: 400 })+ expect(saved).not.toHaveProperty('note')+ expect(saved).not.toHaveProperty('editingWorkoutId')+ expect(reloaded.active).toBeNull()+ expect(reloaded.routines).toEqual(routines)+ })++ it('saves added exercises and sets without persisting a live prescription', () => {+ const state = fixture()+ editCompletedSession(state, 'workout')+ state.active.entries[0].sets.push({ w: 42.5, r: 4, done: true })+ state.active.entries.push({ ...entry(25, 'added'), rid: 'routine', plan: { kind: 'up' } })+ const saved = saveWorkoutEdit(state)+ expect(saved.entries[0].sets).toHaveLength(2)+ expect(saved.entries[1]).toMatchObject({ id: 'added', rid: 'routine' })+ expect(saved.entries[1]).not.toHaveProperty('plan')+ })++ it('rebuilds best weights and historical PR flags after lowering or deleting 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)+ expect(state.exWeights['0025']).toEqual({ w: 30, d: '2026-09-02' })+ expect(state.workouts[0].prs).toEqual(['0025'])+ expect(state.workouts[1].prs).toEqual(['0025'])+ })++ it('preserves repeated occurrences, combined-routine ownership and per-side fields', () => {+ const state = fixture(), workout = state.workouts[0]+ workout.routineIds = ['a', 'b']+ workout.entries = [+ { ...entry(40), rid: 'a', occurrenceId: 'first', opaque: { retained: true } },+ { ...entry(20), rid: 'b', occurrenceId: 'second', sets: [{ w: 20, r: 8, done: true, sides: { L: { w: 12, r: 4, done: true }, R: { w: 8, r: 4, done: true } } }] },+ ]+ editCompletedSession(state, 'workout')+ state.active.entries[1].sets[0].sides.L.w = 14+ const saved = saveWorkoutEdit(state)+ expect(saved.entries.map(item => [item.occurrenceId, item.rid])).toEqual([['first', 'a'], ['second', 'b']])+ expect(saved.entries[0].opaque).toEqual({ retained: true })+ expect(saved.entries[1].sets[0].sides.L.w).toBe(14)+ })++ it('keeps a partially completed per-side occurrence and its opaque ownership', () => {+ const state = fixture()+ state.workouts[0].entries = [{+ ...entry(20), rid: 'routine', occurrenceId: 'partial',+ sets: [{ w: 20, r: 8, done: false, sides: {+ L: { w: 20, r: 4, done: true }, R: { w: 17.5, r: 4, done: false },+ } }],+ }]+ editCompletedSession(state, 'workout')+ const saved = saveWorkoutEdit(state)+ expect(saved.entries[0]).toMatchObject({ rid: 'routine', occurrenceId: 'partial' })+ expect(saved.entries[0].sets[0].sides).toEqual({+ L: { w: 20, r: 4, done: true }, R: { w: 17.5, r: 4, done: false },+ })+ expect(saved.vol).toBe(80)+ })++ it('keeps the draft when the original is missing or changed remotely', () => {+ const deleted = fixture()+ editCompletedSession(deleted, 'workout')+ deleted.workouts = []+ expect(() => saveWorkoutEdit(deleted)).toThrow('deleted on another device')+ expect(deleted.active.editingWorkoutId).toBe('workout')++ 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('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('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)+ })+})diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex d1a458433..14174c7ba 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -1,3 +1,5 @@+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@@ -12,8 +14,9 @@* of an id that both have; workouts sorted by day and start like every other writer* - bodyweight: union by day, the later-edited (`t`) entry of a day that both have* - favEx: ordered set union, the newer copy first- * - exWeights: union by exercise, the larger `w` (the app itself only ever raises it — a PR- * logged on the other device must not be forgotten); exNotes, barWeights: key union+ * - 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* - `_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@@ -58,11 +61,20 @@ export function mergeBodyweight(a = [], b = []) {return [...byDay.values()].sort((x, y) => (x.d < y.d ? -1 : 1))}-function mergeExWeights(n = {}, o = {}) {+function mergeExWeights(n = {}, o = {}, workouts = [], corrected = new Set()) {const out = { ...(o || {}), ...(n || {}) }for (const k of Object.keys(o || {})) {if (n && n[k] && o[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]] : [])].sort((a, b) => b.w - a.w)+ if (candidates.length) out[id] = candidates[0]+ else delete out[id]+ }return out}@@ -76,12 +88,19 @@ export function mergeStates(a, b, { prefer } = {}) {const o = n === a ? b : aconst 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)+ }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)}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.exWeights = clone(mergeExWeights(n.exWeights, o.exWeights, out.workouts, corrected))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.jsindex 62c6a6fbe..76c004c00 100644--- a/frontend/src/lib/sync-merge.test.js+++ b/frontend/src/lib/sync-merge.test.js@@ -80,6 +80,13 @@ 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' })+ })+it('is commutative on the union fields and idempotent', () => {const ab = mergeStates(A(), B()), ba = mergeStates(B(), A())for (const f of ['workouts', 'routines', 'customEx', 'gymCards']) expect(ids(ab[f]).sort()).toEqual(ids(ba[f]).sort())diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex fad9cba71..c03a4b24b 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1256,4 +1256,15 @@ export default {'already added': 'schon drin','no exercises': 'keine Übungen','Pick equipment': 'Gerät wählen',+ 'Edit workout': 'Training bearbeiten',+ 'Workout updated': 'Training aktualisiert',+ 'Save workout changes?': 'Änderungen am Training speichern?',+ 'Save your edits to this workout, or keep the original record.': 'Speichere deine Änderungen an diesem Training oder behalte den ursprünglichen Eintrag.',+ 'Save changes': 'Änderungen speichern',+ "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.jsindex 68e2144a4..bd3471857 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1236,4 +1236,15 @@ export default {'already added': 'ya añadido','no exercises': 'sin ejercicios','Pick equipment': 'Elegir equipamiento',+ 'Edit workout': 'Editar entrenamiento',+ 'Workout updated': 'Entrenamiento actualizado',+ 'Save workout changes?': '¿Guardar los cambios del entrenamiento?',+ 'Save your edits to this workout, or keep the original record.': 'Guarda los cambios de este entrenamiento o conserva el registro original.',+ 'Save changes': 'Guardar cambios',+ "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.jsindex ff4b17cfd..a424158c3 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1236,4 +1236,15 @@ export default {'already added': 'déjà ajouté','no exercises': 'aucun exercice','Pick equipment': 'Choisir l’équipement',+ 'Edit workout': 'Modifier l’entraînement',+ 'Workout updated': 'Entraînement mis à jour',+ 'Save workout changes?': 'Enregistrer les modifications de l’entraînement ?',+ 'Save your edits to this workout, or keep the original record.': 'Enregistrez vos modifications ou conservez l’enregistrement d’origine.',+ 'Save changes': 'Enregistrer les modifications',+ "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.jsindex da466b3f2..2540636b8 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1236,4 +1236,15 @@ export default {'already added': 'पहले से जोड़ा हुआ','no exercises': 'कोई व्यायाम नहीं','Pick equipment': 'उपकरण चुनें',+ 'Edit workout': 'वर्कआउट संपादित करें',+ 'Workout updated': 'वर्कआउट अपडेट हुआ',+ 'Save workout changes?': 'वर्कआउट के बदलाव सहेजें?',+ 'Save your edits to this workout, or keep the original record.': 'इस वर्कआउट के बदलाव सहेजें या मूल रिकॉर्ड रखें।',+ 'Save changes': 'बदलाव सहेजें',+ "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.jsindex f99fa4ff9..5deb35ff2 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1239,4 +1239,15 @@ export default {'already added': 'már hozzáadva','no exercises': 'nincs gyakorlat','Pick equipment': 'Eszköz kiválasztása',+ 'Edit workout': 'Edzés szerkesztése',+ 'Workout updated': 'Edzés frissítve',+ 'Save workout changes?': 'Mented az edzés módosításait?',+ 'Save your edits to this workout, or keep the original record.': 'Mentsd az edzés módosításait, vagy tartsd meg az eredeti bejegyzést.',+ 'Save changes': 'Módosítások mentése',+ "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.jsindex 3c8c8415f..0af30b52c 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1236,4 +1236,15 @@ export default {'already added': 'già aggiunto','no exercises': 'nessun esercizio','Pick equipment': 'Scegli l’attrezzatura',+ 'Edit workout': 'Modifica allenamento',+ 'Workout updated': 'Allenamento aggiornato',+ 'Save workout changes?': 'Salvare le modifiche all’allenamento?',+ 'Save your edits to this workout, or keep the original record.': 'Salva le modifiche a questo allenamento oppure conserva il record originale.',+ 'Save changes': 'Salva modifiche',+ "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.jsindex 48ea492ff..0a42aca23 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1236,4 +1236,15 @@ export default {'already added': '이미 추가됨','no exercises': '운동 없음','Pick equipment': '기구 선택',+ 'Edit workout': '운동 편집',+ 'Workout updated': '운동이 업데이트됨',+ 'Save workout changes?': '운동 변경 사항을 저장할까요?',+ 'Save your edits to this workout, or keep the original record.': '이 운동의 변경 사항을 저장하거나 원래 기록을 유지하세요.',+ 'Save changes': '변경 사항 저장',+ "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.jsindex 213baab72..5992a4473 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1236,4 +1236,15 @@ export default {'already added': 'już dodano','no exercises': 'brak ćwiczeń','Pick equipment': 'Wybierz sprzęt',+ 'Edit workout': 'Edytuj trening',+ 'Workout updated': 'Trening zaktualizowany',+ 'Save workout changes?': 'Zapisać zmiany treningu?',+ 'Save your edits to this workout, or keep the original record.': 'Zapisz zmiany w tym treningu albo zachowaj oryginalny zapis.',+ 'Save changes': 'Zapisz zmiany',+ "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.jsindex 324b0f2ae..221b62465 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -671,6 +671,17 @@ export const PT_BR_OVERRIDES = {'Download & Install': 'Baixar e instalar','Starting download…': 'Iniciando download…','Downloading update…': 'Baixando atualização…',+ 'Edit workout': 'Editar treino',+ 'Workout updated': 'Treino atualizado',+ 'Save workout changes?': 'Salvar alterações do treino?',+ 'Save your edits to this workout, or keep the original record.': 'Salve as alterações deste treino ou mantenha o registro original.',+ 'Save changes': 'Salvar alterações',+ "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.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex ea44d465c..dae449ba3 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1236,4 +1236,15 @@ export default {'already added': 'já adicionado','no exercises': 'sem exercícios','Pick equipment': 'Escolher equipamento',+ 'Edit workout': 'Editar treino',+ 'Workout updated': 'Treino atualizado',+ 'Save workout changes?': 'Guardar alterações do treino?',+ 'Save your edits to this workout, or keep the original record.': 'Guarda as alterações deste treino ou mantém o registo original.',+ 'Save changes': 'Guardar alterações',+ "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.jsindex 46ce8efb2..3070c9065 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1236,4 +1236,15 @@ export default {'already added': 'уже добавлено','no exercises': 'нет упражнений','Pick equipment': 'Выбрать оборудование',+ 'Edit workout': 'Редактировать тренировку',+ 'Workout updated': 'Тренировка обновлена',+ 'Save workout changes?': 'Сохранить изменения тренировки?',+ 'Save your edits to this workout, or keep the original record.': 'Сохраните изменения этой тренировки или оставьте исходную запись.',+ 'Save changes': 'Сохранить изменения',+ "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.jsindex f2b372dbd..2a9cbfa28 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1247,4 +1247,15 @@ export default {'already added': 'เพิ่มแล้ว','no exercises': 'ไม่มีท่าออกกำลังกาย','Pick equipment': 'เลือกอุปกรณ์',+ 'Edit workout': 'แก้ไขการออกกำลังกาย',+ 'Workout updated': 'อัปเดตการออกกำลังกายแล้ว',+ 'Save workout changes?': 'บันทึกการเปลี่ยนแปลงการออกกำลังกายไหม',+ 'Save your edits to this workout, or keep the original record.': 'บันทึกการแก้ไขการออกกำลังกายนี้ หรือเก็บบันทึกเดิมไว้',+ 'Save changes': 'บันทึกการเปลี่ยนแปลง',+ "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.jsindex 95720d15e..202009b30 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1236,4 +1236,15 @@ export default {'already added': 'zaten ekli','no exercises': 'egzersiz yok','Pick equipment': 'Ekipman seç',+ 'Edit workout': 'Antrenmanı düzenle',+ 'Workout updated': 'Antrenman güncellendi',+ 'Save workout changes?': 'Antrenman değişiklikleri kaydedilsin mi?',+ 'Save your edits to this workout, or keep the original record.': 'Bu antrenmandaki düzenlemelerini kaydet veya özgün kaydı koru.',+ 'Save changes': 'Değişiklikleri kaydet',+ "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.jsindex f45110eec..c8022122a 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1236,4 +1236,15 @@ export default {'already added': '已添加','no exercises': '没有动作','Pick equipment': '选择器械',+ 'Edit workout': '编辑训练',+ 'Workout updated': '训练已更新',+ 'Save workout changes?': '保存训练更改?',+ 'Save your edits to this workout, or keep the original record.': '保存对此训练的编辑,或保留原始记录。',+ 'Save changes': '保存更改',+ "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.jsxindex 4c04e4720..2f27ad931 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -37,6 +37,7 @@ import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'import { buildSessionEntries } from './lib/session-start.js'import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'+import { editCompletedSession } from './lib/session-edit.js'const S = () => useStore.getState().Sconst update = (...a) => useStore.getState().update(...a)@@ -1690,6 +1691,12 @@ function WorkoutDetail({ w, close }) {placeholder={t('How the session went as a whole.')}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>}+ <Button icon="pencil" disabled={!!st.active} onClick={() => {+ try { update(state => editCompletedSession(state, w.id)); close(); nav('/workout') }+ catch (error) { toast(t(error.message)) }+ }}>{t('Edit workout')}</Button>+ <div style={{ height: 8 }} /><Button variant="danger" onClick={() => confirmSheet({ title: t('Delete workout?'), message: t('This removes it from your history for good.'), confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast(t('Workout deleted')) } })}>{t('Delete workout')}</Button></>}@@ -1970,6 +1977,7 @@ function ExerciseNote({ entryIdx, close }) {const st = useStore(s => s.S)const update = useStore(s => s.update)const A = st.active+ const editing = !!A?.editingWorkoutIdconst entry = A ? A.entries[entryIdx] : nullconst ex = entry ? exOr(entry.id) : nullconst [note, setNote] = useState(entry?.note || '')@@ -1987,9 +1995,11 @@ function ExerciseNote({ entryIdx, close }) {if (today) { e.note = today; if (pin) e.notePin = true; else delete e.notePin }else { delete e.note; delete e.notePin }}- s.exNotes = s.exNotes || {}- if (always) s.exNotes[entry.id] = always- else delete s.exNotes[entry.id]+ if (!editing) {+ s.exNotes = s.exNotes || {}+ if (always) s.exNotes[entry.id] = always+ else delete s.exNotes[entry.id]+ }})close()}@@ -2007,11 +2017,13 @@ function ExerciseNote({ entryIdx, close }) {<Switch checked={pin} onChange={setPin} disabled={!note.trim()} /></Row></div>- <div style={{ height: 18 }} />- <div className="small muted" style={{ marginBottom: 6 }}>{t('Always for this exercise')}</div>- <textarea className="input" rows={2} maxLength={NOTE_MAX} value={standing}- placeholder={t('Seat height, pin position, a form cue — shown every session.')}- onChange={e => setStanding(e.target.value)} />+ {!editing && <>+ <div style={{ height: 18 }} />+ <div className="small muted" style={{ marginBottom: 6 }}>{t('Always for this exercise')}</div>+ <textarea className="input" rows={2} maxLength={NOTE_MAX} value={standing}+ placeholder={t('Seat height, pin position, a form cue — shown every session.')}+ onChange={e => setStanding(e.target.value)} />+ </>}<div style={{ height: 18 }} /><Button variant="primary" onClick={save}>{t('Save')}</Button></>@@ -2068,6 +2080,35 @@ function WorkoutComplete({ close }) {}export const workoutCompleteSheet = () => ui().openSheet(close => <WorkoutComplete close={close} />, { kind: 'center' })+export function saveWorkoutEdits(onExit = () => nav('/history')) {+ try {+ useStore.getState().saveHistoryEdit()+ useUI.getState().stopRest()+ useUI.getState().stopWork()+ useStore.getState().autoBackupNow()+ toast(t('Workout updated'))+ onExit()+ } catch (error) { toast(t(error.message)) }+}++export function exitWorkoutEdit(onExit = () => nav('/history')) {+ ui().openSheet(close => <>+ <h3>{t('Save workout changes?')}</h3>+ <p className="muted">{t('Save your edits to this workout, or keep the original record.')}</p>+ <Button variant="primary" onClick={() => { close(); saveWorkoutEdits(onExit) }}>{t('Save changes')}</Button>+ <div style={{ height: 8 }} />+ <Button onClick={() => {+ close()+ useStore.getState().discardHistoryEdit()+ useUI.getState().stopRest()+ useUI.getState().stopWork()+ onExit()+ }}>{t("Don't save")}</Button>+ <div style={{ height: 8 }} />+ <Button variant="ghost" className="dim" onClick={close}>{t('Keep editing')}</Button>+ </>, { kind: 'center' })+}+function FinishSummary({ w, prs, e1prs = [], close }) {const st = useStore(s => s.S)return <div style={{ textAlign: 'center', padding: '8px 0' }}>@@ -2090,6 +2131,7 @@ function FinishSummary({ w, prs, e1prs = [], close }) {</div>}export function finishWorkout() {+ if (S().active?.editingWorkoutId) { saveWorkoutEdits(); return }const A = S().activeif (!A) returnconst done = setsDoneActive(A)diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 79451dfd8..070fb47a1 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -7,6 +7,7 @@ import { DEMO, DEMO_SEEDED } from '../lib/demo.js'import { guestAllowed } from '../lib/guest.js'import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, syncReminder, writeAutoBackup } from '../lib/mobile.js'import { mergeStates, localExtras } from '../lib/sync-merge.js'+import { prepareLocalStateForEditMerge, rebuildHistoryDerived, saveWorkoutEdit } from '../lib/session-edit.js'import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'@@ -18,6 +19,7 @@ const KEY = 'gym_state_v1'// a document this device never saw is refused (409) instead of dropping another device's work;// `ts` tells a pull whether anything changed here since. See pushState/pullState.const SYNC_KEY = 'gym_sync'+const HISTORY_EDIT_KEY = 'gym_history_edit_pending'const CHECK_MIN_MS = 3000 // rev checks closer together than this are the same event (focus + visibility)const POLL_MS = 30000 // while the app is open and signed in, ask the server for its revision this oftenexport const DEF = {@@ -116,6 +118,25 @@ export const useStore = create((set, get) => {let offlineChanges = false // a push failed for lack of network — the next one that lands says soconst readSync = () => { try { return JSON.parse(localStorage.getItem(SYNC_KEY)) || null } catch { return null } }+ const readPendingEdits = () => {+ try {+ const value = JSON.parse(localStorage.getItem(HISTORY_EDIT_KEY))+ return Array.isArray(value) ? value : (value?.id ? [value] : [])+ } catch { return [] }+ }+ const writePendingEdits = edits => {+ if (edits.length) localStorage.setItem(HISTORY_EDIT_KEY, JSON.stringify(edits))+ else localStorage.removeItem(HISTORY_EDIT_KEY)+ }+ const clearSentEdits = (sent, sentState) => writePendingEdits(readPendingEdits().filter(current => {+ const captured = sent.find(receipt => JSON.stringify(receipt) === JSON.stringify(current))+ if (!captured) return true+ if (!captured.saved) return false+ const canonical = sentState.workouts?.find(workout => workout.id === captured.id)+ const represented = JSON.stringify(canonical) === JSON.stringify(captured.saved)+ || sentState.active?.editingWorkoutId === captured.id+ return !represented+ }))const writeSync = (rev, ts) => localStorage.setItem(SYNC_KEY, JSON.stringify({ rev, ts: ts || 0 }))// What the banner shows a signed-in user: `offline` when the server could not be reached at// all, `pending` while a change is still owed to it (either way, or a push the server refused).@@ -203,16 +224,20 @@ export const useStore = create((set, get) => {// real change this device now holds — while `ts` in the marker stays old, so a pull that// happens before the push lands still sees it as unsent.const mergeInto = (local, remote, rev) => {- const merged = Object.assign(clone(DEF), mergeStates(local, remote))- merged.active = local.active || null+ const prepared = prepareLocalStateForEditMerge(local, remote, readPendingEdits())+ const merged = Object.assign(clone(DEF), mergeStates(prepared.state, remote))+ merged.active = prepared.state.active || local.active || null+ rebuildHistoryDerived(merged, prepared.affectedExerciseIds)persist(merged, false)- writeSync(rev, readSync()?.ts || 0)+ if (!prepared.blocked) writeSync(rev, readSync()?.ts || 0)+ return prepared.blocked}// Take the server's copy as this device's own, timestamp and all (see persist).const adopt = (next, rev) => { persist(next, false, false); writeSync(rev, next._ts) }const doPush = async (attempt = 0) => {const S = get().S+ const sentEdits = readPendingEdits()const sync = readSync()const force = forceNextconst body = { state: S }@@ -225,6 +250,7 @@ export const useStore = create((set, get) => {if (r.rev == null) localStorage.removeItem(SYNC_KEY)else writeSync(r.rev, S._ts)localStorage.removeItem('gym_dirty')+ clearSentEdits(sentEdits, S)toldTooLarge = false// Back from offline with changes that were waiting: say so once — the banner that promised// "syncs when you're back online" has just kept its word.@@ -241,7 +267,12 @@ export const useStore = create((set, get) => {// Another device wrote since this one last read. The server sent its document along;// merge and push once more against that revision. A second refusal in a row leaves the// copy dirty and the next resume pull takes it from there.- mergeInto(get().S, e.data.state, e.data.rev || 0)+ const blocked = mergeInto(get().S, e.data.state, e.data.rev || 0)+ if (blocked) {+ localStorage.setItem('gym_dirty', '1')+ setSync({ offline: false, pending: true })+ return+ }return doPush(attempt + 1)}localStorage.setItem('gym_dirty', '1')@@ -302,6 +333,7 @@ export const useStore = create((set, get) => {localStorage.removeItem('gym_guest')localStorage.removeItem('gym_dirty')localStorage.removeItem(SYNC_KEY)+ localStorage.removeItem(HISTORY_EDIT_KEY)localStorage.removeItem(KEY)persist(clone(DEF), false)localStorage.removeItem('gym_owner')@@ -332,6 +364,22 @@ export const useStore = create((set, get) => {mut(S)persist(S, push)},+ saveHistoryEdit() {+ const S = clone(get().S)+ const original = clone(S.active?.editingOriginal)+ const id = S.active?.editingWorkoutId+ const saved = saveWorkoutEdit(S)+ if (get().user) writePendingEdits([...readPendingEdits().filter(edit => edit.id !== id), { id, original, saved: clone(saved) }])+ persist(S)+ return saved+ },+ discardHistoryEdit() {+ const S = clone(get().S)+ const id = S.active?.editingWorkoutId+ S.active = null+ if (id) writePendingEdits(readPendingEdits().filter(edit => edit.id !== id))+ persist(S)+ },// A replace that is meant to reach the server (backup import, reset) is a deliberate// overwrite, not a change to merge: the push it arms goes without a baseRev.replaceState(S, push = false) { if (push) forceNext = true; persist(clone(S), push) },@@ -373,6 +421,7 @@ export const useStore = create((set, get) => {if (owner && owner !== u.id) {localStorage.removeItem('gym_dirty')localStorage.removeItem(SYNC_KEY)+ localStorage.removeItem(HISTORY_EDIT_KEY)localStorage.removeItem(KEY)persist(clone(DEF), false)}@@ -612,4 +661,4 @@ export const useStore = create((set, get) => {}})-export { hasData }\ No newline at end of file+export { hasData }diff --git a/frontend/src/store/useStore.restore.test.jsx b/frontend/src/store/useStore.restore.test.jsxindex abf28a23d..c8d09736c 100644--- a/frontend/src/store/useStore.restore.test.jsx+++ b/frontend/src/store/useStore.restore.test.jsx@@ -176,6 +176,7 @@ describe('signing in as a different profile', () => {it('does not move the previous profile data into a brand-new account', async () => {signInAsAThenExpire()+ localStorage.setItem('gym_history_edit_pending', JSON.stringify({ id: 'A-workout' }))api.mockResolvedValue({ state: null })useStore.getState().setUser({ id: 'B', name: 'B' })@@ -187,6 +188,7 @@ describe('signing in as a different profile', () => {expect(useStore.getState().S.active).toBeNull()expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines).toEqual([])expect(localStorage.getItem('gym_owner')).toBe('B')+ expect(localStorage.getItem('gym_history_edit_pending')).toBeNull()})it('adopts the new profile own state even when it is older or a push failed after expiry', async () => {diff --git a/frontend/src/store/useStore.sync.test.jsx b/frontend/src/store/useStore.sync.test.jsxindex b3c2a42ff..f4c616a6f 100644--- a/frontend/src/store/useStore.sync.test.jsx+++ b/frontend/src/store/useStore.sync.test.jsx@@ -162,6 +162,173 @@ describe('push against a revisioned server', () => {expect(localStorage.getItem('gym_dirty')).toBeNull()})+ it('a 409 keeps a history draft but adopts the remotely changed original record', async () => {+ const original = { ...workout('w1'), note: 'original' }+ const active = { ...clone(original), entries: [], editingWorkoutId: 'w1', editingOriginal: clone(original) }+ signedIn({ ...clone(DEF), _ts: 300, workouts: [original], active })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ const remote = { ...clone(DEF), _ts: 200, workouts: [{ ...original, note: 'from phone' }], _rev: 2 }+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: remote }))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })++ await useStore.getState().pushState()++ expect(puts()).toHaveLength(2)+ expect(puts()[1].state.workouts[0].note).toBe('from phone')+ expect(useStore.getState().S.active.editingWorkoutId).toBe('w1')+ expect(useStore.getState().S.active.editingOriginal.note).toBe('original')+ })++ it('a 409 after local Save restores that correction as a draft over the remote original', async () => {+ const row = weight => ({ id: 'sq', target: { mode: 'reps' }, sets: [{ w: weight, r: 5, done: true }] })+ const original = { ...workout('w1'), end: 2, note: 'original', entries: [row(40)] }+ const active = { ...clone(original), cur: 0, entries: [row(50)], editingWorkoutId: 'w1', editingOriginal: clone(original) }+ signedIn({ ...clone(DEF), _ts: 300, workouts: [original], active })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ const remote = { ...clone(DEF), _ts: 400, workouts: [{ ...original, note: 'from phone' }], exWeights: { sq: { w: 40, d: original.d } }, _rev: 2 }+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: remote }))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })++ useStore.getState().saveHistoryEdit()+ await useStore.getState().pushState()++ expect(puts()).toHaveLength(2)+ expect(puts()[1].state.workouts[0].note).toBe('from phone')+ expect(useStore.getState().S.active.entries[0].sets[0].w).toBe(50)+ expect(useStore.getState().S.active.editingOriginal.note).toBe('from phone')+ expect(useStore.getState().S.exWeights.sq.w).toBe(40)+ expect(localStorage.getItem('gym_history_edit_pending')).toBeNull()+ })++ it('restores historical PR flags from canonical history when a lowering edit conflicts', async () => {+ const row = weight => ({ id: 'sq', target: { mode: 'reps' }, sets: [{ w: weight, r: 5, done: true }] })+ const original = { ...workout('w1'), end: 2, entries: [row(40)], prs: ['sq'] }+ const later = { ...workout('w2', '2026-09-02'), end: 3, entries: [row(30)], prs: [] }+ const active = { ...clone(original), cur: 0, entries: [row(20)], editingWorkoutId: 'w1', editingOriginal: clone(original) }+ signedIn({ ...clone(DEF), _ts: 300, workouts: [original, later], active, exWeights: { sq: { w: 40, d: original.d } } })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ const remote = { ...clone(DEF), _ts: 400, workouts: [{ ...original, note: 'from phone' }, later], exWeights: { sq: { w: 40, d: original.d } }, _rev: 2 }+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: remote }))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })++ useStore.getState().saveHistoryEdit()+ expect(useStore.getState().S.workouts[1].prs).toEqual(['sq'])+ await useStore.getState().pushState()++ expect(useStore.getState().S.workouts[1].prs).toEqual([])+ expect(useStore.getState().S.exWeights.sq).toEqual({ w: 40, d: original.d })+ })++ it('keeps a saved correction and its conflict receipt while offline', async () => {+ const original = { ...workout('w1'), end: 2, entries: [{ id: 'sq', target: { mode: 'reps' }, sets: [{ w: 40, r: 5, done: true }] }] }+ const active = { ...clone(original), cur: 0, editingWorkoutId: 'w1', editingOriginal: clone(original) }+ active.entries[0].sets[0].w = 50+ signedIn({ ...clone(DEF), _ts: 300, workouts: [original], active })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockRejectedValueOnce(new TypeError('offline'))++ useStore.getState().saveHistoryEdit()+ await useStore.getState().pushState()++ expect(useStore.getState().S.active).toBeNull()+ expect(useStore.getState().S.workouts[0].entries[0].sets[0].w).toBe(50)+ expect(localStorage.getItem('gym_history_edit_pending')).not.toBeNull()+ expect(localStorage.getItem('gym_dirty')).toBe('1')+ })++ it('does not clear an edit saved after an earlier PUT started', async () => {+ vi.useFakeTimers()+ const row = weight => ({ id: 'sq', target: { mode: 'reps' }, sets: [{ w: weight, r: 5, done: true }] })+ const original = { ...workout('w1'), end: 2, entries: [row(40)] }+ const active = { ...clone(original), cur: 0, entries: [row(50)], editingWorkoutId: 'w1', editingOriginal: clone(original) }+ signedIn({ ...clone(DEF), _ts: 300, workouts: [original], active })+ let release+ api.mockImplementationOnce(() => new Promise(resolve => { release = () => resolve({ ok: true, rev: 2 }) }))++ const earlier = useStore.getState().pushState()+ useStore.getState().saveHistoryEdit()+ release()+ await earlier++ const pending = JSON.parse(localStorage.getItem('gym_history_edit_pending'))+ expect(pending).toHaveLength(1)+ expect(pending[0].saved.entries[0].sets[0].w).toBe(50)+ })++ it('keeps separate offline receipts for edits to two workouts', () => {+ vi.useFakeTimers()+ const row = weight => ({ id: 'sq', target: { mode: 'reps' }, sets: [{ w: weight, r: 5, done: true }] })+ const originals = [+ { ...workout('w1'), end: 2, entries: [row(40)] },+ { ...workout('w2'), end: 2, entries: [row(60)] },+ ]+ const activeFor = (original, weight) => ({+ ...clone(original), cur: 0, entries: [row(weight)],+ editingWorkoutId: original.id, editingOriginal: clone(original),+ })+ signedIn({ ...clone(DEF), workouts: originals, active: activeFor(originals[0], 45) })+ useStore.getState().saveHistoryEdit()+ const second = clone(useStore.getState().S.workouts.find(saved => saved.id === 'w2'))+ useStore.getState().update(state => { state.active = activeFor(second, 65) }, false)+ useStore.getState().saveHistoryEdit()++ const pending = JSON.parse(localStorage.getItem('gym_history_edit_pending'))+ expect(pending.map(edit => edit.id)).toEqual(['w1', 'w2'])+ expect(pending.map(edit => edit.saved.entries[0].sets[0].w)).toEqual([45, 65])+ })++ it('halts conflict retry when a live workout occupies the recovered editor slot', async () => {+ const row = weight => ({ id: 'sq', target: { mode: 'reps' }, sets: [{ w: weight, r: 5, done: true }] })+ const original = { ...workout('w1'), end: 2, note: 'original', entries: [row(40)] }+ const active = { ...clone(original), cur: 0, entries: [row(50)], editingWorkoutId: 'w1', editingOriginal: clone(original) }+ signedIn({ ...clone(DEF), _ts: 300, workouts: [original], active })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ useStore.getState().saveHistoryEdit()+ useStore.getState().update(state => { state.active = { id: 'live', entries: [] } }, false)+ const remote = { ...clone(DEF), _ts: 400, workouts: [{ ...original, note: 'from phone' }], _rev: 2 }+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: remote }))++ await useStore.getState().pushState()++ expect(puts()).toHaveLength(1)+ expect(useStore.getState().S.workouts[0].note).toBe('from phone')+ expect(useStore.getState().S.active.id).toBe('live')+ expect(JSON.parse(localStorage.getItem('gym_history_edit_pending'))[0].saved.entries[0].sets[0].w).toBe(50)+ expect(localStorage.getItem('gym_dirty')).toBe('1')+ })++ it('keeps multiple conflicting corrections and recovers them one editor at a time', async () => {+ vi.useFakeTimers()+ const row = weight => ({ id: 'sq', target: { mode: 'reps' }, sets: [{ w: weight, r: 5, done: true }] })+ const originals = [+ { ...workout('w1'), end: 2, note: 'one', entries: [row(40)] },+ { ...workout('w2'), end: 2, note: 'two', entries: [row(60)] },+ ]+ const saved = [+ { ...clone(originals[0]), entries: [row(45)] },+ { ...clone(originals[1]), entries: [row(65)] },+ ]+ signedIn({ ...clone(DEF), _ts: 300, workouts: saved })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ localStorage.setItem('gym_history_edit_pending', JSON.stringify(originals.map((original, i) => ({+ id: original.id, original, saved: saved[i],+ }))))+ const remote = { ...clone(DEF), _ts: 400, workouts: originals.map(original => ({ ...original, note: 'remote-' + original.id })), _rev: 2 }+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: remote }))++ await useStore.getState().pushState()++ expect(puts()).toHaveLength(1)+ expect(useStore.getState().S.workouts.map(item => item.note)).toEqual(['remote-w1', 'remote-w2'])+ expect(useStore.getState().S.active.editingWorkoutId).toBe('w1')+ expect(JSON.parse(localStorage.getItem('gym_history_edit_pending')).map(edit => edit.id)).toEqual(['w1', 'w2'])+ expect(sync().rev).toBe(1)+ expect(localStorage.getItem('gym_dirty')).toBe('1')++ useStore.getState().discardHistoryEdit()+ expect(JSON.parse(localStorage.getItem('gym_history_edit_pending')).map(edit => edit.id)).toEqual(['w2'])+ })+it('gives up after two conflicts in a row and leaves the copy dirty for the next pull', async () => {signedIn({ ...clone(DEF), _ts: 300, workouts: [workout('w1')] })localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 8e772d080..31d22511e 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -12,7 +12,7 @@ import { t, exerciseNameFor } from '../lib/i18n.js'import { api } from '../lib/api.js'import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor, warmupRestSecFor } from '../lib/supersetFlow.js'import Media from '../components/Media.jsx'-import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'+import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, exitWorkoutEdit, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'import { effortColor } from '../lib/effort.js'import Icon from '../components/Icon.jsx'import { Button, Check, NumberField } from '../components/ui.jsx'@@ -72,7 +72,7 @@ function Elapsed({ start }) {// drops everything that is not a set you are logging — media, tag chips, the note lines, the// "last time" recap and the progression line — leaving the name, the ⋯ menu and the sets.// Nothing dropped is lost: it is all still on the ⋯ menu, or one ⋮ switch back to list/cards.-function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings, onSwap, onMoveUp, onMoveDown, canMoveUp, canMoveDown, onRemoveExercise, busy }) {+function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSide, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings, onSwap, onMoveUp, onMoveDown, canMoveUp, canMoveDown, onRemoveExercise, busy }) {const S = useStore(s => s.S)const update = useStore(s => s.update)const working = useUI(s => s.work)@@ -196,7 +196,7 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFie// Everything about this exercise that is not a set you are logging right now lives behind one// button. What used to be a row of buttons in the header, a chip under the bar, a strip of// three under the sets and four more below the card is a single list you open once a session.- const barInfo = (!cardio && !(bw && !added) && usesBar(ex)) ? (() => {+ const barInfo = (!editing && !cardio && !(bw && !added) && usesBar(ex)) ? (() => {const bar = barWeightFor(S, entry.id)if (!(bar > 0)) return nullconst nextW = entry.sets.find(s => !s.done)?.w@@ -231,7 +231,7 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFieitems: [!warm && mode === 'reps' && !isRestPauseSet(s) && { icon: 'arrowDown', label: t('Drop set'), sub: t('+ Drop'), onClick: () => addDropRow(i) },!warm && mode === 'reps' && !isDropSet(s) && { icon: 'bolt', label: t('Rest-pause burst'), sub: t('+ Burst'), onClick: () => addBurstRow(i) },- { icon: 'trash', label: t('Remove this set'), danger: true, disabled: entry.sets.length <= 1, onClick: () => onRemoveSetAt(i) },+ { icon: 'trash', label: t('Remove this set'), danger: true, disabled: !editing && entry.sets.length <= 1, onClick: () => onRemoveSetAt(i) },],})}@@ -401,7 +401,7 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFie{barInfo && <div className="small dim" style={{ marginBottom: 6, display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="dumbbell" style={{ fontSize: 12 }} />{barInfo.text}</div>}- {guidance && <button type="button" className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}+ {guidance && onProgressionSettings && <button type="button" className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}aria-label={t('Open progression settings')} onClick={onProgressionSettings}><Icon name={plan.kind === 'up' ? 'arrowUp' : plan.kind === 'deload' ? 'arrowDown' : 'lightbulb'} /><span><strong>{t(guidance.policyLabel)}</strong> · {t(...guidance.why)}</span>@@ -439,7 +439,7 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFie{col3 && effortCell(s, i, col3)}{/* A timed set is started, not typed: the timer counts the hold down and checks theset off itself. The checkbox stays for anyone who timed it on their own watch. */}- {timed && <button className="setgo" aria-label={t('Start set')} disabled={s.done || !!working}+ {timed && !editing && <button className="setgo" aria-label={t('Start set')} disabled={s.done || !!working}onClick={() => onStartTimed(i)}><Icon name="play" /></button>}<Check checked={s.done} onChange={() => onToggle(i)} /></div>@@ -509,9 +509,10 @@ function ActiveWorkout() {const update = useStore(s => s.update)const { startRest: liveRest, stopRest, stopWork, work } = useUI()const A = S.active+ const editing = !!A.editingWorkoutId// A past workout has no rest to time — the sets were done days ago. The work timer for// timed sets stays, since counting a hold is how its duration gets entered.- const startRest = A.backfill ? () => {} : liveRest+ const startRest = (A.backfill || editing) ? () => {} : liveRestconst units = supersetUnits(A.entries)const cur = Number.isInteger(A.cur)? Math.min(Math.max(A.cur, 0), Math.max(0, A.entries.length - 1))@@ -615,7 +616,10 @@ function ActiveWorkout() {const m = modeOf({ ...(e.target || {}), id: e.id })e.sets = insertWarmupRow(e.sets, m, e.target || {}, defaultIncrement(e.id, S.unit))})- const removeSetAt = (idx, i) => mutEntry(idx, e => { e.sets = removeRowAt(e.sets, i) })+ const removeSetAt = (idx, i) => mutEntry(idx, e => {+ if (editing) e.sets.splice(i, 1)+ else e.sets = removeRowAt(e.sets, i)+ })const pairAt = (first, second) => update(s => {s.active.entries = pairAdjacent(s.active.entries, first, second)})@@ -649,6 +653,7 @@ function ActiveWorkout() {// exercise-level actions (swap, move, remove) address the entry itself, so the "more" menu of// a superset member acts on that member, not on whatever the marker happens to point at.const blockProps = idx => ({+ editing,onSwap: () => swapActiveWorkoutExercise(idx),onMoveUp: () => moveUnitAt(idx, -1),onMoveDown: () => moveUnitAt(idx, 1),@@ -664,7 +669,7 @@ function ActiveWorkout() {onAddWarmup: () => addWarmup(idx),onRemoveSetAt: i => removeSetAt(idx, i),onStartTimed: i => startTimed(idx, i),- onProgressionSettings: () => openProgressionSettings(idx),+ onProgressionSettings: editing ? null : () => openProgressionSettings(idx),})const navigateUnit = direction => {const targetFor = active => {@@ -701,7 +706,7 @@ function ActiveWorkout() {// level down (it used to be the whole menu).const openViewMenu = () => menuSheet({items: [- { icon: 'plus', label: t('Add routine'), sub: t('Bring another routine into this session'), onClick: addRoutineToSessionSheet },+ !editing && { icon: 'plus', label: t('Add routine'), sub: t('Bring another routine into this session'), onClick: addRoutineToSessionSheet },{ icon: 'list', label: t('Layout'), sub: LAYOUT_LABEL[workoutView] || LAYOUT_LABEL.cards, onClick: openLayoutMenu },],})@@ -805,6 +810,7 @@ function ActiveWorkout() {// checks the set off through the normal path, so rest, supersets and the finish prompt all// behave exactly as they do for a reps set.const startTimed = (idx, i) => {+ if (editing) returnconst e = A.entries[idx]// This tap may be the only one before the hold's countdown beeps (a timed first exercise):// get the audio context running while it still counts as a gesture (iOS, #152).@@ -831,7 +837,7 @@ function ActiveWorkout() {if (side) e.sets[i] = toggleSide(e.sets[i], side)else e.sets[i].done = !e.sets[i].donechecked = e.sets[i].done- if (e.sets[i].done) {+ if (e.sets[i].done && !editing) {beep(S.sound, 1040, 0.12); vibrate(30)// The unit that owns the ticked set — not the marked one. Since !92 the marker no longer// follows a finished exercise, and in list mode any exercise can be worked on, so judging@@ -847,6 +853,7 @@ function ActiveWorkout() {}}}, true)+ if (editing) returnif (workoutDone) workoutCompleteSheet()else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged'))else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged'))@@ -904,7 +911,7 @@ function ActiveWorkout() {// Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only —// guests have no server session. Reads fresh state each tick so progress stays current.useEffect(() => {- if (!useStore.getState().user) return+ if (!useStore.getState().user || editing) returnlet stopped = falseconst ping = active => {const A2 = useStore.getState().S.active@@ -934,15 +941,16 @@ function ActiveWorkout() {while you are somewhere in the middle of a long stack. Cards mode never scrolls far. */}<div className={'whdr' + (listMode ? ' stick' : '')}><div className="hdr">- <button className="iconbtn" aria-label={t('Discard')} onClick={() => confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); stopWork(); nav('/home') } })}><Icon name="xmark" /></button>- <div style={{ textAlign: 'center' }}><div style={{ fontWeight: 600 }}>{A.name}</div><div className="sub">{A.backfill ? fmtDate(A.d, true) : <Elapsed start={A.start} />} · {t('{0} sets', done + '/' + total)}</div></div>+ <button className="iconbtn" aria-label={t(editing ? 'Close editor' : 'Discard')} onClick={() => editing ? exitWorkoutEdit() : confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); stopWork(); nav('/home') } })}><Icon name="xmark" /></button>+ <div style={{ textAlign: 'center' }}><div style={{ fontWeight: 600 }}>{A.name}</div><div className="sub">{(A.backfill || editing) ? fmtDate(A.d, true) : <Elapsed start={A.start} />} · {t('{0} sets', done + '/' + total)}</div></div><div className="row" style={{ gap: 4, flex: 'none' }}><button className="iconbtn" aria-label={t('Workout view')} title={t('Workout view')} onClick={openViewMenu}><Icon name="more" /></button>- <button className="iconbtn" style={{ color: 'var(--acc)' }} aria-label={t('Finish')} onClick={finishWorkout}><Icon name="check" /></button>+ <button className="iconbtn" style={{ color: 'var(--acc)' }} aria-label={t(editing ? 'Save changes' : 'Finish')} onClick={finishWorkout}><Icon name="check" /></button></div></div><div className="wprog"><i style={{ width: (total ? done / total * 100 : 0) + '%' }} /></div></div>+ {editing && <p className="muted small">{t('Editing a saved workout. Date and duration stay unchanged.')}</p>}{A.backfill && <div className="muted small" style={{ marginBottom: 8 }}>{t('Logging a past workout — no rest timers.')}</div>}{A.entries.length ? (listMode ? (@@ -1082,7 +1090,7 @@ function ActiveWorkout() {const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).lengthconst allDone = A.entries.length > 0 && exDone === A.entries.lengthreturn <button className={allDone ? 'btn primary' : 'btn ghost dim'} onClick={finishWorkout}>- {allDone ? t('Finish workout') : t('Finish workout early · {0} exercises', exDone + '/' + A.entries.length)}+ {editing ? t('Save changes') : allDone ? t('Finish workout') : t('Finish workout early · {0} exercises', exDone + '/' + A.entries.length)}</button>})()}<div className="workout-end-spacer" />diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsxindex 5409de4d7..d494a6e94 100644--- a/frontend/src/views/Workout.test.jsx+++ b/frontend/src/views/Workout.test.jsx@@ -67,6 +67,7 @@ vi.mock('../sheets.jsx', () => ({exerciseDetailSheet: vi.fn(),topWeightSheet: mocks.topWeightSheet,finishWorkout: vi.fn(),+ exitWorkoutEdit: vi.fn(),workoutCompleteSheet: mocks.workoutCompleteSheet,confirmSheet: mocks.confirmSheet,swapActiveWorkoutExercise: mocks.swapActiveWorkoutExercise,@@ -197,6 +198,24 @@ beforeEach(() => {mocks.scrollCalls.length = 0})+it('edits a saved set without running live completion, rest or success feedback', async () => {+ 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' } },+ })+ await toggleSet(0)+ expect(mocks.S.active.entries[0].sets[0].done).toBe(true)+ expect(mocks.startRest).not.toHaveBeenCalled()+ expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()+ expect(mocks.toast).not.toHaveBeenCalled()+ expect(container.textContent).toContain('Editing a saved workout')+ expect(container.querySelector('.progline')).toBeNull()+ const more = container.querySelector('button[aria-label="More"]')+ await act(async () => { more.dispatchEvent(new dom.Event('click', { bubbles: true })) })+ expect(mocks.menuSheet.mock.calls.at(-1)[0].items.filter(Boolean).map(item => item.label)).not.toContain('Progression settings')+})+afterEach(async () => {await unmount()})