diff --git a/frontend/src/lib/coach.test.js b/frontend/src/lib/coach.test.js index 09487d6..e12dd11 100644 --- a/frontend/src/lib/coach.test.js +++ b/frontend/src/lib/coach.test.js @@ -449,8 +449,8 @@ describe('created plans', () => { it('replaces the week only when asked, and remaps to the new ids', () => { const s = JSON.parse(JSON.stringify(state())) applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true }) - expect(s.week[1]).toBe(s.routines[2].id) - expect(s.week[3]).toBe(s.routines[3].id) + expect(s.week[1]).toEqual([s.routines[2].id]) // a weekday holds a routine-id list + expect(s.week[3]).toEqual([s.routines[3].id]) expect(s.week[5]).toBeUndefined() // a day the new plan leaves empty is rest }) diff --git a/frontend/src/lib/finish-workout.js b/frontend/src/lib/finish-workout.js index cd2d827..d2fe495 100644 --- a/frontend/src/lib/finish-workout.js +++ b/frontend/src/lib/finish-workout.js @@ -9,6 +9,11 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap sets: entry.sets, topW: bestWeightForEntry(entry) || null, target: entry.target || null, + // Which routine this entry came from, and whether it counts for progression. Written + // only when set/true, so a single-routine non-excluded session is byte-for-byte the + // shape it always was. Without this the whitelist drops both at finish. + ...(entry.rid ? { rid: entry.rid } : {}), + ...(entry.noProg === true ? { noProg: true } : {}), } const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && Object.keys(snapshot).length) { @@ -26,18 +31,25 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap }).filter(entry => entry.sets.some(set => set.done)) const sessionNote = (active?.note || '').trim() + const routineIds = [].concat(active?.routineIds ?? (active?.routineId ? [active.routineId] : [])) + // Legacy `w.excludeFromProgression` mirror: kept for older builds and external readers, but + // it only makes sense when the *whole* session is excluded. Derived from the completed + // entries, not read from `active` (which no longer carries the flag). A mixed session omits + // it — that case is new territory only the per-entry `noProg` readers handle. + const allNoProg = entries.length > 0 && entries.every(e => e.noProg === true) return { id: active.id, d: active.d, start: active.start, end, - routineId: active.routineId, + routineIds, + routineId: routineIds[0] ?? null, name: active.name, bw: active.bw, entries, prs, - ...(active.excludeFromProgression === true ? { excludeFromProgression: true } : {}), + ...(allNoProg ? { excludeFromProgression: true } : {}), ...(sessionNote ? { note: sessionNote } : {}), } } diff --git a/frontend/src/lib/finish-workout.test.js b/frontend/src/lib/finish-workout.test.js index 434d195..cb94394 100644 --- a/frontend/src/lib/finish-workout.test.js +++ b/frontend/src/lib/finish-workout.test.js @@ -4,17 +4,51 @@ import { buildCompletedWorkout } from './finish-workout.js' describe('completed workout boundary', () => { it('builds the same legacy-shaped record doFinishWorkout stores and keeps it visible', () => { const active = { - id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Push', bw: 80, + id: 'active-1', d: '2026-08-08', start: 1000, routineIds: ['routine-1'], name: 'Push', bw: 80, entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }], } const completed = buildCompletedWorkout(active, { end: 2000, prs: [] }) expect(completed).toEqual({ - id: 'active-1', d: '2026-08-08', start: 1000, end: 2000, routineId: 'routine-1', name: 'Push', bw: 80, + id: 'active-1', d: '2026-08-08', start: 1000, end: 2000, + routineIds: ['routine-1'], routineId: 'routine-1', name: 'Push', bw: 80, entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }], prs: [] }) }) + it('mirrors routineIds → routineId, and tolerates a legacy scalar active.routineId', () => { + const base = { + id: 'w', d: '2026-08-08', start: 1, + entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], target: { sets: 1, reps: 8 } }], + } + const combined = buildCompletedWorkout({ ...base, routineIds: ['a', 'b'] }) + expect(combined.routineIds).toEqual(['a', 'b']) + expect(combined.routineId).toBe('a') + + const legacy = buildCompletedWorkout({ ...base, routineId: 'only' }) + expect(legacy.routineIds).toEqual(['only']) + expect(legacy.routineId).toBe('only') + + const freestyle = buildCompletedWorkout(base) + expect(freestyle.routineIds).toEqual([]) + expect(freestyle.routineId).toBe(null) + }) + + it('carries per-entry rid and noProg onto the saved entry, written only when set', () => { + const active = { + id: 'w', d: '2026-08-08', start: 1, routineIds: ['strength', 'rehab'], + entries: [ + { id: '0025', rid: 'strength', sets: [{ done: true, w: 60, r: 8 }], target: { sets: 1, reps: 8 } }, + { id: '0031', rid: 'rehab', noProg: true, sets: [{ done: true, w: 10, r: 12 }], target: { sets: 1, reps: 12 } }, + ], + } + const [a, b] = buildCompletedWorkout(active).entries + expect(a.rid).toBe('strength') + expect('noProg' in a).toBe(false) + expect(b.rid).toBe('rehab') + expect(b.noProg).toBe(true) + }) + it('derives topW from the highest completed non-warm-up work set, not stale entry data', () => { const active = { id: 'active-1', d: '2026-08-08', start: 1000, @@ -45,16 +79,19 @@ describe('completed workout boundary', () => { expect(buildCompletedWorkout(active).entries[0].topW).toBe(60) }) - it('persists progression exclusion only for a marked session', () => { - const active = { - id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Deload', bw: 80, - excludeFromProgression: true, - entries: [{ id: '0025', sets: [{ done: true, w: 30, r: 8 }], target: { sets: 1, reps: 8 } }], - } - expect(buildCompletedWorkout(active, { end: 2000 }).excludeFromProgression).toBe(true) + it('writes the legacy excludeFromProgression mirror iff every completed entry is noProg', () => { + const mk = entries => ({ id: 'w', d: '2026-08-08', start: 1, routineIds: ['x'], entries }) + const done = extra => ({ id: '0025', sets: [{ done: true, w: 30, r: 8 }], target: { sets: 1, reps: 8 }, ...extra }) - const { excludeFromProgression, ...regular } = active - expect(buildCompletedWorkout(regular, { end: 2000 })).not.toHaveProperty('excludeFromProgression') + // rehab-only combined session → present + expect(buildCompletedWorkout(mk([done({ noProg: true }), done({ id: '0031', noProg: true })]))) + .toHaveProperty('excludeFromProgression', true) + // rehab + strength → absent + expect(buildCompletedWorkout(mk([done({ noProg: true }), done({ id: '0031' })]))) + .not.toHaveProperty('excludeFromProgression') + // all-normal → absent + expect(buildCompletedWorkout(mk([done(), done({ id: '0031' })]))) + .not.toHaveProperty('excludeFromProgression') }) it('persists a muscle snapshot only when the caller supplies one', () => { diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index bde541a..9e8683c 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -206,10 +206,28 @@ export function unpairSuperset(items, idx) { return next } +/** + * Is this completed entry excluded from progression / session read-back? + * + * "Excluded" moved from a whole-workout flag to a per-entry one (ENG-11): a rehab routine + * combined with real work excludes only its own exercises. A legacy workout carries the + * whole-workout flag and no per-entry field, so every one of its entries reads as excluded. + * `noProg` is frozen onto the entry from its source routine's `excludeFromProgression` at + * build time — editing the routine flag later never rewrites a saved session. + */ +export function entryExcluded(w, entry) { + return w?.excludeFromProgression === true || entry?.noProg === true +} + export function lastEntryFor(S, exId) { for (let i = S.workouts.length - 1; i >= 0; i--) { - const en = S.workouts[i].entries.find(e => e.id === exId) + const w = S.workouts[i] + const en = w.entries.find(e => e.id === exId) if (!en) continue + // A session that does not count — a planned deload, or a rehab block merged into a real + // session — is not "last time" for the next regular prescription: its reps and durations + // must not seed the rows any more than its weight seeds the progression. + if (entryExcluded(w, en)) continue // Work sets only. Every caller asks the same question — "what did you actually lift last // time" — to seed the next session's rows, to size a freestyle config, and to print "Last // time" on the card. A warm-up answers none of them: seeding position 0 from a 50% ramp row @@ -220,7 +238,7 @@ export function lastEntryFor(S, exId) { // `target` is what the session prescribed; finished workouts carry it so labels and the // progression engine can read a session back the way it was logged. Older workouts have // none — modeOf() falls back to the body part for them, which is what they were. - if (done.length) return { d: S.workouts[i].d, sets: done, target: en.target || null } + if (done.length) return { d: w.d, sets: done, target: en.target || null } } return null } @@ -273,33 +291,49 @@ export function bestWeightFor(S, exId) { })) return best } -export function effectiveRoutineId(S, iso) { +/** + * The routines planned for a date, in merge order. Plural is the primary form now that a + * weekday can hold several routines (`S.week[wd]` is `string[]`); the singular helpers below + * are thin wrappers. `[]` — a stray empty array, or a key that is absent — all mean rest, so + * "is this a rest day?" is `effectiveRoutineIds(S, iso).length === 0`. + * + * `S.dayPlan[iso]` stays scalar (a routine id, the `'rest'` sentinel, or undefined): the + * per-date override and Start-time are single-pick. All array-tolerance is on `S.week`. + */ +export function effectiveRoutineIds(S, iso) { const ov = S.dayPlan[iso] - if (ov === 'rest') return null - if (ov && S.routines.some(r => r.id === ov)) return ov + if (ov === 'rest') return [] + if (ov && S.routines.some(r => r.id === ov)) return [ov] const wd = new Date(iso + 'T12:00:00').getDay() - return S.week[wd] || null + return [].concat(S.week[wd] || []).filter(id => S.routines.some(r => r.id === id)) } -export function effectiveRoutine(S, iso) { - const id = effectiveRoutineId(S, iso) - return id ? S.routines.find(r => r.id === id) || null : null +export function effectiveRoutines(S, iso) { + return effectiveRoutineIds(S, iso).map(id => S.routines.find(r => r.id === id)).filter(Boolean) } +export const effectiveRoutineId = (S, iso) => effectiveRoutineIds(S, iso)[0] ?? null +export const effectiveRoutine = (S, iso) => effectiveRoutines(S, iso)[0] ?? null /** * The next day that actually has something to train, looking forward from `iso` (exclusive). * * Takes a date string rather than reading the clock so callers and tests agree on "today". * A routine with no exercises does not count: starting one lands you in an empty session, so - * it is not an answer to "what is next" (the same guard TabBar applies before starting). + * it is not an answer to "what is next" (the same guard TabBar applies before starting). On a + * combined day, any one routine with exercises makes the day trainable. * Returns null when the whole week is rest. + * + * Return shape carries `routines` (the whole day) plus `routine` = `routines[0]` for the + * "what's next" label. */ export function nextTrainingDay(S, iso) { for (let i = 1; i <= 7; i++) { const d = new Date(iso + 'T12:00:00') d.setDate(d.getDate() + i) const nextIso = isoOf(d) - const routine = effectiveRoutine(S, nextIso) - if (routine && (routine.ex || []).length) return { iso: nextIso, weekday: d.getDay(), routine } + const routines = effectiveRoutines(S, nextIso) + if (routines.some(r => (r.ex || []).length)) { + return { iso: nextIso, weekday: d.getDay(), routines, routine: routines[0] } + } } return null } @@ -329,13 +363,10 @@ export const MAX_PLANNED_WARMUPS = 5 function buildWorkSets(S, cfg, options = {}) { const preferLast = !!options.preferLast const useTarget = !!options.useTarget - // A workout flagged excludeFromProgression (a planned deload) is not "last time" for the - // next regular session either: its reps and durations must not seed the rows any more than - // its weight seeds the prescription. The deload session itself reads the routine's own target. - const regular = (S.workouts || []).some(w => w.excludeFromProgression === true) - ? { ...S, workouts: S.workouts.filter(w => w.excludeFromProgression !== true) } - : S - const last = lastEntryFor(regular, cfg.id) + // `lastEntryFor` now skips any entry that does not count — a planned deload, or a rehab + // block merged into a real session (entryExcluded) — so the rows seed from the last + // *counting* session without this function pre-filtering the history itself. + const last = lastEntryFor(S, cfg.id) const n = Math.max(1, cfg.sets || 1) const mode = modeOf(cfg) const sets = [] diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index a49ca44..93eb5e6 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js' +import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor, effectiveRoutineIds, effectiveRoutines, effectiveRoutineId, effectiveRoutine, lastEntryFor, entryExcluded } from './history.js' import { EXDB } from './exercises.js' // Real ids out of the shipped catalogue, so the body-part fallback is exercised for real. @@ -1019,3 +1019,83 @@ describe('nextTrainingDay', () => { expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 }) }) }) + +// ---- combine routines: plural planner resolver + per-entry noProg (ENG-9) ---- +describe('effectiveRoutineIds / effectiveRoutines', () => { + const routines = [{ id: 'r1', name: 'A', ex: [{ id: '1' }] }, { id: 'r2', name: 'B', ex: [{ id: '2' }] }] + const S = (week, dayPlan = {}) => ({ routines, week, dayPlan }) + const ISO = '2026-08-19' // a Wednesday → getDay() 3 + + it('reads a bare-string weekday value as a one-element list (tolerant reader)', () => { + expect(effectiveRoutineIds(S({ 3: 'r1' }), ISO)).toEqual(['r1']) + }) + it('resolves a multi-id array and filters out routines that no longer exist', () => { + expect(effectiveRoutineIds(S({ 3: ['r1', 'gone', 'r2'] }), ISO)).toEqual(['r1', 'r2']) + expect(effectiveRoutines(S({ 3: ['r1', 'r2'] }), ISO).map(r => r.name)).toEqual(['A', 'B']) + }) + it('treats [], a stray empty array and an absent key all as rest', () => { + expect(effectiveRoutineIds(S({ 3: [] }), ISO)).toEqual([]) + expect(effectiveRoutineIds(S({}), ISO)).toEqual([]) + }) + it('a scalar dayPlan override wins and stays scalar; "rest" is empty', () => { + expect(effectiveRoutineIds(S({ 3: ['r1', 'r2'] }, { [ISO]: 'r2' }), ISO)).toEqual(['r2']) + expect(effectiveRoutineIds(S({ 3: ['r1', 'r2'] }, { [ISO]: 'rest' }), ISO)).toEqual([]) + }) + it('the singular wrappers return [0] ?? null', () => { + expect(effectiveRoutineId(S({ 3: ['r1', 'r2'] }), ISO)).toBe('r1') + expect(effectiveRoutine(S({ 3: ['r1', 'r2'] }), ISO).name).toBe('A') + expect(effectiveRoutineId(S({}), ISO)).toBe(null) + expect(effectiveRoutine(S({}), ISO)).toBe(null) + }) +}) + +describe('nextTrainingDay on a combined day', () => { + const TUE = '2026-08-18' + it('is trainable when any one routine of the day has exercises; return shape carries routines', () => { + const S = { + routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [{ id: '1' }] }], + week: { 3: ['r1', 'r2'] }, dayPlan: {}, + } + const nd = nextTrainingDay(S, TUE) + expect(nd).toMatchObject({ weekday: 3 }) + expect(nd.routines.map(r => r.name)).toEqual(['A', 'B']) + expect(nd.routine.name).toBe('A') + }) + it('skips a day whose every routine is empty', () => { + const S = { + routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [] }, { id: 'r3', name: 'C', ex: [{ id: '1' }] }], + week: { 3: ['r1', 'r2'], 5: ['r3'] }, dayPlan: {}, + } + expect(nextTrainingDay(S, TUE)).toMatchObject({ weekday: 5 }) + }) +}) + +describe('lastEntryFor / buildSets skip a noProg entry', () => { + const LIFT2 = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id + const wk = (d, w, r, extra) => ({ d, entries: [{ id: LIFT2, target: { sets: 1, reps: r, weight: w }, sets: [{ w, r, done: true }], ...extra }] }) + + it('lastEntryFor returns the prior counting session, not a later noProg one', () => { + const S = { workouts: [wk('2026-01-01', 60, 8), wk('2026-01-05', 30, 12, { noProg: true })] } + expect(lastEntryFor(S, LIFT2).d).toBe('2026-01-01') + }) + it('lastEntryFor skips a legacy whole-workout excludeFromProgression session', () => { + const S = { workouts: [wk('2026-01-01', 60, 8), { d: '2026-01-05', excludeFromProgression: true, entries: [{ id: LIFT2, target: { sets: 1, reps: 12, weight: 30 }, sets: [{ w: 30, r: 12, done: true }] }] }] } + expect(lastEntryFor(S, LIFT2).d).toBe('2026-01-01') + }) + it('buildSets seeds opening rows from the last counting session', () => { + const S = { exWeights: {}, workouts: [wk('2026-01-01', 60, 8), wk('2026-01-05', 30, 12, { noProg: true })] } + expect(buildSets(S, { id: LIFT2, sets: 1, reps: 5, weight: 50 })).toEqual([{ w: 60, r: 8, done: false }]) + }) + it('buildSets with only noProg history falls back to the routine target', () => { + const S = { exWeights: {}, workouts: [wk('2026-01-05', 30, 12, { noProg: true })] } + expect(buildSets(S, { id: LIFT2, sets: 1, reps: 5, weight: 50 })).toEqual([{ w: 50, r: 5, done: false }]) + }) + it('freestyleConfig ignores a noProg entry', () => { + const S = { exWeights: {}, workouts: [wk('2026-01-05', 30, 12, { noProg: true })] } + expect(freestyleConfig(S, { id: LIFT2, mode: 'reps', sets: 3, reps: 10, weight: 0 })).toEqual({ id: LIFT2, mode: 'reps', sets: 3, reps: 10, weight: 0 }) + }) + it('bestWeightFor is unchanged — a heavy noProg set still counts toward Best', () => { + const S = { workouts: [wk('2026-01-01', 60, 8), wk('2026-01-05', 140, 3, { noProg: true })] } + expect(bestWeightFor(S, LIFT2)).toBe(140) + }) +}) diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js index 41a1a32..7e37a44 100644 --- a/frontend/src/lib/plan-share.js +++ b/frontend/src/lib/plan-share.js @@ -10,6 +10,7 @@ import { EXIDX, isBodyweightEq } from './exercises.js' import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from './history.js' +import { deriveSessionName } from './session-merge.js' import { uid, todayISO, DAYN, weekOrder, weekStartOf, fmtNum, exCount } from './format.js' import { t, exerciseNameFor } from './i18n-core.js' @@ -100,8 +101,11 @@ export function buildPlanBundle(S, name) { const customEx = (S.customEx || []) .filter(c => usedIds.has(c.id)) .map(c => ({ id: c.id, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) })) + // A weekday can hold several routines (merge order preserved). `[].concat` normalises a + // legacy scalar id to a one-element list, so a bundle written before this change and one + // written after are read the same way at the other end. const week = {} - WEEK_DAYS.forEach(d => { if (S.week?.[d]) week[d] = S.week[d] }) + WEEK_DAYS.forEach(d => { if (S.week?.[d]?.length) week[d] = [].concat(S.week[d]) }) return { opengym_plan: PLAN_FMT, exported: todayISO(), name: name || '', week, routines, customEx } } @@ -146,7 +150,7 @@ export function parsePlan(raw) { dropped, routineCount: routines.length, exerciseCount: routines.reduce((n, r) => n + r.ex.length, 0), - scheduledDays: WEEK_DAYS.filter(d => data.week?.[d]).length + scheduledDays: WEEK_DAYS.filter(d => data.week?.[d]?.length).length } } @@ -182,8 +186,12 @@ export function mergePlan(s, bundle, { schedule } = {}) { }) if (schedule) { WEEK_DAYS.forEach(d => { delete s.week[d] }) - Object.entries(bundle.week || {}).forEach(([d, oldId]) => { - if (ridMap[oldId]) s.week[d] = ridMap[oldId] + Object.entries(bundle.week || {}).forEach(([d, val]) => { + // `[].concat` tolerates a pre-upgrade scalar bundle value. An element whose routine id + // didn't survive parsing is dropped, not written as undefined; a day that ends up empty + // is left absent rather than stored as `[]`. + const ids = [].concat(val).map(oldId => ridMap[oldId]).filter(Boolean) + if (ids.length) s.week[d] = ids }) } return { routines: bundle.routines.length } @@ -243,8 +251,10 @@ function routineHTML(r, unit) { function weekHTML(S) { // The printout is read by whoever exported it, so the week runs in their order. const rows = weekOrder(weekStartOf(S)).map(d => { - const r = S.routines.find(x => x.id === S.week?.[d]) - const val = r ? esc(r.name) : `${esc(t('Rest'))}` + const names = [].concat(S.week?.[d] || []) + .map(id => S.routines.find(x => x.id === id)?.name) + .filter(Boolean) + const val = names.length ? esc(deriveSessionName(names)) : `${esc(t('Rest'))}` return `
${esc(t(DAYN[d]))}
${val}
` }).join('') return `
${rows}
` diff --git a/frontend/src/lib/plan-share.test.js b/frontend/src/lib/plan-share.test.js index 7fc7075..e6fe02d 100644 --- a/frontend/src/lib/plan-share.test.js +++ b/frontend/src/lib/plan-share.test.js @@ -86,3 +86,48 @@ describe('what survives a shared plan', () => { expect(parsePlan(bundle).routines[0].ex[0].intensifier).toEqual({ type: 'dropset', count: 1, pct: 20 }) }) }) + +// ---- combine routines: a weekday holds a routine-id list (ENG-9 §5) ---- +describe('week schedule as a routine-id list', () => { + const twoRoutines = { + routines: [ + { id: 'a', name: 'A', ex: [{ id: '0025', sets: 3, reps: 5 }] }, + { id: 'b', name: 'B', ex: [{ id: '0031', sets: 3, reps: 8 }] }, + ], + customEx: [], + } + + it('build → parse → merge round-trips an array week with arrays intact', () => { + const src = { ...twoRoutines, week: { 1: ['a', 'b'], 3: ['a'] } } + const parsed = parsePlan(JSON.stringify(buildPlanBundle(src, 'Plan'))) + expect(parsed.scheduledDays).toBe(2) + + const target = { routines: [], week: {}, customEx: [] } + mergePlan(target, parsed, { schedule: true }) + const [idA, idB] = target.routines.map(r => r.id) + expect(target.week[1]).toEqual([idA, idB]) + expect(target.week[3]).toEqual([idA]) + }) + + it('tolerates a legacy scalar bundle value', () => { + const legacy = { opengym_plan: 1, name: 'x', customEx: [], week: { 1: 'a' }, routines: twoRoutines.routines } + const parsed = parsePlan(legacy) + expect(parsed.scheduledDays).toBe(1) + const target = { routines: [], week: {}, customEx: [] } + mergePlan(target, parsed, { schedule: true }) + expect(target.week[1]).toEqual([target.routines[0].id]) + }) + + it('mergePlan drops an element whose id did not survive parsing, never writes undefined', () => { + // 'gone' is not among the bundle routines → ridMap has no entry → filtered out + const bundle = { routines: [{ id: 'a', name: 'A', ex: [{ id: '0025', sets: 3, reps: 5 }] }], week: { 1: ['a', 'gone'], 2: ['gone'] }, customEx: [] } + const target = { routines: [], week: {}, customEx: [] } + mergePlan(target, bundle, { schedule: true }) + expect(target.week[1]).toEqual([target.routines[0].id]) + expect(target.week[2]).toBeUndefined() // emptied → left absent, not stored as [] + }) + + it('scheduledDays counts a populated array day as 1 and a [] / absent day as 0', () => { + expect(parsePlan({ opengym_plan: 1, routines: [], customEx: [], week: { 1: ['a'], 2: [], 4: 'b' } }).scheduledDays).toBe(2) + }) +}) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index 48f36cc..a8c5bca 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -16,7 +16,7 @@ // · fewer sets than prescribed → miss // So a session that fell apart can never advance the load as though it had succeeded. -import { modeOf, repStep, rerampWarmups } from './history.js' +import { modeOf, repStep, rerampWarmups, entryExcluded } from './history.js' import { EXIDX } from './exercises.js' import { isWarmupRow } from './workout-model.js' import { normalizeRepRange } from './rep-range.js' @@ -150,12 +150,15 @@ export function readSession(entry, fallback) { export function sessionsFor(S, exId, fallback) { const out = [] ;(S.workouts || []).forEach(w => { - // A planned deload remains a real workout for history and statistics, but it cannot become - // the baseline for the next regular prescription. The routine flag is copied onto the - // active session, then onto this completed workout, so later routine edits do not rewrite it. - if (w.excludeFromProgression === true) return const entry = w.entries.find(e => e.id === exId) - if (entry && entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) }) + if (!entry) return + // A session that does not count for this exercise cannot become the baseline for its next + // prescription. Exclusion is per-entry now (ENG-11): a legacy whole-workout + // `excludeFromProgression` flag still excludes every entry; a merged rehab block excludes + // only its own. `noProg` is frozen onto the entry at build time, so later routine edits + // never rewrite it. This is the only progression-exclusion path in the file. + if (entryExcluded(w, entry)) return + if (entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) }) }) return out } diff --git a/frontend/src/lib/progression.test.js b/frontend/src/lib/progression.test.js index 98c46e6..8294877 100644 --- a/frontend/src/lib/progression.test.js +++ b/frontend/src/lib/progression.test.js @@ -3,6 +3,7 @@ import { readSession, sessionsFor, stallCount, nextPrescription, applyPrescription, policyFor, defaultIncrement, weightIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS } from './progression.js' +import { entryExcluded } from './history.js' import { EXDB } from './exercises.js' const LIFT = EXDB.find(e => e.bp !== 'cardio' && !['upper legs', 'lower legs', 'back', 'hips', 'glutes'].includes(e.bp)).id @@ -443,6 +444,97 @@ describe('sessionsFor', () => { }) }) +// "Excluded from progression" is per-entry now (ENG-11): a rehab routine combined with real +// work must exclude only its own exercises, not the whole session. +describe('per-entry noProg (combine routines)', () => { + const PRESS = EXDB.find(e => e.bp !== 'cardio' && e.id !== LIFT && !['upper legs', 'lower legs', 'back', 'hips', 'glutes'].includes(e.bp)).id + const tgt = w => ({ sets: 3, reps: 5, weight: w }) + const entry = (id, w, reps, extra) => ({ id, target: tgt(w), sets: reps.map(r => ({ w, r, done: true })), ...extra }) + + it('skips a noProg entry for that exercise only, in a mixed combined session', () => { + const S = { + unit: 'kg', + workouts: [{ + d: '2026-02-01', + routineIds: ['strength', 'rehab'], + entries: [entry(LIFT, 60, [5, 5, 5]), entry(PRESS, 40, [5, 5, 5], { noProg: true })], + }], + } + expect(sessionsFor(S, LIFT)).toHaveLength(1) + expect(sessionsFor(S, PRESS)).toHaveLength(0) + }) + + it('still advances the non-excluded exercise of a mixed combined session', () => { + const S = { + unit: 'kg', + workouts: [{ + d: '2026-02-01', + entries: [entry(LIFT, 60, [5, 5, 5]), entry(PRESS, 40, [5, 5, 5], { noProg: true })], + }], + } + expect(nextPrescription(S, { id: LIFT, ...tgt(60), prog: 'linear' }).weight).toBe(62.5) + }) + + it('a noProg gap never becomes the deload / stall baseline', () => { + const S = { + unit: 'kg', + workouts: [ + { d: '2026-02-01', entries: [entry(LIFT, 60, [5, 5, 5])] }, + { d: '2026-02-03', entries: [entry(LIFT, 60, [5, 5, 5])] }, + { d: '2026-02-05', entries: [entry(LIFT, 30, [8, 8, 8], { noProg: true })] }, + ], + } + expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-02-01', '2026-02-03']) + expect(nextPrescription(S, { id: LIFT, ...tgt(60), prog: 'linear' }).weight).toBe(62.5) + }) + + it('honours a legacy whole-workout excludeFromProgression flag (all entries skipped)', () => { + const S = { + unit: 'kg', + workouts: [ + { d: '2026-02-01', entries: [entry(LIFT, 60, [5, 5, 5])] }, + { d: '2026-02-08', excludeFromProgression: true, entries: [entry(LIFT, 30, [8, 8])] }, + ], + } + expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-02-01']) + }) + + it('an exercise only ever logged noProg → sessionsFor [] → nextPrescription kind "first"', () => { + const S = { + unit: 'kg', + workouts: [{ d: '2026-02-01', entries: [entry(LIFT, 30, [8, 8, 8], { noProg: true })] }], + } + expect(sessionsFor(S, LIFT)).toHaveLength(0) + expect(nextPrescription(S, { id: LIFT, ...tgt(50), prog: 'linear' }).kind).toBe('first') + }) + + it('entryExcluded truth table', () => { + expect(entryExcluded({}, {})).toBe(false) + expect(entryExcluded({ excludeFromProgression: true }, {})).toBe(true) + expect(entryExcluded({}, { noProg: true })).toBe(true) + expect(entryExcluded({ excludeFromProgression: true }, { noProg: true })).toBe(true) + }) + + it('stallCount is not reset by a noProg gap at the same weight', () => { + // three real misses at 60, with a noProg 60 session interleaved — still streaks to a deload + const miss = d => ({ d, entries: [entry(LIFT, 60, [4, 4, 4])] }) + const S = { + unit: 'kg', + workouts: [ + { d: '2026-02-01', entries: [entry(LIFT, 60, [5, 5, 5])] }, + miss('2026-02-03'), + { d: '2026-02-04', entries: [entry(LIFT, 60, [3, 3, 3], { noProg: true })] }, + miss('2026-02-05'), + miss('2026-02-07'), + ], + } + const sessions = sessionsFor(S, LIFT) + expect(sessions.map(s => s.d)).toEqual(['2026-02-01', '2026-02-03', '2026-02-05', '2026-02-07']) + expect(stallCount(sessions)).toBe(3) + expect(nextPrescription(S, { id: LIFT, ...tgt(60), prog: 'linear' }).kind).toBe('deload') + }) +}) + // Workouts only began storing their prescription in v1.2.2. Everything logged before that is // targetless, and reading it as "missed" would tell every long-standing user to deload on // their first session after updating — which is exactly what the demo history did. diff --git a/frontend/src/lib/session-merge.js b/frontend/src/lib/session-merge.js new file mode 100644 index 0000000..fef1445 --- /dev/null +++ b/frontend/src/lib/session-merge.js @@ -0,0 +1,44 @@ +// Building one session's entries from more than one routine (the "combine routines" feature). +// +// A combined session is just the concatenation of the entries each routine would have built on +// its own, with `entry.rid` stamped so a saved workout can be read back per routine. There is +// no composite-routine object: nothing is stored that a single-routine session did not already +// store, only widened. Every start path routes through here, including a single-routine start +// (a one-element list) and freestyle (an empty list → no entries, no rid). +// +// Imported only by sheets.jsx and views/Workout.jsx; imports session-start.js (which pulls in +// history.js + progression.js). Nothing in that chain imports this file, so there is no cycle. +import { buildSessionEntries } from './session-start.js' + +/** + * Build a session's entries from an ordered list of routine ids. + * - resolves + filters to still-existing routines, de-duplicates by id (first wins) + * - concatenates each routine's entries in list order + * - stamps `entry.rid` = that routine's id on every entry + * + * Returns `{ entries, routineIds, routines }` — `routineIds` / `routines` are the resolved, + * de-duplicated list, so a caller stores exactly what was built. + */ +export function buildCombinedEntries(st, routineIds) { + const seen = new Set() + const routines = [].concat(routineIds ?? []) + .filter(id => id && !seen.has(id) && seen.add(id)) + .map(id => (st.routines || []).find(r => r.id === id)) + .filter(Boolean) + const entries = routines.flatMap(r => + buildSessionEntries(st, r).map(e => ({ ...e, rid: r.id })) + ) + return { entries, routineIds: routines.map(r => r.id), routines } +} + +/** + * The session name for a combined workout, from routine names in merge order (ENG-12 rule): + * 1–3 routines → join with " + " → "Rehab + Core" + * 4+ routines → first two, then "+ N more" → "Rehab + Core + 2 more" + * An empty list returns null — not a reachable state for a saved or active session. + */ +export function deriveSessionName(names) { + if (!names.length) return null + if (names.length <= 3) return names.join(' + ') + return `${names[0]} + ${names[1]} + ${names.length - 2} more` +} diff --git a/frontend/src/lib/session-merge.test.js b/frontend/src/lib/session-merge.test.js new file mode 100644 index 0000000..23acce6 --- /dev/null +++ b/frontend/src/lib/session-merge.test.js @@ -0,0 +1,58 @@ +import { describe, it, expect } from 'vitest' +import { buildCombinedEntries, deriveSessionName } from './session-merge.js' +import { buildSessionEntries } from './session-start.js' + +const st = { + unit: 'kg', workouts: [], exWeights: {}, + routines: [ + { id: 'r1', name: 'Strength', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60 }, { id: '0031', sets: 3, reps: 8, weight: 40 }] }, + { id: 'r2', name: 'Core', prog: 'off', ex: [{ id: '0047', sets: 3, reps: 12, weight: 0 }] }, + { id: 'rehab', name: 'Rehab', excludeFromProgression: true, ex: [{ id: '0050', sets: 2, reps: 15, weight: 5 }] }, + ], +} + +describe('buildCombinedEntries', () => { + it('concatenates each routine’s entries in list order, stamping rid on every one', () => { + const { entries, routineIds } = buildCombinedEntries(st, ['r1', 'r2']) + expect(entries.map(e => e.id)).toEqual(['0025', '0031', '0047']) + expect(entries.map(e => e.rid)).toEqual(['r1', 'r1', 'r2']) + expect(routineIds).toEqual(['r1', 'r2']) + }) + + it('de-dupes a repeated id (first wins) and drops an id with no matching routine', () => { + const { entries, routineIds } = buildCombinedEntries(st, ['r1', 'gone', 'r1', 'r2']) + expect(routineIds).toEqual(['r1', 'r2']) + expect(entries.map(e => e.rid)).toEqual(['r1', 'r1', 'r2']) + }) + + it('an empty / null list builds nothing', () => { + expect(buildCombinedEntries(st, [])).toMatchObject({ entries: [], routineIds: [], routines: [] }) + expect(buildCombinedEntries(st, null)).toMatchObject({ entries: [], routineIds: [] }) + }) + + it('a single-element list matches the plain buildSessionEntries path (bar the rid stamp)', () => { + const combined = buildCombinedEntries(st, ['r1']).entries.map(({ rid, ...e }) => e) + expect(combined).toEqual(buildSessionEntries(st, st.routines[0])) + }) + + it('carries an excluded routine’s per-entry noProg through the merge', () => { + const { entries } = buildCombinedEntries(st, ['r1', 'rehab']) + expect(entries.find(e => e.id === '0050')).toMatchObject({ rid: 'rehab', noProg: true }) + expect(entries.find(e => e.id === '0025').noProg).toBeUndefined() + }) +}) + +describe('deriveSessionName', () => { + it('is null for an empty list', () => { + expect(deriveSessionName([])).toBe(null) + }) + it('joins 1–3 names with " + "', () => { + expect(deriveSessionName(['Rehab'])).toBe('Rehab') + expect(deriveSessionName(['Rehab', 'Core'])).toBe('Rehab + Core') + expect(deriveSessionName(['A', 'B', 'C'])).toBe('A + B + C') + }) + it('collapses 4+ to "A + B + N more"', () => { + expect(deriveSessionName(['A', 'B', 'C', 'D'])).toBe('A + B + 2 more') + expect(deriveSessionName(['A', 'B', 'C', 'D', 'E'])).toBe('A + B + 3 more') + }) +}) diff --git a/frontend/src/lib/session-start.js b/frontend/src/lib/session-start.js index cc453b5..b6fefed 100644 --- a/frontend/src/lib/session-start.js +++ b/frontend/src/lib/session-start.js @@ -6,19 +6,23 @@ import { buildSets, applyIntensifierPlan, modeOf } from './history.js' import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement } from './progression.js' +// Returns a bare array of session entries. "Excluded from progression" is per-entry now +// (`entry.noProg`, written only when true) rather than a wrapper flag — a rehab routine merged +// into real work must exclude only its own exercises. The merge helper (lib/session-merge.js) +// stamps `entry.rid`; this builder is unaware of which routine it serves, so the single-routine +// and combined paths share it unchanged. export function buildSessionEntries(st, r) { // The prescription is applied as the session is built, so you walk up to the bar with the // right weight already on the screen instead of being told about it afterwards. `plan` is // kept on the entry purely so the workout can explain the number it chose. - const excluded = r?.excludeFromProgression === true - const entries = (r ? r.ex : []).map(cfg => { - const plan = excluded ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r) + const noProg = r?.excludeFromProgression === true + return (r ? r.ex : []).map(cfg => { + const plan = noProg ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r) // The warm-up ramp and the prescription snap to the exercise's own increment (1.25 kg // plates exist), not the unit default; a timed exercise's `inc` is seconds, so it keeps the // default for its optional load. const step = modeOf(cfg) === 'reps' ? weightIncrement(cfg, st.unit) : defaultIncrement(cfg.id, st.unit) const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: plan.kind === 'off' }), plan, step), cfg) - return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets } + return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets, ...(noProg ? { noProg: true } : {}) } }) - return { entries, excluded } } diff --git a/frontend/src/lib/session-start.test.js b/frontend/src/lib/session-start.test.js index 45c2dd9..b40d913 100644 --- a/frontend/src/lib/session-start.test.js +++ b/frontend/src/lib/session-start.test.js @@ -8,7 +8,7 @@ describe('buildSessionEntries', () => { it('ramps the warm-ups on the exercise’s own increment, not the unit default', () => { const r = { id: 'r', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60, inc: 1.25, warmupSets: 2 }] } - const { entries } = buildSessionEntries(st, r) + const entries = buildSessionEntries(st, r) const warm = entries[0].sets.filter(isWarmupRow).map(s => s.w) expect(warm).toHaveLength(2) for (const w of warm) expect(Math.round(w / 1.25 * 1000) / 1000 % 1).toBe(0) // a multiple of 1.25 @@ -17,7 +17,29 @@ describe('buildSessionEntries', () => { it('keeps the unit default for timed exercises, whose inc is seconds', () => { const r = { id: 'r', prog: 'off', ex: [{ id: '0025', mode: 'time', sets: 2, sec: 30, inc: 10, weight: 0 }] } - const { entries } = buildSessionEntries(st, r) + const entries = buildSessionEntries(st, r) expect(entries[0].sets.every(s => s.sec === 30)).toBe(true) }) + + it('returns a bare array — no { entries, excluded } wrapper', () => { + const r = { id: 'r', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60 }] } + const out = buildSessionEntries(st, r) + expect(Array.isArray(out)).toBe(true) + expect(out).toHaveLength(1) + }) + + it('stamps noProg + plan.kind "off" on every entry of an excluded routine, and neither on a normal one', () => { + const ex = [{ id: '0025', sets: 3, reps: 5, weight: 60 }, { id: '0031', sets: 3, reps: 8, weight: 40 }] + const excluded = buildSessionEntries(st, { id: 'rehab', excludeFromProgression: true, ex }) + expect(excluded.every(e => e.noProg === true)).toBe(true) + expect(excluded.every(e => e.plan.kind === 'off')).toBe(true) + + const normal = buildSessionEntries(st, { id: 'r', prog: 'off', ex }) + expect(normal.every(e => e.noProg === undefined)).toBe(true) + }) + + it('does not stamp rid — that is the merge helper’s job', () => { + const r = { id: 'r', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60 }] } + expect(buildSessionEntries(st, r)[0].rid).toBeUndefined() + }) }) diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index f239a0d..2ca09d2 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -103,7 +103,7 @@ export function loadStarterPlan(planId) { if (!plan) return false update(st => { st.routines.push(...plan.routines) - plan.schedule.forEach(({ day, routineId }) => { st.week[day] = routineId }) + plan.schedule.forEach(({ day, routineId }) => { st.week[day] = [routineId] }) }) toast(t('{0} loaded', PLAN_COPY[planId]().name)) return true @@ -120,7 +120,7 @@ function StarterPlanChooser({ close }) { close() // A confirmation is only worth showing when one of those days is actually occupied — by a // routine that still exists, not by a stale id the Plan already shows as "Rest". - const taken = day => week[day] && routines.some(r => r.id === week[day]) + const taken = day => [].concat(week[day] || []).some(id => routines.some(r => r.id === id)) if (!days.some(taken)) { loadStarterPlan(id); return } confirmSheet({ title: t('Load {0}?', name), diff --git a/frontend/src/sheets.starter.test.jsx b/frontend/src/sheets.starter.test.jsx index 007950b..7eeab74 100644 --- a/frontend/src/sheets.starter.test.jsx +++ b/frontend/src/sheets.starter.test.jsx @@ -11,7 +11,8 @@ import { loadStarterPlan, starterPlanSheet } from './sheets.jsx' const mounted = [] const S = () => useStore.getState().S -const nameOn = day => S().routines.find(r => r.id === S().week[day])?.name +// S.week[day] is a routine-id list now; the starter plan writes a one-element list per day. +const nameOn = day => S().routines.find(r => r.id === [].concat(S().week[day] ?? [])[0])?.name // Renders whatever sheet is on top and returns its host element. function renderTop() { @@ -57,7 +58,7 @@ describe('starter plan chooser', () => { }) it('loads straight away when the plan’s weekdays are free, without asking', () => { - useStore.setState(s => ({ S: { ...s.S, week: { 0: 'mine', 6: 'mine' } } })) + useStore.setState(s => ({ S: { ...s.S, week: { 0: ['mine'], 6: ['mine'] } } })) choose('Upper / Lower') expect(useUI.getState().sheets).toHaveLength(0) // no confirmation was raised @@ -65,20 +66,20 @@ describe('starter plan chooser', () => { expect(nameOn(2)).toBe('Lower A') expect(nameOn(4)).toBe('Upper B') expect(nameOn(5)).toBe('Lower B') - expect(S().week[0]).toBe('mine') // untouched weekdays stay put - expect(S().week[6]).toBe('mine') + expect(S().week[0]).toEqual(['mine']) // untouched weekdays stay put + expect(S().week[6]).toEqual(['mine']) expect(S().routines[0].name).toBe('My routine') // and nothing is deleted expect(useUI.getState().toastMsg).toBe('Upper / Lower loaded') }) it('asks first when a weekday the plan wants is already taken', () => { - useStore.setState(s => ({ S: { ...s.S, week: { 3: 'mine' } } })) + useStore.setState(s => ({ S: { ...s.S, week: { 3: ['mine'] } } })) choose('Full Body') const confirm = renderTop() expect(confirm.querySelector('h3').textContent).toBe('Load Full Body?') expect(confirm.textContent).toContain('Monday, Wednesday and Friday') - expect(S().week[3]).toBe('mine') // nothing applied yet + expect(S().week[3]).toEqual(['mine']) // nothing applied yet expect(S().routines).toHaveLength(1) act(() => { buttonFor(confirm, 'Load plan').click() }) @@ -88,7 +89,7 @@ describe('starter plan chooser', () => { }) it('leaves everything alone when the confirmation is cancelled', () => { - useStore.setState(s => ({ S: { ...s.S, week: { 1: 'mine' } } })) + useStore.setState(s => ({ S: { ...s.S, week: { 1: ['mine'] } } })) const before = structuredClone(S()) choose('5×5') @@ -99,7 +100,7 @@ describe('starter plan chooser', () => { }) it('does not ask when only weekdays outside the plan are occupied', () => { - useStore.setState(s => ({ S: { ...s.S, week: { 2: 'mine', 4: 'mine' } } })) // Tue + Thu + useStore.setState(s => ({ S: { ...s.S, week: { 2: ['mine'], 4: ['mine'] } } })) // Tue + Thu choose('5×5') // wants Mon/Wed/Fri expect(useUI.getState().sheets).toHaveLength(0) expect(nameOn(1)).toBe('5×5 A') diff --git a/mcp/src/tools.js b/mcp/src/tools.js index 453ff24..daa229a 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -466,7 +466,7 @@ export const previewSession = { // 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 built = buildSessionEntries(S, r) const exercises = (r.ex || []).map((cfg, i) => { const ex = exerciseOf(cfg.id, S) const mode = modeOf({ ...cfg, id: cfg.id })