From eeee4b461cb0884cb1efe39c420c6a89a5bbfd18 Mon Sep 17 00:00:00 2001 From: Space-Hermes Date: Thu, 6 Aug 2026 11:33:21 +0200 Subject: [PATCH 1/5] feat: muscle map Fatigue + Strength (detraining) views Per-muscle fatigue (72h window, 36h half-life, .25/.5 bands) and retained strength (14d plateau, 28d half-life, .5 floor) views on the Stats page behind a Balance | Fatigue | Strength segmented control. Pure recovery.js module with fatiguedMuscles/detrainedMuscles hooks, owner-approved backward-compatible absolute-level BodyMap extension, 8 i18n keys across English fallback + 11 locale packs, mounted interaction tests. --- frontend/package-lock.json | 289 ++++++++++++++++++++ frontend/package.json | 1 + frontend/src/components/BodyMap.jsx | 8 +- frontend/src/lib/muscles.js | 28 +- frontend/src/lib/recovery-view.js | 17 ++ frontend/src/lib/recovery-view.test.js | 58 ++++ frontend/src/lib/recovery.js | 188 +++++++++++++ frontend/src/lib/recovery.test.js | 213 +++++++++++++++ frontend/src/locales/de.js | 7 + frontend/src/locales/es.js | 7 + frontend/src/locales/fr.js | 7 + frontend/src/locales/hi.js | 7 + frontend/src/locales/it.js | 7 + frontend/src/locales/ko.js | 7 + frontend/src/locales/pl.js | 7 + frontend/src/locales/pt.js | 7 + frontend/src/locales/ru.js | 7 + frontend/src/locales/tr.js | 7 + frontend/src/locales/zh.js | 7 + frontend/src/views/Stats.jsx | 163 +++++++++-- frontend/src/views/Stats.recovery.test.jsx | 300 +++++++++++++++++++++ 21 files changed, 1307 insertions(+), 35 deletions(-) create mode 100644 frontend/src/lib/recovery-view.js create mode 100644 frontend/src/lib/recovery-view.test.js create mode 100644 frontend/src/lib/recovery.js create mode 100644 frontend/src/lib/recovery.test.js create mode 100644 frontend/src/views/Stats.recovery.test.jsx diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 7ca26e4..fbdf56d 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 b8b70ca..3f58498 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 fe71c47..022f180 100644 --- a/frontend/src/components/BodyMap.jsx +++ b/frontend/src/components/BodyMap.jsx @@ -47,11 +47,13 @@ function View({ view, levels, onMuscle, selected }) { /** * * `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 (
diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js index c744812..32db0d9 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 0000000..1abc6ff --- /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 0000000..6ccc7e6 --- /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 0000000..54a2793 --- /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} 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} 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} 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} 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} 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} 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 0000000..2d03dcf --- /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 d62b7c5d..2ad8876 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 27c17f0..537af83 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 9b1de44..e233a3b 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 163cb93..bbf2947 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 af73182..5ccc24b 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 c6a6431..1bcc2bd 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 5d0fc10..dae273c 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 e7e9d0c..a181fe3 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 98a9a7c..a3ba4a7 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 a5853bf..60c3760 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 518427a..bf33ba5 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 f25b3cd..9da7f0f 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
+ {t('Fatigued')}
+ {t('Recovering')}
+ {t('Ready')}
+
+} + +function StrengthLegend() { + return
+ 1
+
{fmtNum(STRENGTH_FLOOR)} +
+} + +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
-
-

{t('Muscle balance')} · {on ? t('by hard sets') : t('by sets worked')}

- {rated && } -
- { 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 ? <> - setSel(s => (s === m ? null : m))} /> - + + {view === 'balance' ? <> +
+

{t('Muscle balance')} · {on ? t('by hard sets') : t('by sets worked')}

+ {rated && } +
+ { 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 ? <> + setSel(s => (s === m ? null : m))} /> + + {sel &&
+ {t(MUSCLE_NAME[sel])} + {sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')} +
} + {!sel && top.map(m =>
+ {t(MUSCLE_NAME[m])} + + {t('{0} sets', sets(m))} +
)} + {missed.length > 0 && <> +

{on ? t('No hard sets in this period') : t('Not trained in this period')}

+
{missed.map(m => {t(MUSCLE_NAME[m])})}
+ } + {!missed.length && worked.length > 0 && +
{on + ? t('Every muscle group got at least one hard set in this period.') + : t('Every muscle group got some work in this period.')}
} + :
{t('No workouts in this period yet.')}
} + : view === 'fatigue' ? <> +

{t('Fatigue')}

+ + +
{t('Fatigue shows how recently each muscle was trained. High means rest.')}
{sel &&
{t(MUSCLE_NAME[sel])} - {sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')} + {fatigueLabel(fatigue[sel])}
} - {!sel && top.map(m =>
- {t(MUSCLE_NAME[m])} - - {t('{0} sets', sets(m))} + : <> +

{t('Strength')}

+ + +
{t('Strength shows retained muscle strength. Train again to reset it.')}
+ {detrained.map(slug =>
+ {t(MUSCLE_NAME[slug])} + + {strengthHint(slug)}
)} - {missed.length > 0 && <> -

{on ? t('No hard sets in this period') : t('Not trained in this period')}

-
{missed.map(m => {t(MUSCLE_NAME[m])})}
- } - {!missed.length && worked.length > 0 && -
{on - ? t('Every muscle group got at least one hard set in this period.') - : t('Every muscle group got some work in this period.')}
} - :
{t('No workouts in this period yet.')}
} + }
} diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx new file mode 100644 index 0000000..e21db45 --- /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('
') + 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 }) + }) +}) From 9af028bde349ec3cdc93d5d09784b34b95791cd3 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 6 Aug 2026 19:16:08 +0200 Subject: [PATCH 2/5] confirmed UI tweaks: fatigued highlighted (red/amber), strongest gold, strength scale labels, exercise list by current strength, 90d volume on strength rows --- frontend/src/index.css | 12 ++++++ frontend/src/locales/de.js | 2 + frontend/src/locales/es.js | 2 + frontend/src/locales/fr.js | 2 + frontend/src/locales/hi.js | 2 + frontend/src/locales/it.js | 2 + frontend/src/locales/ko.js | 2 + frontend/src/locales/pl.js | 2 + frontend/src/locales/pt.js | 2 + frontend/src/locales/ru.js | 2 + frontend/src/locales/tr.js | 2 + frontend/src/locales/zh.js | 2 + frontend/src/views/Stats.jsx | 43 +++++++++++++++------- frontend/src/views/Stats.recovery.test.jsx | 10 ++--- 14 files changed, 69 insertions(+), 18 deletions(-) diff --git a/frontend/src/index.css b/frontend/src/index.css index 9de4f63..024eebe 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -777,6 +777,18 @@ h4.sec{ .bm-m.l2{fill:color-mix(in srgb,var(--acc) 56%,var(--bm-base))} .bm-m.l3{fill:color-mix(in srgb,var(--acc) 78%,var(--bm-base))} .bm-m.l4{fill:var(--acc)} +/* Fatigue view: attention ramp - fatigued muscles highlighted (owner tweak 2026-08-06) */ +.hm-fatigue .bm-m.l4{fill:var(--red)} +.hm-fatigue .bm-m.l3{fill:var(--orange)} +.hm-fatigue .bm-m.l2{fill:var(--yellow)} +.hm-fatigue .bm-m.l1{fill:color-mix(in srgb,var(--yellow) 32%,var(--bm-base))} +.hm-fatigue .hm-c.l4{background:var(--red)} +.hm-fatigue .hm-c.l3{background:var(--orange)} +.hm-fatigue .hm-c.l2{background:var(--yellow)} +/* Strength view: top band pops gold (owner tweak 2026-08-06) */ +.hm-strength .bm-m.l4{fill:var(--yellow);filter:drop-shadow(0 0 1.5px var(--yellow))} +.hm-strength .hm-c.l4{background:var(--yellow)} + .bm-m.sel{stroke:var(--label);stroke-width:7} .bodymap.tappable .bm-m{cursor:pointer} /* A hairline in the surface colour separates neighbouring muscles; the artwork has no diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 2ad8876..69c5006 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -384,6 +384,8 @@ export default { '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.', + 'full': 'voll', + 'floor': 'Minimum', 'Weeks since training: {0}': 'Zuletzt vor {0} Wo. trainiert', 'by sets worked': 'nach Sätzen', 'Week': 'Woche', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 537af83..21bdad4 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -366,6 +366,8 @@ export default { '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.', + 'full': 'completo', + 'floor': 'mínimo', 'Weeks since training: {0}': 'Último entrenamiento: hace {0} sem.', 'by sets worked': 'por series trabajadas', 'Week': 'Semana', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index e233a3b..df946a2 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -366,6 +366,8 @@ export default { '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.', + 'full': 'complet', + 'floor': 'plancher', 'Weeks since training: {0}': 'Dernier entraînement : il y a {0} sem.', 'by sets worked': 'par séries effectuées', 'Week': 'Semaine', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index bbf2947..e649b62 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'थकी हुई', 'Fatigue shows how recently each muscle was trained. High means rest.': 'थकान बताती है कि हर मांसपेशी की ट्रेनिंग कितनी हाल की है। अधिक थकान होने पर आराम करें।', 'Strength shows retained muscle strength. Train again to reset it.': 'शक्ति बताती है कि मांसपेशियों की कितनी ताकत बनी हुई है। इसे रीसेट करने के लिए फिर से ट्रेन करें।', + 'full': 'पूर्ण', + 'floor': 'न्यूनतम', 'Weeks since training: {0}': 'पिछला व्यायाम: {0} सप्ताह पहले', 'by sets worked': 'सेट के अनुसार', 'Week': 'सप्ताह', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 5ccc24b..dc4795e 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -366,6 +366,8 @@ export default { '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.', + 'full': 'pieno', + 'floor': 'minimo', 'Weeks since training: {0}': 'Ultimo allenamento: {0} sett. fa', 'by sets worked': 'per serie svolte', 'Week': 'Settimana', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 1bcc2bd..a09a4ce 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -366,6 +366,8 @@ export default { 'Fatigued': '피로함', 'Fatigue shows how recently each muscle was trained. High means rest.': '피로도는 각 근육을 얼마나 최근에 운동했는지 보여줍니다. 높을수록 휴식이 필요합니다.', 'Strength shows retained muscle strength. Train again to reset it.': '근력은 근육에 남아 있는 힘을 보여줍니다. 다시 운동하면 값이 초기화됩니다.', + 'full': '완전', + 'floor': '최소', 'Weeks since training: {0}': '마지막 운동: {0}주 전', 'by sets worked': '세트 수 기준', 'Week': '이번 주', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index dae273c..2f59aa5 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -366,6 +366,8 @@ export default { '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.', + 'full': 'pełna', + 'floor': 'minimum', 'Weeks since training: {0}': 'Trening: {0} tyg. temu', 'by sets worked': 'wg serii', 'Week': 'Tydzień', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index a181fe3..578cd86 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -366,6 +366,8 @@ export default { '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.', + 'full': 'completo', + 'floor': 'mínimo', 'Weeks since training: {0}': 'Treino: há {0} sem.', 'by sets worked': 'por séries trabalhadas', 'Week': 'Semana', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index a3ba4a7..a1882b6 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'Утомлена', 'Fatigue shows how recently each muscle was trained. High means rest.': 'Усталость показывает, насколько недавно тренировалась каждая мышца. Высокий уровень означает, что пора отдохнуть.', 'Strength shows retained muscle strength. Train again to reset it.': 'Сила показывает, сколько мышечной силы сохранилось. Повторная тренировка сбрасывает это значение.', + 'full': 'полная', + 'floor': 'минимум', 'Weeks since training: {0}': 'Тренировка: {0} нед. назад', 'by sets worked': 'по подходам', 'Week': 'Неделя', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 60c3760..87fe222 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -366,6 +366,8 @@ export default { '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.', + 'full': 'tam', + 'floor': 'minimum', 'Weeks since training: {0}': 'Son antrenman: {0} hafta önce', 'by sets worked': 'çalışılan sete göre', 'Week': 'Hafta', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index bf33ba5..68d1134 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -366,6 +366,8 @@ export default { 'Fatigued': '已疲劳', 'Fatigue shows how recently each muscle was trained. High means rest.': '疲劳度显示每个肌群最近一次训练距今多久。数值越高,越需要休息。', 'Strength shows retained muscle strength. Train again to reset it.': '力量显示肌肉力量保留了多少。再次训练即可重置。', + 'full': '完全', + 'floor': '下限', 'Weeks since training: {0}': '上次训练:{0}周前', 'by sets worked': '按训练组数', 'Week': '本周', diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index 9da7f0f..febef34 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -38,9 +38,9 @@ function latestMuscleTraining(workouts) { } const FATIGUE_LEVELS = [ - { at: 0, level: 4 }, + { at: 0, level: 0 }, { at: 0.25, level: 2 }, - { at: 0.5, level: 0, exclusive: true }, + { at: 0.5, level: 4, exclusive: true }, ] const STRENGTH_LEVELS = [ @@ -72,17 +72,17 @@ export function weeksSinceTraining(now, lastTrained) { } function FatigueLegend() { - return
- {t('Fatigued')}
+ return
+ {t('Fatigued')}
{t('Recovering')}
- {t('Ready')}
+ {t('Ready')}
} function StrengthLegend() { - return
- 1
-
{fmtNum(STRENGTH_FLOOR)} + return
+ 1 {t('full')}
+
{fmtNum(STRENGTH_FLOOR)} {t('floor')}
} @@ -120,6 +120,8 @@ function MuscleBalance({ S }) { const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s)))) const on = hard && rated const load = loadOfWorkouts(inWin, on ? isHardSet : null) + const volWin = S.workouts.filter(w => historyUnitCompatible(w, S.unit) && (w.start || new Date(w.d).getTime()) > now - 90 * 86400000) + const vol90 = loadOfWorkouts(volWin, null) const { worked, missed } = rankOf(load) const top = worked.slice(0, 4) const max = worked.length ? load[worked[0]] : 0 @@ -160,7 +162,7 @@ function MuscleBalance({ S }) { :
{t('No workouts in this period yet.')}
} : view === 'fatigue' ? <>

{t('Fatigue')}

- +
{t('Fatigue shows how recently each muscle was trained. High means rest.')}
{sel &&
@@ -169,13 +171,13 @@ function MuscleBalance({ S }) {
} : <>

{t('Strength')}

- +
{t('Strength shows retained muscle strength. Train again to reset it.')}
{detrained.map(slug =>
{t(MUSCLE_NAME[slug])} - {strengthHint(slug)} + {t('{0} sets', vol90[slug] || 0)}
)} }
@@ -254,7 +256,21 @@ export default function Stats() { 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 exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id]).sort((a, b) => EXIDX[a].n < EXIDX[b].n ? -1 : 1) + const currentOf = id => { + for (let i = S.workouts.length - 1; i >= 0; i--) { + const en = S.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)) + 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 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)) + 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 @@ -339,7 +355,8 @@ export default function Stats() { {exHist.length ? <>
({ value: id, label: EXIDX[id].n }))} /> + options={exHist.map(id => ({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' — ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} /> +
{exOpts.length > 1 && }
diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx index e21db45..6bfc209 100644 --- a/frontend/src/views/Stats.recovery.test.jsx +++ b/frontend/src/views/Stats.recovery.test.jsx @@ -59,11 +59,11 @@ function iso(timestamp) { } function set(done, extra = {}) { - return { done, w: 10, r: 8, ...extra } + return { done, w: 10, r: 8, unit: 'kg', ...extra } } function workout(id, start, entries) { - return { id, d: iso(start), start, entries } + return { id, d: iso(start), start, unit: 'kg', entries } } function entry(id, sets) { @@ -204,7 +204,7 @@ beforeEach(() => { 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() + const card = muscleCard() expectPressed(buttonWithText(card, 'Muscle balance')) expectPressed(buttonWithText(card, 'Week')) @@ -268,7 +268,7 @@ describe('Stats muscle recovery view runtime', () => { 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') + expect(container.textContent).toContain('1 sets') // 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) @@ -286,7 +286,7 @@ describe('Stats muscle recovery view runtime', () => { 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) + expect(Object.values(levelsOf(fatigueMap.load, fatigueMap.thresholds)).every(level => level === 4)).toBe(true) await unmountStats() resetFixture([allSubfullWorkout()]) From d1cede21d3f95b38052c3f3ec36e13434f6ae52c Mon Sep 17 00:00:00 2001 From: root Date: Thu, 6 Aug 2026 19:16:47 +0200 Subject: [PATCH 3/5] fix dropdown label em-dash expression --- frontend/src/views/Stats.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index febef34..41be0e7 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -355,7 +355,7 @@ export default function Stats() { {exHist.length ? <>
({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' — ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} /> + options={exHist.map(id => ({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
{exOpts.length > 1 && } From 6c91adefcd28e8328ba2eb0df4bf81556b8ea9e3 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 6 Aug 2026 19:17:41 +0200 Subject: [PATCH 4/5] volWin: plain 90d window filter (upstream-adapted) --- frontend/src/views/Stats.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index 41be0e7..3186f9c 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -120,7 +120,7 @@ function MuscleBalance({ S }) { const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s)))) const on = hard && rated const load = loadOfWorkouts(inWin, on ? isHardSet : null) - const volWin = S.workouts.filter(w => historyUnitCompatible(w, S.unit) && (w.start || new Date(w.d).getTime()) > now - 90 * 86400000) + 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 top = worked.slice(0, 4) From 86f3476f5fb36cc98c49d1d6c5cd8b7a1ca7e66c Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 09:02:38 +0200 Subject: [PATCH 5/5] fatigue: saturating volume-based model, no window cliff, reachable level bands --- frontend/src/lib/recovery.js | 21 ++++-- frontend/src/lib/recovery.test.js | 83 +++++++++++++++------- frontend/src/views/Stats.jsx | 4 +- frontend/src/views/Stats.recovery.test.jsx | 18 ++--- 4 files changed, 84 insertions(+), 42 deletions(-) diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js index 54a2793..ebc8020 100644 --- a/frontend/src/lib/recovery.js +++ b/frontend/src/lib/recovery.js @@ -2,7 +2,13 @@ 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 +// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve +// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting +// fatigue level without ever pinning it, and the value can then fade asymptotically. +export const FATIGUE_REF_VOLUME = 3 +// Computational bound for the stimulus scan, not a semantic cliff: after 30 days (20 +// half-lives) a session contributes below 1e-6 to the accumulated value. +export const FATIGUE_SCAN_MS = 30 * 24 * 60 * 60 * 1000 /** Exponential half-life for fatigue stimulus. */ export const FATIGUE_HALF_LIFE_MS = 129600000 @@ -89,16 +95,19 @@ function fatigueValue(events, now) { lastTimestamp = event.timestamp } value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS) - return clamp(value, 0, 1) + // Normalise the accumulated stimulus to a saturating fatigue level: more volume starts + // higher but never pins, and the value fades asymptotically - no window-edge cliff. + return 1 - Math.exp(-value / FATIGUE_REF_VOLUME) } /** * 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. + * set contributes the exercise's `musclesOf` weights; the scan is bounded to FATIGUE_SCAN_MS for + * performance, not semantics. Stimuli are accumulated chronologically with a 36-hour half-life, + * decayed to `now`, and normalised with the saturation curve 1 - exp(-v / FATIGUE_REF_VOLUME). + * The result always contains every drawable muscle slug. * * @param {Array} workouts Workout history with `start`/`d` and entry set arrays. * @param {number} now Current time in milliseconds; injected to keep this function deterministic. @@ -106,7 +115,7 @@ function fatigueValue(events, now) { */ export function fatigueOf(workouts, now) { const current = Number(now) - const cutoff = current - FATIGUE_WINDOW_MS + const cutoff = current - FATIGUE_SCAN_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) diff --git a/frontend/src/lib/recovery.test.js b/frontend/src/lib/recovery.test.js index 2d03dcf..0f0d35a 100644 --- a/frontend/src/lib/recovery.test.js +++ b/frontend/src/lib/recovery.test.js @@ -1,8 +1,9 @@ import { describe, expect, it } from 'vitest' import { FATIGUE_HALF_LIFE_MS, + FATIGUE_REF_VOLUME, + FATIGUE_SCAN_MS, FATIGUE_STATES, - FATIGUE_WINDOW_MS, STRENGTH_FLOOR, STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, @@ -53,7 +54,8 @@ 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_REF_VOLUME).toBe(3) + expect(FATIGUE_SCAN_MS).toBe(30 * DAY) expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR) expect(STRENGTH_FULL_MS).toBe(14 * DAY) expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY) @@ -86,14 +88,29 @@ describe('fatigueOf and strengthOf', () => { for (const slug of MUSCLES) { const weight = WEIGHTED_WEIGHTS[slug] || 0 - expect(fatigue[slug]).toBe(weight) + expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight / FATIGUE_REF_VOLUME), 10) 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), - ) + // one set never crosses the fatigued threshold on the saturating curve + expect(fatiguedMuscles(workouts, NOW)).toEqual([]) + }) + + it('raises starting fatigue with volume, never pins, and fades without a cliff', () => { + const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG] + expect(at0(1)).toBeCloseTo(1 - Math.exp(-1 / FATIGUE_REF_VOLUME), 10) + expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 / FATIGUE_REF_VOLUME), 10) + expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 / FATIGUE_REF_VOLUME), 10) + expect(at0(12)).toBeGreaterThan(at0(5)) + expect(at0(5)).toBeGreaterThan(at0(1)) + expect(at0(12)).toBeLessThan(1) + // one half-life later the gradient is still visible at any volume + const later = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS, 12)], NOW)[SINGLE_SLUG] + expect(later).toBeCloseTo(1 - Math.exp(-6 / FATIGUE_REF_VOLUME), 10) + expect(later).toBeLessThan(at0(12)) + // no cliff: 72h keeps decaying instead of snapping to zero + const old = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)], NOW)[SINGLE_SLUG] + expect(old).toBeGreaterThan(0) + expect(old).toBeLessThan(0.25) }) it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => { @@ -101,18 +118,23 @@ describe('fatigueOf and strengthOf', () => { 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) + expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight * expectedDecay / FATIGUE_REF_VOLUME), 10) + } + if (age === FATIGUE_HALF_LIFE_MS) { + expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-0.5 / FATIGUE_REF_VOLUME), 10) } - 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) + expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-(0.5 ** 0.5) / FATIGUE_REF_VOLUME), 10) } } }) - 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()) + it('fades a 72-hour-old set below the ready threshold instead of hard-cutting', () => { + const workouts = [doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)] + const value = fatigueOf(workouts, NOW)[SINGLE_SLUG] + expect(value).toBeGreaterThan(0) + expect(value).toBeLessThan(0.25) + expect(fatigueStateOf(value)).toBe(FATIGUE_STATES.READY) expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1) }) @@ -126,11 +148,15 @@ describe('fatigueOf and strengthOf', () => { }) describe('fatigue state boundaries', () => { + // Inverse of the saturation curve: raw stimulus needed to land exactly on a target level. + const rawAt = target => -FATIGUE_REF_VOLUME * Math.log(1 - target) + it('classifies exactly .25 as recovering and .2499 as ready', () => { const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG] + const sets = 3 const valueAt = target => { - const age = FATIGUE_HALF_LIFE_MS * Math.log2(weight / target) - const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)[SECONDARY_SLUG] + const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * weight / rawAt(target)) + const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG] expect(value).toBeCloseTo(target, 10) return stableFloat(value) } @@ -140,15 +166,16 @@ describe('fatigue state boundaries', () => { }) 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 sets = 3 + const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.4999)), sets)] const aboveHalf = [ - doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(1 / 0.5001)), + doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.5001)), sets), ] 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(half).toBeCloseTo(0.4999, 10) + expect(fatigueStateOf(stableFloat(half))).toBe(FATIGUE_STATES.RECOVERING) expect(fatiguedMuscles(atHalf, NOW)).toEqual([]) expect(above).toBeCloseTo(0.5001, 10) expect(fatigueStateOf(stableFloat(above))).toBe(FATIGUE_STATES.FATIGUED) @@ -179,22 +206,24 @@ describe('strengthOf', () => { }) describe('accumulation and purity', () => { - it('matches the sum of independently decayed stimuli in chronological order', () => { + it('matches the saturated 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( + const raw = ages.reduce( (sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS), 0, ) + const expected = 1 - Math.exp(-raw / FATIGUE_REF_VOLUME) - expect(expected).toBeLessThan(1) - expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 12) - expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 12) + expect(raw).toBeLessThan(FATIGUE_REF_VOLUME) + expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10) + expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10) }) - it('clamps saturation and returns identical results without mutating inputs or sharing state', () => { + it('saturates without pinning 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) + expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(1 - Math.exp(-2 / FATIGUE_REF_VOLUME), 10) + expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1) const workouts = [ doneWorkoutAt(SINGLE.id, NOW - 64 * HOUR), diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index 3186f9c..af08fba 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -39,8 +39,10 @@ function latestMuscleTraining(workouts) { const FATIGUE_LEVELS = [ { at: 0, level: 0 }, + { at: 0.15, level: 1 }, { at: 0.25, level: 2 }, - { at: 0.5, level: 4, exclusive: true }, + { at: 0.4, level: 3 }, + { at: 0.55, level: 4, exclusive: true }, ] const STRENGTH_LEVELS = [ diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx index 6bfc209..bf06701 100644 --- a/frontend/src/views/Stats.recovery.test.jsx +++ b/frontend/src/views/Stats.recovery.test.jsx @@ -71,8 +71,9 @@ function entry(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) + // A 6-set chest day on the saturating curve crosses .5 at ~55.05 hours, so the edge + // flips fatigued -> recovering after one 60-second interval tick. + const fatigueEdge = now - (36 * Math.log2(6 / (3 * Math.LN2)) * 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. @@ -81,7 +82,7 @@ function lifecycleWorkouts(now = BASE_NOW) { const absCompleted = now - 20 * DAY const absUndone = now - DAY return [ - workout('fatigue-edge', fatigueEdge, [entry('1254', [set(true, { rir: 0 })])]), + workout('fatigue-edge', fatigueEdge, [entry('1254', Array.from({ length: 6 }, () => 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 })])]), @@ -90,8 +91,9 @@ function lifecycleWorkouts(now = BASE_NOW) { } 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. + // Eight completed sets per exercise: on the saturating curve every involved muscle gets + // raw >= 3.2 (0.4 x 8), i.e. a fatigue value above the .55 top band regardless of the + // catalogue's secondary-muscle metadata. const ids = [ ['1018', 1], // trapezius ['1012', 1], // deltoids @@ -111,7 +113,7 @@ function allFatiguedWorkout(now = BASE_NOW) { ['1000', 1], // calves ['1396', 2], // calves + tibialis ] - return workout('all-fatigued', now, ids.map(([id, count]) => entry(id, Array.from({ length: count }, () => set(true))))) + return workout('all-fatigued', now, ids.map(([id]) => entry(id, Array.from({ length: 8 }, () => set(true))))) } function allSubfullWorkout(now = BASE_NOW) { @@ -226,7 +228,7 @@ describe('Stats muscle recovery view runtime', () => { expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy() expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy() expect(lastMap().selected).toBe('chest') - expect(lastMap().load.chest).toBe(2) + expect(lastMap().load.chest).toBe(7) }) it('refreshes fatigue presentation, Balance 30-day filtering, and the mounted tree on the 60-second tick', async () => { @@ -253,7 +255,7 @@ describe('Stats muscle recovery view runtime', () => { expect(strengthRows()).toContain('Quads') await click(viewButton('Muscle balance')) - expect(lastMap().load.chest).toBe(1) + expect(lastMap().load.chest).toBe(6) expectPressed(balanceRangeButton('30d')) })