diff --git a/api/coach/core/schemas.js b/api/coach/core/schemas.js index 9779e73..163b457 100644 --- a/api/coach/core/schemas.js +++ b/api/coach/core/schemas.js @@ -59,6 +59,11 @@ const EX_SCHEMA = { required: ['id', 'sets'] }; +// `week` and `routines[].id` are required, not optional: the week is the only thing that says +// which day trains which routine, and it points at a routine by id. A schema that leaves either +// out lets a small local model answer with routines that have no id and a week naming "r1" — +// grammar-valid, and something validate.js can only ever reject ("the week schedules 0 days but +// 3 were asked for"), through the repair round and out as a failed job. export const CREATE_SCHEMA = { type: 'object', properties: { @@ -67,15 +72,22 @@ export const CREATE_SCHEMA = { summary: STR, basedOn: STR, week: { type: 'object' }, + // The caps are the validator's own (MAX_ROUTINES, MAX_EX_PER_ROUTINE), stated here as well + // because "1-7 routines, each 3-12 exercises" in create.md is only a request. A small model + // that starts repeating itself does not stop at a request: qwen2.5:3b walks the library id by + // id, three sets of eight apiece, until it hits the output limit — twelve minutes for an + // answer that arrives cut in half and cannot be parsed. maxItems ends that run at seven + // routines instead. routines: { type: 'array', + maxItems: 7, items: { type: 'object', properties: { id: STR, name: STR, emoji: STR, prog: STR, why: STR, - ex: { type: 'array', items: EX_SCHEMA } + ex: { type: 'array', maxItems: 20, items: EX_SCHEMA } }, - required: ['name', 'ex'] + required: ['id', 'name', 'ex'] } }, customEx: { @@ -83,7 +95,7 @@ export const CREATE_SCHEMA = { items: { type: 'object', properties: { id: STR, n: STR, bp: STR, desc: STR }, required: ['id', 'n'] } } }, - required: ['coach_contract', 'routines'] + required: ['coach_contract', 'week', 'routines'] }; export const DEBRIEF_SCHEMA = { diff --git a/api/test/prompt-split.test.js b/api/test/prompt-split.test.js index 1b0072b..deb80c3 100644 --- a/api/test/prompt-split.test.js +++ b/api/test/prompt-split.test.js @@ -4,6 +4,7 @@ import { buildPrompt, buildPromptParts, taskOf } from '../coach/core/prompt.js'; import { SCHEMAS } from '../coach/core/schemas.js'; import { build, FULL_DETAIL_SESSIONS } from '../coach/core/payload.js'; import { chatCompletionsSpec } from '../coach/core/adapters/openai.js'; +import { validatePlan } from '../coach/core/validate.js'; const S = (workouts = []) => ({ lang: 'en', unit: 'kg', routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 8 }] }], @@ -48,6 +49,32 @@ test('every task has a flat schema — no $ref, no anyOf/oneOf (llama.cpp gramma assert.equal(taskOf('create', { refine: 'x' }), 'refine'); }); +test('the create schema requires what the week resolves through: a routine id, and a week', () => { + // A schema handed to a grammar-constrained decoder is the only thing standing between a small + // local model and an answer the validator can only reject. These two fields are where that + // showed: llama3.2:3b and qwen2.5:3b both answer with routines that carry no `id` and a week + // naming what they put in `name`, which costs a job and a repair round to find out. + assert.ok(SCHEMAS.create.properties.routines.items.required.includes('id')); + assert.ok(SCHEMAS.create.required.includes('week')); + assert.equal(SCHEMAS.refine, SCHEMAS.create); // refine reuses it, same guarantee + + const noId = { + coach_contract: 1, + routines: [{ name: 'r1', ex: [{ id: '0001', sets: 3, reps: 8 }] }], + week: { 1: 'r1' } + }; + const checked = validatePlan(noId, { daysPerWeek: 1 }); + assert.ok(!checked.ok); + assert.ok(checked.errors.some(e => e.includes('week[1] points at "r1"'))); +}); + +test('the create schema caps the two arrays the validator caps, so a repeating model stops', () => { + // validate.js slices at MAX_ROUTINES / MAX_EX_PER_ROUTINE; a model that never stops emitting + // otherwise runs to the output limit first and the answer arrives truncated and unparseable. + assert.equal(SCHEMAS.create.properties.routines.maxItems, 7); + assert.equal(SCHEMAS.create.properties.routines.items.properties.ex.maxItems, 20); +}); + test('older sessions in a review window are compacted, the recent ones keep full sets', () => { const many = Array.from({ length: FULL_DETAIL_SESSIONS + 4 }, (_, i) => workout('2026-08-' + String(i + 1).padStart(2, '0'))); const p = build(S(many), { handle: 'h1', kind: 'review' }); diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index c9d70aa..9a49fad 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -26,6 +26,7 @@ import Workout from './views/Workout.jsx' import Stats from './views/Stats.jsx' import History from './views/History.jsx' import Library from './views/Library.jsx' +import Muscles from './views/Muscles.jsx' import Settings from './views/Settings.jsx' import Admin from './views/Admin.jsx' import CoachChat from './views/CoachChat.jsx' @@ -123,6 +124,7 @@ function Shell() { } /> } /> } /> + } /> } /> {/* The Coach screens gate themselves on the instance config; the routes exist unconditionally so a deep link from a notification lands somewhere sane diff --git a/frontend/src/components/BodyMap.test.jsx b/frontend/src/components/BodyMap.test.jsx index 1cc2b43..cc328bb 100644 --- a/frontend/src/components/BodyMap.test.jsx +++ b/frontend/src/components/BodyMap.test.jsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import React, { act } from 'react' import { createRoot } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import BodyMap, { BodyMapLegend } from './BodyMap.jsx' globalThis.IS_REACT_ACT_ENVIRONMENT = true @@ -9,6 +9,14 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true let container let root +// BodyMap fetches its ~90 KB of geometry with a dynamic import on first render, and the +// waitFor below allows one second for it. That is ample once the module is in the ESM +// registry and not always ample when it is not: on a loaded CI runner the first map render +// in this file paid the cold import and timed out, while every later test passed on the +// component's warm CACHE. Import it here so the wait covers rendering, not module loading, +// and the file stops depending on how fast the machine is. +beforeAll(() => import('../lib/body-paths.js')) + beforeEach(() => { container = document.createElement('div') document.body.appendChild(container) diff --git a/frontend/src/components/MuscleExplorer.jsx b/frontend/src/components/MuscleExplorer.jsx new file mode 100644 index 0000000..e0cdfb6 --- /dev/null +++ b/frontend/src/components/MuscleExplorer.jsx @@ -0,0 +1,97 @@ +import { useMemo, useState } from 'react' +import { useStore } from '../store/useStore.js' +import { BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js' +import { activeProfile, exAvailable } from '../lib/equipment.js' +import { bestWeightFor } from '../lib/history.js' +import { fmtNum } from '../lib/format.js' +import { MUSCLES, MUSCLE_NAME, musclesOf } from '../lib/muscles.js' +import { t, exerciseNameFor } from '../lib/i18n.js' +import BodyMap from './BodyMap.jsx' +import { Thumb } from './Media.jsx' +import Icon from './Icon.jsx' +import { Button } from './ui.jsx' +import { tappable } from '../lib/use-sheet-keyboard.js' + +// One explorer for the Library and every catalogue picker. Supplying `onPick` turns +// a result into a selection; without it the explorer behaves like the normal Library. +export default function MuscleExplorer({ onPick, onDetail, onPlan }) { + const S = useStore(s => s.S) + const [selected, setSelected] = useState(null) + const [q, setQ] = useState('') + const [bp, setBp] = useState('') + const [eq, setEq] = useState('') + const [shown, setShown] = useState(40) + const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session + // Same rule as the Library and the picker: the active equipment profile narrows the catalogue + // (and the per-muscle counts) unless the user asks for everything. + const profile = activeProfile(S) + const catalog = useMemo(() => { + const all = allExercises(S) + return (profile && !showAll) ? all.filter(e => exAvailable(S, e)) : all + }, [S.customEx, S.equipFilterOn, S.activeEquipId, S.equipProfiles, showAll]) + const counts = useMemo(() => Object.fromEntries(MUSCLES.map(m => [m, + catalog.filter(e => musclesOf(e)[m]).length + ])), [catalog]) + const pick = muscle => { setSelected(muscle === selected ? null : muscle); setEq(''); setShown(40) } + const targeted = selected ? catalog.filter(e => musclesOf(e)[selected]) : [] + const base = targeted.filter(e => (!bp || e.bp === bp) && matchExercise(e, q)) + const eqOpts = equipmentOf(base) + const eqOn = eqOpts.includes(eq) ? eq : '' + const exercises = eqOn ? base.filter(e => e.eq === eqOn) : base + const choose = ex => onPick ? onPick(ex) : onDetail(ex) + + return <> + {profile &&
+ + {showAll ? t('Showing all equipment') : t('Showing what you have in "{0}"', profile.name)} + +
} +
+ +
+ {MUSCLES.map(m => )} +
+
+ + {!selected && onPick &&
{t('Choose a muscle to see exercises that train it.')}
} + + {selected && <> +
+

{t('Exercises for {0}', t(MUSCLE_NAME[selected]))}

+ +
+
+ { setQ(e.target.value); setShown(40) }} /> +
+
1 ? 8 : 12 }}> + + {BODYPARTS.map(b => )} +
+ {eqOpts.length > 1 &&
+ + {eqOpts.map(x => )} +
} +
+ {exercises.slice(0, shown).map(e => { + const best = bestWeightFor(S, e.id) + const primary = musclesOf(e)[selected] === 1 + return
choose(e))}> + +
{exerciseNameFor(e)}
{t(primary ? 'Primary target' : 'Also trains')} · {t(e.tg || e.bp)} · {t(e.eq)}
+ {onPick ? : <> + {best > 0 && {fmtNum(best)}} + + } +
+ })} + {exercises.length === 0 &&
{t('No match')}
} +
+ {exercises.length > shown && <>
} + } + +} diff --git a/frontend/src/components/TabBar.jsx b/frontend/src/components/TabBar.jsx index 156d4d7..d54e31c 100644 --- a/frontend/src/components/TabBar.jsx +++ b/frontend/src/components/TabBar.jsx @@ -13,7 +13,7 @@ export default function TabBar({ onStart }) { const isGuest = useStore(s => s.isGuest()) if (!user && !isGuest) return null const cur = loc.pathname.split('/')[1] || 'home' - const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') + const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') || (cur === 'muscles' && k === 'library') const startWorkout = () => { if (!S.active) { diff --git a/frontend/src/components/TimerFlash.jsx b/frontend/src/components/TimerFlash.jsx index f620237..42efa31 100644 --- a/frontend/src/components/TimerFlash.jsx +++ b/frontend/src/components/TimerFlash.jsx @@ -1,8 +1,22 @@ +import { useEffect } from 'react' import { useUI } from '../store/useUI.js' -// A new key restarts the CSS sequence even when two timers finish close together. -// The layer never catches taps and ends transparent, so it can safely stay mounted. +// Flips the app's real light/dark theme on and off twice (~2.4s) instead of laying an +// opaque black/white rectangle over the screen — the alert reads as the app itself +// blinking, and it always settles back on whatever theme the user actually had. export default function TimerFlash() { const id = useUI(s => s.timerFlashId) - return id ? -
{t('Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.')}
- +
{t('Set up your weekly routine to get going — or load a ready-made starter plan.')}
+
)} diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx index 5822a78..b591abb 100644 --- a/frontend/src/views/Library.jsx +++ b/frontend/src/views/Library.jsx @@ -1,4 +1,5 @@ import { useRef, useState } from 'react' +import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js' import { activeProfile, exAvailable } from '../lib/equipment.js' @@ -12,6 +13,7 @@ import { Button } from '../components/ui.jsx' import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js' export default function Library() { + const nav = useNavigate() const S = useStore(s => s.S) const [q, setQ] = useState('') const [bp, setBp] = useState('') @@ -30,7 +32,9 @@ export default function Library() { useRevealActiveChip(eqStrip, eqOn) return <> -

{t('Exercises')}

{t('{0} exercises with animations', EXDB.length)}
+

{t('Exercises')}

{t('{0} exercises with animations', EXDB.length)}
+ +
{ setQ(e.target.value); setShown(40) }} />
{profile &&
diff --git a/frontend/src/views/Muscles.jsx b/frontend/src/views/Muscles.jsx new file mode 100644 index 0000000..a1de3db --- /dev/null +++ b/frontend/src/views/Muscles.jsx @@ -0,0 +1,15 @@ +import { useNavigate } from 'react-router-dom' +import { t } from '../lib/i18n.js' +import MuscleExplorer from '../components/MuscleExplorer.jsx' +import { exerciseDetailSheet, addToRoutineSheet } from '../sheets.jsx' +import Icon from '../components/Icon.jsx' + +export default function Muscles() { + const nav = useNavigate() + return <> +
+

{t('Explore muscles')}

{t('Choose a muscle to see exercises that train it.')}
+ + + +} diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsx index faa2842..77e69c1 100644 --- a/frontend/src/views/Plan.jsx +++ b/frontend/src/views/Plan.jsx @@ -2,7 +2,7 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js' import { t } from '../lib/i18n.js' -import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx' +import { dayAssignSheet, starterPlanSheet, planToolsSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { Button } from '../components/ui.jsx' import { tappable } from '../lib/use-sheet-keyboard.js' @@ -66,7 +66,7 @@ export default function Plan() {
{r.name}
{exCount(r.ex.length)}
)}
: <>
{t('No routines yet.')}
{t('Create one or load the starter plan.')}
- + } diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx index 701b062..0cce769 100644 --- a/frontend/src/views/RoutineEdit.jsx +++ b/frontend/src/views/RoutineEdit.jsx @@ -1,16 +1,18 @@ import { useNavigate, useParams } from 'react-router-dom' import { useEffect, useRef, useState } from 'react' import { useStore } from '../store/useStore.js' +import { useUI } from '../store/useUI.js' import { exOr } from '../lib/exercises.js' import { activeProfile, exAvailable } from '../lib/equipment.js' import { uid } from '../lib/format.js' import { t, exerciseNameFor } from '../lib/i18n.js' -import { supersetUnits, moveSupersetUnit, cleanupSg, exLine } from '../lib/history.js' +import { supersetUnits, moveSupersetUnit, cleanupSg, exLine, defaultConfig } from '../lib/history.js' import { Thumb } from '../components/Media.jsx' import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { glyphOf } from '../lib/glyphs.js' import { Button, Row, SelectRow, Switch } from '../components/ui.jsx' +import { copyRoutine } from '../lib/routines.js' import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js' import BodyMap from '../components/BodyMap.jsx' import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js' @@ -305,6 +307,7 @@ export default function RoutineEdit() { const { id } = useParams() const S = useStore(s => s.S) const update = useStore(s => s.update) + const toast = useUI(s => s.toast) const r = S.routines.find(x => x.id === id) useEffect(() => { if (!r) nav('/plan') }, [!!r]) // Editing here has no explicit "save" — every field change persists immediately. A single @@ -423,7 +426,20 @@ export default function RoutineEdit() { })()}
{t('Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.')}
- + +
+
+ - +
) return <> @@ -252,7 +260,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov {dropsOf(s).map((d, di) => (
{t('Drop {0}', di + 1)} - {miniStepper(d.w, 2.5, true, v => setDropField(i, di, 'w', v))} + {miniStepper(d.w, loadStep, true, v => setDropField(i, di, 'w', v), true)} {miniStepper(d.r, 1, false, v => setDropField(i, di, 'r', v))}
@@ -320,6 +328,12 @@ function ActiveWorkout() { const unit = A.entries.length ? unitOf(units, cur) : [] const unitIdx = units.findIndex(u => u === unit) const isSuperset = unit.length > 1 + // Cards show one unit at a time with Prev/Next + swipe; list stacks every unit so the + // whole session is visible and scrollable (Settings → During a workout → Workout view). + // Every set handler below is already entry-index parameterised, so list mode only changes + // what is rendered — completion, rest, top-weight and auto-advance share one path. + // Unknown/absent values read as cards, keeping every pre-existing profile as it was. + const listMode = S.workoutView === 'list' // Superset flow: center the actionable row when completing a set moves to the partner or // back to the first exercise of the next round. Entry-bound maps keep repeated exercise IDs // distinct, while each rendered set index identifies the existing row within that entry. @@ -360,13 +374,13 @@ function ActiveWorkout() { } }) useEffect(() => { - if (!isSuperset) return + if (!isSuperset || listMode) return const entry = A.entries[cur] const firstIncomplete = entry?.sets.findIndex(s => !s.done) ?? -1 const setIdx = firstIncomplete >= 0 ? firstIncomplete : (entry?.sets.length ?? 0) - 1 const el = (setIdx >= 0 && setRefs.current.get(entry)?.get(setIdx)) || exRefs.current.get(entry) if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'center' }) - }, [cur, isSuperset, A.entries.length]) + }, [cur, isSuperset, listMode, A.entries.length]) const total = A.entries.reduce((n, e) => n + e.sets.length, 0) const done = setsDoneActive(A) @@ -423,6 +437,17 @@ function ActiveWorkout() { }, true) } + // One prop object per entry so the card and list layouts share the exact same wiring. + const blockProps = idx => ({ + onToggle: i => toggle(idx, i), + onField: (i, f, v) => setField(idx, i, f, v), + onAddSet: () => addSet(idx), + onRemoveSet: () => removeSet(idx), + onAddWarmup: () => addWarmup(idx), + onRemoveSetAt: i => removeSetAt(idx, i), + onStartTimed: i => startTimed(idx, i), + onProgressionSettings: () => openProgressionSettings(idx), + }) const navigateUnit = direction => { const targetFor = active => { if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null @@ -437,6 +462,10 @@ function ActiveWorkout() { if (target != null) s.active.cur = target }) } + // List mode shows every unit at once, so the "current" exercise is chosen by tapping + // "Set current" on its header instead of Prev/Next. The bottom Move/Swap/Remove actions + // keep operating on it, and completing sets still advances it on its own. + const focusUnit = firstIdx => update(s => { if (s.active) s.active.cur = firstIdx }) const onSwipePointerDown = event => { if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return @@ -459,28 +488,43 @@ function ActiveWorkout() { const state = useStore.getState().S const entry = state.active?.entries?.[idx] if (!entry) return + const activeId = state.active.id + const entryId = entry.id + const entryCount = state.active.entries.length const routine = state.routines.find(r => r.id === state.active.routineId) - exConfigSheet(exOr(entry.id), entry.target, cfg => update(s => { - const activeEntry = s.active?.entries?.[idx] - if (!activeEntry) return - const full = { ...cfg, id: activeEntry.id } - const activeRoutine = s.routines.find(r => r.id === s.active.routineId) - const step = defaultIncrement(activeEntry.id, s.unit) - // A config without a set count keeps the rows the session already has. - if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1 - const plan = nextPrescription(s, full, activeRoutine) - // The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are - // rebuilt from the new config the way the session was, and only what you already logged - // is kept in place (done warm-ups first, then done work sets, then the fresh remainder). - const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full) - const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x)) - const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x)) - const freshWarm = fresh.filter(isWarmupRow) - const freshWork = fresh.filter(x => !isWarmupRow(x)) - activeEntry.target = { ...cfg } - activeEntry.plan = plan - activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)] - }), null, routine) + exConfigSheet(exOr(entryId), entry.target, cfg => { + // Store updates clone the state tree. If this exact object is no longer at the captured + // index, the list changed while the sheet was open; an id check alone cannot distinguish + // duplicate occurrences of the same exercise, so fail closed before cloning again. + // Every store write clones the tree (the bar-weight stepper inside this very sheet does + // one), so object identity is useless here. Same workout, same list length and the same + // exercise at the captured index is what "nothing shifted" means. + const current = useStore.getState().S + if (current.active?.id !== activeId || current.active.entries?.length !== entryCount || current.active.entries?.[idx]?.id !== entryId) return + update(s => { + const activeEntry = s.active?.id === activeId ? s.active.entries?.[idx] : null + // The sheet may outlive its workout or entry. Never apply its result to whatever later + // happens to occupy the same index. + if (!activeEntry || activeEntry.id !== entryId) return + const full = { ...cfg, id: activeEntry.id } + const activeRoutine = s.routines.find(r => r.id === s.active.routineId) + const step = defaultIncrement(activeEntry.id, s.unit) + // A config without a set count keeps the rows the session already has. + if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1 + const plan = nextPrescription(s, full, activeRoutine) + // The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are + // rebuilt from the new config the way the session was, and only what you already logged + // is kept in place (done warm-ups first, then done work sets, then the fresh remainder). + const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step, useTarget: plan.kind === 'off' }), plan, step), full) + const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x)) + const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x)) + const freshWarm = fresh.filter(isWarmupRow) + const freshWork = fresh.filter(x => !isWarmupRow(x)) + activeEntry.target = { ...cfg } + activeEntry.plan = plan + activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)] + }) + }, null, routine) } // Remove a whole exercise from the session. The confirmation always asks first; in a @@ -530,25 +574,28 @@ function ActiveWorkout() { const toggle = (idx, i) => { const m = modeAt(idx) const cardioEntry = m === 'cardio' - let askTop = false, exJustDone = false, workoutDone = false, checked = false - mutEntry(idx, e => { + let exJustDone = false, workoutDone = false, checked = false + update(s => { + const e = s.active.entries[idx] e.sets[i].done = !e.sets[i].done checked = e.sets[i].done if (e.sets[i].done) { beep(S.sound, 1040, 0.12); vibrate(30) - const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done)) + // The unit that owns the ticked set — not the marked one. Since !92 the marker no longer + // follows a finished exercise, and in list mode any exercise can be worked on, so judging + // the marker's unit here declared the workout complete after one set elsewhere. + const ownUnit = unitOf(units, idx) + const unitDone = ownUnit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done)) if (unitDone) workoutDone = !nextUnfinishedUnit(A.entries, supersetUnits(A.entries), idx) - // Only loaded reps training has a "working weight" worth confirming — a bodyweight - // plank has nothing to put in that slider, and neither does a set of push-ups - // (issue #32: the fewest taps that still record what happened). - const loaded = m === 'reps' && !(isBw({ ...(e.target || {}), id: e.id }) && !e.sets.some(x => x.w > 0)) - if (e.sets.every(x => x.done)) { exJustDone = true; if (loaded && !e.asked) { e.asked = true; askTop = true } } + if (e.sets.every(x => x.done)) { + exJustDone = true + // topW is captured now; exWeights only at the finish (doFinishWorkout), so a typo you + // correct before finishing, or a discarded workout, never becomes the remembered best. + e.topW = bestWeightForEntry(e) || null + } } - }) - // reps: topWeight first (it chains into the finish/continue prompt on the last unit). - // cardio/timed or already-confirmed: go straight to the prompt. - if (askTop) topWeightSheet(idx) - else if (workoutDone) workoutCompleteSheet() + }, true) + if (workoutDone) workoutCompleteSheet() else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged')) else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged')) @@ -584,7 +631,6 @@ function ActiveWorkout() { // stopRest() first so a rest that belongs after this set replaces the one that was running. if (freshUnitDone) stopRest() if (!freshUnit || freshUnit.length <= 1) { - if (freshUnitDone && !askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] }) if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx) return } @@ -592,11 +638,7 @@ function ActiveWorkout() { const step = supersetFlowStep(fresh.entries, freshUnit, idx) if (!step) return if (step.unitDone) { - if (nextUnit?.length) { - // The top-weight sheet's explicit "Just close" path owns the choice not to advance. - if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] }) - if (!restBeforeWarmup) startRest(restSec, idx) - } + if (nextUnit?.length && !restBeforeWarmup) startRest(restSec, idx) } else { if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx }) if (step.roundDone) startRest(restSec, idx) @@ -640,7 +682,43 @@ function ActiveWorkout() {
{A.backfill &&
{t('Logging a past workout — no rest timers.')}
} - {A.entries.length ? <> + {A.entries.length ? (listMode ? ( +
+ {units.map((u, ui) => { + const multi = u.length > 1 + const isCur = u.includes(cur) + return
+
+ {multi ? t('Superset {0} / {1}', ui + 1, units.length) : t('Exercise {0} / {1}', ui + 1, units.length)} + {isCur + ? {t('Current')} + : } +
+ {multi ? ( +
+
+ {t('Superset · do these back-to-back, rest when done')} + +
+ {u.map((idx, k) => { + const entry = A.entries[idx] + return
bindExRef(entry, el)} className="ss-ex" data-exidx={idx}> + {k > 0 &&
+
} + bindSetRef(entry, setIdx, el)} + {...blockProps(idx)} /> +
+ })} +
+ ) : ( + 0 ? () => pairAt(u[0] - 1, u[0]) : null} + onPairNext={u[0] < A.entries.length - 1 ? () => pairAt(u[0], u[0] + 1) : null} + {...blockProps(u[0])} /> + )} +
+ })} +
+ ) : <>
{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}
bindExRef(entry, el)} className="ss-ex" data-exidx={idx}> {k > 0 &&
+
} bindSetRef(entry, setIdx, el)} - onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} onProgressionSettings={() => openProgressionSettings(idx)} /> + {...blockProps(idx)} />
})}
) : ( - toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} onProgressionSettings={() => openProgressionSettings(cur)} /> + )} - :
{t('Freestyle workout — add your first exercise.')}
} + ) :
{t('Freestyle workout — add your first exercise.')}
}
-
+ {!listMode &&
-
-
-
} + {!listMode &&
} + {listMode && A.entries.length > 0 &&
{t('Move, swap and remove below act on the exercise marked {0}.', t('Current'))}
} + {A.entries.length > 0 && <>
diff --git a/frontend/src/views/Workout.stepper.test.jsx b/frontend/src/views/Workout.stepper.test.jsx new file mode 100644 index 0000000..4b849d6 --- /dev/null +++ b/frontend/src/views/Workout.stepper.test.jsx @@ -0,0 +1,206 @@ +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 Workout from './Workout.jsx' + +// This suite pins down the superset stepper regression: one tap on a +/- button must move the +// value by exactly one step. The bug was a stale closure — in a superset both ExerciseBlock +// instances share the same store subscription, so updating one member's field re-renders the +// partner and replaces the render-time `s` snapshot the button handler had closed over. The +// fix reads the current value from the store at call time. The mocked `update` below clones the +// whole state on every write (structuredClone), which is exactly what invalidates those +// snapshots, so this environment reproduces the original two-taps-per-increment behaviour. +const mocks = vi.hoisted(() => { + const state = { + S: null, + startRest: vi.fn(), + stopRest: vi.fn(), + stopWork: vi.fn(), + toast: vi.fn(), + } + state.storeSnapshot = () => ({ + S: state.S, + user: null, + update: mut => { + const next = structuredClone(state.S) + mut(next) + state.S = next + }, + }) + state.uiSnapshot = () => ({ + timer: null, + work: null, + startRest: state.startRest, + stopRest: state.stopRest, + stopWork: state.stopWork, + shiftRestOwner: vi.fn(), + startWork: vi.fn(), + toast: state.toast, + }) + return state +}) + +vi.mock('../store/useStore.js', () => { + const useStore = selector => selector(mocks.storeSnapshot()) + useStore.getState = mocks.storeSnapshot + return { useStore } +}) +vi.mock('../store/useUI.js', () => { + const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot() + useUI.getState = mocks.uiSnapshot + return { useUI } +}) +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../sheets.jsx', () => ({ + startFlow: vi.fn(), + exercisePicker: vi.fn(), + exConfigSheet: vi.fn(), + exerciseDetailSheet: vi.fn(), + topWeightSheet: vi.fn(), + finishWorkout: vi.fn(), + workoutCompleteSheet: vi.fn(), + confirmSheet: vi.fn(), + swapActiveWorkoutExercise: vi.fn(), + barWeightSheet: vi.fn(), + exerciseNoteSheet: vi.fn(), + sessionNoteSheet: vi.fn(), +})) +vi.mock('../components/Media.jsx', () => ({ default: () => null })) +vi.mock('../lib/api.js', () => ({ + api: vi.fn(() => Promise.resolve({})), + IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics', +})) + +let dom +let root +let container + +function exercise(id, sets, extra = {}) { + return { + id, + target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false }, + sets: sets.map(done => ({ w: 60, r: 5, done })), + ...extra, + } +} + +function workout(entries, cur = 0) { + return { + unit: 'kg', restSec: 90, sound: false, effort: 'none', gifSize: 'full', + workouts: [], exWeights: {}, routines: [], + active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries }, + } +} + +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', 'Blob']) globalThis[key] = dom[key] + dom.Element.prototype.scrollIntoView = vi.fn() + globalThis.IS_REACT_ACT_ENVIRONMENT = true + container = document.getElementById('root') + root = createRoot(container) +} + +async function mount(entries, cur = 0) { + mocks.S = workout(entries, cur) + installDom() + await act(async () => { root.render(React.createElement(Workout)) }) +} + +async function unmount() { + if (!root) return + await act(async () => { root.unmount() }) + root = null + container = null + dom = null +} + +// The +/- controls live in `.stp` cells, one per editable column. For a plain reps set the +// order is [weight, reps]; this returns the Increase/Decrease button for a given column of a +// given set row inside a given exercise block (addressed by its data-exidx wrapper). +function stepperButton(exidx, setRow, col, direction) { + const block = container.querySelector(`[data-exidx="${exidx}"]`) + expect(block).toBeTruthy() + const row = block.querySelectorAll('.setrow')[setRow] + expect(row).toBeTruthy() + const cell = row.querySelectorAll('.stp')[col] + expect(cell).toBeTruthy() + return cell.querySelector(`button[aria-label="${direction}"]`) +} + +async function tap(button) { + expect(button).toBeTruthy() + await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) }) +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +afterEach(async () => { + await unmount() +}) + +describe('superset stepper — one tap moves one step', () => { + // Weight steps by 2.5. A single tap on the first exercise of a superset must land on 62.5, + // not stay at 60 waiting for a second tap. + it('increments a superset member weight by one step per tap', async () => { + await mount([ + exercise('press', [false], { sg: 'group' }), + exercise('row', [false], { sg: 'group' }), + ]) + + await tap(stepperButton(0, 0, 0, 'Increase')) + + expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5) + }) + + // Reps step by 1 and do not cascade, so they isolate the stepper from weight's carry-through. + // Three taps must reach 8 (5 -> 6 -> 7 -> 8); the stale closure made every tap after the + // first re-apply against last render's value, so the count would lag behind the taps. + it('advances reps by exactly one per tap across repeated taps', async () => { + await mount([ + exercise('press', [false], { sg: 'group' }), + exercise('row', [false], { sg: 'group' }), + ]) + + await tap(stepperButton(0, 0, 1, 'Increase')) + await tap(stepperButton(0, 0, 1, 'Increase')) + await tap(stepperButton(0, 0, 1, 'Increase')) + + expect(mocks.S.active.entries[0].sets[0].r).toBe(8) + }) + + // The partner exercise shares the subscription that gets replaced on every write. Tapping its + // stepper after the first exercise has already been bumped must still act on the partner's own + // current value, not a snapshot from before the clone. + it('steps the partner exercise correctly after the first member was changed', async () => { + await mount([ + exercise('press', [false], { sg: 'group' }), + exercise('row', [false], { sg: 'group' }), + ]) + + await tap(stepperButton(0, 0, 1, 'Increase')) + await tap(stepperButton(1, 0, 1, 'Increase')) + + expect(mocks.S.active.entries[0].sets[0].r).toBe(6) + expect(mocks.S.active.entries[1].sets[0].r).toBe(6) + }) + + // Decrement walks the same path and must not undershoot or need a double tap either. + it('decrements a superset member weight by one step per tap', async () => { + await mount([ + exercise('press', [false], { sg: 'group' }), + exercise('row', [false], { sg: 'group' }), + ]) + + await tap(stepperButton(0, 0, 0, 'Decrease')) + + expect(mocks.S.active.entries[0].sets[0].w).toBe(57.5) + }) +}) diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index 72c0082..ce1a157 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client' import { parseHTML } from 'linkedom' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import Workout from './Workout.jsx' +import { nextPrescription } from '../lib/progression.js' const mocks = vi.hoisted(() => { const state = { @@ -137,6 +138,13 @@ async function toggleSet(index) { await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) }) } +async function pressNext() { + const button = [...container.querySelectorAll('button')] + .find(button => button.textContent.trim() === 'Next') + expect(button).toBeTruthy() + await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) }) +} + async function pressProgression(index = 0) { const button = container.querySelectorAll('.progline')[index] expect(button).toBeTruthy() @@ -205,8 +213,50 @@ describe('Workout set completion flow', () => { expect(mocks.startRest).not.toHaveBeenCalled() }) + it('auto-captures a completed weighted exercise without prompting, leaving navigation to Next', async () => { + await mount([exercise('plain-bench', [false]), exercise('next', [false])]) + + await toggleSet(0) + + expect(mocks.S.active.entries[0].topW).toBe(60) + expect(mocks.S.exWeights['plain-bench']).toBeUndefined() // written at the finish, not while ticking + expect(mocks.topWeightSheet).not.toHaveBeenCalled() + expect(mocks.S.active.cur).toBe(0) + expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) + + await pressNext() + + expect(mocks.S.active.cur).toBe(1) + }) + + it('auto-captures superset members without prompting, then leaves the completed unit for Next', async () => { + const group = 'superset-1' + await mount([ + exercise('superset-a', [false], { sg: group }), + exercise('superset-b', [false], { sg: group }), + exercise('next', [false]), + ]) + + await toggleSet(0) + + expect(mocks.topWeightSheet).not.toHaveBeenCalled() + expect(mocks.S.active.cur).toBe(1) + expect(mocks.startRest).not.toHaveBeenCalled() + + await rerender() + await toggleSet(1) + + expect(mocks.topWeightSheet).not.toHaveBeenCalled() + expect(mocks.S.active.cur).toBe(1) + expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) + + await pressNext() + + expect(mocks.S.active.cur).toBe(2) + }) + it.each(['warmup', 'warm-up', 'warm_up'])( - 'does not start transition rest before an incomplete %s row in the next ordinary exercise', + 'does not navigate or start transition rest before an incomplete %s row in the next ordinary exercise', async phase => { await mount([ exercise('current', [false], { asked: true }), @@ -221,12 +271,12 @@ describe('Workout set completion flow', () => { await toggleSet(0) - expect(mocks.S.active.cur).toBe(1) + expect(mocks.S.active.cur).toBe(0) expect(mocks.startRest).not.toHaveBeenCalled() }, ) - it('does not start transition rest when a completed superset advances to an incomplete warm-up', async () => { + it('does not navigate or start transition rest when a completed superset meets an incomplete warm-up', async () => { await mount([ exercise('superset-a', [true], { sg: 'group', asked: true }), exercise('superset-b', [false], { sg: 'group', asked: true }), @@ -241,11 +291,11 @@ describe('Workout set completion flow', () => { await toggleSet(1) - expect(mocks.S.active.cur).toBe(2) + expect(mocks.S.active.cur).toBe(1) expect(mocks.startRest).not.toHaveBeenCalled() }) - it('does not start transition rest before a warm-up while top-weight confirmation owns navigation', async () => { + it('leaves the completed ordinary exercise selected without transition rest before an incomplete warm-up', async () => { await mount([ exercise('current-loaded', [false]), exercise('next', [false, false], { @@ -259,7 +309,7 @@ describe('Workout set completion flow', () => { await toggleSet(0) - expect(mocks.topWeightSheet).toHaveBeenCalledWith(0) + expect(mocks.topWeightSheet).not.toHaveBeenCalled() expect(mocks.S.active.cur).toBe(0) expect(mocks.startRest).not.toHaveBeenCalled() }) @@ -284,7 +334,7 @@ describe('Workout set completion flow', () => { expect(mocks.startRest).not.toHaveBeenCalled() }) - it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => { + it('leaves a completed superset selected without opening a top-weight sheet', async () => { const group = 'superset-1' await mount([ exercise('superset-a', [true, true, true], { sg: group, asked: true }), @@ -293,12 +343,12 @@ describe('Workout set completion flow', () => { ], 1) await toggleSet(5) - expect(mocks.topWeightSheet).toHaveBeenCalledWith(1) + expect(mocks.topWeightSheet).not.toHaveBeenCalled() expect(mocks.S.active.cur).toBe(1) expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) }) - it('skips completed intervening units and selects the next unfinished superset as one unit', async () => { + it('does not auto-select an unfinished superset after completing an ordinary exercise', async () => { await mount([ exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }), exercise('already-done', [true], { asked: true }), @@ -308,13 +358,13 @@ describe('Workout set completion flow', () => { await toggleSet(0) - expect(mocks.S.active.cur).toBe(2) + expect(mocks.S.active.cur).toBe(0) expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() expect(mocks.toast).toHaveBeenCalledWith('Hold logged') expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) }) - it('wraps to earlier unfinished work instead of showing a false completion prompt', async () => { + it('does not auto-select earlier unfinished work after completing an ordinary exercise', async () => { await mount([ exercise('pending-earlier', [false], { asked: true }), exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }), @@ -322,12 +372,12 @@ describe('Workout set completion flow', () => { await toggleSet(0) - expect(mocks.S.active.cur).toBe(0) + expect(mocks.S.active.cur).toBe(1) expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) }) - it('keeps top-weight confirmation in control without declaring completion while work remains', async () => { + it('leaves a completed ordinary exercise selected without declaring completion while work remains', async () => { await mount([ exercise('current-loaded', [false]), exercise('pending', [false], { asked: true }), @@ -335,9 +385,10 @@ describe('Workout set completion flow', () => { await toggleSet(0) - expect(mocks.topWeightSheet).toHaveBeenCalledWith(0) + expect(mocks.topWeightSheet).not.toHaveBeenCalled() expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() expect(mocks.S.active.cur).toBe(0) + expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) }) it('shows workout completion only when no unfinished unit remains', async () => { @@ -349,6 +400,7 @@ describe('Workout set completion flow', () => { await toggleSet(0) expect(mocks.workoutCompleteSheet).toHaveBeenCalledOnce() + expect(mocks.S.active.cur).toBe(1) expect(mocks.startRest).not.toHaveBeenCalled() }) }) @@ -360,7 +412,7 @@ describe('Workout add exercise flow', () => { active: { routineId: 'routine-1' }, routines: [{ id: 'routine-1', ex: [] }], }], - ])('inserts after the current unit and continues to pending work in a %s session', async (_label, overrides) => { + ])('inserts after the current unit and leaves the inserted exercise selected after completion in a %s session', async (_label, overrides) => { await mount([ exercise('current', [true], { asked: true }), exercise('pending', [false], { asked: true }), @@ -378,7 +430,7 @@ describe('Workout add exercise flow', () => { await toggleSet(0) expect(mocks.S.active.entries[1].sets[0].done).toBe(true) - expect(mocks.S.active.cur).toBe(2) + expect(mocks.S.active.cur).toBe(1) expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() }) @@ -401,6 +453,69 @@ describe('Workout add exercise flow', () => { }) }) +describe('active workout weight controls', () => { + const press = async (label, selector) => { + const control = container.querySelector(selector) + const button = control?.querySelector(`button[aria-label="${label}"]`) + expect(button).toBeTruthy() + await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) }) + await rerender() + } + + it('uses the configured reps weight step for manual increases and decreases, with the default fallback', async () => { + await mount([exercise('plain-bench', [false], { + target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false, inc: 1 }, + })]) + + await press('Increase', '.setrow .stp.w') + expect(mocks.S.active.entries[0].sets[0].w).toBe(61) + await press('Decrease', '.setrow .stp.w') + expect(mocks.S.active.entries[0].sets[0].w).toBe(60) + + await unmount() + await mount([exercise('plain-bench', [false])]) + await press('Increase', '.setrow .stp.w') + expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5) + }) + + it('matches automatic progression rounding for a fractional configured step', async () => { + const target = { mode: 'reps', sets: 1, reps: 5, weight: 60, bodyweight: false, inc: 1.25 } + const automatic = nextPrescription({ + unit: 'kg', + workouts: [{ d: '2026-08-30', entries: [{ id: 'plain-bench', target, sets: [{ w: 60, r: 5, done: true }] }] }], + }, { id: 'plain-bench', ...target }) + + await mount([exercise('plain-bench', [false], { target, sets: [{ w: 60, r: 5, done: false }] })]) + await press('Increase', '.setrow .stp.w') + + expect(automatic.weight).toBe(61.3) + expect(mocks.S.active.entries[0].sets[0].w).toBe(automatic.weight) + }) + + it('uses the configured reps weight step for drop-set weight controls', async () => { + await mount([exercise('plain-bench', [false], { + target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false, inc: 1 }, + sets: [{ w: 60, r: 5, done: false, type: 'dropset', drops: [{ w: 50, r: 5 }] }], + })]) + + await press('Increase', '.subrow .stp') + + expect(mocks.S.active.entries[0].sets[0].drops[0].w).toBe(51) + }) + + it('keeps timed seconds and optional timed weight on their existing steps', async () => { + await mount([exercise('timed-plank', [false], { + target: { mode: 'time', sec: 30, weight: 60, bodyweight: false, inc: 1 }, + sets: [{ sec: 30, w: 60, done: false }], + })]) + + await press('Increase', '.setrow .stp.w') + expect(mocks.S.active.entries[0].sets[0].sec).toBe(35) + await press('Increase', '.setrow .stp.r') + expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5) + }) +}) + describe('Workout discard timer lifecycle', () => { it('preserves active timers while discard is awaiting confirmation', async () => { const timer = { left: 30, total: 90, endsAt: Date.now() + 30_000 } @@ -477,6 +592,47 @@ describe('progression guidance', () => { expect(mocks.S.active.cur).toBe(0) }) + it('does not save into a different duplicate occurrence after the entry list shifts', async () => { + const plan = { + policy: 'linear', kind: 'up', weight: 62.5, + why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'], + } + const first = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 5, weight: 60, marker: 'first' } }) + const second = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 8, weight: 80, marker: 'second' } }) + const third = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 10, weight: 100, marker: 'third' } }) + await mount([first, second, third], 1) + await pressProgression() + const save = mocks.exConfigSheet.mock.calls[0][2] + + mocks.S.active.entries.splice(0, 1) + await act(async () => { save({ ...second.target, prog: 'double', repsMin: 6 }) }) + + expect(mocks.S.active.entries.map(entry => entry.target.marker)).toEqual(['second', 'third']) + expect(mocks.S.active.entries[0].target.prog).toBeUndefined() + expect(mocks.S.active.entries[1].target.prog).toBeUndefined() + }) + + it('does not save through a sheet left open from a replaced workout', async () => { + const plan = { + policy: 'linear', kind: 'up', weight: 62.5, + why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'], + } + const original = exercise('plain-bench', [false], { plan }) + await mount([original]) + await pressProgression() + const save = mocks.exConfigSheet.mock.calls[0][2] + const replacement = exercise('plain-bench', [false], { + plan, + target: { mode: 'reps', reps: 10, weight: 100, marker: 'replacement' }, + }) + mocks.S.active = { ...mocks.S.active, id: 'replacement-workout', entries: [replacement] } + + await act(async () => { save({ ...original.target, prog: 'double', repsMin: 6 }) }) + + expect(mocks.S.active.entries[0].target).toEqual(replacement.target) + expect(mocks.S.active.entries[0].target.prog).toBeUndefined() + }) + it('leaves the active entry unchanged when progression settings are cancelled', async () => { const entry = exercise('plain-bench', [true, false], { plan: { @@ -697,3 +853,92 @@ describe('active exercise swap control', () => { expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(1) }) }) + +describe('workout list view', () => { + const units = () => [...container.querySelectorAll('.wl-unit')] + const focusButton = unit => [...unit.querySelectorAll('button')].find(b => b.textContent.trim() === 'Set current') + + it('stacks every exercise, labels each unit, and hides card navigation', async () => { + await mount([exercise('plain-bench', [false, false]), exercise('plain-row', [false])], 0, { workoutView: 'list' }) + + expect(container.querySelector('[data-testid="workout-list"]')).toBeTruthy() + expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeNull() + expect(units().length).toBe(2) + // Every set in the session is visible at once: 2 + 1 checkboxes, not just the current one. + expect(container.querySelectorAll('[role="checkbox"]').length).toBe(3) + expect(units().map(u => u.querySelector('.wl-hd .muted')?.textContent)).toEqual([ + 'Exercise 1 / 2', 'Exercise 2 / 2', + ]) + expect(units()[0].textContent).toContain('Current') + expect(focusButton(units()[1])).toBeTruthy() + const navButtons = [...container.querySelectorAll('button')] + .filter(b => b.textContent.trim() === 'Prev' || b.textContent.trim() === 'Next') + expect(navButtons.length).toBe(0) + }) + + it('marks the current unit and moves the mark with Set current', async () => { + await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])], 0, { workoutView: 'list' }) + + await act(async () => { focusButton(units()[1]).dispatchEvent(new dom.Event('click', { bubbles: true })) }) + expect(mocks.S.active.cur).toBe(1) + + await rerender() + expect(units()[0].textContent).not.toContain('Current') + expect(units()[1].textContent).toContain('Current') + expect(focusButton(units()[0])).toBeTruthy() + }) + + // Since !92 finishing an exercise no longer moves the current marker on its own (cards use + // Next, the list uses "Set current"); completion still starts the rest like cards do. + it('completing a set in list mode starts the rest and leaves the current marker in place, like cards do', async () => { + await mount([ + exercise('plain-bench', [false], { asked: true }), + exercise('plain-row', [false], { asked: true }), + ], 0, { workoutView: 'list' }) + + await toggleSet(0) + + expect(mocks.S.active.entries[0].sets[0].done).toBe(true) + expect(mocks.S.active.cur).toBe(0) + expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) + }) + + it('does not declare the workout complete after a set of a non-current exercise while sets remain', async () => { + // The marker stays on the finished bench (!92); ticking the first of three row sets must + // not open the completion sheet — the row's own unit still has two sets to go. + await mount([ + exercise('plain-bench', [true], { asked: true }), + exercise('plain-row', [false, false, false], { asked: true }), + ], 0, { workoutView: 'list' }) + + await toggleSet(1) + + expect(mocks.S.active.entries[1].sets[0].done).toBe(true) + expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() + expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) + }) + + it('renders a superset as one grouped unit with its own unpair control', async () => { + await mount([ + exercise('bench', [false], { sg: 'g1', asked: true }), + exercise('row', [false], { sg: 'g1', asked: true }), + exercise('squat', [false], { asked: true }), + ], 0, { workoutView: 'list' }) + + expect(units().length).toBe(2) + expect(units()[0].querySelector('.ss-card')).toBeTruthy() + expect(units()[1].querySelector('.ss-card')).toBeNull() + expect(units().map(u => u.querySelector('.wl-hd .muted')?.textContent)).toEqual([ + 'Superset 1 / 2', 'Exercise 2 / 2', + ]) + }) + + it('defaults to cards when the setting is absent (pre-existing profiles)', async () => { + await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])]) + + expect(container.querySelector('[data-testid="workout-list"]')).toBeNull() + expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeTruthy() + // Only the current exercise's sets are on screen. + expect(container.querySelectorAll('[role="checkbox"]').length).toBe(1) + }) +}) diff --git a/frontend/src/views/starter-entry.test.jsx b/frontend/src/views/starter-entry.test.jsx new file mode 100644 index 0000000..5dab0a8 --- /dev/null +++ b/frontend/src/views/starter-entry.test.jsx @@ -0,0 +1,51 @@ +// @vitest-environment happy-dom +// Home and Plan both offer the starter plan to someone who has no routines yet. Both used to +// wire the button straight to the loader, which quietly handed the click event in as the plan +// id and loaded nothing at all — so both entry points are pinned here. +import React, { act } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createRoot } from 'react-dom/client' +import { useStore } from '../store/useStore.js' +import { starterPlanSheet } from '../sheets.jsx' +import Home from './Home.jsx' +import Plan from './Plan.jsx' + +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../sheets.jsx', () => ({ + starterPlanSheet: vi.fn(), bwSheet: vi.fn(), goalSheet: vi.fn(), dayOverrideSheet: vi.fn(), + calendarSheet: vi.fn(), startFlow: vi.fn(), bwDeltaColor: () => '', + dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(), +})) + +let host, root +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + starterPlanSheet.mockClear() + useStore.setState(s => ({ S: { ...s.S, routines: [], week: {}, active: null }, user: null })) + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() +}) + +const starterButton = () => [...host.querySelectorAll('button')].find(b => b.textContent === 'Load starter plan') + +describe.each([['Home', Home], ['Plan', Plan]])('%s empty state', (_name, View) => { + it('opens the starter plan chooser instead of loading one plan blind', () => { + act(() => root.render()) + const button = starterButton() + expect(button).toBeTruthy() + + act(() => { button.click() }) + expect(starterPlanSheet).toHaveBeenCalledTimes(1) + }) + + it('drops the offer once the user has routines', () => { + useStore.setState(s => ({ S: { ...s.S, routines: [{ id: 'r', name: 'Mine', emoji: 'star', ex: [] }] } })) + act(() => root.render()) + expect(starterButton()).toBeFalsy() + }) +}) diff --git a/frontend/src/views/week-start.test.jsx b/frontend/src/views/week-start.test.jsx index 34bf2a3..e05c0c5 100644 --- a/frontend/src/views/week-start.test.jsx +++ b/frontend/src/views/week-start.test.jsx @@ -44,7 +44,7 @@ vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false })) vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() })) vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null })) vi.mock('../sheets.jsx', () => ({ - loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), + starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(), })) diff --git a/mcp/README.md b/mcp/README.md index 0cff276..18532ad 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -67,12 +67,13 @@ the server's stderr. ## Tools -Eight read-only tools in v1: +Nine read-only tools in v1: | Tool | What it answers | |---|---| | `list_routines` | What routines are saved in my profile? (names + exercise counts) | -| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) | +| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight and rest per exercise) | +| `preview_session` | What will the app actually put on screen when I start this routine — after the progression policy and my history have overridden the plan? | | `get_week_plan` | What's on my plan this week, including today with any date-specific override? | | `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. | | `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. | @@ -80,6 +81,13 @@ Eight read-only tools in v1: | `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. | | `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. | +`get_routine` and `preview_session` answer two different questions, and confusing them is the +easiest way for a coach to give wrong advice. `get_routine` reports what the routine *stores*. +`preview_session` reports what the athlete will actually *see*: a routine holding "squat 3×8 @ +60 kg" opens at 75 kg if the policy deloaded from the last logged session, and the rep counts +come from history, not the plan. The routine's own numbers are the last fallback the session +builder consults, not the first. Ask `preview_session` before naming a weight. + Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels) are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to re-interpret them. @@ -112,7 +120,7 @@ dependencies landed in `frontend/`, no public exports changed. cd mcp && npm test ``` -32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture +58 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override, missing routine, zero-workout history, no synced state, superset links, three 1RM formulas. "Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent @@ -122,8 +130,8 @@ their own 92 tests in `frontend/src/lib/*.test.js`. ## Roadmap - **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access. -- **Phase 1.5:** a `progression_next` tool (what does the policy prescribe next?). No new - deps; small surface area. +- **Done (Phase 1.5):** `preview_session` — the policy's next prescription, the opening set + rows it produces, and which of plan / confirmed weight / history each number came from. - **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify- write of `state-.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`, diff --git a/mcp/src/tools.js b/mcp/src/tools.js index 3d20b40..453ff24 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -4,10 +4,10 @@ import { z } from 'zod' import { getState, getUser } from './state.js' import { - setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder + fmt, setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder } from './labels.js' import { - modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId + modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId, lastEntryFor } from '../../frontend/src/lib/history.js' import { exOr } from '../../frontend/src/lib/exercises.js' import { isWarmupRow } from '../../frontend/src/lib/workout-model.js' @@ -16,6 +16,7 @@ import { } from '../../frontend/src/lib/onerm.js' import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js' import { policyFor } from '../../frontend/src/lib/progression.js' +import { buildSessionEntries } from '../../frontend/src/lib/session-start.js' /* ---------- helpers ---------- */ @@ -105,7 +106,7 @@ export const listRoutines = { /** get_routine — the full exercise list for one routine, including set/rep targets. */ export const getRoutine = { name: 'get_routine', - description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.', + description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, any per-exercise custom increment you can override, and each exercise\'s own rest in seconds (absent means it inherits the global rest timer). Use routine_id from list_routines.', schema: { routine_id: z.string().min(1) }, handler: ({ routine_id }) => { const S = getState() @@ -138,6 +139,9 @@ export const getRoutine = { speed: mode === 'cardio' ? (cfg.speed || 0) : undefined, weight: cfg.weight != null ? cfg.weight : undefined, increment: cfg.inc != null ? cfg.inc : undefined, + // The exercise's own rest (issue #10). Absent means it inherits the global rest + // timer; a superset rests once, taking the longest its members ask for. + rest_sec: cfg.restSec > 0 ? cfg.restSec : undefined, policy: policyFor(cfg, r, mode), policy_override: cfg.prog || null, superset_group: cfg.sg || null, @@ -407,10 +411,161 @@ export const muscleBalance = { } } +/* ---------- preview_session ---------- */ + +// Where a number on the session screen actually came from. A routine's own sets/reps/weight +// are the LAST fallback, not the first: buildSets() prefers the confirmed working weight and +// the previous session's reps, and applyPrescription() then overwrites the weight with +// whatever the progression policy decided. Reporting the winner is the whole point of this +// tool — "the plan says 60" is not an answer to "what will the app show me". +function sourceOf(S, cfg, plan, field) { + // Progression off (or a deload routine): the session is built from the routine's own target, + // exactly as session-start.js does with useTarget — history and the confirmed weight are ignored. + if (!plan || plan.kind === 'off') return 'routine_plan' + const decided = plan.kind !== 'first' && plan[field] != null + if (decided) return 'progression' + if (field === 'weight') { + const conf = (S.exWeights || {})[cfg.id] + if (conf && conf.w > 0) return 'confirmed_weight' + } + return lastEntryFor(S, cfg.id) ? 'last_session' : 'routine_plan' +} + +const SOURCE_TEXT = { + progression: 'the progression policy overrode the routine', + confirmed_weight: 'your confirmed working weight for this exercise', + last_session: 'carried over from the last time you did this exercise', + routine_plan: "the routine's own target" +} + +/** preview_session — what starting this routine will actually put on screen. */ +export const previewSession = { + name: 'preview_session', + description: + 'Preview the session a routine will actually open with — the numbers the user will see after the progression policy and their training history have overridden the routine\'s own targets. This is NOT the same as get_routine: a routine storing "squat 3x8 @ 60kg" can open at 75kg because the policy deloaded from the last logged session, and reps carry from history rather than from the plan. Always call this (not get_routine) before telling someone what weight they are about to lift, or before judging whether an edit to a routine had any effect. Returns, per exercise, the planned target, the policy\'s decision and its stated reason, the opening set rows, and where each number came from. Defaults to today\'s scheduled routine.', + schema: { + routine_id: z.string().min(1).optional().describe('Routine to preview. Defaults to the routine scheduled for `date`.'), + date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Date the session would be started on, YYYY-MM-DD. Affects which routine is scheduled and any one-off day override. Defaults to today.') + }, + handler: ({ routine_id, date }) => { + const S = getState() + if (!S) return noState() + const now = new Date() + const iso = date || (now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' + String(now.getDate()).padStart(2, '0')) + + let r + if (routine_id) { + r = (S.routines || []).find(x => x.id === routine_id) + if (!r) { const e = new Error(`no routine with id ${JSON.stringify(routine_id)}`); e.code = 'ENOENT'; throw e } + } else { + r = effectiveRoutine(S, iso) + if (!r) return { date: iso, routine_id: null, routine_name: null, rest_day: true, note: 'no routine is scheduled for this date (rest day)', exercises: [] } + } + + const unit = S.unit || 'kg' + // The same builder the app starts a session with (sheets.jsx beginWorkout → session-start.js): + // prescription, step, progression-off targets, deload routines and warm-up ramps all come from + // there, so the preview cannot drift from what the screen shows. + const built = buildSessionEntries(S, r).entries + const exercises = (r.ex || []).map((cfg, i) => { + const ex = exerciseOf(cfg.id, S) + const mode = modeOf({ ...cfg, id: cfg.id }) + const plan = built[i].plan + const rows = built[i].sets + const work = rows.filter(s => !isWarmupRow(s)) + const openW = work.length ? (work[0].w || 0) : 0 + const openR = work.length ? (work[0].r || 0) : 0 + const openSec = work.length ? (work[0].sec || 0) : 0 + const openMin = work.length ? (work[0].min || 0) : 0 + const wSrc = sourceOf(S, cfg, plan, 'weight') + const rSrc = sourceOf(S, cfg, plan, 'reps') + return { + position: i + 1, + id: cfg.id, + name: ex.n, + mode, + policy: plan.policy, + policy_name: policyName(plan.policy), + planned: { + sets: cfg.sets || 1, + reps: mode === 'reps' ? (cfg.reps || 0) : undefined, + sec: mode === 'time' ? (cfg.sec || 0) : undefined, + min: mode === 'cardio' ? (cfg.min || 0) : undefined, + weight: cfg.weight != null ? cfg.weight : undefined, + summary: exLine(cfg, unit) + }, + prescription: { + kind: plan.kind, + weight: plan.weight != null ? plan.weight : undefined, + reps: plan.reps != null ? plan.reps : undefined, + sets: plan.sets != null ? plan.sets : undefined, + sec: plan.sec != null ? plan.sec : undefined, + why: plan.why ? fmt(plan.why[0], plan.why.slice(1)) : null + }, + opening_sets: rows.map(s => ({ + phase: isWarmupRow(s) ? 'warmup' : 'work', + type: s.type || 'straight', + label: setLabel(cfg.id, { ...s, done: undefined }, { ...cfg, id: cfg.id }), + w: Number(s.w) || 0, + r: Number(s.r) || 0, + sec: Number(s.sec) || 0, + min: Number(s.min) || 0, + speed: Number(s.speed) || 0 + })), + weight_source: wSrc, + weight_source_text: SOURCE_TEXT[wSrc], + reps_source: mode === 'reps' ? rSrc : undefined, + reps_source_text: mode === 'reps' ? SOURCE_TEXT[rSrc] : undefined, + // The headline: did editing the routine change anything the user will see? Tracked per + // dimension — a bodyweight exercise whose weight is 0 either way still counts when the + // rep target moved, and saying which one moved saves the caller diffing it themselves. + changed: [ + ...(mode === 'reps' && cfg.weight != null && openW !== cfg.weight ? ['weight'] : []), + ...(mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps ? ['reps'] : []), + ...(mode === 'time' && (cfg.sec || 0) > 0 && openSec !== cfg.sec ? ['sec'] : []), + ...(mode === 'cardio' && (cfg.min || 0) > 0 && openMin !== cfg.min ? ['min'] : []) + ], + differs_from_plan: + (mode === 'reps' && cfg.weight != null && openW !== cfg.weight) || + (mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps) || + (mode === 'time' && (cfg.sec || 0) > 0 && openSec !== cfg.sec) || + (mode === 'cardio' && (cfg.min || 0) > 0 && openMin !== cfg.min) + } + }) + + const differing = exercises.filter(e => e.differs_from_plan) + return { + date: iso, + routine_id: r.id, + routine_name: r.name, + unit, + policy: policyFor(null, r, 'reps'), + policy_name: policyName(policyFor(null, r, 'reps')), + exercises, + // Surfaced separately so a coach reading this cannot miss it: these are the exercises + // where what the routine stores and what the athlete will see are two different numbers. + overridden_count: differing.length, + overridden: differing.map(e => ({ + name: e.name, + planned_weight: e.planned.weight, + opening_weight: e.opening_sets.filter(s => s.phase === 'work')[0]?.w ?? null, + planned_reps: e.planned.reps, + opening_reps: e.opening_sets.filter(s => s.phase === 'work')[0]?.r ?? null, + planned_sec: e.planned.sec, + opening_sec: e.opening_sets.filter(s => s.phase === 'work')[0]?.sec ?? null, + planned_min: e.planned.min, + opening_min: e.opening_sets.filter(s => s.phase === 'work')[0]?.min ?? null, + changed: e.changed, + reason: e.prescription.why || e.weight_source_text + })) + } + } +} + /* ---------- registration list ---------- */ export const TOOLS = [ - listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance + listRoutines, getRoutine, previewSession, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance ] function noState() { diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js index 7b6e480..b6674a4 100644 --- a/mcp/test/tools.test.js +++ b/mcp/test/tools.test.js @@ -129,6 +129,17 @@ describe('get_routine', () => { expect(r.exercises[0]).toMatchObject({ reps: 8, reps_min: 8, reps_max: 12 }) }) + test('reports an exercise\'s own rest, and leaves it out when it inherits the timer', () => { + S.routines[0].ex[0].restSec = 180 + delete S.routines[0].ex[1]?.restSec + + const r = call('get_routine', { routine_id: S.routines[0].id }) + expect(r.exercises[0].rest_sec).toBe(180) + // An exercise with no rest of its own inherits the global timer. Absent says that; + // a zero would read as "no rest at all", which is a different prescription. + expect(JSON.parse(JSON.stringify(r)).exercises[1]).not.toHaveProperty('rest_sec') + }) + test('projects routine and exercise progression rules from prog', () => { S.routines[0].prog = 'greyskull' S.routines[0].ex[0].prog = 'double' @@ -663,3 +674,177 @@ describe('shared: no-state fallback', () => { // failure rather than inherits null silently. afterAll(() => { _seedStateForTests(S = freshState()) }) }) + +/* ---------- preview_session ---------- */ + +// The gap this tool exists to close: a routine stores sets/reps/weight, but those are the +// LAST fallback the session builder consults. These tests pin the precedence — progression +// beats the confirmed working weight, which beats the routine's own number — because getting +// it backwards is how a coach ends up telling someone to squat a weight the app never shows. +describe('preview_session', () => { + const WD = new Date(FAKE_TODAY_ISO + 'T12:00:00Z').getDay() + + // One routine, one exercise, scheduled for the pinned "today". Nothing from the demo seed, + // so the arithmetic below is checkable by hand. + // Linear by default: with progression off the app opens the routine's own numbers (see the + // two tests at the end), so history-vs-plan precedence is only observable under a policy. + function only(cfg, { prog = 'linear', workouts = [], exWeights = {}, routine = {} } = {}) { + S.routines = [{ id: 'r-preview', name: 'Preview', emoji: 'barbell', prog, ex: [cfg], ...routine }] + S.week = { [WD]: 'r-preview' } + S.dayPlan = {} + S.workouts = workouts + S.exWeights = exWeights + _seedStateForTests(S) + } + + test('defaults to the routine scheduled for today', () => { + only({ id: '0025', sets: 3, reps: 8, weight: 50 }) + const r = call('preview_session') + expect(r.date).toBe(FAKE_TODAY_ISO) + expect(r.routine_name).toBe('Preview') + expect(r.exercises).toHaveLength(1) + expect(r.exercises[0].name).toBe('barbell bench press') + }) + + test('with no history and no confirmed weight, the routine\'s own number is what opens', () => { + only({ id: '0025', sets: 3, reps: 8, weight: 50 }) + const e = call('preview_session').exercises[0] + expect(e.weight_source).toBe('routine_plan') + expect(e.opening_sets.map(s => s.w)).toEqual([50, 50, 50]) + expect(e.opening_sets.map(s => s.r)).toEqual([8, 8, 8]) + expect(e.differs_from_plan).toBe(false) + expect(call('preview_session').overridden_count).toBe(0) + }) + + test('a confirmed working weight beats the routine\'s number', () => { + only({ id: '0025', sets: 2, reps: 8, weight: 50 }, { exWeights: { '0025': { w: 72.5, d: '2026-07-20' } } }) + const e = call('preview_session').exercises[0] + expect(e.weight_source).toBe('confirmed_weight') + expect(e.opening_sets.every(s => s.w === 72.5)).toBe(true) + expect(e.changed).toEqual(['weight']) + }) + + test('the progression policy beats both, and its reason is reported', () => { + // Every rep hit at 60 last time under linear progression → +2.5, regardless of the 100 + // the routine stores. + only({ id: '0025', sets: 3, reps: 5, weight: 100 }, { + prog: 'linear', + exWeights: { '0025': { w: 100, d: '2026-07-20' } }, + workouts: [{ + id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview', + entries: [{ + id: '0025', + target: { id: '0025', sets: 3, reps: 5, weight: 60 }, + sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] + }] + }] + }) + const out = call('preview_session') + const e = out.exercises[0] + expect(e.prescription.kind).toBe('up') + expect(e.weight_source).toBe('progression') + expect(e.opening_sets.every(s => s.w === 62.5)).toBe(true) + expect(e.prescription.why).toMatch(/Every rep last time/) + expect(e.changed).toEqual(['weight']) + + expect(out.overridden_count).toBe(1) + expect(out.overridden[0]).toMatchObject({ + name: 'barbell bench press', planned_weight: 100, opening_weight: 62.5 + }) + expect(out.overridden[0].reason).toMatch(/Every rep last time/) + }) + + test('reps carry from the last session even when the routine asks for something else', () => { + only({ id: '0025', sets: 2, reps: 12, weight: 60 }, { + workouts: [{ + id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview', + entries: [{ + id: '0025', + target: { id: '0025', sets: 2, reps: 5, weight: 60 }, + sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] + }] + }] + }) + const e = call('preview_session').exercises[0] + expect(e.opening_sets.map(s => s.r)).toEqual([5, 5]) // not the 12 the routine stores + expect(e.reps_source).toBe('last_session') + expect(e.changed).toContain('reps') + }) + + test('planned drop sets show up on the opening rows', () => { + only({ id: '0025', sets: 2, reps: 10, weight: 50, intensifier: { type: 'dropset', count: 1, pct: 20 } }) + const e = call('preview_session').exercises[0] + expect(e.opening_sets.every(s => s.type === 'dropset')).toBe(true) + }) + + test('an explicit routine_id overrides the schedule', () => { + only({ id: '0025', sets: 3, reps: 8, weight: 50 }) + const other = { id: 'r-other', name: 'Other', prog: 'off', ex: [{ id: '0043', sets: 5, reps: 5, weight: 80 }] } + S.routines.push(other) + _seedStateForTests(S) + expect(call('preview_session', { routine_id: 'r-other' }).routine_name).toBe('Other') + }) + + test('a rest day returns no exercises rather than an error', () => { + only({ id: '0025', sets: 3, reps: 8, weight: 50 }) + S.week = {} + _seedStateForTests(S) + const r = call('preview_session') + expect(r.rest_day).toBe(true) + expect(r.exercises).toEqual([]) + }) + + test('with progression off the routine\'s own numbers open, whatever history says (matches session-start.js)', () => { + only({ id: '0025', sets: 3, reps: 8, weight: 50 }, { + prog: 'off', + exWeights: { '0025': { w: 72.5, d: '2026-07-20' } }, + workouts: [{ + id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview', + entries: [{ id: '0025', target: { id: '0025', sets: 3, reps: 5, weight: 60 }, sets: [{ w: 60, r: 5, done: true }] }] + }] + }) + const out = call('preview_session') + const e = out.exercises[0] + expect(e.prescription.kind).toBe('off') + expect(e.opening_sets.map(s => [s.w, s.r])).toEqual([[50, 8], [50, 8], [50, 8]]) + expect(e.weight_source).toBe('routine_plan') + expect(e.reps_source).toBe('routine_plan') + expect(e.differs_from_plan).toBe(false) + expect(out.overridden_count).toBe(0) + }) + + test('a deload routine (excludeFromProgression) opens its own numbers even under a policy', () => { + only({ id: '0025', sets: 3, reps: 5, weight: 50 }, { + prog: 'linear', routine: { excludeFromProgression: true }, + workouts: [{ + id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview', + entries: [{ id: '0025', target: { id: '0025', sets: 3, reps: 5, weight: 60 }, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] }] + }] + }) + const e = call('preview_session').exercises[0] + expect(e.prescription.kind).toBe('off') + expect(e.opening_sets.every(s => s.w === 50 && s.r === 5)).toBe(true) + expect(e.weight_source).toBe('routine_plan') + }) + + test('a timed exercise that progressed is listed as overridden too', () => { + only({ id: '0025', mode: 'time', sets: 3, sec: 30, inc: 10 }, { + prog: 'time', + workouts: [{ + id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview', + entries: [{ id: '0025', target: { id: '0025', mode: 'time', sets: 3, sec: 30 }, sets: [{ sec: 45, done: true }, { sec: 45, done: true }, { sec: 45, done: true }] }] + }] + }) + const out = call('preview_session') + const e = out.exercises[0] + expect(e.prescription.kind).toBe('up') + expect(e.changed).toEqual(['sec']) + expect(e.differs_from_plan).toBe(true) + expect(out.overridden[0].opening_sec).toBeGreaterThan(30) + }) + + test('an unknown routine_id is an error, not an empty session', () => { + only({ id: '0025', sets: 3, reps: 8, weight: 50 }) + expect(() => call('preview_session', { routine_id: 'nope' })).toThrow(/no routine with id/) + }) +})