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.

Workout editor: held against the sessions before it, closes without asking when nothing changed, refuses an empty duration; a re-logged day keeps its note and a past workout earns its badges

Duarte Santos092b8245fa29
diff --git a/frontend/src/lib/backfill.js b/frontend/src/lib/backfill.js
index 9ef8db1fa..6c2354eb0 100644
--- a/frontend/src/lib/backfill.js
+++ b/frontend/src/lib/backfill.js
@@ -27,18 +27,26 @@ export const backfillEnd = active => active.start + Math.max(1, active.backfill?
// is not, since that one is gone once this is saved. A confirmed working weight (exWeights) dated
// after the day is later progression as well; one with no date is kept, nothing says when it came.
// A view for reading only: the lists are new, everything else is S's own.
-export function historyAsOf(S, { d, start = 0, replaceId = null }) {
- const filedBefore = w => (w.d || '') < d || ((w.d || '') === d && (w.start || 0) <= start)
- const workouts = (S.workouts || []).filter(w => filedBefore(w) && !(replaceId && w.id === replaceId))
+// `strict` leaves out a workout started at the very same moment too: the one being edited, when
+// it predates ids and has none to leave it out by.
+export function historyAsOf(S, { d, start = 0, replaceId = null, strict = false }) {
+ const sameDayBefore = w => (strict ? (w.start || 0) < start : (w.start || 0) <= start)
+ const filedBefore = w => (w.d || '') < d || ((w.d || '') === d && sameDayBefore(w))
+ const workouts = (S.workouts || []).filter(w => filedBefore(w) && !(replaceId != null && w.id === replaceId))
const exWeights = Object.fromEntries(Object.entries(S.exWeights || {}).filter(([, kept]) => !kept?.d || kept.d <= d))
return { ...S, workouts, exWeights }
}
// The history the running session is built from and held against: as of its own day while it is
-// logged into the past, and the whole log for a live one (S itself, so that costs nothing).
+// logged into the past, and the whole log for a live one (S itself, so that costs nothing). A
+// saved workout open in the editor is held against what came before it, without itself: read
+// from the whole log, its "Last time" line was itself, or a later session, and the Best chip
+// compared it with lifts made after it (QA 1.3.9).
export const sessionHistory = S => {
const A = S?.active
- return A?.backfill ? historyAsOf(S, { d: A.d, start: A.start, replaceId: A.backfill.replaceId }) : S
+ if (A?.backfill) return historyAsOf(S, { d: A.d, start: A.start, replaceId: A.backfill.replaceId })
+ if (A?.editingWorkoutId != null) return historyAsOf(S, { d: A.d, start: A.start, replaceId: A.editingWorkoutId, strict: true })
+ return S
}
// The workouts array is chronological (History reverses it), so a past workout cannot just be
@@ -58,16 +66,25 @@ export function insertChronological(workouts, w) {
// The history after a backfilled session is filed: the workout it replaces (if any) is gone
// and the new one sits in date order. Returns a new array; the caller stores it.
//
-// Replacing re-logs that day's sets, not its photos and videos: those move onto the new record
-// (after any it has), stamped like any other edit of a saved workout, so the progress photo of a
-// day logged again is not dropped with the old sets. `w` is changed in place when they do.
+// Replacing re-logs that day's sets, not its photos and videos or its session note: those move
+// onto the new record (the media after any it has; the note ahead of one written now), stamped
+// like any other edit of a saved workout, so the progress photo or the "felt the knee" of a day
+// logged again is not dropped with the old sets. `w` is changed in place when they do.
export function completeBackfill(workouts, active, w, now = Date.now()) {
const replaceId = active.backfill?.replaceId
if (!replaceId) return insertChronological(workouts, w)
const replaced = workouts.find(x => x.id === replaceId)
const had = Array.isArray(w.media) ? w.media.length : 0
- if (replaced) mergeWorkoutMedia(w, replaced)
- if ((Array.isArray(w.media) ? w.media.length : 0) > had) stampWorkout(w, now)
+ let carried = false
+ if (replaced) {
+ mergeWorkoutMedia(w, replaced)
+ const old = (replaced.note || '').trim(), fresh = (w.note || '').trim()
+ if (old && old !== fresh) {
+ w.note = fresh && !fresh.includes(old) ? `${old}\n${fresh}` : (fresh || old)
+ carried = w.note !== fresh
+ }
+ }
+ if (carried || (Array.isArray(w.media) ? w.media.length : 0) > had) stampWorkout(w, now)
return insertChronological(workouts.filter(x => x.id !== replaceId), w)
}
diff --git a/frontend/src/lib/backfill.test.js b/frontend/src/lib/backfill.test.js
index 417fd8843..473da8209 100644
--- a/frontend/src/lib/backfill.test.js
+++ b/frontend/src/lib/backfill.test.js
@@ -68,6 +68,18 @@ describe('completeBackfill', () => {
const plain = completeBackfill(list, { backfill: { durationMin: 60, replaceId: 'b' } }, w('y', '2026-01-05', 30), 777)
expect('media' in plain[1] || '_ts' in plain[1]).toBe(false)
})
+ // QA 1.3.9: the sets were logged again and the day's note went with the old record.
+ it('carries the replaced workout\'s note, ahead of one written now, stamped', () => {
+ const noted = [list[0], { ...list[1], note: 'knee felt off' }, list[2]]
+ const kept = completeBackfill(noted, { backfill: { durationMin: 60, replaceId: 'b' } }, w('x', '2026-01-05', 30), 777)
+ expect(kept[1]).toMatchObject({ id: 'x', note: 'knee felt off', _ts: 777 })
+ const both = completeBackfill(noted, { backfill: { durationMin: 60, replaceId: 'b' } }, { ...w('y', '2026-01-05', 30), note: 'redid it' }, 778)
+ expect(both[1].note).toBe('knee felt off\nredid it')
+ // The same note typed again is not doubled, and needs no stamp.
+ const same = completeBackfill(noted, { backfill: { durationMin: 60, replaceId: 'b' } }, { ...w('z', '2026-01-05', 30), note: 'knee felt off' }, 779)
+ expect(same[1].note).toBe('knee felt off')
+ expect('_ts' in same[1]).toBe(false)
+ })
})
// #284: a missed Monday logged on Saturday opened at Friday's progression and saved it as Monday's.
@@ -110,6 +122,17 @@ describe('sessionHistory', () => {
expect(sessionHistory(past).workouts.map(x => x.id)).toEqual(['a'])
expect(sessionHistory({ workouts: list })).toEqual({ workouts: list })
})
+
+ // QA 1.3.9: the editor read the whole log, so "Last time" and the Best chip on a workout being
+ // corrected were itself or a later session.
+ it('is the history before the edited workout, without it, while a saved workout is in the editor', () => {
+ const editing = { workouts: list, exWeights: {}, active: { d: '2026-01-05', start: 10, editingWorkoutId: 'b' } }
+ expect(sessionHistory(editing).workouts.map(x => x.id)).toEqual(['a'])
+ // One from before ids, keyed by its day and start, is left out by its start.
+ const legacy = [w('a', '2026-01-01', 10), { ...w(undefined, '2026-01-05', 10), id: undefined }, w('d', '2026-01-09', 10)]
+ const old = { workouts: legacy, exWeights: {}, active: { d: '2026-01-05', start: 10, editingWorkoutId: '2026-01-05|10' } }
+ expect(sessionHistory(old).workouts.map(x => x.d)).toEqual(['2026-01-01'])
+ })
})
// #284: a past session that went as planned is logged with one tap instead of one per set.
diff --git a/frontend/src/lib/session-edit.js b/frontend/src/lib/session-edit.js
index 325b68d17..a30391624 100644
--- a/frontend/src/lib/session-edit.js
+++ b/frontend/src/lib/session-edit.js
@@ -47,6 +47,14 @@ function sameData(a, b) {
// and the id it freezes for a workout from before ids.
const DERIVED = ['id', 'vol', 'prs', '_ts']
const savedData = w => Object.fromEntries(Object.entries(w).filter(([k]) => !DERIVED.includes(k)))
+// …compared the way the data reads, for asking whether closing loses anything: a record that never
+// had `routineIds` or a `topW` (an import, a workout from an older build) holds nothing a Save
+// would add beyond [] / null / the top set its sets already say. (Save itself still writes those.)
+const comparable = w => {
+ const out = Object.fromEntries(Object.entries(savedData(w)).filter(([, v]) => v !== null && !(Array.isArray(v) && !v.length)))
+ if (Array.isArray(out.entries)) out.entries = out.entries.map(e => (e && typeof e === 'object' ? (({ topW, ...rest }) => rest)(e) : e))
+ return out
+}
// The best load one workout logged for an exercise, across every occurrence of it.
function bestIn(workout, id) {
@@ -135,7 +143,46 @@ export function saveWorkoutEdit(state, now = Date.now()) {
// Never saved empty: the editor asks to delete the workout instead (deleteEditedWorkout).
if (editLeftEmpty(active)) throw new Error('Nothing logged yet')
const current = state.workouts[index]
+ const record = draftRecord(active, current, key)
+ // A Save that changed nothing closes the editor and leaves the record as it is. A new stamp
+ // would outrank an edit another device made since and has not synced yet (sets added on the
+ // phone), for nothing — the date and duration rows skip an unchanged save the same way.
+ if (sameData(savedData(record), savedData(current))) {
+ state.active = null
+ return current
+ }
+ record.vol = workoutVolume(record)
+ stampWorkout(record, now)
+ state.workouts[index] = record
+
+ // 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)
+ lowerKeptWeights(state, touched, current, saved)
+ state.active = null
+ return saved
+}
+
+/**
+ * Whether closing the editor would lose nothing: Save would write the record exactly as history
+ * holds it. Closing then just closes — asking "Save workout changes?" about a workout nobody
+ * touched (QA 1.3.9) made every look at a past session end in a question. A record deleted
+ * meanwhile, or a draft left empty, is a change: those still ask.
+ */
+export function editChangesNothing(state) {
+ const active = state?.active
+ const key = active?.editingWorkoutId
+ if (key == null || editLeftEmpty(active)) return false
+ const current = list(state.workouts).find(w => keyOf(w) === key)
+ if (!current) return false
+ return sameData(comparable(draftRecord(active, current, key)), comparable(current))
+}
+// The record Save would write for this draft over `current`, before its volume and stamp.
+function draftRecord(active, current, key) {
const updated = buildCompletedWorkout(active, {
end: current.end,
prs: current.prs || [],
@@ -163,26 +210,7 @@ export function saveWorkoutEdit(state, now = Date.now()) {
if (value == null || value === '') delete record[k]
else record[k] = value
}
- // A Save that changed nothing closes the editor and leaves the record as it is. A new stamp
- // would outrank an edit another device made since and has not synced yet (sets added on the
- // phone), for nothing — the date and duration rows skip an unchanged save the same way.
- if (sameData(savedData(record), savedData(current))) {
- state.active = null
- return current
- }
- record.vol = workoutVolume(record)
- stampWorkout(record, now)
- state.workouts[index] = record
-
- // 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)
- lowerKeptWeights(state, touched, current, saved)
- state.active = null
- return saved
+ return record
}
/** The saved record the editor is open on, as history holds it now — or null (none open, or it
diff --git a/frontend/src/lib/session-edit.test.js b/frontend/src/lib/session-edit.test.js
index 1db6c3c49..e86f62562 100644
--- a/frontend/src/lib/session-edit.test.js
+++ b/frontend/src/lib/session-edit.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { editCompletedSession, saveWorkoutEdit, editLeftEmpty, deleteEditedWorkout } from './session-edit.js'
+import { editCompletedSession, saveWorkoutEdit, editLeftEmpty, deleteEditedWorkout, editChangesNothing } from './session-edit.js'
import { mergeStates } from './sync-merge.js'
import { entryExcluded, lastEntryFor } from './history.js'
@@ -324,3 +324,36 @@ describe('an edit that leaves no set', () => {
expect(state.exWeights['0027']).toEqual({ w: 70, d: '2026-08-01' })
})
})
+
+// QA 1.3.9: closing the editor asked "Save workout changes?" about a workout nobody had touched.
+describe('editChangesNothing', () => {
+ it('is true for a workout opened and left alone, even after a reload', () => {
+ const state = fixture()
+ editCompletedSession(state, 'workout')
+ expect(editChangesNothing(state)).toBe(true)
+ expect(editChangesNothing(JSON.parse(JSON.stringify(state)))).toBe(true)
+ })
+ it('is false once a set, the note or the exercises changed', () => {
+ for (const change of [
+ s => { s.active.entries[0].sets[0].w = 45 },
+ s => { s.active.note = 'new' },
+ s => { s.active.entries.push(entry(20, 'added')) },
+ ]) {
+ const state = fixture()
+ editCompletedSession(state, 'workout')
+ change(state)
+ expect(editChangesNothing(state)).toBe(false)
+ }
+ })
+ it('is false for a draft left empty or a record deleted meanwhile, which still need a decision', () => {
+ const state = fixture()
+ editCompletedSession(state, 'workout')
+ state.active.entries[0].sets[0].done = false
+ expect(editChangesNothing(state)).toBe(false)
+ const gone = fixture()
+ editCompletedSession(gone, 'workout')
+ gone.workouts = []
+ expect(editChangesNothing(gone)).toBe(false)
+ expect(editChangesNothing({ active: null, workouts: [] })).toBe(false)
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index f61d4c5f1..1c443b6e4 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1706,4 +1706,5 @@ export default {
'Red': 'أحمر',
'Teal': 'أزرق مخضر',
'Yellow': 'أصفر',
+ 'Enter how long it took — at least 1 minute.': 'أدخل المدة التي استغرقها — دقيقة واحدة على الأقل.',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index c087cab0c..fc9684c7d 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1673,4 +1673,5 @@ export default {
'Red': 'Rot',
'Teal': 'Türkis',
'Yellow': 'Gelb',
+ 'Enter how long it took — at least 1 minute.': 'Gib ein, wie lange es gedauert hat — mindestens 1 Minute.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 7235951ed..bed0c468f 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1653,4 +1653,5 @@ export default {
'Red': 'Rojo',
'Teal': 'Turquesa',
'Yellow': 'Amarillo',
+ 'Enter how long it took — at least 1 minute.': 'Indica cuánto duró — al menos 1 minuto.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 0156f5896..e70f4ebfd 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1653,4 +1653,5 @@ export default {
'Red': 'Rouge',
'Teal': 'Turquoise',
'Yellow': 'Jaune',
+ 'Enter how long it took — at least 1 minute.': 'Indique combien de temps ça a duré — au moins 1 minute.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 07c9f3a25..63054da5a 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1653,4 +1653,5 @@ export default {
'Red': 'लाल',
'Teal': 'फ़िरोज़ी',
'Yellow': 'पीला',
+ 'Enter how long it took — at least 1 minute.': 'बताएँ कि इसमें कितना समय लगा — कम से कम 1 मिनट।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 542e1f976..6b2d555c1 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1656,4 +1656,5 @@ export default {
'Red': 'Piros',
'Teal': 'Türkiz',
'Yellow': 'Sárga',
+ 'Enter how long it took — at least 1 minute.': 'Add meg, meddig tartott — legalább 1 perc.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 0ab246beb..13cf09db4 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1653,4 +1653,5 @@ export default {
'Red': 'Rosso',
'Teal': 'Turchese',
'Yellow': 'Giallo',
+ 'Enter how long it took — at least 1 minute.': 'Inserisci quanto è durato — almeno 1 minuto.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index a92d626ad..8b8d5cc3a 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1653,4 +1653,5 @@ export default {
'Red': '빨강',
'Teal': '청록',
'Yellow': '노랑',
+ 'Enter how long it took — at least 1 minute.': '걸린 시간을 입력하세요 — 최소 1분.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 7af729925..1e01f24d3 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1653,4 +1653,5 @@ export default {
'Red': 'Czerwony',
'Teal': 'Turkusowy',
'Yellow': 'Żółty',
+ 'Enter how long it took — at least 1 minute.': 'Wpisz, ile to trwało — co najmniej 1 minutę.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index c99f5ee30..5365d0eb7 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -998,6 +998,7 @@ export const PT_BR_OVERRIDES = {
'Red': 'Vermelho',
'Teal': 'Turquesa',
'Yellow': 'Amarelo',
+ 'Enter how long it took — at least 1 minute.': 'Informe quanto tempo levou — pelo menos 1 minuto.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index d671c44aa..0fbe3e9e3 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1653,4 +1653,5 @@ export default {
'Red': 'Vermelho',
'Teal': 'Turquesa',
'Yellow': 'Amarelo',
+ 'Enter how long it took — at least 1 minute.': 'Indica quanto tempo demorou — pelo menos 1 minuto.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 1155d1962..a40d0feed 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1653,4 +1653,5 @@ export default {
'Red': 'Красный',
'Teal': 'Бирюзовый',
'Yellow': 'Жёлтый',
+ 'Enter how long it took — at least 1 minute.': 'Укажите, сколько это длилось — не меньше 1 минуты.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 59af577e3..348a842de 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1664,4 +1664,5 @@ export default {
'Red': 'แดง',
'Teal': 'เขียวน้ำทะเล',
'Yellow': 'เหลือง',
+ 'Enter how long it took — at least 1 minute.': 'ใส่ระยะเวลาที่ใช้ — อย่างน้อย 1 นาที',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 7839946d6..8d860f5b2 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1653,4 +1653,5 @@ export default {
'Red': 'Kırmızı',
'Teal': 'Turkuaz',
'Yellow': 'Sarı',
+ 'Enter how long it took — at least 1 minute.': 'Ne kadar sürdüğünü gir — en az 1 dakika.',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 96e568947..a10649538 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1622,14 +1622,14 @@ export default {
// --- a swap or an add during a workout changes only this session ---
'Use in this workout': 'Використати в цьому тренуванні',
'Add to this workout': 'Додати до цього тренування',
- 'No weight to enter — just time the hold.': 'Вага не потрібна — лише засікайте час утримання.',
+ 'No weight to enter — just time the hold.': 'Вага не потрібна — лише засікай час утримання.',
// --- how this device confirms a passkey, and where it keeps it ---
'Face ID / Touch ID': 'Face ID / Touch ID',
'fingerprint or face unlock': 'відбиток пальця або розблокування обличчям',
'your fingerprint, face or PIN': 'відбиток пальця, обличчя або PIN-код',
'iCloud Keychain': 'Зв’язка ключів iCloud',
'Google Password Manager': 'Менеджер паролів Google',
- 'your password manager': 'ваш менеджер паролів',
+ 'your password manager': 'твій менеджер паролів',
// --- screen-reader labels on icon buttons ---
'Previous week': 'Попередній тиждень',
'Next week': 'Наступний тиждень',
@@ -1650,4 +1650,5 @@ export default {
'Red': 'Червоний',
'Teal': 'Бірюзовий',
'Yellow': 'Жовтий',
+ 'Enter how long it took — at least 1 minute.': 'Вкажи, скільки це тривало — щонайменше 1 хвилину.',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 26c27e07d..db5309b95 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1653,4 +1653,5 @@ export default {
'Red': '红色',
'Teal': '青色',
'Yellow': '黄色',
+ 'Enter how long it took — at least 1 minute.': '请输入用时 — 至少 1 分钟。',
}
diff --git a/frontend/src/sheets.backfill.test.jsx b/frontend/src/sheets.backfill.test.jsx
index fcc83e687..f770d0b1f 100644
--- a/frontend/src/sheets.backfill.test.jsx
+++ b/frontend/src/sheets.backfill.test.jsx
@@ -115,11 +115,17 @@ describe('log a past workout', () => {
expect(useStore.getState().S.active.backfill.durationMin).toBe(45)
})
- it('an emptied duration still starts a one-minute session, not the default hour', () => {
+ // An emptied duration is neither the default hour nor a silent minute (QA 1.3.9): nothing
+ // starts until a length is typed, and the sheet says so.
+ it('an emptied duration starts nothing and asks for a length', () => {
logPastWorkoutSheet()
const host = mountTopSheet()
act(() => { type(host.querySelector('input[type=date]'), '2020-01-02') })
act(() => { type(host.querySelector('input.num'), '') })
+ expect(host.textContent).toContain('Enter how long it took — at least 1 minute.')
+ act(() => { button(host, 'Continue').click() })
+ expect(useStore.getState().S.active).toBeFalsy()
+ act(() => { type(host.querySelector('input.num'), '1') })
act(() => { button(host, 'Continue').click() })
expect(useStore.getState().S.active.backfill.durationMin).toBe(1)
})
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index e895fd0a3..d471cdb95 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -45,8 +45,8 @@ import { buildSessionEntries, buildPlannedEntry, builtOutOfProgression } from '.
import { joinSessionNoProg } from './lib/session-noprog.js'
import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill, historyAsOf, sessionHistory } from './lib/backfill.js'
-import { moveWorkout, sameWorkout, startTimeOf, durationMinOf, setWorkoutDuration } from './lib/workout-date.js'
-import { editCompletedSession, editLeftEmpty, editedRecord } from './lib/session-edit.js'
+import { moveWorkout, sameWorkout, startTimeOf, durationMinOf, setWorkoutDuration, rebuildPrHistory } from './lib/workout-date.js'
+import { editCompletedSession, editLeftEmpty, editedRecord, editChangesNothing } from './lib/session-edit.js'
import { stampWorkout } from './lib/sync-merge.js'
import { weeklyWeights } from './lib/bodyweight.js'
import { workoutText } from './lib/workout-text.js'
@@ -1915,7 +1915,11 @@ export const workoutDateSheet = (w, onDone) => ui().openSheet(close => <WorkoutD
// do not depend on the length and are left alone.
function WorkoutDurationEdit({ w, onDone, close }) {
const [dur, setDur] = useState(durationMinOf(w))
+ // A cleared field reads as 0, and saving that made the session one minute long without a word
+ // (QA 1.3.9): it is refused with the reason under the field, and the saved length stays.
+ const durInvalid = !(dur >= 1)
const save = () => {
+ if (durInvalid) { toast(t('Enter how long it took — at least 1 minute.')); return }
let changed = false
update(s => {
const next = setWorkoutDuration(s.workouts, w, dur) // at least a minute, however the field was left
@@ -1929,7 +1933,9 @@ function WorkoutDurationEdit({ w, onDone, close }) {
return <>
<h3>{t('Change duration')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Forgot to finish on time? Set how long the session really took. It keeps its start time and its sets.')}</div>
- <Stepper label={t('Duration')} unit={t('min')} value={dur} step={5} min={1} decimal={false} onChange={v => setDur(Math.round(v))} />
+ {/* min 0, not 1: the stepper would put a cleared field back to 1 as it lost focus to Save. */}
+ <Stepper label={t('Duration')} unit={t('min')} value={dur} step={5} min={0} decimal={false} invalid={durInvalid} onChange={v => setDur(Math.round(v))} />
+ {durInvalid && <div className="small" style={{ color: 'var(--red)', marginTop: 6 }}>{t('Enter how long it took — at least 1 minute.')}</div>}
<div style={{ height: 18 }} />
<Button variant="primary" onClick={save}>{t('Save')}</Button>
</>
@@ -2203,6 +2209,7 @@ function LogPastWorkout({ initial, close }) {
}
const submit = () => {
if (!date || date > today) { toast(t('Pick a day up to today')); return }
+ if (!(dur >= 1)) { toast(t('Enter how long it took — at least 1 minute.')); return }
const existing = workoutsOn(st, date)
if (!existing.length) { go(null); return }
ui().openSheet(c => <SameDayChoice iso={date} existing={existing} close={c}
@@ -2216,7 +2223,8 @@ function LogPastWorkout({ initial, close }) {
<input type="date" className="timef" value={date} max={today} onChange={e => setDate(e.target.value)} /></Row>
<Row icon="clock" title={t('Start time')}>
<input type="time" className="timef" value={time} onChange={e => setTime(e.target.value)} /></Row>
- <Stepper label={t('Duration')} unit={t('min')} value={dur} step={5} min={1} decimal={false} onChange={v => setDur(Math.round(v))} />
+ <Stepper label={t('Duration')} unit={t('min')} value={dur} step={5} min={0} decimal={false} invalid={!(dur >= 1)} onChange={v => setDur(Math.round(v))} />
+ {!(dur >= 1) && <div className="small" style={{ color: 'var(--red)', marginTop: 6 }}>{t('Enter how long it took — at least 1 minute.')}</div>}
<div style={{ height: 8 }} />
<SelectRow icon="dumbbell" title={t('Routine')} value={routineId} options={options} onChange={setRoutineId} />
<div style={{ height: 18 }} />
@@ -2562,18 +2570,20 @@ export function saveWorkoutEdits(onExit = () => nav('/history')) {
}
export function exitWorkoutEdit(onExit = () => nav('/history')) {
+ const leave = () => {
+ useStore.getState().discardHistoryEdit()
+ useUI.getState().stopRest()
+ useUI.getState().stopWork()
+ onExit()
+ }
+ // Nothing to save: closing just closes, as it does for a workout only looked at.
+ if (editChangesNothing(S())) { leave(); return }
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>
+ <Button onClick={() => { close(); leave() }}>{t("Don't save")}</Button>
<div style={{ height: 8 }} />
<Button variant="ghost" className="dim" onClick={close}>{t('Keep editing')}</Button>
</>, { kind: 'center' })
@@ -2620,8 +2630,10 @@ function doFinishWorkout() {
const past = !!A.backfill
const prs = []
const e1prs = []
- // A workout logged into the past cannot claim records against the history that came after
- // it, so a backfilled session reports none and leaves the confirmed weights alone.
+ // A workout logged into the past is held against the history before it, the way an edit of a
+ // saved one is (rebuildPrHistory, below): it gains a badge it leads with, and a later session
+ // it outdoes loses its own. It used to report none at all while the editor's Save awarded them
+ // (QA 1.3.9). The confirmed weights are left alone either way.
if (!past) A.entries.forEach(e => {
const loads = e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w).filter(w => w > 0)
const mx = loads.length ? loads.reduce((a, b) => betterWeight(e.id, a, b)) : 0
@@ -2637,9 +2649,14 @@ function doFinishWorkout() {
snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null,
})
w.vol = workoutVolume(w)
+ let shown = w
update(s => {
if (past) {
- s.workouts = completeBackfill(s.workouts, A, w)
+ const replaced = A.backfill.replaceId ? s.workouts.find(x => x.id === A.backfill.replaceId) : null
+ const touched = [...new Set([...(replaced?.entries || []), ...w.entries].map(e => e?.id).filter(id => id != null))]
+ s.workouts = rebuildPrHistory(completeBackfill(s.workouts, A, w), touched, w)
+ shown = s.workouts.find(x => x === w || (w.id != null && x.id === w.id)) || w
+ prs.push(...[...(shown.prs || [])])
} else {
w.entries.forEach(e => {
const mx = bestWeightForEntry(e)
@@ -2652,5 +2669,5 @@ function doFinishWorkout() {
useStore.getState().autoBackupNow()
useUI.getState().stopRest()
beep(snd(), 880, 0.15); beep(snd(), 1100, 0.15, 0.18); beep(snd(), 1320, 0.3, 0.36)
- ui().openSheet(close => <FinishSummary w={w} prs={prs} e1prs={e1prs} close={close} />, { kind: 'center', locked: true })
+ ui().openSheet(close => <FinishSummary w={shown} prs={prs} e1prs={e1prs} close={close} />, { kind: 'center', locked: true })
}
diff --git a/frontend/src/sheets.missed-day.test.jsx b/frontend/src/sheets.missed-day.test.jsx
index 7b66a9a52..6bb693e71 100644
--- a/frontend/src/sheets.missed-day.test.jsx
+++ b/frontend/src/sheets.missed-day.test.jsx
@@ -111,7 +111,10 @@ describe('logging a missed planned day', () => {
act(() => finishWorkout())
expect(S().active).toBeNull()
const [w] = S().workouts
- expect(w).toMatchObject({ d: '2026-09-14', routineIds: ['A', 'B'], prs: [] })
+ expect(w).toMatchObject({ d: '2026-09-14', routineIds: ['A', 'B'] })
+ // Nothing logged before it: every loaded lift in it leads, and gets its badge the way Save in
+ // the editor would give it one (QA 1.3.9 — a backfilled finish used to award none).
+ expect(w.prs).toEqual(w.entries.filter(e => e.sets.some(x => x.w > 0)).map(e => e.id))
expect(new Date(w.start).getHours()).toBe(18)
expect(w.entries.map(e => [e.rid, e.sets.every(s => s.done)])).toEqual([['A', true], ['B', true]])
expect(w.entries[0].planned).toMatchObject({ sets: 2, reps: 10 })
@@ -152,3 +155,32 @@ describe('logging a missed planned day', () => {
expect(host.textContent).toContain('Freestyle')
})
})
+
+// QA 1.3.9: a past workout finished with no badges, while the same sets saved from the editor
+// earned them. Both now go through rebuildPrHistory: the logged day gains the badge it leads with
+// against what came before it, and a later session it outdoes loses its own.
+describe('badges on a workout logged into the past', () => {
+ const pushed = (id, d, w, prs = []) => ({
+ id, d, start: new Date(d + 'T18:00:00').getTime(), end: new Date(d + 'T19:00:00').getTime(), name: 'Push',
+ routineIds: ['A'], prs, entries: [{ id: BENCH, rid: 'A', target: { sets: 1, reps: 10, weight: w, mode: 'reps' },
+ sets: [{ w, r: 10, done: true }] }],
+ })
+ it('awards what the day leads with and takes the badge from a later session it outdoes', () => {
+ install({ workouts: [pushed('fri', '2026-09-11', 50, [BENCH]), pushed('tue', '2026-09-15', 52.5, [BENCH])] })
+ dayOverrideSheet('2026-09-14')
+ tapInTopSheet('Log this workout')
+ tapInTopSheet('Continue')
+ act(() => { useStore.getState().update(s => {
+ s.active.entries = markAllSetsDone(s.active.entries).map(e => e.id === BENCH
+ ? { ...e, sets: e.sets.map(x => (x.phase === 'warmup' ? x : { ...x, w: 60 })) }
+ : e)
+ }) })
+ act(() => finishWorkout())
+ const byDay = Object.fromEntries(S().workouts.map(w => [w.d, w.prs]))
+ expect(byDay['2026-09-14']).toContain(BENCH)
+ expect(byDay['2026-09-15']).not.toContain(BENCH) // 52.5 no longer leads what came before it
+ expect(byDay['2026-09-11']).toContain(BENCH)
+ // The summary names it.
+ expect(mountTopSheet().textContent).toContain('New PR:')
+ })
+})
diff --git a/frontend/src/sheets.workoutdate.test.jsx b/frontend/src/sheets.workoutdate.test.jsx
index 5d649bff1..440ded15a 100644
--- a/frontend/src/sheets.workoutdate.test.jsx
+++ b/frontend/src/sheets.workoutdate.test.jsx
@@ -233,16 +233,25 @@ describe('changing the duration of a saved workout', () => {
expect(after.end - after.start).toBe(75 * 60000)
})
- it('a field left empty or at 0 comes back as one minute, and saves as one', () => {
- const host = render(() => workoutDurationSheet(history()[1]))
+ // QA 1.3.9: a cleared field was put back to 1 as it lost focus to Save, and the session saved as
+ // one minute long without a word. It is refused now, with the reason, and the length is kept.
+ it('refuses a field left empty or at 0, says why, and keeps the saved length', () => {
+ const before = history()[1]
+ const host = render(() => workoutDurationSheet(before))
const field = host.querySelector('input.num')
- act(() => { type(field, '0') })
- expect(field.value).toBe('0')
- act(() => { field.dispatchEvent(new FocusEvent('focusout', { bubbles: true })) })
- expect(field.value).toBe('1')
+ for (const typed of ['', '0']) {
+ act(() => { type(field, typed) })
+ act(() => { field.dispatchEvent(new FocusEvent('focusout', { bubbles: true })) })
+ expect(field.value === '' || field.value === '0', typed).toBe(true)
+ expect(host.textContent).toContain('Enter how long it took — at least 1 minute.')
+ act(() => { button(host, 'Save').click() })
+ expect(history()[1]).toEqual(before)
+ expect(useUI.getState().toast).toHaveBeenLastCalledWith('Enter how long it took — at least 1 minute.')
+ }
+ act(() => { type(field, '40') })
+ expect(host.textContent).not.toContain('at least 1 minute')
act(() => { button(host, 'Save').click() })
- const after = history()[1]
- expect(after.end - after.start).toBe(60000)
+ expect(history()[1].end - history()[1].start).toBe(40 * 60000)
})
it('saving the same length closes and touches nothing', () => {