Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

feat: muscle map Fatigue + Strength (detraining) views

Space-Hermeseeee4b461cb0
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 7ca26e41e..fbdf56d6d 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -24,6 +24,7 @@
"@capacitor/cli": "^7.6.8",
"@capacitor/ios": "^7.6.8",
"@vitejs/plugin-react": "^6.0.3",
+ "linkedom": "^0.18.13",
"vite": "^8.1.5",
"vitest": "^4.1.10"
}
@@ -2594,6 +2595,13 @@
"url": "https://github.com/sponsors/fb55"
}
},
+ "node_modules/cssom": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz",
+ "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/dargs": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz",
@@ -3337,6 +3345,105 @@
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"dev": true
},
+ "node_modules/html-escaper": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz",
+ "integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/htmlparser2": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
+ "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
+ "dev": true,
+ "funding": [
+ "https://github.com/fb55/htmlparser2?sponsor=1",
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.2.2",
+ "entities": "^7.0.1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/dom-serializer/node_modules/entities": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^2.3.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/domutils": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
+ "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/entities": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
@@ -3826,6 +3933,181 @@
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
"dev": true
},
+ "node_modules/linkedom": {
+ "version": "0.18.13",
+ "resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.13.tgz",
+ "integrity": "sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "css-select": "^7.0.0",
+ "cssom": "^0.5.0",
+ "html-escaper": "^3.0.3",
+ "htmlparser2": "^10.1.0",
+ "uhyphen": "^0.2.0"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "peerDependencies": {
+ "canvas": ">= 2"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/linkedom/node_modules/boolbase": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz",
+ "integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/linkedom/node_modules/css-select": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz",
+ "integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^2.0.0",
+ "css-what": "^8.0.0",
+ "domhandler": "^6.0.1",
+ "domutils": "^4.0.2",
+ "nth-check": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/linkedom/node_modules/css-what": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz",
+ "integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/linkedom/node_modules/dom-serializer": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
+ "integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^3.0.0",
+ "domhandler": "^6.0.0",
+ "entities": "^8.0.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/linkedom/node_modules/domelementtype": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
+ "integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
+ "node_modules/linkedom/node_modules/domhandler": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
+ "integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/linkedom/node_modules/domutils": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz",
+ "integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^3.0.0",
+ "domelementtype": "^3.0.0",
+ "domhandler": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
+ "node_modules/linkedom/node_modules/entities": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",
+ "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/linkedom/node_modules/nth-check": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz",
+ "integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/fb55/nth-check?sponsor=1"
+ }
+ },
"node_modules/load-json-file": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz",
@@ -5886,6 +6168,13 @@
"node": ">=0.8.0"
}
},
+ "node_modules/uhyphen": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz",
+ "integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index b8b70caae..3f5849806 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -28,6 +28,7 @@
"@capacitor/cli": "^7.6.8",
"@capacitor/ios": "^7.6.8",
"@vitejs/plugin-react": "^6.0.3",
+ "linkedom": "^0.18.13",
"vite": "^8.1.5",
"vitest": "^4.1.10"
}
diff --git a/frontend/src/components/BodyMap.jsx b/frontend/src/components/BodyMap.jsx
index fe71c47d9..022f1807d 100644
--- a/frontend/src/components/BodyMap.jsx
+++ b/frontend/src/components/BodyMap.jsx
@@ -47,11 +47,13 @@ function View({ view, levels, onMuscle, selected }) {
/**
* <BodyMap load={{ chest: 12, … }} body="male" />
* `load` is effective sets per muscle (see lib/muscles.js); shading is relative to
- * the hardest-worked muscle in that same load, so it always reads as a balance.
+ * the hardest-worked muscle in that same load, so it always reads as a balance. Pass ordered
+ * `{ at, level, exclusive? }` `thresholds` for a fixed absolute scale (recovery views use this
+ * to keep their semantic bands stable); omitting it preserves the balance behavior.
*/
-export default function BodyMap({ load = {}, body = 'male', onMuscle, selected, className = '' }) {
+export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle, selected, className = '' }) {
const paths = useBodyPaths()
- const levels = levelsOf(load)
+ const levels = levelsOf(load, thresholds)
const g = paths && (paths[body] || paths.male)
return (
<div className={'bodymap ' + className}>
diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js
index c744812a0..32db0d94f 100644
--- a/frontend/src/lib/muscles.js
+++ b/frontend/src/lib/muscles.js
@@ -119,11 +119,31 @@ export const loadOfActive = active =>
loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).length })))
/**
- * Shade buckets 0–4 per muscle, relative to the hardest-worked muscle in the same
- * window. Relative rather than absolute on purpose: the map answers "is my training
- * balanced", which only means anything as a comparison within one period.
+ * Shade buckets 0–4 per muscle.
+ *
+ * With no `thresholds`, levels remain relative to the hardest-worked muscle in the same
+ * window. This is the original balance-map behavior. When `thresholds` is supplied, levels
+ * use an absolute scale instead: it is an ordered array of `{ at, level, exclusive? }` rules,
+ * and the last matching rule wins. An exclusive rule matches values strictly greater than
+ * `at`; otherwise the boundary is inclusive. Values below the first matching rule are l0.
+ * Absolute rules let recovery views keep fixed semantic bands instead of renormalizing to the
+ * strongest muscle on screen.
*/
-export function levelsOf(load) {
+export function levelsOf(load, thresholds) {
+ if (thresholds) {
+ const lv = {}
+ MUSCLES.forEach(m => {
+ const value = Number(load[m] || 0)
+ let level = 0
+ for (const rule of thresholds) {
+ const matches = rule.exclusive ? value > rule.at : value >= rule.at
+ if (matches) level = Math.max(0, Math.min(4, rule.level))
+ }
+ lv[m] = level
+ })
+ return lv
+ }
+
const max = Math.max(0, ...MUSCLES.map(m => load[m] || 0))
const lv = {}
MUSCLES.forEach(m => {
diff --git a/frontend/src/lib/recovery-view.js b/frontend/src/lib/recovery-view.js
new file mode 100644
index 000000000..1abc6ffa4
--- /dev/null
+++ b/frontend/src/lib/recovery-view.js
@@ -0,0 +1,17 @@
+import { FATIGUE_STATES } from './recovery.js'
+
+/**
+ * Select the consumer-facing fatigue state for one numeric recovery value.
+ * Values below .25 are ready, .25 through .5 are recovering, and values above .5 are fatigued.
+ * Keeping this boundary selector in production code prevents views and tests from drifting apart.
+ *
+ * @param {number} value Numeric fatigue value from fatigueOf().
+ * @returns {'ready'|'recovering'|'fatigued'} The stable state label for the UI.
+ */
+export function fatigueStateOf(value) {
+ return value < 0.25
+ ? FATIGUE_STATES.READY
+ : value <= 0.5
+ ? FATIGUE_STATES.RECOVERING
+ : FATIGUE_STATES.FATIGUED
+}
diff --git a/frontend/src/lib/recovery-view.test.js b/frontend/src/lib/recovery-view.test.js
new file mode 100644
index 000000000..6ccc7e61d
--- /dev/null
+++ b/frontend/src/lib/recovery-view.test.js
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest'
+import { FATIGUE_STATES, fatigueOf, strengthOf } from './recovery.js'
+import { fatigueStateOf } from './recovery-view.js'
+import { MUSCLES, levelsOf } from './muscles.js'
+
+const FATIGUE_BANDS = [
+ { at: 0, level: 4 },
+ { at: 0.25, level: 2 },
+ { at: 0.5, level: 0, exclusive: true },
+]
+const STRENGTH_BANDS = [
+ { at: 0.5, level: 0 },
+ { at: 0.625, level: 1 },
+ { at: 0.75, level: 2 },
+ { at: 0.875, level: 3 },
+ { at: 1, level: 4 },
+]
+
+describe('production recovery view selectors', () => {
+ it('preserves the relative balance scale when no thresholds are supplied', () => {
+ const levels = levelsOf({ chest: 10, biceps: 5 })
+ expect(levels.chest).toBe(4)
+ expect(levels.biceps).toBe(2)
+ })
+
+ it('uses the production fatigue selector at both approved boundaries', () => {
+ expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
+ expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
+ expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
+ expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
+ })
+
+ it('renders fatigue bands on a fixed absolute scale rather than relative to the map maximum', () => {
+ const levels = levelsOf({
+ chest: 0.25,
+ biceps: 0.6,
+ triceps: 0.1,
+ }, FATIGUE_BANDS)
+ expect(levels.chest).toBe(2)
+ expect(levels.biceps).toBe(0)
+ expect(levels.triceps).toBe(4)
+ })
+
+ it('renders strength on fixed .5-to-1 bands with full retention at l4', () => {
+ const levels = levelsOf({ chest: 0.9, biceps: 1, triceps: 0.5 }, STRENGTH_BANDS)
+ expect(levels.chest).toBe(3)
+ expect(levels.biceps).toBe(4)
+ expect(levels.triceps).toBe(0)
+ })
+
+ it('keeps selectors tied to the same render-time clock', () => {
+ const now = Date.UTC(2026, 0, 22)
+ const workout = { start: now - 15 * 86400000, d: '2026-01-07', entries: [] }
+ expect(strengthOf([workout], now).chest).toBe(0.5)
+ expect(fatigueOf([workout], now).chest).toBe(0)
+ expect(strengthOf([workout], now + 7 * 86400000).chest).toBe(0.5)
+ })
+})
diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js
new file mode 100644
index 000000000..54a27932b
--- /dev/null
+++ b/frontend/src/lib/recovery.js
@@ -0,0 +1,188 @@
+import { EXIDX } from './exercises.js'
+import { MUSCLES, musclesOf } from './muscles.js'
+
+/** Completed-workout window used when calculating current fatigue. */
+export const FATIGUE_WINDOW_MS = 259200000
+
+/** Exponential half-life for fatigue stimulus. */
+export const FATIGUE_HALF_LIFE_MS = 129600000
+
+/** Period after training during which retained strength remains at full value. */
+export const STRENGTH_FULL_MS = 1209600000
+
+/** Exponential half-life for retained strength after the full-retention period. */
+export const STRENGTH_HALF_LIFE_MS = 2419200000
+
+/** Minimum retained-strength value for an untrained or fully detrained muscle. */
+export const STRENGTH_FLOOR = 0.5
+
+/**
+ * Stable labels for consumer fatigue buckets: values below 0.25 are ready, values from 0.25
+ * through 0.5 are recovering, and values above 0.5 are fatigued.
+ */
+export const FATIGUE_STATES = Object.freeze({
+ READY: 'ready',
+ RECOVERING: 'recovering',
+ FATIGUED: 'fatigued',
+})
+
+/**
+ * Return exponential decay expressed as a fraction of one half-life.
+ *
+ * @param {number} ageMs Elapsed age of the stimulus in milliseconds.
+ * @param {number} halfLifeMs Duration of one half-life in milliseconds.
+ * @returns {number} Remaining fraction, using the exact `0.5 ** (age / halfLife)` formula.
+ */
+export function halfLifeDecay(ageMs, halfLifeMs) {
+ return 0.5 ** (ageMs / halfLifeMs)
+}
+
+// The v2 data contract has one timestamp per workout, not per set. Keep this fallback in one
+// place so fatigue and strength use exactly the same stimulus time as effort.js.
+function workoutTimestamp(workout) {
+ const timestamp = workout?.start || new Date(workout?.d).getTime()
+ return Number.isFinite(timestamp) ? timestamp : Number(timestamp)
+}
+
+function emptyMuscleMap(value) {
+ return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
+}
+
+function clamp(value, min, max) {
+ return Math.min(max, Math.max(min, value))
+}
+
+// Yield one weighted stimulus per completed set. Repeating the exercise's muscle weights for
+// every done set is equivalent to multiplying musclesOf(ex) by the completed-set count while
+// preserving the workout/set shape already used by the app.
+function completedStimuli(workouts, include) {
+ const stimuli = []
+ for (const workout of workouts || []) {
+ const timestamp = workoutTimestamp(workout)
+ if (!Number.isFinite(timestamp) || !include(timestamp)) continue
+ for (const entry of workout.entries || []) {
+ const weights = musclesOf(EXIDX[entry.id])
+ for (const set of entry.sets || []) {
+ if (set?.done !== true) continue
+ for (const [slug, weight] of Object.entries(weights)) {
+ if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) {
+ stimuli.push({ slug, timestamp, stimulus: weight })
+ }
+ }
+ }
+ }
+ }
+ return stimuli
+}
+
+const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true]))
+
+function fatigueValue(events, now) {
+ if (!events.length) return 0
+ events.sort((a, b) => a.timestamp - b.timestamp)
+
+ let value = 0
+ let lastTimestamp = events[0].timestamp
+ for (const event of events) {
+ value *= halfLifeDecay(event.timestamp - lastTimestamp, FATIGUE_HALF_LIFE_MS)
+ value += event.stimulus
+ lastTimestamp = event.timestamp
+ }
+ value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS)
+ return clamp(value, 0, 1)
+}
+
+/**
+ * Calculate current per-muscle fatigue from completed sets in the recent window.
+ *
+ * Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed
+ * set contributes the exercise's `musclesOf` weights; sets exactly 72 hours old are excluded.
+ * Stimuli are accumulated chronologically with a 36-hour half-life, decayed to `now`, and
+ * clamped to [0, 1]. The result always contains every drawable muscle slug.
+ *
+ * @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.
+ * @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.
+ */
+export function fatigueOf(workouts, now) {
+ const current = Number(now)
+ const cutoff = current - FATIGUE_WINDOW_MS
+ const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff)
+ const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
+ for (const stimulus of stimuli) byMuscle[stimulus.slug].push(stimulus)
+
+ const result = emptyMuscleMap(0)
+ if (!Number.isFinite(current)) return result
+ for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current)
+ return result
+}
+
+/**
+ * Calculate retained per-muscle strength from the latest completed stimulus in all history.
+ *
+ * A muscle with no completed set starts at the 0.5 floor. After a completed set, strength is
+ * 1.0 through 14 days old, then decays toward the floor with a 28-day half-life. Any later
+ * completed set becomes the new latest stimulus and resets the 14-day full-retention period.
+ * The result always contains every drawable muscle slug.
+ *
+ * @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.
+ * @returns {Record<string, number>} Retained-strength values keyed by every drawable muscle slug.
+ */
+export function strengthOf(workouts, now) {
+ const current = Number(now)
+ const latest = Object.fromEntries(MUSCLES.map(slug => [slug, -Infinity]))
+ const stimuli = completedStimuli(workouts, () => true)
+ for (const stimulus of stimuli) {
+ if (stimulus.timestamp > latest[stimulus.slug]) latest[stimulus.slug] = stimulus.timestamp
+ }
+
+ const result = emptyMuscleMap(STRENGTH_FLOOR)
+ if (!Number.isFinite(current)) return result
+ for (const slug of MUSCLES) {
+ const lastTimestamp = latest[slug]
+ if (!Number.isFinite(lastTimestamp)) continue
+ const age = current - lastTimestamp
+ if (age <= STRENGTH_FULL_MS) {
+ result[slug] = 1
+ } else {
+ result[slug] = Math.max(
+ STRENGTH_FLOOR,
+ halfLifeDecay(age - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS),
+ )
+ }
+ }
+ return result
+}
+
+/**
+ * List muscles currently above the fatigued threshold.
+ *
+ * @param {Array<object>} workouts Workout history passed to {@link fatigueOf}.
+ * @param {number} now Current time in milliseconds passed to {@link fatigueOf}.
+ * @returns {string[]} Muscle slugs whose fatigue value is greater than 0.5, in `MUSCLES`
+ * head-to-toe order.
+ * @example
+ * const avoid = fatiguedMuscles(workouts, now)
+ */
+export function fatiguedMuscles(workouts, now) {
+ return Object.entries(fatigueOf(workouts, now))
+ .filter(([, value]) => value > 0.5)
+ .map(([slug]) => slug)
+}
+
+/**
+ * List muscles whose retained strength is below full retention.
+ *
+ * @param {Array<object>} workouts Workout history passed to {@link strengthOf}.
+ * @param {number} now Current time in milliseconds passed to {@link strengthOf}.
+ * @returns {string[]} Muscle slugs whose retained strength is less than 1.0, in `MUSCLES`
+ * head-to-toe order; never-trained muscles are included at the 0.5 floor.
+ * @example
+ * const targets = detrainedMuscles(workouts, now)
+ */
+export function detrainedMuscles(workouts, now) {
+ return Object.entries(strengthOf(workouts, now))
+ .filter(([, value]) => value < 1)
+ .map(([slug]) => slug)
+}
diff --git a/frontend/src/lib/recovery.test.js b/frontend/src/lib/recovery.test.js
new file mode 100644
index 000000000..2d03dcf2b
--- /dev/null
+++ b/frontend/src/lib/recovery.test.js
@@ -0,0 +1,213 @@
+import { describe, expect, it } from 'vitest'
+import {
+ FATIGUE_HALF_LIFE_MS,
+ FATIGUE_STATES,
+ FATIGUE_WINDOW_MS,
+ STRENGTH_FLOOR,
+ STRENGTH_FULL_MS,
+ STRENGTH_HALF_LIFE_MS,
+ detrainedMuscles,
+ fatiguedMuscles,
+ fatigueOf,
+ halfLifeDecay,
+ strengthOf,
+} from './recovery.js'
+import { EXDB } from './exercises.js'
+import { MUSCLES, musclesOf } from './muscles.js'
+import { fatigueStateOf } from './recovery-view.js'
+
+const HOUR = 60 * 60 * 1000
+const DAY = 24 * HOUR
+const NOW = Date.UTC(2026, 0, 1, 12)
+
+// Keep fixtures tied to the shipped catalogue while making the expected stimulus explicit.
+const SINGLE = EXDB.find(ex => {
+ const weights = musclesOf(ex)
+ return ex.bp !== 'cardio' && Object.keys(weights).length === 1 && Object.values(weights)[0] === 1
+})
+const WEIGHTED = EXDB.find(ex => {
+ const weights = musclesOf(ex)
+ return ex.bp !== 'cardio' && Object.values(weights).includes(0.4)
+})
+if (!SINGLE || !WEIGHTED) throw new Error('recovery tests require single- and secondary-weight fixtures')
+
+const SINGLE_WEIGHTS = musclesOf(SINGLE)
+const WEIGHTED_WEIGHTS = musclesOf(WEIGHTED)
+const SINGLE_SLUG = Object.keys(SINGLE_WEIGHTS)[0]
+const WEIGHTED_PRIMARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 1)
+const SECONDARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 0.4)
+if (!WEIGHTED_PRIMARY_SLUG || !SECONDARY_SLUG) throw new Error('recovery tests require weighted primary and secondary fixtures')
+
+const workoutAt = (id, start, sets = [{ done: true }]) => ({
+ d: new Date(start).toISOString(),
+ start,
+ entries: [{ id, sets: sets.map(set => ({ ...set })) }],
+})
+const doneWorkoutAt = (id, start, count = 1) =>
+ workoutAt(id, start, Array.from({ length: count }, () => ({ done: true })))
+const zeroFatigue = () => Object.fromEntries(MUSCLES.map(slug => [slug, 0]))
+const floorStrength = () => Object.fromEntries(MUSCLES.map(slug => [slug, STRENGTH_FLOOR]))
+
+// Numeric fatigue remains the math API; the UI boundary selector is imported from production.
+const stableFloat = value => Number(value.toFixed(12))
+
+describe('recovery constants', () => {
+ it('exports the pinned windows, half-lives, floor, and state labels', () => {
+ expect(FATIGUE_WINDOW_MS).toBe(72 * HOUR)
+ expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR)
+ expect(STRENGTH_FULL_MS).toBe(14 * DAY)
+ expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY)
+ expect(STRENGTH_FLOOR).toBe(0.5)
+ expect(FATIGUE_STATES).toEqual({ READY: 'ready', RECOVERING: 'recovering', FATIGUED: 'fatigued' })
+ expect(halfLifeDecay(FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS)).toBe(0.5)
+ })
+})
+
+describe('fatigueOf and strengthOf', () => {
+ it('returns every muscle, ready/floor defaults, and hook defaults for empty history', () => {
+ const fatigue = fatigueOf([], NOW)
+ const strength = strengthOf([], NOW)
+
+ expect(Object.keys(fatigue)).toEqual(MUSCLES)
+ expect(fatigue).toEqual(zeroFatigue())
+ expect(Object.values(fatigue).map(fatigueStateOf)).toEqual(
+ MUSCLES.map(() => FATIGUE_STATES.READY),
+ )
+ expect(Object.keys(strength)).toEqual(MUSCLES)
+ expect(strength).toEqual(floorStrength())
+ expect(fatiguedMuscles([], NOW)).toEqual([])
+ expect(detrainedMuscles([], NOW)).toEqual(MUSCLES)
+ })
+
+ it('applies one completed set to each of the exercise muscle weights', () => {
+ const workouts = [doneWorkoutAt(WEIGHTED.id, NOW)]
+ const fatigue = fatigueOf(workouts, NOW)
+ const strength = strengthOf(workouts, NOW)
+
+ for (const slug of MUSCLES) {
+ const weight = WEIGHTED_WEIGHTS[slug] || 0
+ expect(fatigue[slug]).toBe(weight)
+ expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
+ }
+ expect(fatiguedMuscles(workouts, NOW)).toEqual(
+ Object.entries(WEIGHTED_WEIGHTS)
+ .filter(([, weight]) => weight > 0.5)
+ .map(([slug]) => slug),
+ )
+ })
+
+ it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => {
+ for (const age of [FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS / 2]) {
+ const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)
+ const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS)
+ for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) {
+ expect(fatigue[slug]).toBeCloseTo(weight * expectedDecay, 12)
+ }
+ if (age === FATIGUE_HALF_LIFE_MS) expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBe(0.5)
+ if (age === FATIGUE_HALF_LIFE_MS / 2) {
+ expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(0.5 ** 0.5, 12)
+ }
+ }
+ })
+
+ it('excludes a completed set exactly at the strict 72-hour window edge', () => {
+ const workouts = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_WINDOW_MS)]
+ expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue())
+ expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
+ })
+
+ it('ignores sets whose done flag is false for both axes', () => {
+ const workouts = [workoutAt(WEIGHTED.id, NOW, [{ done: false }])]
+ expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue())
+ expect(strengthOf(workouts, NOW)).toEqual(floorStrength())
+ expect(fatiguedMuscles(workouts, NOW)).toEqual([])
+ expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES)
+ })
+})
+
+describe('fatigue state boundaries', () => {
+ it('classifies exactly .25 as recovering and .2499 as ready', () => {
+ const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
+ const valueAt = target => {
+ const age = FATIGUE_HALF_LIFE_MS * Math.log2(weight / target)
+ const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)[SECONDARY_SLUG]
+ expect(value).toBeCloseTo(target, 10)
+ return stableFloat(value)
+ }
+
+ expect(fatigueStateOf(valueAt(0.25))).toBe(FATIGUE_STATES.RECOVERING)
+ expect(fatigueStateOf(valueAt(0.2499))).toBe(FATIGUE_STATES.READY)
+ })
+
+ it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => {
+ const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS)]
+ const aboveHalf = [
+ doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(1 / 0.5001)),
+ ]
+ const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG]
+ const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG]
+
+ expect(half).toBe(0.5)
+ expect(fatigueStateOf(half)).toBe(FATIGUE_STATES.RECOVERING)
+ expect(fatiguedMuscles(atHalf, NOW)).toEqual([])
+ expect(above).toBeCloseTo(0.5001, 10)
+ expect(fatigueStateOf(stableFloat(above))).toBe(FATIGUE_STATES.FATIGUED)
+ expect(fatiguedMuscles(aboveHalf, NOW)).toEqual([SINGLE_SLUG])
+ })
+})
+
+describe('strengthOf', () => {
+ const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG]
+
+ it('stays at full retention through 14 days and decays from 15 days by the 28-day half-life', () => {
+ expect(strengthAt(STRENGTH_FULL_MS)).toBe(1)
+ expect(strengthAt(15 * DAY)).toBeCloseTo(0.5 ** (1 / 28), 10)
+ })
+
+ it('clamps the 42-day half-life point and later 56-day value at the .5 floor', () => {
+ expect(strengthAt(42 * DAY)).toBe(0.5)
+ expect(strengthAt(56 * DAY)).toBe(STRENGTH_FLOOR)
+ })
+
+ it('resets retained strength when a later completed session retrains the muscle', () => {
+ const workouts = [
+ doneWorkoutAt(SINGLE.id, NOW - 20 * DAY),
+ doneWorkoutAt(SINGLE.id, NOW),
+ ]
+ expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
+ })
+})
+
+describe('accumulation and purity', () => {
+ it('matches the sum of independently decayed stimuli in chronological order', () => {
+ const ages = [64 * HOUR, 40 * HOUR]
+ const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age))
+ const expected = ages.reduce(
+ (sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
+ 0,
+ )
+
+ expect(expected).toBeLessThan(1)
+ expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 12)
+ expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 12)
+ })
+
+ it('clamps saturation and returns identical results without mutating inputs or sharing state', () => {
+ const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)]
+ expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBe(1)
+
+ const workouts = [
+ doneWorkoutAt(SINGLE.id, NOW - 64 * HOUR),
+ doneWorkoutAt(SINGLE.id, NOW - 40 * HOUR),
+ ]
+ const before = JSON.parse(JSON.stringify(workouts))
+ const firstFatigue = fatigueOf(workouts, NOW)
+ const firstStrength = strengthOf(workouts, NOW)
+ const secondFatigue = fatigueOf(workouts, NOW)
+ const secondStrength = strengthOf(workouts, NOW)
+
+ expect(secondFatigue).toEqual(firstFatigue)
+ expect(secondStrength).toEqual(firstStrength)
+ expect(workouts).toEqual(before)
+ })
+})
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index d62b7c5df..2ad887664 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -378,6 +378,13 @@ export default {
'Admin dashboard': 'Admin-Dashboard',
// --- muscle map ---
'Muscle balance': 'Muskelbalance',
+ 'Fatigue': 'Ermüdung',
+ 'Ready': 'Bereit',
+ 'Recovering': 'In Erholung',
+ 'Fatigued': 'Ermüdet',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'Die Ermüdung zeigt, wie lange das Training jedes Muskels zurückliegt. Ein hoher Wert bedeutet: Pause.',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'Die Kraft zeigt, wie viel Muskelkraft erhalten ist. Trainiere erneut, um sie zurückzusetzen.',
+ 'Weeks since training: {0}': 'Zuletzt vor {0} Wo. trainiert',
'by sets worked': 'nach Sätzen',
'Week': 'Woche',
'not trained': 'nicht trainiert',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 27c17f01b..537af8342 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': 'Panel de administración',
// --- muscle map ---
'Muscle balance': 'Equilibrio muscular',
+ 'Fatigue': 'Fatiga',
+ 'Ready': 'Listo',
+ 'Recovering': 'En recuperación',
+ 'Fatigued': 'Fatigado',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatiga indica cuánto tiempo ha pasado desde el último entrenamiento de cada músculo. Un valor alto indica que toca descansar.',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'La fuerza muestra cuánta fuerza muscular se conserva. Vuelve a entrenar para restablecerla.',
+ 'Weeks since training: {0}': 'Último entrenamiento: hace {0} sem.',
'by sets worked': 'por series trabajadas',
'Week': 'Semana',
'not trained': 'sin entrenar',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 9b1de4455..e233a3ba5 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': 'Tableau d’administration',
// --- muscle map ---
'Muscle balance': 'Équilibre musculaire',
+ 'Fatigue': 'Fatigue',
+ 'Ready': 'Prêt',
+ 'Recovering': 'En récupération',
+ 'Fatigued': 'Fatigué',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatigue indique à quand remonte le dernier entraînement de chaque muscle. Un niveau élevé signifie qu’il est temps de se reposer.',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'La force indique combien de force musculaire est conservée. Entraîne-toi à nouveau pour la réinitialiser.',
+ 'Weeks since training: {0}': 'Dernier entraînement : il y a {0} sem.',
'by sets worked': 'par séries effectuées',
'Week': 'Semaine',
'not trained': 'non travaillé',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 163cb93f7..bbf29473f 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': 'एडमिन डैशबोर्ड',
// --- muscle map ---
'Muscle balance': 'मांसपेशी संतुलन',
+ 'Fatigue': 'थकान',
+ 'Ready': 'तैयार',
+ 'Recovering': 'पुनर्प्राप्ति में',
+ 'Fatigued': 'थकी हुई',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'थकान बताती है कि हर मांसपेशी की ट्रेनिंग कितनी हाल की है। अधिक थकान होने पर आराम करें।',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'शक्ति बताती है कि मांसपेशियों की कितनी ताकत बनी हुई है। इसे रीसेट करने के लिए फिर से ट्रेन करें।',
+ 'Weeks since training: {0}': 'पिछला व्यायाम: {0} सप्ताह पहले',
'by sets worked': 'सेट के अनुसार',
'Week': 'सप्ताह',
'not trained': 'प्रशिक्षित नहीं',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index af7318242..5ccc24b46 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': 'Pannello di amministrazione',
// --- muscle map ---
'Muscle balance': 'Equilibrio muscolare',
+ 'Fatigue': 'Fatica',
+ 'Ready': 'Pronto',
+ 'Recovering': 'In recupero',
+ 'Fatigued': 'Affaticato',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatica mostra quanto è recente l’allenamento di ogni muscolo. Un valore alto significa che serve riposo.',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'La forza mostra quanta forza muscolare hai mantenuto. Allenati di nuovo per reimpostarla.',
+ 'Weeks since training: {0}': 'Ultimo allenamento: {0} sett. fa',
'by sets worked': 'per serie svolte',
'Week': 'Settimana',
'not trained': 'non allenato',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index c6a6431f9..1bcc2bddf 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': '관리자 대시보드',
// --- muscle map ---
'Muscle balance': '근육 균형',
+ 'Fatigue': '피로',
+ 'Ready': '준비됨',
+ 'Recovering': '회복 중',
+ 'Fatigued': '피로함',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': '피로도는 각 근육을 얼마나 최근에 운동했는지 보여줍니다. 높을수록 휴식이 필요합니다.',
+ 'Strength shows retained muscle strength. Train again to reset it.': '근력은 근육에 남아 있는 힘을 보여줍니다. 다시 운동하면 값이 초기화됩니다.',
+ 'Weeks since training: {0}': '마지막 운동: {0}주 전',
'by sets worked': '세트 수 기준',
'Week': '이번 주',
'not trained': '훈련 안 함',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 5d0fc10a3..dae273ca7 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': 'Panel administratora',
// --- muscle map ---
'Muscle balance': 'Równowaga mięśniowa',
+ 'Fatigue': 'Zmęczenie',
+ 'Ready': 'Gotowe',
+ 'Recovering': 'W regeneracji',
+ 'Fatigued': 'Zmęczony',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'Zmęczenie pokazuje, jak niedawno trenowano każdą partię mięśni. Wysoki poziom oznacza potrzebę odpoczynku.',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'Siła pokazuje, ile siły mięśniowej pozostało. Ponowny trening przywraca jej poziom wyjściowy.',
+ 'Weeks since training: {0}': 'Trening: {0} tyg. temu',
'by sets worked': 'wg serii',
'Week': 'Tydzień',
'not trained': 'nietrenowane',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index e7e9d0c3f..a181fe368 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': 'Painel de administração',
// --- muscle map ---
'Muscle balance': 'Equilíbrio muscular',
+ 'Fatigue': 'Fadiga',
+ 'Ready': 'Pronto',
+ 'Recovering': 'Em recuperação',
+ 'Fatigued': 'Fatigado',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'A fadiga mostra há quanto tempo cada músculo foi treinado. Um nível elevado significa que é preciso descansar.',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'A força mostra quanta força muscular se mantém. Treina novamente para repor o valor.',
+ 'Weeks since training: {0}': 'Treino: há {0} sem.',
'by sets worked': 'por séries trabalhadas',
'Week': 'Semana',
'not trained': 'sem treino',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 98a9a7c65..a3ba4a722 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': 'Панель администратора',
// --- muscle map ---
'Muscle balance': 'Баланс мышц',
+ 'Fatigue': 'Усталость',
+ 'Ready': 'Готова',
+ 'Recovering': 'Восстанавливается',
+ 'Fatigued': 'Утомлена',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'Усталость показывает, насколько недавно тренировалась каждая мышца. Высокий уровень означает, что пора отдохнуть.',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'Сила показывает, сколько мышечной силы сохранилось. Повторная тренировка сбрасывает это значение.',
+ 'Weeks since training: {0}': 'Тренировка: {0} нед. назад',
'by sets worked': 'по подходам',
'Week': 'Неделя',
'not trained': 'не тренировалась',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index a5853bf70..60c3760a3 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': 'Yönetici paneli',
// --- muscle map ---
'Muscle balance': 'Kas dengesi',
+ 'Fatigue': 'Yorgunluk',
+ 'Ready': 'Hazır',
+ 'Recovering': 'Toparlanıyor',
+ 'Fatigued': 'Yorgun',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': 'Yorgunluk, her kasın ne kadar süre önce çalıştırıldığını gösterir. Yüksek değer dinlenmek gerektiği anlamına gelir.',
+ 'Strength shows retained muscle strength. Train again to reset it.': 'Kuvvet, kas gücünün ne kadarının korunduğunu gösterir. Yeniden çalışarak değeri sıfırlayabilirsin.',
+ 'Weeks since training: {0}': 'Son antrenman: {0} hafta önce',
'by sets worked': 'çalışılan sete göre',
'Week': 'Hafta',
'not trained': 'çalışılmadı',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 518427a57..bf33ba58d 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -360,6 +360,13 @@ export default {
'Admin dashboard': '管理后台',
// --- muscle map ---
'Muscle balance': '肌肉平衡',
+ 'Fatigue': '疲劳',
+ 'Ready': '准备好',
+ 'Recovering': '恢复中',
+ 'Fatigued': '已疲劳',
+ 'Fatigue shows how recently each muscle was trained. High means rest.': '疲劳度显示每个肌群最近一次训练距今多久。数值越高,越需要休息。',
+ 'Strength shows retained muscle strength. Train again to reset it.': '力量显示肌肉力量保留了多少。再次训练即可重置。',
+ 'Weeks since training: {0}': '上次训练:{0}周前',
'by sets worked': '按训练组数',
'Week': '本周',
'not trained': '未训练',
diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx
index f25b3cd57..9da7f0f35 100644
--- a/frontend/src/views/Stats.jsx
+++ b/frontend/src/views/Stats.jsx
@@ -1,4 +1,4 @@
-import { useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
@@ -10,7 +10,9 @@ import LineChart from '../components/LineChart.jsx'
import Heatmap from '../components/Heatmap.jsx'
import Icon from '../components/Icon.jsx'
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
-import { loadOfWorkouts, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
+import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
+import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js'
+import { fatigueStateOf } from '../lib/recovery-view.js'
import { e1rmSeries, best1RM } from '../lib/onerm.js'
import {
hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
@@ -20,11 +22,93 @@ import { Button, Segmented, SelectRow } from '../components/ui.jsx'
// 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).
+function latestMuscleTraining(workouts) {
+ const latest = {}
+ for (const workout of workouts || []) {
+ const timestamp = Number(workout?.start || new Date(workout?.d).getTime())
+ if (!Number.isFinite(timestamp)) continue
+ for (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 (latest[slug] == null || timestamp > latest[slug]) latest[slug] = timestamp
+ }
+ }
+ }
+ return latest
+}
+
+const FATIGUE_LEVELS = [
+ { at: 0, level: 4 },
+ { at: 0.25, level: 2 },
+ { at: 0.5, level: 0, exclusive: true },
+]
+
+const STRENGTH_LEVELS = [
+ { at: STRENGTH_FLOOR, level: 0 },
+ { at: 0.625, level: 1 },
+ { at: 0.75, level: 2 },
+ { at: 0.875, level: 3 },
+ { at: 1, level: 4 },
+]
+
+function useNow() {
+ const [, setTick] = useState(0)
+ useEffect(() => {
+ const iv = setInterval(() => setTick(tick => tick + 1), 60000)
+ return () => clearInterval(iv)
+ }, [])
+ return Date.now()
+}
+
+/**
+ * Return the whole weeks since a completed muscle-training timestamp.
+ *
+ * @param {number} now Current render-time timestamp in milliseconds.
+ * @param {number} lastTrained Timestamp of the latest completed training event.
+ * @returns {number} Non-negative whole weeks, including zero for ages under seven days.
+ */
+export function weeksSinceTraining(now, lastTrained) {
+ return Math.max(0, Math.floor((now - lastTrained) / 86400000 / 7))
+}
+
+function FatigueLegend() {
+ return <div className="hm-legend" aria-label={t('Fatigue')}>
+ <span>{t('Fatigued')}</span><div className="hm-c l0" />
+ <span>{t('Recovering')}</span><div className="hm-c l2" />
+ <span>{t('Ready')}</span><div className="hm-c l4" />
+ </div>
+}
+
+function StrengthLegend() {
+ return <div className="hm-legend" aria-label={t('Strength')}>
+ <span>1</span><div className="hm-c l4" /><div className="hm-c l3" /><div className="hm-c l2" />
+ <div className="hm-c l1" /><div className="hm-c l0" /><span>{fmtNum(STRENGTH_FLOOR)}</span>
+ </div>
+}
+
+function fatigueLabel(value) {
+ const state = fatigueStateOf(value)
+ return t(state === 'ready' ? 'Ready' : state === 'recovering' ? 'Recovering' : 'Fatigued')
+}
+
function MuscleBalance({ S }) {
+ const [view, setView] = useState('balance')
const [win, setWin] = useState(7)
const [hard, setHard] = useState(false)
const [sel, setSel] = useState(null)
- const now = Date.now()
+ const now = useNow()
+ const workouts = S.workouts
+ const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now])
+ const strength = useMemo(() => strengthOf(workouts, now), [workouts, now])
+ 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])
+ return t('Weeks since training: {0}', weeks)
+ }
+ const toggleSel = m => setSel(s => (s === m ? null : m))
const inWin = S.workouts.filter(w =>
win === 0 ? true
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
@@ -42,35 +126,58 @@ function MuscleBalance({ S }) {
const sets = m => Math.round((load[m] || 0) * 10) / 10
return <div className="card">
- <div className="row between" style={{ marginBottom: 8 }}>
- <h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
- {rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
- onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
- </div>
- <Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
- options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
- {inWin.length ? <>
- <BodyMap className="tappable" load={load} body={S.body} selected={sel}
- onMuscle={m => setSel(s => (s === m ? null : m))} />
- <BodyMapLegend />
+ <Segmented className="seg-range" value={view} onChange={setView}
+ options={[{ value: 'balance', label: t('Muscle balance') }, { value: 'fatigue', label: t('Fatigue') }, { value: 'strength', label: t('Strength') }]} />
+ {view === 'balance' ? <>
+ <div className="row between" style={{ marginBottom: 8 }}>
+ <h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
+ {rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
+ onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
+ </div>
+ <Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
+ options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
+ {inWin.length ? <>
+ <BodyMap className="tappable" load={load} body={S.body} selected={sel}
+ onMuscle={m => setSel(s => (s === m ? null : m))} />
+ <BodyMapLegend />
+ {sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
+ <span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
+ <span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
+ </div>}
+ {!sel && top.map(m => <div key={m} className="mrow">
+ <span className="nm">{t(MUSCLE_NAME[m])}</span>
+ <span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
+ <span className="v">{t('{0} sets', sets(m))}</span>
+ </div>)}
+ {missed.length > 0 && <>
+ <h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
+ <div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
+ </>}
+ {!missed.length && worked.length > 0 &&
+ <div className="muted small" style={{ marginTop: 10 }}>{on
+ ? t('Every muscle group got at least one hard set in this period.')
+ : t('Every muscle group got some work in this period.')}</div>}
+ </> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
+ </> : view === 'fatigue' ? <>
+ <h2>{t('Fatigue')}</h2>
+ <BodyMap className="tappable" load={fatigue} thresholds={FATIGUE_LEVELS} body={S.body} selected={sel} onMuscle={toggleSel} />
+ <FatigueLegend />
+ <div className="muted small" style={{ marginTop: 10 }}>{t('Fatigue shows how recently each muscle was trained. High means rest.')}</div>
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
- <span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
+ <span className="v">{fatigueLabel(fatigue[sel])}</span>
</div>}
- {!sel && top.map(m => <div key={m} className="mrow">
- <span className="nm">{t(MUSCLE_NAME[m])}</span>
- <span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
- <span className="v">{t('{0} sets', sets(m))}</span>
+ </> : <>
+ <h2>{t('Strength')}</h2>
+ <BodyMap className="tappable" 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>
+ {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>
+ <span className="v">{strengthHint(slug)}</span>
</div>)}
- {missed.length > 0 && <>
- <h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
- <div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
- </>}
- {!missed.length && worked.length > 0 &&
- <div className="muted small" style={{ marginTop: 10 }}>{on
- ? t('Every muscle group got at least one hard set in this period.')
- : t('Every muscle group got some work in this period.')}</div>}
- </> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
+ </>}
</div>
}
diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx
new file mode 100644
index 000000000..e21db45e3
--- /dev/null
+++ b/frontend/src/views/Stats.recovery.test.jsx
@@ -0,0 +1,300 @@
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { parseHTML } from 'linkedom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { MUSCLES, MUSCLE_NAME, levelsOf, rankOf } from '../lib/muscles.js'
+import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js'
+import { fatigueStateOf } from '../lib/recovery-view.js'
+import Stats, { weeksSinceTraining } from './Stats.jsx'
+
+const DAY = 86400000
+const HOUR = 3600000
+const BASE_NOW = Date.UTC(2026, 0, 22, 12)
+
+const mocks = vi.hoisted(() => ({
+ maps: [],
+ mapMounts: 0,
+ S: {
+ unit: 'kg', body: 'male', effort: 'rir', targetW: null,
+ bodyweight: [], routines: [], workouts: [],
+ },
+}))
+
+vi.mock('../store/useStore.js', () => ({
+ useStore: selector => selector({ S: mocks.S }),
+}))
+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
+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/Heatmap.jsx', () => ({ default: () => React.createElement('div') }))
+vi.mock('../components/Icon.jsx', () => ({ default: props => React.createElement('span', props) }))
+vi.mock('../components/BodyMap.jsx', () => ({
+ default: props => {
+ mocks.maps.push(props)
+ React.useEffect(() => {
+ mocks.mapMounts++
+ return () => {}
+ }, [])
+ return React.createElement(
+ 'div',
+ { 'data-body-map': true, 'data-selected-muscle': props.selected || '' },
+ React.createElement('button', {
+ 'data-muscle': 'chest',
+ onClick: () => props.onMuscle?.('chest'),
+ }, 'Chest'),
+ )
+ },
+ BodyMapLegend: () => React.createElement('div', { 'data-balance-legend': true }),
+}))
+
+let dom
+let root
+let container
+
+function iso(timestamp) {
+ return new Date(timestamp).toISOString().slice(0, 10)
+}
+
+function set(done, extra = {}) {
+ return { done, w: 10, r: 8, ...extra }
+}
+
+function workout(id, start, entries) {
+ return { id, d: iso(start), start, entries }
+}
+
+function entry(id, sets) {
+ return { id, sets }
+}
+
+function lifecycleWorkouts(now = BASE_NOW) {
+ // The 36-hour fatigue edge crosses .5 after one 60-second interval tick.
+ const fatigueEdge = now - (36 * HOUR - 30000)
+ // This completed set is in the initial 30-day Balance window, then ages out after one tick.
+ const balanceEdge = now - (30 * DAY - 30000)
+ // The 14-day strength edge becomes sub-full after one tick.
+ const strengthEdge = now - (14 * DAY - 30000)
+ // This completed event must remain the latest training event for abs: the newer set is undone.
+ const absCompleted = now - 20 * DAY
+ const absUndone = now - DAY
+ return [
+ workout('fatigue-edge', fatigueEdge, [entry('1254', [set(true, { rir: 0 })])]),
+ workout('balance-edge', balanceEdge, [entry('1254', [set(true, { rir: 2 })])]),
+ workout('strength-edge', strengthEdge, [entry('1001', [set(true, { rir: 2 })])]),
+ workout('abs-completed', absCompleted, [entry('1002', [set(true, { rir: 2 })])]),
+ workout('abs-undone', absUndone, [entry('1002', [set(false, { rir: 0 })])]),
+ ]
+}
+
+function allFatiguedWorkout(now = BASE_NOW) {
+ // Primary muscles have one completed set. The three secondary-only map slugs have two
+ // completed sets so their .4 weights are also above the production .5 fatigue boundary.
+ const ids = [
+ ['1018', 1], // trapezius
+ ['1012', 1], // deltoids
+ ['1167', 1], // chest
+ ['1013', 1], // upper-back
+ ['3011', 1], // serratus
+ ['1413', 1], // biceps
+ ['1399', 1], // triceps
+ ['1016', 1], // forearm
+ ['1005', 2], // abs + obliques
+ ['1010', 1], // lower-back
+ ['1003', 1], // gluteal
+ ['1001', 1], // quadriceps
+ ['1511', 1], // hamstring
+ ['1494', 1], // adductors
+ ['1002', 2], // abs + hip-flexors
+ ['1000', 1], // calves
+ ['1396', 2], // calves + tibialis
+ ]
+ return workout('all-fatigued', now, ids.map(([id, count]) => entry(id, Array.from({ length: count }, () => set(true)))))
+}
+
+function allSubfullWorkout(now = BASE_NOW) {
+ return workout('all-subfull', now - 15 * DAY, [entry('1254', [set(true)])])
+}
+
+function resetFixture(workouts = lifecycleWorkouts()) {
+ mocks.S.workouts = workouts
+ mocks.maps.length = 0
+ mocks.mapMounts = 0
+}
+
+function installDom() {
+ const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
+ dom = parsed.window
+ globalThis.window = dom
+ globalThis.document = dom.document
+ Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
+ for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key]
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ container = document.getElementById('root')
+ root = createRoot(container)
+}
+
+async function mountStats() {
+ installDom()
+ await act(async () => { root.render(React.createElement(Stats)) })
+}
+
+async function unmountStats() {
+ if (!root) return
+ await act(async () => { root.unmount() })
+ root = null
+ container = null
+ dom = null
+}
+
+function muscleCard() {
+ return [...container.querySelectorAll('.card')].find(card =>
+ [...card.querySelectorAll('.seg button')].some(button =>
+ ['Muscle balance', 'Fatigue', 'Strength'].includes(button.textContent.trim())))
+}
+
+function buttonWithText(scope, text) {
+ return [...scope.querySelectorAll('button')].find(button => button.textContent.trim() === text)
+}
+
+function viewButton(text) {
+ return buttonWithText(muscleCard(), text)
+}
+
+function balanceRangeButton(text) {
+ const segments = muscleCard().querySelectorAll('.seg')
+ return buttonWithText(segments[1], text)
+}
+
+async function click(button) {
+ expect(button, `expected a button named ${button?.textContent || 'unknown'}`).toBeTruthy()
+ await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
+}
+
+async function tick(milliseconds) {
+ await act(async () => { await vi.advanceTimersByTimeAsync(milliseconds) })
+}
+
+function lastMap() {
+ return mocks.maps.at(-1)
+}
+
+function expectPressed(button) {
+ expect(button?.getAttribute('aria-pressed')).toBe('true')
+}
+
+function strengthRows() {
+ return [...muscleCard().querySelectorAll('.mrow .nm')].map(node => node.textContent.trim())
+}
+
+afterEach(async () => {
+ await unmountStats()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(BASE_NOW)
+ resetFixture()
+})
+
+describe('Stats muscle recovery view runtime', () => {
+ it('starts in Balance and preserves range, hard filter, and selected muscle through every real view transition', async () => {
+ await mountStats()
+ const card = muscleCard()
+
+ expectPressed(buttonWithText(card, 'Muscle balance'))
+ expectPressed(buttonWithText(card, 'Week'))
+
+ await click(balanceRangeButton('30d'))
+ await click(buttonWithText(card, 'All'))
+ await click(card.querySelector('[data-muscle="chest"]'))
+ expectPressed(balanceRangeButton('30d'))
+ expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
+ expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
+
+ await click(viewButton('Fatigue'))
+ expect(container.textContent).toContain('Fatigue shows how recently each muscle was trained. High means rest.')
+ await click(viewButton('Strength'))
+ expect(container.textContent).toContain('Strength shows retained muscle strength. Train again to reset it.')
+ await click(viewButton('Muscle balance'))
+
+ expectPressed(balanceRangeButton('30d'))
+ expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
+ expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
+ expect(lastMap().selected).toBe('chest')
+ expect(lastMap().load.chest).toBe(2)
+ })
+
+ it('refreshes fatigue presentation, Balance 30-day filtering, and the mounted tree on the 60-second tick', async () => {
+ await mountStats()
+ await click(balanceRangeButton('30d'))
+ await click(viewButton('Fatigue'))
+ await click(muscleCard().querySelector('[data-muscle="chest"]'))
+
+ const beforeTickMounts = mocks.mapMounts
+ const beforeTick = lastMap().load.chest
+ expect(fatigueStateOf(beforeTick)).toBe(FATIGUE_STATES.FATIGUED)
+ expect(container.textContent).toContain('Fatigued')
+
+ await tick(60000)
+
+ const afterTick = lastMap().load.chest
+ expect(mocks.mapMounts).toBe(beforeTickMounts)
+ expect(afterTick).toBeLessThan(0.5)
+ expect(fatigueStateOf(afterTick)).toBe(FATIGUE_STATES.RECOVERING)
+ expect(container.textContent).toContain('Recovering')
+
+ await click(viewButton('Strength'))
+ expect(lastMap().load.quadriceps).toBeLessThan(1)
+ expect(strengthRows()).toContain('Quads')
+
+ await click(viewButton('Muscle balance'))
+ expect(lastMap().load.chest).toBe(1)
+ expectPressed(balanceRangeButton('30d'))
+ })
+
+ it('ignores an undone latest set, floors rendered training age, and follows production rankOf ordering', async () => {
+ await mountStats()
+ await click(viewButton('Strength'))
+
+ const load = lastMap().load
+ const expectedRows = rankOf(load).worked
+ .filter(slug => load[slug] < 1)
+ .map(slug => MUSCLE_NAME[slug])
+ expect(strengthRows()).toEqual(expectedRows)
+
+ // The newer abs row is undone, so the rendered hint uses the completed event from 20 days ago.
+ expect(container.textContent).toContain('Weeks since training: 2')
+
+ // The production helper used by Stats' rendered strength hint floors six elapsed days to zero.
+ expect(weeksSinceTraining(BASE_NOW, BASE_NOW - 6 * DAY)).toBe(0)
+ })
+
+ it('uses production boundaries and fixed absolute bands for all-fatigued and all-subfull maps', async () => {
+ expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
+ expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
+ expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
+ expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
+
+ resetFixture([allFatiguedWorkout()])
+ await mountStats()
+ await click(viewButton('Fatigue'))
+ const fatigueMap = lastMap()
+ expect(Object.keys(fatigueMap.load)).toEqual(MUSCLES)
+ expect(Object.values(fatigueMap.load).every(value => value > 0.5)).toBe(true)
+ expect(Object.values(levelsOf(fatigueMap.load, fatigueMap.thresholds)).every(level => level === 0)).toBe(true)
+
+ await unmountStats()
+ resetFixture([allSubfullWorkout()])
+ await mountStats()
+ await click(viewButton('Strength'))
+ const strengthMap = lastMap()
+ expect(Object.values(strengthMap.load).every(value => value < 1)).toBe(true)
+ expect(Math.min(...Object.values(strengthMap.load))).toBe(STRENGTH_FLOOR)
+ expect(strengthMap.thresholds.at(-1)).toEqual({ at: 1, level: 4 })
+ })
+})