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
fix: aggregate repeated exercises consistently in history and stats
Space-Hermes2b47058d6df1
diff --git a/frontend/src/lib/exercise-history.js b/frontend/src/lib/exercise-history.jsindex 72b205b76..0e1238763 100644--- a/frontend/src/lib/exercise-history.js+++ b/frontend/src/lib/exercise-history.js@@ -1,4 +1,4 @@-import { metricModeForEntry, metricRowsForEntry, bestWeightForEntry, modeOf } from './history.js'+import { metricEntriesForExercise, bestWeightForEntry, completedRepsOf, modeOf } from './history.js'import { completedVolumeOf } from './workout-model.js'import { bestSetOf } from './onerm.js'@@ -32,11 +32,14 @@ export function exerciseHistory(S, exId, { limit = HISTORY_SESSIONS } = {}) {// inserted by date rather than appended.const logged = []workouts.forEach(w => {- const en = (w.entries || []).find(e => e.id === exId)- if (!en) return- const mode = metricModeForEntry(en)- if (!mode) return- const rows = metricRowsForEntry(en, mode)+ // A combined session can contain the same exercise more than once. Keep one dated+ // snapshot, but read every completed occurrence that shares the session's latest mode.+ const entries = metricEntriesForExercise(w, exId)+ if (!entries.length) return+ const mode = entries.at(-1).mode+ const sameMode = entries.filter(item => item.mode === mode)+ const rows = sameMode.flatMap(item => item.rows)+ const en = { ...sameMode.at(-1).entry, sets: rows }if (rows.length) logged.push({ w, en, mode, rows })})logged.sort((a, b) => startOf(a.w) - startOf(b.w))@@ -50,7 +53,7 @@ export function exerciseHistory(S, exId, { limit = HISTORY_SESSIONS } = {}) {const valueOf = ({ en, rows }) => {if (metric === 'min') return rows.reduce((a, s) => a + (Number(s.min) || 0), 0)if (metric === 'sec') return Math.max(0, ...rows.map(s => Number(s.sec) || 0))- if (metric === 'reps') return Math.max(0, ...rows.map(s => Number(s.r) || 0))+ if (metric === 'reps') return Math.max(0, ...rows.map(completedRepsOf))return bestWeightForEntry(en)}diff --git a/frontend/src/lib/exercise-history.test.js b/frontend/src/lib/exercise-history.test.jsindex a6b8e2159..384b3f65c 100644--- a/frontend/src/lib/exercise-history.test.js+++ b/frontend/src/lib/exercise-history.test.js@@ -109,4 +109,44 @@ describe('exerciseHistory', () => {expect(h.points).toHaveLength(1)expect(h.sessions.map(s => [s.id, s.value])).toEqual([['b', 20], ['a', null]])})++ it('aggregates duplicate occurrences into one dated snapshot and keeps only completed work', () => {+ const first = { id: 'bench', target: { mode: 'reps' }, sets: [warm(120, 5), work(60, 5)] }+ const later = { id: 'bench', target: { mode: 'reps' }, sets: [work(80, 5), work(200, 5, false)] }+ const S = { workouts: [{ id: 'combined', d: iso(4), start: T0 + 4 * DAY, entries: [first, later] }] }+ const before = structuredClone(S)+ const h = exerciseHistory(S, 'bench')+ expect(h).toMatchObject({ total: 1, best: 80, prId: 'combined' })+ expect(h.sessions[0]).toMatchObject({ id: 'combined', d: iso(4), value: 80, volume: 700 })+ expect(h.sessions[0].sets).toEqual([work(60, 5), work(80, 5)])+ expect(h.sessions[0].e1rm).toBe(estimate1RM(80, 5))+ expect(S).toEqual(before)+ })++ it('uses completed per-side limbs from duplicate occurrences without combining modes', () => {+ const partialSide = {+ id: 'bench', target: { mode: 'reps', side: true }, sets: [{ phase: 'work', w: 100, r: 10, done: false,+ sides: { L: { w: 100, r: 5, done: true }, R: { w: 200, r: 5, done: false } } }],+ }+ const timed = { id: 'bench', target: { mode: 'time' }, sets: [{ sec: 60, done: true }] }+ const S = { workouts: [{ id: 'sides', d: iso(5), start: T0 + 5 * DAY, entries: [timed, partialSide] }] }+ const h = exerciseHistory(S, 'bench')+ expect(h).toMatchObject({ total: 1, mode: 'reps', metric: 'weight', best: 100 })+ expect(h.sessions[0]).toMatchObject({ value: 100, volume: 500, e1rm: estimate1RM(100, 5) })+ expect(h.sessions[0].sets).toHaveLength(1)+ expect(h.sessions[0].sets[0]).toBe(partialSide.sets[0])+ })++ it('aggregates timed and cardio duplicates by their own metric', () => {+ const hold = { id: 'hold', d: iso(6), start: T0 + 6 * DAY, entries: [+ { id: 'plank', target: { mode: 'time' }, sets: [{ sec: 30, done: true }] },+ { id: 'plank', target: { mode: 'time' }, sets: [{ sec: 45, done: true }] },+ ] }+ const run = { id: 'run', d: iso(7), start: T0 + 7 * DAY, entries: [+ { id: 'run', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 9, done: true }] },+ { id: 'run', target: { mode: 'cardio' }, sets: [{ min: 5, speed: 10, done: true }] },+ ] }+ expect(exerciseHistory({ workouts: [hold] }, 'plank').sessions[0]).toMatchObject({ value: 45, volume: null })+ expect(exerciseHistory({ workouts: [run] }, 'run').sessions[0]).toMatchObject({ value: 25, volume: null })+ })})diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.jsindex ce3e19b89..45fa223a9 100644--- a/frontend/src/lib/history.js+++ b/frontend/src/lib/history.js@@ -1,7 +1,7 @@// Pure helpers over the state object S (ported 1:1 from the vanilla app).import { todayISO, isoOf, weekKey, weekStartOf, fmtNum } from './format.js'import { isCardio, isBodyweightEq } from './exercises.js'-import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, completedVolumeOf, nextDropWeight, splitBurstReps, makeSideSet, isSideSet, syncSideAggregate } from './workout-model.js'+import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, completedVolumeOf, hasCompletedWork, nextDropWeight, splitBurstReps, makeSideSet, isSideSet, syncSideAggregate } from './workout-model.js'const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}// Completed-state-independent work rows whose authoritative mode matches the requested mode.const workRowsForMode = (entry = {}, mode = 'reps') => {@@ -687,7 +687,7 @@ export function workSetsDone(w) {}const METRIC_MODES = ['reps', 'time', 'cardio']-const completedRowsForMode = (entry, mode) => workRowsForMode(entry, mode).filter(s => s.done === true && !isWarmupRow(s))+const completedRowsForMode = (entry, mode) => workRowsForMode(entry, mode).filter(s => hasCompletedWork(s) && !isWarmupRow(s))export function metricRowsForEntry(entry, mode) {const requested = typeof mode === 'string' ? mode.trim().toLowerCase() : ''@@ -704,6 +704,30 @@ export function metricModeForEntry(entry, fallback = null) {return modeForEntry(entry, fallback)}+/** Every saved occurrence of an exercise in one workout, in its stored order. */+export function entriesForExercise(workout, exId) {+ if (exId == null || exId === '') return []+ return (workout?.entries || []).filter(entry => entry?.id === exId)+}++/** Metric data for every occurrence in one workout, including legacy reps topW-only records. */+export function metricEntriesForExercise(workout, exId) {+ return entriesForExercise(workout, exId)+ .map(entry => ({ entry, mode: metricModeForEntry(entry) }))+ .map(({ entry, mode }) => ({ entry, mode, rows: mode ? metricRowsForEntry(entry, mode) : [] }))+ .filter(item => item.rows.length || (item.mode === 'reps' && bestWeightForEntry(item.entry) > 0))+}++/** Total reps from one completed row, counting only completed limbs of a per-side row. */+export function completedRepsOf(set = {}) {+ if (isSideSet(set)) {+ return [set.sides.L, set.sides.R]+ .filter(side => side?.done === true)+ .reduce((total, side) => total + Math.max(0, Number(side.r) || 0), 0)+ }+ return set?.done === true ? Math.max(0, Number(set.r) || 0) : 0+}+/** Best load from completed work rows, with a guarded reps-only legacy topW fallback. */export function bestWeightForEntry(entry = {}) {@@ -716,14 +740,19 @@ export function bestWeightForEntry(entry = {}) {// completed work row (timed holds can carry an added load too).const completedRows = repsRows.length? repsRows- : workRows.filter(set => set?.done === true && !isWarmupRow(set))+ : workRows.filter(set => hasCompletedWork(set) && !isWarmupRow(set))let best = 0let hasUsableWeight = falsecompletedRows.forEach(set => {- const weight = Number(set?.w)- if (!Number.isFinite(weight)) return- hasUsableWeight = true- if (weight > best) best = weight+ const completedSets = isSideSet(set)+ ? [set.sides.L, set.sides.R].filter(side => side?.done === true)+ : [set]+ completedSets.forEach(completedSet => {+ const weight = Number(completedSet?.w)+ 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, alwaysdiff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.jsindex 5fd3edae5..be691dd57 100644--- a/frontend/src/lib/history.test.js+++ b/frontend/src/lib/history.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, setsDone, setsDoneActive, setUnits, doneUnits, setUnitsTotal, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor, effectiveRoutineIds, effectiveRoutines, effectiveRoutineId, effectiveRoutine, lastEntryFor, entryExcluded } from './history.js'+import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, completedRepsOf, metricRowsForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, setsDone, setsDoneActive, setUnits, doneUnits, setUnitsTotal, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor, effectiveRoutineIds, effectiveRoutines, effectiveRoutineId, effectiveRoutine, lastEntryFor, entryExcluded } from './history.js'import { makeSideSet, setSideField, toggleSide } from './workout-model.js'import { EXDB } from './exercises.js'@@ -1055,6 +1055,17 @@ describe('per-side aggregate stays readable by existing consumers', () => {const s = toggleSide(toggleSide(setSideField(makeSideSet({ w: 15, r: 16 }), 'R', 'w', 17.5), 'L'), 'R')expect(bestWeightForEntry({ id: LIFT, target: { id: LIFT, side: true }, sets: [s] })).toBe(17.5)})++ it('uses only completed side loads and reps when the other limb is unfinished', () => {+ const partial = {+ id: LIFT,+ target: { id: LIFT, mode: 'reps', side: true },+ sets: [{ phase: 'work', w: 200, r: 10, done: false,+ sides: { L: { w: 100, r: 5, done: true }, R: { w: 200, r: 5, done: false } } }],+ }+ expect(bestWeightForEntry(partial)).toBe(100)+ expect(completedRepsOf(metricRowsForEntry(partial, 'reps')[0])).toBe(5)+ })})describe('per-side set counters', () => {diff --git a/frontend/src/lib/onerm.js b/frontend/src/lib/onerm.jsindex 2602118e0..b9cb89a8b 100644--- a/frontend/src/lib/onerm.js+++ b/frontend/src/lib/onerm.js@@ -1,4 +1,5 @@-import { isWarmupRow } from './workout-model.js'+import { isSideSet } from './workout-model.js'+import { entriesForExercise, metricRowsForEntry } from './history.js'// Estimated one-rep max (issue #18).//// Deliberately knows nothing about the exercise database: an estimate needs a weight AND a@@ -44,22 +45,33 @@ export function estimate1RM(w, r, formula = DEFAULT_FORMULA) {// exercise, with no rep count attached, so it cannot produce an estimate.export function bestSetOf(entry, formula = DEFAULT_FORMULA) {let best = null- ;(entry?.sets || []).forEach(s => {- if (!s.done || isWarmupRow(s)) return- const est = estimate1RM(s.w, s.r, formula)- if (est !== null && (!best || est > best.est)) best = { est, w: Number(s.w), r: Math.round(Number(s.r)) }+ metricRowsForEntry(entry, 'reps').forEach(s => {+ const sets = isSideSet(s)+ ? [s.sides.L, s.sides.R].filter(side => side?.done === true)+ : [s]+ sets.forEach(set => {+ const est = estimate1RM(set.w, set.r, formula)+ if (est !== null && (!best || est > best.est)) best = { est, w: Number(set.w), r: Math.round(Number(set.r)) }+ })})return best}+function bestSetOfEntries(entries, formula = DEFAULT_FORMULA) {+ let best = null+ for (const entry of entries || []) {+ const candidate = bestSetOf(entry, formula)+ if (candidate && (!best || candidate.est > best.est)) best = candidate+ }+ return best+}+// One point per workout in which the exercise produced an estimate — feeds the trend chart.// Chronological, matching the order workouts are appended in.export function e1rmSeries(S, exId, formula = DEFAULT_FORMULA) {const pts = [];(S.workouts || []).forEach(w => {- const entry = w.entries.find(e => e.id === exId)- if (!entry) return- const best = bestSetOf(entry, formula)+ const best = bestSetOfEntries(entriesForExercise(w, exId), formula)if (best) pts.push({ t: w.start, d: w.d, y: best.est, w: best.w, r: best.r })})return ptsdiff --git a/frontend/src/lib/onerm.test.js b/frontend/src/lib/onerm.test.jsindex e1c5c5dcb..4daa22902 100644--- a/frontend/src/lib/onerm.test.js+++ b/frontend/src/lib/onerm.test.js@@ -122,6 +122,27 @@ describe('e1rmSeries / best1RM', () => {expect(best1RM({ workouts: [] }, 'bench')).toBeNull()expect(best1RM({}, 'bench')).toBeNull()})++ it('takes the strongest duplicate occurrence once per dated workout', () => {+ const workouts = [{ d: '2026-02-01', start: 1, entries: [+ { id: 'bench', sets: [{ w: 60, r: 5, done: true }] },+ { id: 'bench', sets: [{ w: 100, r: 5, done: true }] },+ ] }]+ expect(e1rmSeries({ workouts }, 'bench')).toEqual([{ t: 1, d: '2026-02-01', y: 116.7, w: 100, r: 5 }])+ expect(best1RM({ workouts }, 'bench')).toMatchObject({ est: 116.7, w: 100, r: 5, d: '2026-02-01' })+ })++ it('estimates each completed per-side limb and leaves timed/cardio rows out', () => {+ const sides = { id: 'bench', target: { mode: 'reps', side: true }, sets: [{ w: 100, r: 10, done: false,+ sides: { L: { w: 100, r: 5, done: true }, R: { w: 90, r: 5, done: false } } }] }+ expect(bestSetOf(sides)).toEqual({ est: 116.7, w: 100, r: 5 })+ expect(e1rmSeries({ workouts: [{ start: 1, d: '2026-02-01', entries: [sides] }] }, 'bench'))+ .toEqual([{ t: 1, d: '2026-02-01', y: 116.7, w: 100, r: 5 }])+ expect(e1rmSeries({ workouts: [{ start: 1, d: '2026-02-01', entries: [+ { id: 'hold', target: { mode: 'time' }, sets: [{ sec: 60, w: 200, r: 5, done: true }] },+ { id: 'run', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 9, r: 5, done: true }] },+ ] }] }, 'hold')).toEqual([])+ })})describe('is1RMRecord', () => {diff --git a/frontend/src/lib/strength-exercises.js b/frontend/src/lib/strength-exercises.jsindex 0db827b13..946fa93a5 100644--- a/frontend/src/lib/strength-exercises.js+++ b/frontend/src/lib/strength-exercises.js@@ -7,10 +7,11 @@// catalogue-first (EXIDX), exactly like the fatigue/strength maps, falling back to the// logged snapshot (muscleWeights) for exercises no longer in the catalogue.import { best1RM } from './onerm.js'+import { entriesForExercise } from './history.js'import { STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, STRENGTH_FLOOR, halfLifeDecay } from './recovery.js'import { musclesOf } from './muscles.js'import { EXIDX } from './exercises.js'-import { isWarmupRow } from './workout-model.js'+import { hasCompletedWork, isWarmupRow } from './workout-model.js'import { exerciseNameFor } from './i18n-core.js'const round1 = value => Math.round(value * 10) / 10@@ -29,9 +30,8 @@ function lastWorkSetAt(S, id) {for (const workout of S?.workouts || []) {const ts = workout.start || new Date(workout.d).getTime()if (!Number.isFinite(ts) || ts <= latest) continue- const entry = (workout.entries || []).find(e => e.id === id)- if (!entry) continue- if ((entry.sets || []).some(s => s.done === true && !isWarmupRow(s))) latest = ts+ const entries = entriesForExercise(workout, id)+ if (entries.some(entry => (entry.sets || []).some(s => hasCompletedWork(s) && !isWarmupRow(s)))) latest = ts}return Number.isFinite(latest) ? latest : null}@@ -71,12 +71,52 @@ function resolvedExerciseName(entry) {return entry && typeof entry === 'object' && entry.n ? entry.n : null}-function firstEntryWithId(S, id) {- for (const workout of S?.workouts || []) {- const entry = (workout.entries || []).find(e => e.id === id)- if (entry) return entry+function workoutDay(workout) {+ const day = workout?.d+ return typeof day === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(day) ? day : null+}++function workoutTimestamp(workout) {+ if (Number.isFinite(workout?.start)) return workout.start+ const day = workoutDay(workout)+ const timestamp = day ? new Date(day + 'T12:00:00').getTime() : NaN+ return Number.isFinite(timestamp) ? timestamp : -Infinity+}++function entriesWithId(S, id) {+ let order = 0+ return (S?.workouts || []).flatMap(workout => entriesForExercise(workout, id).map(entry => ({+ entry,+ day: workoutDay(workout),+ timestamp: workoutTimestamp(workout),+ order: order++,+ })))+}++const hasSavedMetadata = entry => Boolean(+ entry?.n+ || (entry?.muscleWeights && Object.keys(entry.muscleWeights).length)+ || (entry?.muscleSnapshot && Object.keys(entry.muscleSnapshot).length),+)++function isNewerOccurrence(a, b) {+ if (!b) return true+ if (a.day && b.day && a.day !== b.day) return a.day > b.day+ if (a.day !== b.day) return !!a.day+ if (a.timestamp !== b.timestamp) return a.timestamp > b.timestamp+ return a.order > b.order+}++// Use the latest dated occurrence that carries a snapshot for display metadata, while keeping+// the latest dated occurrence as a fallback for old history. The catalogue still wins for built-ins.+function representativeEntry(occurrences) {+ let fallback = null+ let withMetadata = null+ for (const occurrence of occurrences) {+ if (isNewerOccurrence(occurrence, fallback)) fallback = occurrence+ if (hasSavedMetadata(occurrence.entry) && isNewerOccurrence(occurrence, withMetadata)) withMetadata = occurrence}- return null+ return (withMetadata || fallback)?.entry || null}/**@@ -93,7 +133,7 @@ export function strengthExerciseRows(S, now) {for (const id of ids) {const best = best1RM(S, id)if (!best) continue- const entry = firstEntryWithId(S, id)+ const entry = representativeEntry(entriesWithId(S, id))const lastAt = lastWorkSetAt(S, id)const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)rows.push({@@ -115,30 +155,25 @@ export function strengthExerciseRows(S, now) {* tapped muscle filters the list, the row still speaks for the exercise.*/export function strengthExerciseRowsForMuscle(S, now, slug) {- const workouts = S?.workouts || []const seen = new Map()- for (const workout of workouts) {- for (const entry of workout.entries || []) {- if (seen.has(entry.id)) continue- const weights = snapshotWeights(entry)- const weight = weights[slug]- if (!weight) continue- const best = best1RM(S, entry.id)- if (!best) continue- const lastAt = lastWorkSetAt(S, entry.id)- const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)- const primary = primaryMuscleOf(entry)- seen.set(entry.id, {- id: entry.id,- name: resolvedExerciseName(entry) || entry.id,- weight,- primary: primary ? primary.slug : null,- est: best.est,- estDate: best.d,- decay,- current: round1(best.est * decay),- })- }+ for (const metric of strengthExerciseRows(S, now)) {+ const entries = entriesWithId(S, metric.id)+ const entry = representativeEntry(entries)+ // A deleted custom exercise may have snapshots on more than one occurrence. The latest+ // metadata-bearing snapshot answers the muscle filter, without mutating either record.+ const weight = snapshotWeights(entry)[slug]+ if (!weight) continue+ const primary = primaryMuscleOf(entry)+ seen.set(metric.id, {+ id: metric.id,+ name: resolvedExerciseName(entry) || metric.id,+ weight,+ primary: primary ? primary.slug : null,+ est: metric.est,+ estDate: metric.estDate,+ decay: metric.decay,+ current: metric.current,+ })}return [...seen.values()].sort((a, b) => b.current - a.current || String(a.name).localeCompare(String(b.name)))}diff --git a/frontend/src/lib/strength-exercises.test.js b/frontend/src/lib/strength-exercises.test.jsindex d76518628..77beb0f7c 100644--- a/frontend/src/lib/strength-exercises.test.js+++ b/frontend/src/lib/strength-exercises.test.js@@ -130,6 +130,47 @@ describe('strengthExerciseRows', () => {expect(benchRow.decay).toBeCloseTo(benchDecay, 4)expect(benchRow.current).toBeCloseTo(Math.round(102 * benchDecay * 10) / 10, 2)})++ it('uses a later completed duplicate for strength and its saved metadata', () => {+ const preparation = {+ id: 'deleted-duplicate',+ muscleSnapshot: { n: 'Preparation copy', muscleWeights: { chest: 1 } },+ sets: [{ phase: 'warmup', w: 200, r: 5, done: true }],+ }+ const work = {+ id: 'deleted-duplicate',+ muscleSnapshot: { n: 'Working copy', muscleWeights: { back: 1 } },+ sets: [{ phase: 'work', w: 100, r: 5, done: true }],+ }+ const S = unitState([workout(3, [preparation, work])])+ const before = structuredClone(S)+ const row = strengthExerciseRows(S, NOW)[0]+ expect(row).toMatchObject({ id: 'deleted-duplicate', name: 'Working copy', primary: 'back', est: 116.7, current: 116.7 })+ expect(strengthExerciseRowsForMuscle(S, NOW, 'back')[0]).toMatchObject({ id: 'deleted-duplicate', weight: 1 })+ expect(strengthExerciseRowsForMuscle(S, NOW, 'chest')).toEqual([])+ expect(S).toEqual(before)+ })++ it('chooses deleted-exercise metadata from the newest workout date', () => {+ const newest = {+ id: 'deleted-by-date',+ muscleSnapshot: { n: 'Newest copy', muscleWeights: { back: 1 } },+ sets: [{ phase: 'work', w: 100, r: 5, done: true }],+ }+ const older = {+ id: 'deleted-by-date',+ muscleSnapshot: { n: 'Older copy', muscleWeights: { chest: 1 } },+ sets: [{ phase: 'work', w: 90, r: 5, done: true }],+ }+ const S = unitState([+ workout(3, [newest]),+ workout(30, [older]),+ ])+ const row = strengthExerciseRows(S, NOW)[0]+ expect(row).toMatchObject({ id: 'deleted-by-date', name: 'Newest copy', primary: 'back' })+ expect(strengthExerciseRowsForMuscle(S, NOW, 'back')[0]).toMatchObject({ name: 'Newest copy', weight: 1 })+ expect(strengthExerciseRowsForMuscle(S, NOW, 'chest')).toEqual([])+ })})describe('strengthExerciseRowsForMuscle', () => {diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsxindex 636e26640..5ac033184 100644--- a/frontend/src/views/Stats.jsx+++ b/frontend/src/views/Stats.jsx@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { EXIDX, matchExercise } from '../lib/exercises.js'-import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'+import { lastBW, streakWeeks, setLabel, modeOf, effortOf, entriesForExercise, metricEntriesForExercise, metricModeForEntry, bestWeightForEntry, completedRepsOf } from '../lib/history.js'import { fmtNum, fmtDate, fmtVol, todayISO, weekStartOf } from '../lib/format.js'import { t, exerciseNameFor, getLang } from '../lib/i18n.js'import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'@@ -299,6 +299,13 @@ export default function Stats() {const workouts = S.workoutsconst monthW = workouts.filter(w => String(w.d || '').slice(0, 7) === todayISO().slice(0, 7)).length+ const metricDataOf = (workout, id) => {+ const entries = metricEntriesForExercise(workout, id)+ const mode = entries.at(-1)?.mode || null+ const sameMode = entries.filter(item => item.mode === mode)+ const best = mode === 'reps' ? Math.max(0, ...sameMode.map(item => bestWeightForEntry(item.entry))) : 0+ return { mode, entries: sameMode, rows: sameMode.flatMap(item => item.rows), best }+ }const entryOf = id => workouts.flatMap(w => w.entries).find(e => e.id === id)const listOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]const firstAvailable = (...values) => {@@ -333,16 +340,18 @@ export default function Stats() {}const currentOf = id => {for (let i = workouts.length - 1; i >= 0; i--) {- const en = workouts[i].entries.find(e => e.id === id)- if (!en) continue- const mode = metricModeForEntry(en) || modeOf({ id })- const rows = metricRowsForEntry(en, mode)- const mx = mode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...rows.map(s => mode === 'cardio' ? (s.speed || 0) : mode === 'time' ? (s.sec || 0) : (s.w || 0)))+ const data = metricDataOf(workouts[i], id)+ if (!data.mode) continue+ const mode = data.mode+ const rows = data.rows+ const mx = mode === 'reps'+ ? data.best+ : Math.max(0, ...rows.map(s => mode === 'cardio' ? (s.speed || 0) : mode === 'time' ? (s.sec || 0) : (s.w || 0)))if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit }// Unloaded reps work still has a current figure — its rep count. Without this the whole// picker label went blank and the exercise sorted to the bottom as if it had no history.if (mode === 'reps') {- const reps = Math.max(0, ...rows.map(s => Number(s.r) || 0))+ const reps = Math.max(0, ...rows.map(completedRepsOf))if (reps > 0) return { mx: reps, unit: t('reps') }}}@@ -356,9 +365,11 @@ export default function Stats() {// target also contains timed/cardio work. Entries without reps rows use their selected mode.const curMode = curEx ? (() => {for (let i = workouts.length - 1; i >= 0; i--) {- const en = workouts[i].entries.find(e => e.id === curEx)- if (en) {- const mode = metricModeForEntry(en)+ const data = metricDataOf(workouts[i], curEx)+ if (data.mode) return data.mode+ const entries = entriesForExercise(workouts[i], curEx)+ for (let j = entries.length - 1; j >= 0; j--) {+ const mode = metricModeForEntry(entries[j])if (mode) return mode}}@@ -371,26 +382,22 @@ export default function Stats() {// them (issue #5). When nothing in an exercise's history was ever loaded, the progress IS// the rep count, so plot that. Add a weighted set later and it switches back to weight on// its own, which is also the honest reading: that is when load became the thing improving.- const repsOnly = curEx && curMode === 'reps' && !workouts.some(w => {- const en = w.entries.find(e => e.id === curEx)- return en && bestWeightForEntry(en) > 0- })- const bestRepsOf = en => Math.max(0, ...metricRowsForEntry(en, 'reps').map(s => Number(s.r) || 0))+ const repsOnly = curEx && curMode === 'reps' && !workouts.some(w =>+ entriesForExercise(w, curEx).some(en => bestWeightForEntry(en) > 0))const metric = s => curCardio ? (s.speed || 0) : curTimed ? (s.sec || 0) : (s.w || 0)const exUnit = curCardio ? 'km/h' : curTimed ? 's' : repsOnly ? t('reps') : S.unitlet exPts = [], exList = [], exBest = 0if (curEx) {workouts.forEach(w => {- const en = w.entries.find(e => e.id === curEx)- if (en) {- const loggedMode = metricModeForEntry(en)- if (loggedMode !== curMode) return- const doneSets = metricRowsForEntry(en, curMode)+ const data = metricDataOf(w, curEx)+ if (data.mode === curMode) {+ const doneSets = data.rows+ const representative = data.entries.at(-1)?.entryconst mx = curMode === 'reps'- ? (repsOnly ? bestRepsOf(en) : bestWeightForEntry(en))+ ? (repsOnly ? Math.max(0, ...doneSets.map(completedRepsOf)) : data.best): Math.max(0, ...doneSets.map(metric))if (mx > 0) {- exPts.push({ t: w.start, y: mx, d: w.d, sets: doneSets, target: en.target })+ exPts.push({ t: w.start, y: mx, d: w.d, sets: doneSets, target: representative?.target })if (mx > exBest) exBest = mx}}diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsxindex 402981f0f..ded42a26e 100644--- a/frontend/src/views/Stats.recovery.test.jsx+++ b/frontend/src/views/Stats.recovery.test.jsx@@ -19,6 +19,7 @@ const LEGACY_SNAPSHOT_ID = 'legacy-snapshot-only'const mocks = vi.hoisted(() => ({maps: [],+ charts: [],mapMounts: 0,S: {unit: 'kg', body: 'male', effort: 'rir', targetW: null,@@ -34,7 +35,10 @@ vi.mock('../sheets.jsx', () => ({bwSheet: () => {}, goalSheet: () => {}, calendarSheet: () => {}, workoutDetailSheet: () => {},WorkoutRow: () => React.createElement('div'), bwDeltaColor: () => 'inherit',}))-vi.mock('../components/LineChart.jsx', () => ({ default: () => React.createElement('div') }))+vi.mock('../components/LineChart.jsx', () => ({ default: props => {+ mocks.charts.push(props)+ return React.createElement('div')+} }))vi.mock('../components/Heatmap.jsx', () => ({ default: () => React.createElement('div') }))vi.mock('../components/Icon.jsx', () => ({ default: props => React.createElement('span', props) }))vi.mock('../components/BodyMap.jsx', () => ({@@ -138,6 +142,7 @@ function resetFixture(workouts = lifecycleWorkouts()) {mocks.S.bodyweight = []mocks.S.workouts = workoutsmocks.maps.length = 0+ mocks.charts.length = 0mocks.mapMounts = 0useUI.setState({ sheets: [] })}@@ -307,6 +312,62 @@ describe('Stats muscle recovery view runtime', () => {})describe('Stats exercise progress picker', () => {+ it('keeps a legacy reps record whose load is stored only in topW', async () => {+ resetFixture([workout('legacy-topw', BASE_NOW, [+ { id: '0025', target: { mode: 'reps' }, topW: 70, sets: [] },+ ])])+ await mountStats()++ const card = [...container.querySelectorAll('.card')].find(el => el.querySelector('h2')?.textContent.trim() === 'Exercise progress')+ expect(card.textContent).toContain('70 kg')+ const progressChart = mocks.charts.find(chart => chart.points?.some(point => point.y === 70))+ expect(progressChart?.points).toHaveLength(1)+ expect(progressChart.points[0].y).toBe(70)+ })++ it('keeps the strongest topW across repeated legacy records', async () => {+ resetFixture([workout('legacy-topw-duplicates', BASE_NOW, [+ { id: '0025', target: { mode: 'reps' }, topW: 70, sets: [] },+ { id: '0025', target: { mode: 'reps' }, topW: 60, sets: [] },+ ])])+ await mountStats()++ const card = [...container.querySelectorAll('.card')].find(el => el.querySelector('h2')?.textContent.trim() === 'Exercise progress')+ expect(card.textContent).toContain('70 kg')+ const progressChart = mocks.charts.find(chart => chart.points?.some(point => point.y === 70))+ expect(progressChart?.points).toHaveLength(1)+ expect(progressChart.points[0].y).toBe(70)+ })++ it('keeps a legacy topW when a modern occurrence shares the workout', async () => {+ resetFixture([workout('modern-and-legacy', BASE_NOW, [+ entry('0025', [set(true, { w: 50, r: 5 })]),+ { id: '0025', target: { mode: 'reps' }, topW: 70, sets: [] },+ ])])+ await mountStats()++ const card = [...container.querySelectorAll('.card')].find(el => el.querySelector('h2')?.textContent.trim() === 'Exercise progress')+ expect(card.textContent).toContain('70 kg')+ const progressChart = mocks.charts.find(chart => chart.points?.some(point => point.y === 70))+ expect(progressChart?.points).toHaveLength(1)+ expect(progressChart.points[0].y).toBe(70)+ })++ it('aggregates duplicate exercise occurrences into one progress point', async () => {+ resetFixture([workout('duplicate', BASE_NOW, [+ entry('0025', [set(true, { w: 60, r: 5 })]),+ entry('0025', [set(true, { w: 80, r: 5 })]),+ ])])+ await mountStats()++ const card = [...container.querySelectorAll('.card')].find(el => el.querySelector('h2')?.textContent.trim() === 'Exercise progress')+ expect(card.textContent).toContain('80 kg')+ const progressChart = mocks.charts.find(chart => chart.points?.some(point => point.y === 80))+ expect(progressChart?.points).toHaveLength(1)+ expect(progressChart.points[0].y).toBe(80)+ expect(card.textContent).toContain('60×5 80×5')+ })+it('filters with the shared exercise matcher and still selects from the mounted sheet', async () => {resetFixture(exercisePickerWorkouts())await mountStats()diff --git a/frontend/src/views/Stats.test.js b/frontend/src/views/Stats.test.jsindex 50f5ec758..6f6972642 100644--- a/frontend/src/views/Stats.test.js+++ b/frontend/src/views/Stats.test.js@@ -22,9 +22,10 @@ describe('Stats mixed-entry metric contract', () => {expect(source).toContain('{...tappable(() => onExercise && onExercise(row.id))}')})- it('uses the shared metric mode and row helpers rather than entryMode as a chart gate', () => {+ it('uses the shared metric mode and occurrence helpers rather than entryMode as a chart gate', () => {expect(source).toContain('metricModeForEntry')- expect(source).toContain('metricRowsForEntry')+ expect(source).toContain('metricEntriesForExercise')+ expect(source).toContain('completedRepsOf')expect(source).toContain('bestWeightForEntry')expect(source).not.toContain('const loggedMode = entryMode(en)')expect(source).not.toContain('(en.topW || 0)')