Merge !92: fix: capture working weight automatically

This commit is contained in:
Duarte Santos committed 2026-09-04 16:53:52 +02:00
commit f00400206d
6 files changed
+131 -51

No files matched your search

+3 -1
View File
@@ -1,11 +1,13 @@
// The persisted boundary for a finished session. Keep this pure so compatibility tests can
// exercise the exact shape the UI writes without mounting React or mutating store state.
import { bestWeightForEntry } from './history.js'
export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snapshotFor } = {}) {
const entries = (active?.entries || []).map(entry => {
const completed = {
id: entry.id,
sets: entry.sets,
topW: entry.topW || null,
topW: bestWeightForEntry(entry) || null,
target: entry.target || null,
}
const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null
+30
View File
@@ -15,6 +15,36 @@ describe('completed workout boundary', () => {
})
})
it('derives topW from the highest completed non-warm-up work set, not stale entry data', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
entries: [{
id: '0025', topW: 80, target: { mode: 'reps', sets: 2, reps: 8 },
sets: [
{ phase: 'warmup', done: true, w: 120, r: 8 },
{ done: true, w: 75, r: 8 },
{ done: true, w: 85, r: 7 },
{ done: false, w: 100, r: 8 },
],
}],
}
expect(buildCompletedWorkout(active).entries[0].topW).toBe(85)
expect(buildCompletedWorkout({
...active,
entries: [{ ...active.entries[0], topW: 120 }],
}).entries[0].topW).toBe(85)
})
it('keeps a legacy topW when old completed rows have no usable weight', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
entries: [{ id: '0025', topW: 60, sets: [{ done: true, r: 8 }] }],
}
expect(buildCompletedWorkout(active).entries[0].topW).toBe(60)
})
it('persists progression exclusion only for a marked session', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Deload', bw: 80,
+14 -10
View File
@@ -626,20 +626,24 @@ export function bestWeightForEntry(entry = {}) {
? entry.sets.filter(s => phaseForSet(s) === 'work')
: []
const repsRows = metricRowsForEntry(entry, 'reps')
if (!repsRows.length) {
return workRows.reduce((best, set) => {
if (set?.done !== true || isWarmupRow(set)) return best
const weight = Number(set.w)
return Number.isFinite(weight) && weight > best ? weight : best
}, 0)
}
// Reps rows are the authoritative load metric for a mixed entry. Otherwise use every
// completed work row (timed holds can carry an added load too).
const completedRows = repsRows.length
? repsRows
: workRows.filter(set => set?.done === true && !isWarmupRow(set))
let best = 0
repsRows.forEach(set => {
let hasUsableWeight = false
completedRows.forEach(set => {
const weight = Number(set?.w)
if (Number.isFinite(weight) && weight > best) best = weight
if (!Number.isFinite(weight)) return
hasUsableWeight = true
if (weight > best) best = weight
})
// A real completed row, including an explicit zero for an unloaded bodyweight set, always
// wins. A manual topW is only useful for old records whose rows did not carry a usable load.
if (hasUsableWeight) return best
const parentMode = modeForSet({}, target)
const hasNonRepsWorkRow = workRows.some(set => modeForSet(set, target) !== 'reps')
const hasWarmupRow = Array.isArray(entry.sets) && entry.sets.some(isWarmupRow)
+2 -2
View File
@@ -4,7 +4,7 @@ import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js'
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js'
import { beep, vibrate } from './lib/sound.js'
import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
@@ -1740,7 +1740,7 @@ function doFinishWorkout() {
s.workouts = completeBackfill(s.workouts, A, w)
} else {
w.entries.forEach(e => {
const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0)
const mx = bestWeightForEntry(e)
if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } }
})
s.workouts.push(w)
+15 -22
View File
@@ -4,14 +4,14 @@ import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { usesBar, barWeightFor, plateSplit } from '../lib/bar.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement, stepWeight } from '../lib/progression.js'
@@ -107,8 +107,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// Only worth surfacing while there is still work left: once the exercise is finished, a note
// telling you what to do in it is behind you, and the block is already long.
const pinnedNote = entry.sets.some(s => !s.done) ? pinnedNoteFor(S, entry.id) : null
// The same number the "confirm your working weight" sheet calls your best, so the two
// never disagree inside one session: heaviest logged set, or the working weight you kept.
// The number is the heaviest logged set, or the working weight you kept.
const best = cardio ? 0 : Math.max(bestWeightFor(S, entry.id), (S.exWeights[entry.id] || {}).w || 0)
// What the progression policy decided for this session, and why (issue #17). Computed when
// the session was built so the reason matches the numbers already in the rows.
@@ -550,25 +549,24 @@ function ActiveWorkout() {
const toggle = (idx, i) => {
const m = modeAt(idx)
const cardioEntry = m === 'cardio'
let askTop = false, exJustDone = false, workoutDone = false, checked = false
mutEntry(idx, e => {
let exJustDone = false, workoutDone = false, checked = false
update(s => {
const e = s.active.entries[idx]
e.sets[i].done = !e.sets[i].done
checked = e.sets[i].done
if (e.sets[i].done) {
beep(S.sound, 1040, 0.12); vibrate(30)
const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done))
if (unitDone) workoutDone = !nextUnfinishedUnit(A.entries, supersetUnits(A.entries), idx)
// Only loaded reps training has a "working weight" worth confirming — a bodyweight
// plank has nothing to put in that slider, and neither does a set of push-ups
// (issue #32: the fewest taps that still record what happened).
const loaded = m === 'reps' && !(isBw({ ...(e.target || {}), id: e.id }) && !e.sets.some(x => x.w > 0))
if (e.sets.every(x => x.done)) { exJustDone = true; if (loaded && !e.asked) { e.asked = true; askTop = true } }
if (e.sets.every(x => x.done)) {
exJustDone = true
const mx = bestWeightForEntry(e)
e.topW = mx || null
if (!s.active.backfill && mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: todayISO() } }
}
}
})
// reps: topWeight first (it chains into the finish/continue prompt on the last unit).
// cardio/timed or already-confirmed: go straight to the prompt.
if (askTop) topWeightSheet(idx)
else if (workoutDone) workoutCompleteSheet()
}, true)
if (workoutDone) workoutCompleteSheet()
else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged'))
else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged'))
@@ -604,7 +602,6 @@ function ActiveWorkout() {
// stopRest() first so a rest that belongs after this set replaces the one that was running.
if (freshUnitDone) stopRest()
if (!freshUnit || freshUnit.length <= 1) {
if (freshUnitDone && !askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
@@ -612,11 +609,7 @@ function ActiveWorkout() {
const step = supersetFlowStep(fresh.entries, freshUnit, idx)
if (!step) return
if (step.unitDone) {
if (nextUnit?.length) {
// The top-weight sheet's explicit "Just close" path owns the choice not to advance.
if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup) startRest(restSec, idx)
}
if (nextUnit?.length && !restBeforeWarmup) startRest(restSec, idx)
} else {
if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx })
if (step.roundDone) startRest(restSec, idx)
+67 -16
View File
@@ -138,6 +138,13 @@ async function toggleSet(index) {
await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressNext() {
const button = [...container.querySelectorAll('button')]
.find(button => button.textContent.trim() === 'Next')
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressProgression(index = 0) {
const button = container.querySelectorAll('.progline')[index]
expect(button).toBeTruthy()
@@ -206,8 +213,50 @@ describe('Workout set completion flow', () => {
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('auto-captures a completed weighted exercise without prompting, leaving navigation to Next', async () => {
await mount([exercise('plain-bench', [false]), exercise('next', [false])])
await toggleSet(0)
expect(mocks.S.active.entries[0].topW).toBe(60)
expect(mocks.S.exWeights['plain-bench'].w).toBe(60)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
await pressNext()
expect(mocks.S.active.cur).toBe(1)
})
it('auto-captures superset members without prompting, then leaves the completed unit for Next', async () => {
const group = 'superset-1'
await mount([
exercise('superset-a', [false], { sg: group }),
exercise('superset-b', [false], { sg: group }),
exercise('next', [false]),
])
await toggleSet(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
await rerender()
await toggleSet(1)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
await pressNext()
expect(mocks.S.active.cur).toBe(2)
})
it.each(['warmup', 'warm-up', 'warm_up'])(
'does not start transition rest before an incomplete %s row in the next ordinary exercise',
'does not navigate or start transition rest before an incomplete %s row in the next ordinary exercise',
async phase => {
await mount([
exercise('current', [false], { asked: true }),
@@ -222,12 +271,12 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
},
)
it('does not start transition rest when a completed superset advances to an incomplete warm-up', async () => {
it('does not navigate or start transition rest when a completed superset meets an incomplete warm-up', async () => {
await mount([
exercise('superset-a', [true], { sg: 'group', asked: true }),
exercise('superset-b', [false], { sg: 'group', asked: true }),
@@ -242,11 +291,11 @@ describe('Workout set completion flow', () => {
await toggleSet(1)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('does not start transition rest before a warm-up while top-weight confirmation owns navigation', async () => {
it('leaves the completed ordinary exercise selected without transition rest before an incomplete warm-up', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('next', [false, false], {
@@ -260,7 +309,7 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
})
@@ -285,7 +334,7 @@ describe('Workout set completion flow', () => {
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => {
it('leaves a completed superset selected without opening a top-weight sheet', async () => {
const group = 'superset-1'
await mount([
exercise('superset-a', [true, true, true], { sg: group, asked: true }),
@@ -294,12 +343,12 @@ describe('Workout set completion flow', () => {
], 1)
await toggleSet(5)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(1)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('skips completed intervening units and selects the next unfinished superset as one unit', async () => {
it('does not auto-select an unfinished superset after completing an ordinary exercise', async () => {
await mount([
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
exercise('already-done', [true], { asked: true }),
@@ -309,13 +358,13 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.toast).toHaveBeenCalledWith('Hold logged')
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('wraps to earlier unfinished work instead of showing a false completion prompt', async () => {
it('does not auto-select earlier unfinished work after completing an ordinary exercise', async () => {
await mount([
exercise('pending-earlier', [false], { asked: true }),
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
@@ -323,12 +372,12 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('keeps top-weight confirmation in control without declaring completion while work remains', async () => {
it('leaves a completed ordinary exercise selected without declaring completion while work remains', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('pending', [false], { asked: true }),
@@ -336,9 +385,10 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('shows workout completion only when no unfinished unit remains', async () => {
@@ -350,6 +400,7 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.workoutCompleteSheet).toHaveBeenCalledOnce()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
})
})
@@ -361,7 +412,7 @@ describe('Workout add exercise flow', () => {
active: { routineId: 'routine-1' },
routines: [{ id: 'routine-1', ex: [] }],
}],
])('inserts after the current unit and continues to pending work in a %s session', async (_label, overrides) => {
])('inserts after the current unit and leaves the inserted exercise selected after completion in a %s session', async (_label, overrides) => {
await mount([
exercise('current', [true], { asked: true }),
exercise('pending', [false], { asked: true }),
@@ -379,7 +430,7 @@ describe('Workout add exercise flow', () => {
await toggleSet(0)
expect(mocks.S.active.entries[1].sets[0].done).toBe(true)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
})