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: add strength exercise view and history snapshots
Space Hermesf3ba7de47931
diff --git a/frontend/src/lib/finish-workout.js b/frontend/src/lib/finish-workout.jsnew file mode 100644index 000000000..f34f92ba0--- /dev/null+++ b/frontend/src/lib/finish-workout.js@@ -0,0 +1,29 @@+// 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.+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,+ target: entry.target || null,+ }+ const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null+ if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && Object.keys(snapshot).length) {+ completed.muscleSnapshot = { ...snapshot }+ }+ return completed+ }).filter(entry => entry.sets.some(set => set.done))++ return {+ id: active.id,+ d: active.d,+ start: active.start,+ end,+ routineId: active.routineId,+ name: active.name,+ bw: active.bw,+ entries,+ prs,+ }+}diff --git a/frontend/src/lib/finish-workout.test.js b/frontend/src/lib/finish-workout.test.jsnew file mode 100644index 000000000..2dbe951df--- /dev/null+++ b/frontend/src/lib/finish-workout.test.js@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest'+import { buildCompletedWorkout } from './finish-workout.js'++describe('completed workout boundary', () => {+ it('builds the same legacy-shaped record doFinishWorkout stores and keeps it visible', () => {+ const active = {+ id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Push', bw: 80,+ entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }],+ }+ const completed = buildCompletedWorkout(active, { end: 2000, prs: [] })+ expect(completed).toEqual({+ id: 'active-1', d: '2026-08-08', start: 1000, end: 2000, routineId: 'routine-1', name: 'Push', bw: 80,+ entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }],+ prs: []+ })+ })++ it('persists a muscle snapshot only when the caller supplies one', () => {+ const active = {+ id: 'active-1', d: '2026-08-08', start: 1000,+ entries: [+ { id: 'catalogue', sets: [{ done: true }] },+ { id: 'custom', sets: [{ done: true }] },+ ],+ }+ const completed = buildCompletedWorkout(active, {+ end: 2000,+ snapshotFor: entry => entry.id === 'custom'+ ? { n: 'Custom lift', muscleWeights: { chest: 1 } }+ : null,+ })++ expect(completed.entries[0]).not.toHaveProperty('muscleSnapshot')+ expect(completed.entries[1].muscleSnapshot).toEqual({+ n: 'Custom lift', muscleWeights: { chest: 1 },+ })+ })+})diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.jsindex d2613455d..9c440aebd 100644--- a/frontend/src/lib/history.js+++ b/frontend/src/lib/history.js@@ -1,6 +1,16 @@// Pure helpers over the state object S (ported 1:1 from the vanilla app).import { todayISO, isoOf, weekKey, fmtNum } from './format.js'import { isCardio, isBodyweightEq } from './exercises.js'+import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode } 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') => {+ const source = objectOf(entry)+ const target = objectOf(source.target || source)+ const expectedMode = normalizeMode(mode, 'reps')+ return (Array.isArray(source.sets) ? source.sets : [])+ .filter(set => phaseForSet(set) === 'work' && modeForSet(set, target) === expectedMode)+}// i18n-core, not i18n: this file is imported by mcp/, which is plain Node with no Vite and no// React. i18n.js is the Vite half — import.meta.glob over the locale packs, useSyncExternalStore// for the hook — and it re-exports this very `t` from core, so nothing changes here except what@@ -224,10 +234,7 @@ export function freestyleConfig(S, cfg) {export function bestWeightFor(S, exId) {let best = 0S.workouts.forEach(w => w.entries.forEach(e => {- if (e.id === exId) {- e.sets.forEach(s => { if (s.done && s.w > best) best = s.w })- if (e.topW && e.topW > best) best = e.topW- }+ if (e.id === exId) best = Math.max(best, bestWeightForEntry(e))}))return best}@@ -330,10 +337,10 @@ export function streakWeeks(S) {* undone take the new value (null deletes the key). Done sets are never rewritten.*/export function cascadeWeight(rows, from, value) {- const warm = !!rows[from]?.warmup+ const warm = isWarmupRow(rows[from])const next = rows.slice()for (let j = from + 1; j < next.length; j++) {- if (!!next[j].warmup === warm && !next[j].done) {+ if (isWarmupRow(next[j]) === warm && !next[j].done) {if (value == null) delete next[j].welse next[j].w = value}@@ -343,14 +350,14 @@ export function cascadeWeight(rows, from, value) {/** Insert a warm-up row before the first work row, copying the preceding warm-up's values. */export function insertWarmupRow(rows, mode, target) {- const firstWork = rows.findIndex(x => !x.warmup)+ const firstWork = rows.findIndex(x => !isWarmupRow(x))const at = firstWork === -1 ? rows.length : firstWorkconst l = rows[at - 1] || rows[rows.length - 1]const warm = mode === 'cardio'- ? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, warmup: true }+ ? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, phase: 'warmup', warmup: true }: mode === 'time'- ? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, warmup: true }- : { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, warmup: true }+ ? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, phase: 'warmup', warmup: true }+ : { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, phase: 'warmup', warmup: true }const next = rows.slice()next.splice(at, 0, warm)return next@@ -367,6 +374,57 @@ export function removeRowAt(rows, i) {/** Completed non-warm-up sets across a workout's entries. */export function workSetsDone(w) {return (w?.entries || []).reduce(- (n, e) => n + (e.sets || []).filter(s => s.done && !s.warmup).length, 0,+ (n, e) => n + (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0,)}++const METRIC_MODES = ['reps', 'time', 'cardio']+const completedRowsForMode = (entry, mode) => workRowsForMode(entry, mode).filter(s => s.done === true && !isWarmupRow(s))++export function metricRowsForEntry(entry, mode) {+ const requested = typeof mode === 'string' ? mode.trim().toLowerCase() : ''+ const resolved = METRIC_MODES.includes(requested) ? requested : metricModeForEntry(entry)+ return resolved ? completedRowsForMode(entry, resolved) : []+}++/** The authoritative metric for an entry; reps rows take precedence over timed/cardio rows. */++export function metricModeForEntry(entry, fallback = null) {+ for (const mode of METRIC_MODES) {+ if (completedRowsForMode(entry, mode).length) return mode+ }+ return modeForEntry(entry, fallback)+}++/** Best load from completed work rows, with a guarded reps-only legacy topW fallback. */++export function bestWeightForEntry(entry = {}) {+ const target = entry.target || entry+ const workRows = Array.isArray(entry.sets)+ ? 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)+ }++ let best = 0+ repsRows.forEach(set => {+ const weight = Number(set?.w)+ if (Number.isFinite(weight) && weight > best) best = weight+ })++ const parentMode = modeForSet({}, target)+ const hasNonRepsWorkRow = workRows.some(set => modeForSet(set, target) !== 'reps')+ const hasWarmupRow = Array.isArray(entry.sets) && entry.sets.some(isWarmupRow)+ const topWeight = Number(entry.topW)+ // topW predates phase-tagged warm-ups. It remains a fallback for legacy all-work records,+ // but cannot override resolved work rows once any warm-up marker exists.+ if (parentMode === 'reps' && !hasNonRepsWorkRow && !hasWarmupRow+ && Number.isFinite(topWeight) && topWeight > best) best = topWeight+ return best+}diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.jsindex 68d1f0a71..fed50f5ae 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 { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'+import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'import { EXDB } from './exercises.js'// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.@@ -9,49 +9,6 @@ const CARDIO = EXDB.find(e => e.bp === 'cardio').idconst LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').idconst BW = EXDB.find(e => e.eq === 'body weight').id-describe('superset editing', () => {- it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => {- const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]-- const paired = pairAdjacent(entries, 1, 2, 'sg-new')-- expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }])- expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])- expect(supersetUnits(paired)).toEqual([[0], [1, 2]])- })-- it('merges both contiguous groups when their boundary entries are paired', () => {- const entries = [- { id: 'a', sg: 'left' }, { id: 'b', sg: 'left' },- { id: 'c', sg: 'right' }, { id: 'd', sg: 'right' }- ]-- const merged = pairAdjacent(entries, 1, 2)-- expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left'])- expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right'])- })-- it('unpairs one entry and removes sg values left without an adjacent partner', () => {- const entries = [- { id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' },- { id: 'd', sg: 'orphan' }- ]-- const unpaired = unpairSuperset(entries, 1)-- expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }])- expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan'])- })-- it('rejects a non-adjacent pairing request', () => {- const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]-- expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/)- expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])- })-})-describe('modeOf', () => {it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => {expect(modeOf({ id: CARDIO })).toBe('cardio')@@ -520,6 +477,99 @@ describe('workoutVolume', () => {const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }expect(workoutVolume(w)).toBe(0)})++ it('recognizes both warm-up schemas in work-set counts', () => {+ const w = {+ unit: 'kg',+ entries: [{+ id: LIFT,+ unit: 'kg',+ sets: [+ { warmup: true, unit: 'kg', w: 20, r: 5, done: true },+ { phase: 'warmup', unit: 'kg', w: 30, r: 5, done: true },+ { phase: 'work', unit: 'kg', w: 60, r: 5, done: true },+ ],+ }],+ }+ expect(workSetsDone(w)).toBe(1)+ })++ it('does not use a warm-up as the previous best working weight', () => {+ expect(bestWeightFor({ workouts: [{ entries: [{ id: LIFT, topW: 120, sets: [+ { phase: 'warmup', done: true, w: 120 },+ { phase: 'work', done: true, w: 80 },+ ] }] }] }, LIFT)).toBe(80)+ expect(bestWeightFor({ workouts: [{ entries: [{ id: LIFT, topW: 120, sets: [+ { phase: 'warmup', done: true, w: 120 },+ ] }] }] }, LIFT)).toBe(0)+ })++ it('uses completed non-warm-up load for timed entries', () => {+ expect(bestWeightForEntry({ target: { mode: 'time' }, topW: 200, sets: [+ { phase: 'warmup', sec: 30, w: 30, done: true },+ { phase: 'work', sec: 60, w: 20, done: true },+ { phase: 'work', sec: 75, w: 25, done: true },+ { phase: 'work', sec: 90, w: 40, done: false },+ ] })).toBe(25)+ })++ it('does not report a repeated weighted timed hold as a new load PR (blocker 3)', () => {+ const prior = {+ id: LIFT,+ target: { mode: 'time' },+ sets: [{ phase: 'work', sec: 60, w: 20, done: true }],+ }+ const repeated = {+ id: LIFT,+ target: { mode: 'time' },+ sets: [{ phase: 'work', sec: 60, w: 20, done: true }],+ }+ const state = { workouts: [{ entries: [prior] }] }+ const repeatedWeight = Math.max(0, ...repeated.sets.filter(set => set.done).map(set => set.w || 0))++ expect(bestWeightForEntry(prior)).toBe(20)+ expect(repeatedWeight > bestWeightFor(state, LIFT)).toBe(false)+ })+})++describe('superset editing', () => {+ it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => {+ const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]+ const paired = pairAdjacent(entries, 1, 2, 'sg-new')++ expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }])+ expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])+ expect(supersetUnits(paired)).toEqual([[0], [1, 2]])+ })++ it('merges both contiguous groups when their boundary entries are paired', () => {+ const entries = [+ { id: 'a', sg: 'left' }, { id: 'b', sg: 'left' },+ { id: 'c', sg: 'right' }, { id: 'd', sg: 'right' }+ ]+ const merged = pairAdjacent(entries, 1, 2)++ expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left'])+ expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right'])+ })++ it('unpairs one entry and removes sg values left without an adjacent partner', () => {+ const entries = [+ { id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' },+ { id: 'd', sg: 'orphan' }+ ]+ const unpaired = unpairSuperset(entries, 1)++ expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }])+ expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan'])+ })++ it('rejects a non-adjacent pairing request', () => {+ const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]++ expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/)+ expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])+ })})diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.jsindex 00927a20e..2120443f8 100644--- a/frontend/src/lib/muscles.js+++ b/frontend/src/lib/muscles.js@@ -7,7 +7,8 @@// map can actually draw, via ALIAS below. Anything genuinely undrawable (hands,// ankles, "cardiovascular system") maps to null and is dropped rather than guessed at.-import { EXIDX , smOf } from './exercises.js'+import { isWarmupRow } from './workout-model.js'+import { EXIDX, smOf } from './exercises.js'// The muscles a map can shade, in head-to-toe order — also the order of any list// built from them, so "what am I neglecting" reads top-down like a body.@@ -69,21 +70,118 @@ const BY_BODYPART = {const SECONDARY = 0.4 // a supporting muscle counts this much against a primary-/** Muscles one exercise trains: { slug: 0…1 }. */+const arrayOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]++// Completed history entries may retain a nested snapshot after their custom exercise is+// deleted from the profile catalogue. Prefer that snapshot when the outer entry has no muscle+// metadata of its own, while keeping direct/legacy entry fields authoritative when present.+function metadataOf(ex) {+ if (!ex || typeof ex !== 'object') return ex+ const hasDirect = ['muscleGroups', 'muscles', 'targetMuscles'].some(key => Object.prototype.hasOwnProperty.call(ex, key))+ || [ex.tg, ex.mg, ...arrayOf(ex.sm)].some(value => value != null && value !== '')+ return !hasDirect && ex.muscleSnapshot && typeof ex.muscleSnapshot === 'object' && !Array.isArray(ex.muscleSnapshot)+ ? ex.muscleSnapshot+ : ex+}++function explicitGroupsOf(ex) {+ if (!ex || typeof ex !== 'object') return null+ if (Object.prototype.hasOwnProperty.call(ex, 'muscleGroups')) {+ const groups = arrayOf(ex.muscleGroups)+ return groups.length ? groups : null+ }+ if (Object.prototype.hasOwnProperty.call(ex, 'muscles')) {+ const groups = arrayOf(ex.muscles)+ return groups.length ? groups : null+ }+ if (Object.prototype.hasOwnProperty.call(ex, 'targetMuscles')) {+ const groups = arrayOf(ex.targetMuscles)+ return groups.length ? groups : null+ }+ return null+}++/** True only when the catalogue explicitly supplied muscle groups, not a body-part fallback. */+export function hasExplicitMuscleMetadata(ex) {+ const source = metadataOf(ex)+ if (!source || typeof source !== 'object') return false+ const groups = explicitGroupsOf(source)+ if (groups && groups.some(value => canonicalMuscle(value))) return true+ return [source.tg, source.mg, ...arrayOf(source.sm)].some(value => canonicalMuscle(value))+}++function canonicalMuscle(value) {+ const name = String(value || '').toLowerCase().trim()+ if (MUSCLES.includes(name)) return name+ return ALIAS[name] || null+}++/** Canonical unique muscle groups, accepting both new arrays and legacy single fields. */+export function muscleGroupsOf(ex) {+ const sourceEx = metadataOf(ex)+ const explicit = explicitGroupsOf(sourceEx)+ const source = explicit || [sourceEx?.tg, sourceEx?.mg, ...arrayOf(smOf(sourceEx))]+ const out = []+ source.forEach(value => {+ const slug = canonicalMuscle(value)+ if (slug && !out.includes(slug)) out.push(slug)+ })+ if (!out.length && explicit == null) Object.keys(BY_BODYPART[sourceEx?.bp] || {}).forEach(slug => { if (!out.includes(slug)) out.push(slug) })+ return out+}++export const normalizeMuscleGroups = muscleGroupsOf++/** True when any requested group matches; an empty request is an intentionally unfiltered query. */+export function matchesMuscleGroups(ex, requested) {+ const wanted = arrayOf(requested).map(canonicalMuscle).filter(Boolean)+ if (!wanted.length) return true+ const groups = new Set(muscleGroupsOf(ex))+ return wanted.some(group => groups.has(group))+}++/** Muscles one exercise trains: { slug: 0…1 }. Duplicate metadata never adds load twice. */export function musclesOf(ex) {if (!ex) return {}+ const sourceEx = metadataOf(ex)+ if (sourceEx !== ex) return musclesOf(sourceEx)+ if (ex.muscleWeights && typeof ex.muscleWeights === 'object' && !Array.isArray(ex.muscleWeights)) {+ const snapshot = {}+ MUSCLES.forEach(slug => {+ const weight = Number(ex.muscleWeights[slug])+ if (Number.isFinite(weight) && weight > 0) snapshot[slug] = weight+ })+ if (Object.keys(snapshot).length) return snapshot+ }const out = {}const add = (name, w) => {- const slug = ALIAS[String(name || '').toLowerCase().trim()]+ const slug = canonicalMuscle(name)if (slug) out[slug] = Math.max(out[slug] || 0, w)}- add(ex.tg, 1)- ;smOf(ex).forEach(m => add(m, SECONDARY))+ const explicit = explicitGroupsOf(ex)+ if (explicit) explicit.forEach(m => add(m, 1))+ else {+ add(ex.tg, 1)+ add(ex.mg, SECONDARY)+ arrayOf(smOf(ex)).forEach(m => add(m, SECONDARY))+ }// Nothing recognised (custom exercises, or a target we don't draw) — use the body part.if (!Object.keys(out).length) Object.assign(out, BY_BODYPART[ex.bp] || {})return out}+/** Snapshot display and weighted muscle metadata into a completed history entry. */+export function exerciseMuscleSnapshot(ex) {+ if (!ex || typeof ex !== 'object') return {}+ const out = {}+ if (ex.n != null) out.n = ex.n+ if (ex.bp != null) out.bp = ex.bp+ const weights = musclesOf(ex)+ if (Object.keys(weights).length) out.muscleWeights = { ...weights }+ if (hasExplicitMuscleMetadata(ex)) out.muscleGroups = [...muscleGroupsOf(ex)]+ return out+}+/*** Training load per muscle, in "effective sets".* `items` is [{ id, sets }] — sets being a count, so a 4×8 bench press weighs four@@ -92,9 +190,12 @@ export function musclesOf(ex) {*/export function loadOf(items) {const load = {}- items.forEach(({ id, sets }) => {+ items.forEach(item => {+ const { id, sets } = item || {}if (!sets) return- const m = musclesOf(EXIDX[id])+ const historical = item.ex || item.exercise+ const source = historical?.muscleWeights ? historical : (EXIDX[id] || historical || item)+ const m = musclesOf(source)for (const slug in m) load[slug] = (load[slug] || 0) + m[slug] * sets})return load@@ -108,15 +209,15 @@ export function loadOf(items) {*/export const loadOfWorkouts = (workouts, pick) =>loadOf((workouts || []).flatMap(w =>- (w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup && (!pick || pick(s))).length }))))+ (w.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length }))))/** Load a routine *would* produce, from its planned set counts. */export const loadOfRoutine = routine =>- loadOf((routine?.ex || []).map(c => ({ id: c.id, sets: c.sets || 1 })))+ loadOf((routine?.ex || []).map(c => ({ id: c.id, ex: c, sets: c.sets || 1 })))/** Load for a workout still in progress — the sets ticked so far. */export const loadOfActive = active =>- loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup).length })))+ loadOf((active?.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length })))/*** Shade buckets 0–4 per muscle.diff --git a/frontend/src/lib/onerm.js b/frontend/src/lib/onerm.jsindex c3a0b11cb..2602118e0 100644--- a/frontend/src/lib/onerm.js+++ b/frontend/src/lib/onerm.js@@ -1,3 +1,4 @@+import { isWarmupRow } from './workout-model.js'// Estimated one-rep max (issue #18).//// Deliberately knows nothing about the exercise database: an estimate needs a weight AND a@@ -44,7 +45,7 @@ export function estimate1RM(w, r, formula = DEFAULT_FORMULA) {export function bestSetOf(entry, formula = DEFAULT_FORMULA) {let best = null;(entry?.sets || []).forEach(s => {- if (!s.done || s.warmup) return+ if (!s.done || isWarmupRow(s)) returnconst 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)) }})diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.jsindex ebc8020fd..477c19387 100644--- a/frontend/src/lib/recovery.js+++ b/frontend/src/lib/recovery.js@@ -111,9 +111,13 @@ function fatigueValue(events, now) {** @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.* @param {number} now Current time in milliseconds; injected to keep this function deterministic.+ * @param {{unit?: string}} options Reserved profile-level options; unit is supplied at the UI boundary.* @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.*/-export function fatigueOf(workouts, now) {+export function fatigueOf(workouts, now, options = {}) {+ // Keep the profile unit at this boundary for a future separately reviewed tonnage model.+ // The current mainline set-count model is intentionally unit-independent.+ void options.unitconst current = Number(now)const cutoff = current - FATIGUE_SCAN_MSconst stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff)diff --git a/frontend/src/lib/strength-exercises.js b/frontend/src/lib/strength-exercises.jsnew file mode 100644index 000000000..c4669a2b8--- /dev/null+++ b/frontend/src/lib/strength-exercises.js@@ -0,0 +1,143 @@+// Per-exercise rows for the Strength view: best estimated 1RM from the user's own logged+// sets, the exercise's OWN retained-strength decay (same 14-day plateau / 28-day half-life+// / 0.5 floor model as the muscle map, applied to the exercise's last done work set), and+// the expected CURRENT 1RM (= estimate x decay). The body map keeps the per-muscle model;+// the exercise list deliberately reads per-exercise, so an old exercise shows its own+// decline even when its muscle is kept fresh by other work. Muscle mapping is+// 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 { 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'++const round1 = value => Math.round(value * 10) / 10++// Same retained-strength curve the muscle map uses, applied to one exercise's age.+function strengthFromAge(ageMs) {+ if (!Number.isFinite(ageMs) || ageMs < 0) return STRENGTH_FLOOR+ if (ageMs <= STRENGTH_FULL_MS) return 1+ return Math.max(STRENGTH_FLOOR, halfLifeDecay(ageMs - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS))+}++// Timestamp of the exercise's latest completed WORK set (warm-ups excluded - they are prep,+// not stimulus, and the strength model is built on effective work).+function lastWorkSetAt(S, id) {+ let latest = -Infinity+ 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+ }+ return Number.isFinite(latest) ? latest : null+}++function snapshotWeights(entry) {+ const catalogue = entry && typeof entry === 'object' ? EXIDX[entry.id] : null+ if (catalogue) {+ const weights = musclesOf(catalogue)+ if (Object.keys(weights).length) return weights+ }+ const direct = entry && typeof entry === 'object'+ ? (entry.muscleWeights || entry.muscleSnapshot?.muscleWeights)+ : null+ if (direct && typeof direct === 'object' && !Array.isArray(direct) && Object.keys(direct).length) {+ return direct+ }+ return musclesOf(entry)+}++// Highest-weight muscle of an exercise - used for the primary/secondary badge and the+// per-muscle link, not for the decay (the exercise's own decay is what the row shows).+export function primaryMuscleOf(entry) {+ const weights = snapshotWeights(entry)+ let best = null+ for (const [slug, weight] of Object.entries(weights)) {+ if (!best || weight > best.weight) best = { slug, weight }+ }+ return best+}++function exerciseName(entry) {+ // Imported history often has no name snapshot (entries are { id, sets, topW }) - the+ // catalogue (or the registered custom) is the canonical name source.+ const ex = entry && typeof entry === 'object' ? EXIDX[entry.id] : null+ if (ex?.n) return ex.n+ if (entry?.muscleSnapshot?.n) return entry.muscleSnapshot.n+ 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+ }+ return null+}++/**+ * Strength rows for every exercise with an estimate: best estimated 1RM (work sets only,+ * warm-ups excluded), the estimate's date, the exercise's primary muscle, the exercise's+ * OWN decay (from its last done work set), and the expected current 1RM (estimate x decay).+ * Sorted by expected current 1RM, strongest first. Exercises without a usable estimate are+ * omitted - a made-up number is worse than no number.+ */+export function strengthExerciseRows(S, now) {+ const workouts = S?.workouts || []+ const ids = [...new Set(workouts.flatMap(w => (w.entries || []).map(e => e.id)))]+ const rows = []+ for (const id of ids) {+ const best = best1RM(S, id)+ if (!best) continue+ const entry = firstEntryWithId(S, id)+ const lastAt = lastWorkSetAt(S, id)+ const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)+ rows.push({+ id,+ name: exerciseName(entry) || id,+ est: best.est,+ estDate: best.d,+ primary: primaryMuscleOf(entry) ? primaryMuscleOf(entry).slug : null,+ decay,+ current: round1(best.est * decay),+ })+ }+ return rows.sort((a, b) => b.current - a.current || String(a.name).localeCompare(String(b.name)))+}++/**+ * Strength rows for the exercises whose logged snapshot includes `slug` (primary 1 /+ * secondary 0.4 badge), each with the exercise's OWN decay and expected current 1RM - the+ * 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: exerciseName(entry) || entry.id,+ weight,+ primary: primary ? primary.slug : null,+ est: best.est,+ estDate: best.d,+ decay,+ current: round1(best.est * decay),+ })+ }+ }+ 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.jsnew file mode 100644index 000000000..d76518628--- /dev/null+++ b/frontend/src/lib/strength-exercises.test.js@@ -0,0 +1,176 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { strengthExerciseRows, strengthExerciseRowsForMuscle, primaryMuscleOf } from './strength-exercises.js'+import { registerCustom } from './exercises.js'++const DAY = 86400000+const NOW = Date.UTC(2026, 7, 8, 12) // 2026-08-08 12:00 UTC++const CUSTOMS = [+ { id: 'bench', n: 'Bench Press', tg: 'chest', mg: 'triceps', sm: ['deltoids'] },+ { id: 'squat', n: 'Squat', tg: 'quadriceps', mg: 'glutes' },+ { id: 'fly', n: 'Cable Crossovers', tg: 'deltoids', mg: 'chest' },+ { id: 'pushdown', n: 'Triceps Pushdown', tg: 'triceps' },+ { id: 'undone', n: 'Undone Lift', tg: 'upper-back' },+ { id: 'stretch', n: 'Chest Stretch', tg: 'chest' },+]++beforeEach(() => registerCustom(CUSTOMS))+afterEach(() => registerCustom([]))++function workout(dayAgo, entries) {+ const d = new Date(NOW - dayAgo * DAY)+ const iso = d.toISOString().slice(0, 10)+ return { id: 'x' + iso, d: iso, start: NOW - dayAgo * DAY, unit: 'kg', entries }+}++const bench = { id: 'bench', n: 'Bench Press', muscleWeights: { chest: 1, triceps: 0.4, deltoids: 0.4 }, sets: [+ { phase: 'warmup', w: 40, r: 8, done: true, unit: 'kg' },+ { phase: 'work', w: 80, r: 8, done: true, unit: 'kg' },+ { phase: 'work', w: 85, r: 6, done: true, unit: 'kg' },+] }+// est 85x6 -> 102.0 ; 80x8 -> 101.3 ; warmup 40x8 -> 50.7 (must never win)++const squat = { id: 'squat', n: 'Squat', muscleWeights: { quadriceps: 1, glutes: 0.4 }, sets: [+ { phase: 'work', w: 100, r: 5, done: true, unit: 'kg' },+] }+// est 100x5 -> 116.7 ; trained 30 days ago -> quadriceps decayed (30d - 14d = 16d / 28d half-life)++const fly = { id: 'fly', n: 'Cable Crossovers', muscleWeights: { chest: 0.4, deltoids: 1 }, sets: [+ { phase: 'work', w: 20, r: 12, done: true, unit: 'kg' },+] }+// est 20x12 -> 28 ; chest is SECONDARY here++const pushdown = { id: 'pushdown', n: 'Triceps Pushdown', muscleWeights: { triceps: 1 }, sets: [+ { phase: 'work', w: 30, r: 10, done: true, unit: 'kg' },+] }+// est 30x10 -> 40++const undone = { id: 'undone', n: 'Undone Lift', muscleWeights: { 'upper-back': 1 }, sets: [+ { phase: 'work', w: 200, r: 5, done: false, unit: 'kg' },+] }++const noLoad = { id: 'stretch', n: 'Chest Stretch', muscleWeights: { chest: 0.4 }, sets: [+ { phase: 'work', w: 0, r: 10, done: true },+] }++const unitState = (workouts) => ({ unit: 'kg', workouts })++describe('strengthExerciseRows', () => {+ it('lists every exercise with an estimate, warm-ups excluded, sorted by expected current 1RM', () => {+ const S = unitState([+ workout(3, [bench]),+ workout(30, [squat]),+ workout(3, [fly, pushdown]),+ workout(2, [undone, noLoad]),+ ])+ const rows = strengthExerciseRows(S, NOW)+ // undone (no completed set) and stretch (no load) have no estimate -> omitted+ expect(rows.map(r => r.id).sort()).toEqual(['bench', 'fly', 'pushdown', 'squat'])+ // strongest expected current first: bench 102 > squat ~78.5 > pushdown 40 > fly 28+ expect(rows[0].id).toBe('bench')+ expect(rows.at(-1).id).toBe('fly')+ })++ it('keeps warm-up sets out of the estimate and reports the date of the best work set', () => {+ const S = unitState([workout(3, [bench])])+ const rows = strengthExerciseRows(S, NOW)+ expect(rows).toHaveLength(1)+ expect(rows[0].est).toBe(102) // 85x6, not 80x8, not the 40x8 warm-up+ expect(rows[0].estDate).toBe('2026-08-05')+ expect(rows[0].primary).toBe('chest')+ })++ it('resolves real exercise names from the catalogue even when entries lack a name snapshot', () => {+ // Imported history entries are { id, sets, topW } - no `n` snapshot. The catalogue+ // (or the registered custom) must supply the display name, not the raw id.+ const nameless = { id: 'bench', sets: bench.sets } // no n, no muscleWeights+ const S = unitState([workout(3, [nameless])])+ const rows = strengthExerciseRows(S, NOW)+ expect(rows).toHaveLength(1)+ expect(rows[0].name).toBe('Bench Press')+ expect(rows[0].id).toBe('bench')+ const muscleRows = strengthExerciseRowsForMuscle(S, NOW, 'chest')+ expect(muscleRows[0].name).toBe('Bench Press')+ })++ it('uses nested exercise snapshots for a deleted custom exercise', () => {+ const deleted = {+ id: 'deleted-custom',+ muscleSnapshot: { n: 'Deleted custom', muscleWeights: { chest: 1 } },+ sets: [{ phase: 'work', warmup: true, w: 80, r: 8, done: true, unit: 'kg' }],+ }+ const S = unitState([workout(3, [deleted])])+ const rows = strengthExerciseRows(S, NOW)+ expect(rows).toHaveLength(1)+ expect(rows[0]).toMatchObject({ id: 'deleted-custom', name: 'Deleted custom', primary: 'chest', est: 101.3 })+ expect(strengthExerciseRowsForMuscle(S, NOW, 'chest')[0].name).toBe('Deleted custom')+ })++ it('applies the exercise own decay to the expected current 1RM', () => {+ const S = unitState([workout(3, [bench]), workout(30, [squat])])+ const rows = strengthExerciseRows(S, NOW)+ const benchRow = rows.find(r => r.id === 'bench')+ const squatRow = rows.find(r => r.id === 'squat')+ // bench last done 3 days ago -> still inside the 14-day full-retention plateau+ expect(benchRow.decay).toBe(1)+ expect(benchRow.current).toBe(102)+ // squat last done 30 days ago -> 16 days past the plateau at a 28-day half-life+ const squatDecay = 0.5 ** (16 / 28)+ expect(squatRow.decay).toBeCloseTo(squatDecay, 4)+ expect(squatRow.current).toBeCloseTo(Math.round(116.7 * squatDecay * 10) / 10, 2)+ })++ it('keeps the exercise own decay even when its muscle is kept fresh by other work', () => {+ // bench last done 30 days ago, but chest is fresh (fly trained 3 days ago): the row+ // speaks for the exercise, so bench still shows its own decline.+ const S = unitState([workout(30, [bench]), workout(3, [fly])])+ const rows = strengthExerciseRows(S, NOW)+ const benchRow = rows.find(r => r.id === 'bench')+ const benchDecay = 0.5 ** (16 / 28)+ expect(benchRow.decay).toBeCloseTo(benchDecay, 4)+ expect(benchRow.current).toBeCloseTo(Math.round(102 * benchDecay * 10) / 10, 2)+ })+})++describe('strengthExerciseRowsForMuscle', () => {+ it('lists primary and secondary exercises for the tapped muscle, with that muscle decay', () => {+ const S = unitState([workout(3, [bench, fly, pushdown])])+ const rows = strengthExerciseRowsForMuscle(S, NOW, 'chest')+ expect(rows.map(r => r.id).sort()).toEqual(['bench', 'fly'])+ const benchRow = rows.find(r => r.id === 'bench')+ const flyRow = rows.find(r => r.id === 'fly')+ expect(benchRow.weight).toBe(1)+ expect(benchRow.primary).toBe('chest')+ expect(flyRow.weight).toBe(0.4)+ expect(flyRow.primary).toBe('deltoids')+ expect(flyRow.decay).toBe(1) // chest is at full retention+ expect(flyRow.current).toBe(28)+ })++ it('the tapped muscle filters the list; the row decay stays the exercise own', () => {+ const S = unitState([workout(3, [bench]), workout(30, [fly])])+ const rows = strengthExerciseRowsForMuscle(S, NOW, 'triceps')+ const benchRow = rows.find(r => r.id === 'bench')+ // bench trains triceps secondarily (0.4), so it appears under the tapped triceps -+ // but the decay is bench's own (3 days ago -> full), not triceps' stale muscle value.+ expect(benchRow.weight).toBe(0.4)+ expect(benchRow.primary).toBe('chest')+ expect(benchRow.decay).toBe(1)+ expect(benchRow.current).toBe(102)+ })++ it('returns nothing for a muscle nothing trains', () => {+ const S = unitState([workout(3, [bench])])+ expect(strengthExerciseRowsForMuscle(S, NOW, 'biceps')).toEqual([])+ })+})++describe('primaryMuscleOf', () => {+ it('prefers the catalogue, then the logged snapshot, and handles missing metadata', () => {+ expect(primaryMuscleOf({ id: 'bench', muscleWeights: {} }).slug).toBe('chest') // catalogue wins+ expect(primaryMuscleOf({ muscleWeights: { chest: 1, triceps: 0.4 } }).slug).toBe('chest') // snapshot fallback+ expect(primaryMuscleOf({ tg: 'back', mg: 'biceps' }).slug).toBe('upper-back') // canonicalised+ expect(primaryMuscleOf({})).toBeNull()+ expect(primaryMuscleOf(null)).toBeNull()+ })+})diff --git a/frontend/src/lib/workout-model.js b/frontend/src/lib/workout-model.jsnew file mode 100644index 000000000..e296ee608--- /dev/null+++ b/frontend/src/lib/workout-model.js@@ -0,0 +1,74 @@+// Focused workout semantics shared by session, history, and strength views.+// Legacy records have no explicit phase or mode, so the defaults preserve main's work/reps shape.++const MODES = ['reps', 'time', 'cardio']+const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}++function normalizedPhase(value, fallback = 'work') {+ const token = typeof value === 'string' ? value.trim().toLowerCase() : ''+ if (token === 'warmup' || token === 'warm-up' || token === 'warm_up') return 'warmup'+ if (token === 'work') return 'work'+ return fallback === 'warmup' ? 'warmup' : 'work'+}++/** Resolve a row's phase. An explicit phase wins over the legacy warmup boolean. */+export function phaseForSet(set, fallback = 'work') {+ const source = objectOf(set)+ if (source.phase != null && source.phase !== '') return normalizedPhase(source.phase, fallback)+ return source.warmup === true ? 'warmup' : normalizedPhase(undefined, fallback)+}++export function isWarmupRow(set) {+ return phaseForSet(set) === 'warmup'+}++export function normalizeMode(value, fallback = 'reps') {+ const token = typeof value === 'string' ? value.trim().toLowerCase() : ''+ if (MODES.includes(token)) return token+ return MODES.includes(fallback) ? fallback : 'reps'+}++function modeFromUnit(value) {+ const token = typeof value === 'string' ? value.trim().toLowerCase() : ''+ if (['rep', 'reps', 'repetition', 'repetitions'].includes(token)) return 'reps'+ if (['sec', 'secs', 'second', 'seconds'].includes(token)) return 'time'+ if (['min', 'mins', 'minute', 'minutes'].includes(token)) return 'cardio'+ return null+}++function explicitMode(source) {+ const value = objectOf(source).mode+ const token = typeof value === 'string' ? value.trim().toLowerCase() : ''+ return MODES.includes(token) ? token : modeFromUnit(objectOf(source).unit)+}++function inferredMode(source) {+ const value = objectOf(source)+ const explicit = explicitMode(value)+ if (explicit) return explicit+ if (String(value.mode || '').trim().toLowerCase() === 'amrap') return 'reps'+ if (value.min != null || value.speed != null) return 'cardio'+ if (value.sec != null || value.seconds != null || value.durationSec != null) return 'time'+ if (value.r != null || value.reps != null || value.actualReps != null) return 'reps'+ return null+}++/** Resolve one row's mode: explicit row, parent target, then legacy result fields. */+export function modeForSet(set, target = {}) {+ return explicitMode(set) || inferredMode(target) || inferredMode(set) || 'reps'+}++/** Resolve a single mode for an entry; mixed work-row modes intentionally return null. */+export function modeForEntry(entry, fallback = null) {+ const source = objectOf(entry)+ const target = objectOf(source.target || source)+ const sets = Array.isArray(source.sets) ? source.sets : []+ const work = sets.filter(set => !isWarmupRow(set))+ const observed = work.length ? work : sets+ const modes = [...new Set(observed.map(set => modeForSet(set, target)))]+ if (modes.length > 1) return null+ if (modes.length === 1) return modes[0]+ const targetMode = inferredMode(target)+ if (targetMode) return targetMode+ return fallback == null ? modeForSet(source, target) : normalizeMode(fallback)+}diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex 14d2720f0..d0f6d3622 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -14,12 +14,14 @@ import Icon from './components/Icon.jsx'import { Button, Slider, Switch, Segmented, SelectRow, Row } from './components/ui.jsx'import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'import BodyMap from './components/BodyMap.jsx'-import { loadOfWorkouts } from './lib/muscles.js'+import { exerciseMuscleSnapshot, loadOfWorkouts } from './lib/muscles.js'import { parseImport, mergeImport } from './lib/import-csv.js'import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js'import { MOBILE, shareExport } from './lib/mobile.js'+import { buildCompletedWorkout } from './lib/finish-workout.js'+import { isWarmupRow } from './lib/workout-model.js'const S = () => useStore.getState().Sconst update = (...a) => useStore.getState().update(...a)@@ -388,10 +390,15 @@ export function deleteCustomEx(ex, afterDelete) {confirmText: t('Delete'), danger: true,onConfirm: () => {update(s => {+ // Keep display and muscle metadata in history before the custom catalogue row disappears.+ const snapshot = exerciseMuscleSnapshot(ex)+ s.workouts.forEach(w => w.entries.forEach(e => {+ if (e.id !== ex.id) return+ e.n = ex.n+ if (!e.muscleSnapshot || !Object.keys(e.muscleSnapshot).length) e.muscleSnapshot = snapshot+ }))s.customEx = (s.customEx || []).filter(x => x.id !== ex.id)s.routines.forEach(r => { r.ex = r.ex.filter(e => e.id !== ex.id); cleanupSg(r.ex) })- // stamp the name into history entries so past workouts stay readable- s.workouts.forEach(w => w.entries.forEach(e => { if (e.id === ex.id) e.n = ex.n }))delete s.exWeights[ex.id]})toast(t('Exercise deleted'))@@ -849,7 +856,7 @@ function TopWeight({ entryIdx, close }) {// to sit after every one of them.const entry = A ? A.entries[entryIdx] : nullconst ex = entry && EXIDX[entry.id]- const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done).map(s => s.w || 0)) : 0+ const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w || 0)) : 0const prevBest = entry ? Math.max((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id)) : 0const [v, setV] = useState(entry ? (Math.max(maxSet, prevBest) || entry.target.weight || 0) : 0)useEffect(() => { if (!entry) close() }, [!entry])@@ -939,25 +946,22 @@ function doFinishWorkout() {const prs = []const e1prs = []A.entries.forEach(e => {- const mx = Math.max(0, ...e.sets.filter(s => s.done).map(s => s.w))+ const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w))if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id)// A heavier estimate without a heavier top set is its own kind of progress —// same weight for more reps. Reported separately so it can't be read as a load PR.const rec = is1RMRecord(st, e.id, e)if (rec && !prs.includes(e.id)) e1prs.push({ id: e.id, ...rec })})- const w = {- id: A.id, d: A.d, start: A.start, end: Date.now(), routineId: A.routineId, name: A.name, bw: A.bw,- // `target` (what the session prescribed) is kept alongside the sets: without it a- // finished workout cannot say whether it hit its reps, and a timed session reads back- // as "0 reps". It is what the progression engine works from.- entries: A.entries.map(e => ({ id: e.id, sets: e.sets, topW: e.topW || null, target: e.target || null })).filter(e => e.sets.some(s => s.done)),- prs- }+ const w = buildCompletedWorkout(A, {+ end: Date.now(),+ prs,+ snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null,+ })w.vol = workoutVolume(w)update(s => {w.entries.forEach(e => {- const mx = Math.max(0, ...e.sets.filter(x => x.done).map(x => x.w || 0), e.topW || 0)+ const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0)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)diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsxindex af08fbab4..b2e5a2652 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 } from '../lib/exercises.js'-import { lastBW, streakWeeks, setLabel, modeOf, effortOf } from '../lib/history.js'+import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'import { t } from '../lib/i18n.js'import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'@@ -12,6 +12,7 @@ import Icon from '../components/Icon.jsx'import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js'+import { strengthExerciseRowsForMuscle } from '../lib/strength-exercises.js'import { fatigueStateOf } from '../lib/recovery-view.js'import { e1rmSeries, best1RM } from '../lib/onerm.js'import {@@ -19,6 +20,7 @@ import {effortHistogram, isHardSet, HARD_RIR} from '../lib/effort.js'import { Button, Segmented, SelectRow } from '../components/ui.jsx'+import { isWarmupRow } from '../lib/workout-model.js'// Which muscles the training in a window actually hit — and, the point of the card,// which ones it keeps missing. Shading is relative within the window (lib/muscles.js).@@ -28,8 +30,9 @@ function latestMuscleTraining(workouts) {const timestamp = Number(workout?.start || new Date(workout?.d).getTime())if (!Number.isFinite(timestamp)) continuefor (const entry of workout.entries || []) {- if (!(entry.sets || []).some(set => set?.done === true)) continue- for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) {+ if (!(entry.sets || []).some(set => set?.done === true && !isWarmupRow(set))) continue+ const exercise = EXIDX[entry.id] || entry.exercise || entry+ for (const slug of Object.keys(musclesOf(exercise))) {if (latest[slug] == null || timestamp > latest[slug]) latest[slug] = timestamp}}@@ -37,7 +40,7 @@ function latestMuscleTraining(workouts) {return latest}-const FATIGUE_LEVELS = [+export const FATIGUE_LEVELS = [{ at: 0, level: 0 },{ at: 0.15, level: 1 },{ at: 0.25, level: 2 },@@ -45,7 +48,7 @@ const FATIGUE_LEVELS = [{ at: 0.55, level: 4, exclusive: true },]-const STRENGTH_LEVELS = [+export const STRENGTH_LEVELS = [{ at: STRENGTH_FLOOR, level: 0 },{ at: 0.625, level: 1 },{ at: 0.75, level: 2 },@@ -100,11 +103,10 @@ function MuscleBalance({ S }) {const [sel, setSel] = useState(null)const now = useNow()const workouts = S.workouts- const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now])+ const fatigue = useMemo(() => fatigueOf(workouts, now, { unit: S.unit }), [workouts, now, S.unit])const strength = useMemo(() => strengthOf(workouts, now), [workouts, now])+ const muscleExercises = useMemo(() => (sel ? strengthExerciseRowsForMuscle(S, now, sel) : []), [S, now, sel])const lastTrained = useMemo(() => latestMuscleTraining(workouts), [workouts])- const { worked: strengthOrder } = rankOf(strength)- const detrained = strengthOrder.filter(slug => strength[slug] < 1)const strengthHint = slug => {if (lastTrained[slug] == null) return t('not trained')const weeks = weeksSinceTraining(now, lastTrained[slug])@@ -125,6 +127,8 @@ function MuscleBalance({ S }) {const volWin = S.workouts.filter(w => (w.start || new Date(w.d).getTime()) > now - 90 * 86400000)const vol90 = loadOfWorkouts(volWin, null)const { worked, missed } = rankOf(load)+ const { worked: strengthOrder } = rankOf(strength)+ const detrained = strengthOrder.filter(slug => strength[slug] < 1)const top = worked.slice(0, 4)const max = worked.length ? load[worked[0]] : 0const sets = m => Math.round((load[m] || 0) * 10) / 10@@ -176,6 +180,25 @@ function MuscleBalance({ S }) {<BodyMap className="tappable hm-strength" load={strength} thresholds={STRENGTH_LEVELS} body={S.body} selected={sel} onMuscle={toggleSel} /><StrengthLegend /><div className="muted small" style={{ marginTop: 10 }}>{t('Strength shows retained muscle strength. Train again to reset it.')}</div>+ {sel && <>+ <h4 className="sec" style={{ marginTop: 14 }}>{t('Exercises')} · {t(MUSCLE_NAME[sel])}</h4>+ {muscleExercises.length ? muscleExercises.map(row => (+ <div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch' }}>+ <span className="nm" style={{ whiteSpace: 'normal', lineHeight: 1.35, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>+ <span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {row.name}+ {row.primary === sel+ ? <span className="dim" style={{ fontSize: 11, marginLeft: 6 }}>{t('primary')}</span>+ : <span className="dim" style={{ fontSize: 11, marginLeft: 6 }}>{t('secondary')}</span>}+ </span>+ <span className="small dim" style={{ display: 'block', fontWeight: 400 }}>{t('Est. 1RM')}: {fmtNum(row.est)} {S.unit} · {fmtDate(row.estDate, true)}</span>+ </span>+ <span className="bar" style={{ alignSelf: 'center' }}><i style={{ width: '100%', background: 'linear-gradient(to right, var(--acc) ' + Math.round(row.decay * 100) + '%, var(--surface-2) ' + Math.round(row.decay * 100) + '%)' }} /></span>+ <span className="v" style={{ alignSelf: 'center' }}>{fmtNum(row.current)} {S.unit}<span className="dim"> · {Math.round(row.decay * 100)}%</span></span>+ </div>+ )) : <div className="muted small">{t('No exercises with an estimated 1RM yet.')}</div>}+ </>}+ {!sel && <div className="muted small" style={{ marginTop: 10 }}>{t('Tap a muscle to see its exercises.')}</div>}{detrained.map(slug => <div key={slug} className="mrow"><span className="nm">{t(MUSCLE_NAME[slug])}</span><span className="bar"><i style={{ width: Math.round(strength[slug] * 100) + '%' }} /></span>@@ -185,6 +208,7 @@ function MuscleBalance({ S }) {</div>}+// How hard the training was — the half of the picture a volume chart cannot show. Everything// is computed in RIR (lib/effort.js) and converted to whichever scale this profile reads.// Every number carries how much of the training it speaks for: rating is optional and off by@@ -248,7 +272,6 @@ export default function Stats() {const [exId, setExId] = useState(null)const [exMetric, setExMetric] = useState('top')const now = Date.now()- const anyEffort = hasEffort(S)const kind = displayScale(S)const hd = scaleName(kind)@@ -256,31 +279,34 @@ export default function Stats() {.map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))const bw30 = S.bodyweight.filter(b => (b.t || new Date(b.d).getTime()) > now - 30 * 86400000)const bwDelta30 = bw30.length > 1 ? bw30[bw30.length - 1].w - bw30[0].w : null- const monthW = S.workouts.filter(w => w.d.slice(0, 7) === todayISO().slice(0, 7)).length+ const workouts = S.workouts+ const monthW = workouts.filter(w => String(w.d || '').slice(0, 7) === todayISO().slice(0, 7)).length+ const nameOf = id => EXIDX[id]?.n || workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || idconst currentOf = id => {- for (let i = S.workouts.length - 1; i >= 0; i--) {- const en = S.workouts[i].entries.find(e => e.id === 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 = modeOf({ ...(en.target || {}), id })- const metric = s2 => mode === 'cardio' ? (s2.speed || 0) : mode === 'time' ? (s2.sec || 0) : (s2.w || 0)- const mx = Math.max(0, ...en.sets.filter(s2 => s2.done).map(metric), mode === 'time' || mode === 'cardio' ? 0 : (en.topW || 0))+ 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)))if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit }}return { mx: 0, unit: S.unit }}- const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id])+ const exHist = [...new Set(workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id] || nameOf(id) !== id)const exCurrent = Object.fromEntries(exHist.map(id => [id, currentOf(id)]))- exHist.sort((a, b) => exCurrent[b].mx - exCurrent[a].mx || (EXIDX[a].n < EXIDX[b].n ? -1 : 1))-+ exHist.sort((a, b) => exCurrent[b].mx - exCurrent[a].mx || nameOf(a).localeCompare(nameOf(b)))const curEx = exId && exHist.includes(exId) ? exId : exHist[0] || null- // How this exercise was logged most recently decides what the curve means: top weight,- // longest hold or top speed. Sets logged in another mode lack the field and score 0, so a- // switched exercise drops its old points instead of mixing seconds into a weight chart.+ // A completed reps work row is authoritative for strength metrics, even when the parent+ // target also contains timed/cardio work. Entries without reps rows use their selected mode.const curMode = curEx ? (() => {- for (let i = S.workouts.length - 1; i >= 0; i--) {- const en = S.workouts[i].entries.find(e => e.id === curEx)- if (en) return modeOf({ ...(en.target || {}), id: 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)+ if (mode) return mode+ }}return modeOf({ id: curEx })})() : 'reps'@@ -290,16 +316,25 @@ export default function Stats() {const exUnit = curCardio ? 'km/h' : curTimed ? 's' : S.unitlet exPts = [], exList = [], exBest = 0if (curEx) {- S.workouts.forEach(w => {+ workouts.forEach(w => {const en = w.entries.find(e => e.id === curEx)- if (en) { const mx = Math.max(0, ...en.sets.filter(s => s.done).map(metric), curCardio || curTimed ? 0 : (en.topW || 0)); if (mx > 0) { exPts.push({ t: w.start, y: mx, d: w.d, sets: en.sets.filter(s => s.done), target: en.target }); if (mx > exBest) exBest = mx } }+ if (en) {+ const loggedMode = metricModeForEntry(en)+ if (loggedMode !== curMode) return+ const doneSets = metricRowsForEntry(en, curMode)+ const mx = curMode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...doneSets.map(metric))+ if (mx > 0) {+ exPts.push({ t: w.start, y: mx, d: w.d, sets: doneSets, target: en.target })+ if (mx > exBest) exBest = mx+ }+ }})exList = exPts.slice(-5).reverse()}// Estimated 1RM (issue #18) — only reps-mode training produces one, so cardio and timed// work simply have no points and the toggle stays hidden.- const e1Pts = curEx ? e1rmSeries(S, curEx) : []- const e1Best = curEx ? best1RM(S, curEx) : null+ const e1Pts = curEx && curMode === 'reps' ? e1rmSeries(S, curEx) : []+ const e1Best = curEx && curMode === 'reps' ? best1RM(S, curEx) : nullconst showE1 = e1Pts.length > 0// Effort on this exercise, per session. It rides on the top-set curve as well as having a// curve of its own, because the two only mean something together: the same weight moved@@ -324,19 +359,20 @@ export default function Stats() {<button className="iconbtn" onClick={() => nav('/history')} aria-label={t('History')}><Icon name="history" /></button></div><div className="tiles">- <div className="tile"><div className="l"><Icon name="dumbbell" />{t('Workouts')}</div><div className="v">{S.workouts.length}</div></div>+ <div className="tile"><div className="l"><Icon name="dumbbell" />{t('Workouts')}</div><div className="v">{workouts.length}</div></div><div className="tile"><div className="l"><Icon name="calendar" />{t('This month')}</div><div className="v">{monthW}</div></div><div className="tile"><div className="l"><Icon name="flame" />{t('Week streak')}</div><div className="v">{streakWeeks(S)}</div></div><div className="tile"><div className="l"><Icon name="scale" />{t('Weight 30d')}</div><div className="v" style={{ fontSize: 22, color: bwDelta30 === null ? 'inherit' : bwDeltaColor(bwDelta30, (lastBW(S) || {}).w || 0) }}>{bwDelta30 === null ? '—' : (bwDelta30 > 0 ? '+' : '') + fmtNum(bwDelta30) + ' ' + S.unit}</div></div>+</div><div className="card"><h2>{t('Activity — last 12 months')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('by time trained')}</span></h2>- <Heatmap S={S} onDay={iso => { const ws = S.workouts.filter(w => w.d === iso); if (ws.length === 1) workoutDetailSheet(ws[0]); else if (ws.length) calendarSheet(iso) }} />+ <Heatmap S={S} onDay={iso => { const ws = workouts.filter(w => w.d === iso); if (ws.length === 1) workoutDetailSheet(ws[0]); else if (ws.length) calendarSheet(iso) }} /></div>- {S.workouts.length > 0 && <MuscleBalance S={S} />}- {anyEffort && <EffortCard S={S} />}+ {workouts.length > 0 && <MuscleBalance S={S} />}+ {hasEffort(S) && <EffortCard S={S} />}<div className="cols"><div className="card">@@ -357,8 +393,7 @@ export default function Stats() {{exHist.length ? <><div className="sect-b" style={{ marginBottom: 10 }}><SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId}- options={exHist.map(id => ({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />-+ options={exHist.map(id => ({ value: id, label: nameOf(id) + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} /></div>{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}<div className="chart">@@ -382,12 +417,12 @@ export default function Stats() {</div></div>- {S.workouts.length > 0 && <>+ {workouts.length > 0 && <><div className="row between" style={{ marginBottom: 10 }}><h4 className="sec" style={{ margin: 0 }}>{t('Recent workouts')}</h4>- <Button size="sm" variant="ghost" trailingIcon="chevronRight" onClick={() => nav('/history')}>{t('All')} {S.workouts.length}</Button>+ <Button size="sm" variant="ghost" trailingIcon="chevronRight" onClick={() => nav('/history')}>{t('All')} {workouts.length}</Button></div>- <div className="list">{[...S.workouts].reverse().slice(0, 6).map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>+ <div className="list">{[...workouts].reverse().slice(0, 6).map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div></>}</>}