Skip to content

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

Planned sessions open at the routine's sets and reps; history decides the weight (#275)

Duarte Santosaf916e002e7f
diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js
index 8695cc775..219eb16d4 100644
--- a/frontend/src/lib/history.js
+++ b/frontend/src/lib/history.js
@@ -428,6 +428,12 @@ function buildWorkSets(S, cfg, options = {}) {
// A deload routine must use its own prescription instead of carrying regular-session values
// into the workout. Other planned sessions keep the existing history-first behaviour.
const prevAt = i => (!useTarget && last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
+ // `options.planReps`: a planned session opens at the routine's own reps, and history only
+ // decides the weight (Settings → "Planned sessions start from", lib/session-start.js). Without
+ // it every row copied last session's reps, so a plan edited from 15 to 10 — or trained at 15
+ // once — kept opening at 15 while the routine still read "2 × 10" (#275). Freestyle has no
+ // plan to own anything and keeps reproducing what you did (preferLast).
+ const planReps = !!options.planReps && !preferLast && cfg.reps > 0
if (mode === 'cardio') {
for (let i = 0; i < n; i++) {
@@ -460,11 +466,12 @@ function buildWorkSets(S, cfg, options = {}) {
const w = useTarget
? (cfg.weight > 0 ? cfg.weight : (lastRegular && lastRegular.r > 0 ? lastRegular.w : cfg.weight))
: usable ? usable.w : (conf && conf.w > 0 ? conf.w : cfg.weight)
- const row = { w, r: usable ? usable.r : cfg.reps, done: false }
+ const row = { w, r: planReps || !usable ? cfg.reps : usable.r, done: false }
// A unilateral exercise logs each side on its own (issue #60): the row splits into L/R,
// each seeded with half the total reps at the same weight. When "last time" was itself a
- // per-side set, carry its two sides over verbatim so an asymmetry you logged persists.
- if (isPerSide(cfg)) sets.push(usable && isSideSet(usable) ? seedSideFromLast(row, usable) : makeSideSet(row))
+ // per-side set, carry its two sides over so an asymmetry you logged persists — both sides'
+ // weights always, their reps only when the plan does not own them.
+ if (isPerSide(cfg)) sets.push(usable && isSideSet(usable) ? seedSideFromLast(row, usable, planReps) : makeSideSet(row))
else sets.push(row)
}
return sets
@@ -472,12 +479,13 @@ function buildWorkSets(S, cfg, options = {}) {
// Seed a fresh per-side row from a previous per-side set: same reps/weight each side, nothing
// done, no effort carried (that is logged afresh each session). Falls back to an even split if
-// the previous row was not actually per-side.
-function seedSideFromLast(row, prev) {
+// the previous row was not actually per-side. With `planReps` the reps are the row's own —
+// the plan's total, split the way makeSideSet splits it — and only the weights carry over.
+function seedSideFromLast(row, prev, planReps) {
const base = makeSideSet(row)
if (!isSideSet(prev)) return base
- const carry = s => ({ w: Number(s?.w) || 0, r: Number(s?.r) || 0, done: false })
- return syncSideAggregate({ ...base, sides: { L: carry(prev.sides.L), R: carry(prev.sides.R) } })
+ const carry = (s, key) => ({ w: Number(s?.w) || 0, r: planReps ? base.sides[key].r : Number(s?.r) || 0, done: false })
+ return syncSideAggregate({ ...base, sides: { L: carry(prev.sides.L, 'L'), R: carry(prev.sides.R, 'R') } })
}
/**
diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js
index f49eadb99..b01921196 100644
--- a/frontend/src/lib/history.test.js
+++ b/frontend/src/lib/history.test.js
@@ -489,6 +489,35 @@ describe('buildSets', () => {
expect(buildSets({ ...S, workouts: [] }, { id: LIFT, sets: 1, reps: 8, weight: 50 })).toEqual([{ w: 75, r: 8, done: false }])
})
+ it('opens at the plan\'s reps with planReps, taking only the weight from the last session', () => {
+ const S = { exWeights: {}, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 15, done: true }, { w: 62.5, r: 12, done: true }] }] }] }
+ expect(buildSets(S, { id: LIFT, sets: 2, reps: 10, weight: 50 }, { planReps: true }))
+ .toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 10, done: false }])
+ // Planned warm-ups copy the work row, so they follow the plan too.
+ expect(buildSets(S, { id: LIFT, sets: 1, reps: 10, weight: 50, warmupSets: 1 }, { planReps: true, step: 2.5 }).map(s => s.r))
+ .toEqual([10, 10])
+ })
+
+ it('keeps each side\'s carried weight and splits the plan\'s reps evenly with planReps', () => {
+ const side = (w, r) => ({ w, r, done: true })
+ const S = { exWeights: {}, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, target: { side: true }, sets: [
+ { w: 22.5, r: 13, done: true, sides: { L: side(22.5, 7), R: side(20, 6) } },
+ ] }] }] }
+ const [row] = buildSets(S, { id: LIFT, sets: 1, reps: 16, weight: 20, side: true }, { planReps: true })
+ expect(row.sides.L).toMatchObject({ w: 22.5, r: 8 })
+ expect(row.sides.R).toMatchObject({ w: 20, r: 8 })
+ expect(row.r).toBe(16)
+ // Without it the logged asymmetry carries over, reps included.
+ const [carried] = buildSets(S, { id: LIFT, sets: 1, reps: 16, weight: 20, side: true })
+ expect([carried.sides.L.r, carried.sides.R.r]).toEqual([7, 6])
+ })
+
+ it('ignores planReps for freestyle, which reproduces what you did', () => {
+ const S = { exWeights: {}, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 15, done: true }] }] }] }
+ expect(buildSets(S, { id: LIFT, sets: 1, reps: 10, weight: 50 }, { planReps: true, preferLast: true }))
+ .toEqual([{ w: 60, r: 15, done: false }])
+ })
+
it('can preserve each last set weight for freestyle instead of using the working-weight hint', () => {
const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [
{ w: 60, r: 10, done: true }, { w: 62.5, r: 8, done: true }
diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js
index 88477c1f1..c1674a807 100644
--- a/frontend/src/lib/progression.js
+++ b/frontend/src/lib/progression.js
@@ -332,7 +332,9 @@ export function stallCount(sessions, policy) {
* Returns `{ weight, reps, sec, why, kind }` — `kind` being one of
* first | up | hold | deload | off, and `why` a translatable template + args so the app can
* always answer "why this number?". A field the policy has no opinion on comes back
- * undefined and the caller keeps whatever the plan said.
+ * undefined and the caller keeps whatever the plan said — for reps, unless the profile starts
+ * planned sessions from the last session, in which case the rows keep last time's (see
+ * startsFromLast in session-start.js).
*/
export function nextPrescription(S, cfg, routine) {
const mode = modeOf(cfg)
@@ -514,10 +516,16 @@ export function nextPrescription(S, cfg, routine) {
export function applyPrescription(sets, p, step = 2.5) {
if (!p || p.kind === 'off' || p.kind === 'first') return sets
const out = sets.map(s => {
- // Never rewrite a logged set, and never rewrite a warm-up: the prescription speaks to
- // the work rows only (a ticked warm-up falling through here would be the data-loss the
- // cascade fix removed, two files over).
- if (s.done || isWarmupRow(s)) return s
+ // Never rewrite a logged set (a ticked warm-up falling through here would be the data-loss
+ // the cascade fix removed, two files over). The prescription speaks to the work rows; an
+ // open warm-up only follows the reps or the hold it settled on, because insertWarmupRow
+ // copied those from the work row before the policy had spoken. Its weight is re-ramped last.
+ if (s.done) return s
+ if (isWarmupRow(s)) {
+ if (p.reps != null && s.r != null) return { ...s, r: p.reps }
+ if (p.sec != null && s.sec != null) return { ...s, sec: p.sec }
+ return s
+ }
if (isSideSet(s)) {
const sides = Object.fromEntries(['L', 'R'].map(side => {
const row = s.sides[side]
diff --git a/frontend/src/lib/progression.test.js b/frontend/src/lib/progression.test.js
index 742cc7cd8..d6b2aa0ab 100644
--- a/frontend/src/lib/progression.test.js
+++ b/frontend/src/lib/progression.test.js
@@ -853,6 +853,19 @@ describe('applyPrescription never touches warm-up rows (round 3)', () => {
expect(out[0]).toEqual({ w: 20, r: 8, done: true, warmup: true })
})
+ it('an open warm-up follows the reps or the hold the policy settled on, never a done one', () => {
+ // insertWarmupRow copies the work row's reps before the prescription is applied, so without
+ // this a bodyweight climb or a double-progression aim left the warm-up at the old number.
+ const reps = applyPrescription([
+ { w: 20, r: 8, done: true, warmup: true },
+ { w: 0, r: 10, done: false, phase: 'warmup' },
+ { w: 0, r: 10, done: false },
+ ], { kind: 'up', weight: 0, reps: 12 })
+ expect(reps.map(s => s.r)).toEqual([8, 12, 12])
+ const held = applyPrescription([{ sec: 30, w: 0, done: false, phase: 'warmup' }, { sec: 30, w: 0, done: false }], { kind: 'up', sec: 35 })
+ expect(held.map(s => s.sec)).toEqual([35, 35])
+ })
+
it('an all-warm-up entry terminates and stays untouched', () => {
const sets = [
{ w: 20, r: 8, done: true, warmup: true },
diff --git a/frontend/src/lib/session-start.js b/frontend/src/lib/session-start.js
index 6da1f1fe4..2816cdb79 100644
--- a/frontend/src/lib/session-start.js
+++ b/frontend/src/lib/session-start.js
@@ -6,6 +6,40 @@
import { buildSets, applyIntensifierPlan, modeOf } from './history.js'
import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement } from './progression.js'
+/**
+ * Where a planned session's reps come from (Settings → During a workout). 'plan', the default:
+ * the routine's own sets × reps, with history and the progression policy deciding the weight —
+ * and a policy that moves reps (double progression, bodyweight, a timed hold) still moving them
+ * from there. 'last': the reps you logged last time, the way every planned session opened before
+ * this setting existed. A profile saved before it, or one that never chose, reads as 'plan'.
+ */
+export const startsFromLast = st => st?.startFrom === 'last'
+
+/**
+ * One planned exercise, built the way a session builds it: the prescription, the rows it opens
+ * with and the target it is judged against. The session start, a mid-session edit of the
+ * exercise, and an exercise added to or swapped into a planned session all build through here,
+ * so an entry cannot come out differently depending on where it was made. `routine` is the one
+ * the exercise is planned in: its own history comes first (#216) and its policy applies.
+ * `noProg` builds the routine's own numbers with no prescription, as an excluded routine does.
+ */
+export function buildPlannedEntry(st, cfg, routine, { noProg = false } = {}) {
+ // `plan` is kept on the entry purely so the workout can explain the number it chose.
+ const plan = noProg ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, routine)
+ // 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 rows = buildSets(st, cfg, { step, rid: routine?.id, useTarget: plan.kind === 'off', planReps: !startsFromLast(st) })
+ const sets = applyIntensifierPlan(applyPrescription(rows, plan, step), cfg)
+ const target = { ...cfg }
+ if (plan.weight != null) target.weight = plan.weight
+ if (plan.reps != null) target.reps = plan.reps
+ if (plan.sec != null) target.sec = plan.sec
+ if (plan.sets != null) target.sets = plan.sets
+ return { target, plan, sets }
+}
+
// 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)
@@ -13,21 +47,10 @@ import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement
// only reads the routine's id, to start each exercise from that routine's own history (#216).
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.
+ // right weight already on the screen instead of being told about it afterwards.
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, rid: r?.id, useTarget: plan.kind === 'off' }), plan, step), cfg)
- const target = { ...cfg }
- if (plan.weight != null) target.weight = plan.weight
- if (plan.reps != null) target.reps = plan.reps
- if (plan.sec != null) target.sec = plan.sec
- if (plan.sets != null) target.sets = plan.sets
+ const { target, plan, sets } = buildPlannedEntry(st, cfg, r, { noProg })
return { id: cfg.id, sg: cfg.sg, target, plan, sets, ...(noProg ? { noProg: true } : {}) }
})
}
diff --git a/frontend/src/lib/session-start.plan.test.js b/frontend/src/lib/session-start.plan.test.js
new file mode 100644
index 000000000..abf10230b
--- /dev/null
+++ b/frontend/src/lib/session-start.plan.test.js
@@ -0,0 +1,148 @@
+// A routine saved as "2 × 10" has to open as 2 × 10 (Discord report, #275). Every scenario starts
+// the session the way beginWorkout does (buildCombinedEntries → buildSessionEntries) and logs it
+// the way the finish path does (buildCompletedWorkout), so the history each one reads has the
+// exact shape the app saves — `target`, `rid` and all.
+import { describe, it, expect } from 'vitest'
+import { buildCombinedEntries } from './session-merge.js'
+import { buildSessionEntries } from './session-start.js'
+import { buildCompletedWorkout } from './finish-workout.js'
+import { POLICIES } from './progression.js'
+import { isWarmupRow } from './workout-model.js'
+
+const BENCH = '0025' // barbell bench press — loaded, 2.5 kg step
+const work = e => e.sets.filter(s => !isWarmupRow(s))
+const reps = e => work(e).map(s => s.r)
+const clone = v => JSON.parse(JSON.stringify(v))
+const state = (routines, extra = {}) => ({ unit: 'kg', exWeights: {}, routines: clone(routines), workouts: [], week: {}, dayPlan: {}, ...extra })
+const cfgOf = (st, rid, exId = BENCH) => st.routines.find(r => r.id === rid).ex.find(c => c.id === exId)
+const start = (st, rids) => buildCombinedEntries(st, rids).entries
+
+// Train the given routines: start them for real, optionally type something else into the work
+// rows (`typed`: an object, or a function of the row index), tick everything and finish.
+let day = 1
+function train(st, rids, typed) {
+ const entries = start(st, rids).map(e => {
+ let i = -1
+ return { ...e, sets: e.sets.map(s => {
+ if (isWarmupRow(s)) return { ...s, done: true }
+ i++
+ return { ...s, ...(typeof typed === 'function' ? typed(i) : typed || {}), done: true }
+ }) }
+ })
+ const d = `2026-08-${String(day).padStart(2, '0')}`
+ const active = { id: 'w' + day, d, start: day * 1000, routineIds: rids, name: 'x', entries }
+ day++
+ st.workouts.push(buildCompletedWorkout(active, { end: active.start + 1 }))
+}
+
+describe('a planned session opens at the plan\'s reps', () => {
+ it('when the same exercise was trained at 15 in another routine', () => {
+ const st = state([
+ { id: 'A', name: 'Plan A', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 60 }] },
+ { id: 'B', name: 'Plan B', ex: [{ id: BENCH, sets: 2, reps: 15, weight: 40 }] },
+ ])
+ train(st, ['B'])
+ const [a] = start(st, ['A'])
+ expect(work(a)).toHaveLength(2)
+ expect(reps(a)).toEqual([10, 10])
+ expect(a.target.reps).toBe(10)
+ })
+
+ for (const prog of [undefined, 'linear', 'greyskull', 'off']) {
+ it(`after the routine was edited from 15 to 10 · policy ${prog || '(default)'}`, () => {
+ const st = state([{ id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 15, weight: 50, ...(prog ? { prog } : {}) }] }])
+ train(st, ['A'])
+ train(st, ['A'])
+ cfgOf(st, 'A').reps = 10
+ const [e] = start(st, ['A'])
+ expect(reps(e)).toEqual([10, 10])
+ expect(e.target.reps).toBe(10)
+ })
+ }
+
+ it('after one session logged at 15 on a 10 target — it does not stick', () => {
+ const st = state([{ id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 50 }] }])
+ expect(reps(start(st, ['A'])[0])).toEqual([10, 10])
+ train(st, ['A'], { r: 15 })
+ const [next] = start(st, ['A'])
+ expect(reps(next)).toEqual([10, 10])
+ expect(next.plan.kind).toBe('up') // the weight still moves: 15 ≥ 10 was a hit
+ expect(work(next).map(s => s.w)).toEqual([52.5, 52.5])
+ train(st, ['A'])
+ expect(reps(start(st, ['A'])[0])).toEqual([10, 10])
+ })
+
+ it('under Greyskull, whose AMRAP set carried its own count before', () => {
+ const st = state([{ id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 50, prog: 'greyskull' }] }])
+ train(st, ['A'], i => (i === 1 ? { r: 15 } : {}))
+ const [e] = start(st, ['A'])
+ expect(e.plan.reps).toBeUndefined()
+ expect(reps(e)).toEqual([10, 10])
+ })
+
+ it('with planned warm-ups, which follow the plan\'s reps too', () => {
+ const st = state([
+ { id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 60, warmupSets: 1 }] },
+ { id: 'B', name: 'B', ex: [{ id: BENCH, sets: 2, reps: 15, weight: 40 }] },
+ ])
+ train(st, ['B'])
+ const [e] = start(st, ['A'])
+ expect(e.sets.filter(isWarmupRow).map(s => s.r)).toEqual([10])
+ })
+
+ it('on a combined day that holds the exercise twice, each block at its own plan', () => {
+ const st = state([
+ { id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 60 }] },
+ { id: 'B', name: 'B', ex: [{ id: BENCH, sets: 2, reps: 15, weight: 40 }] },
+ ])
+ train(st, ['B'])
+ const [a, b] = start(st, ['A', 'B'])
+ expect(reps(a)).toEqual([10, 10])
+ expect(reps(b)).toEqual([15, 15])
+ })
+
+ it('for a new routine\'s default policy, with a legacy session logged at 15', () => {
+ const st = state([{ id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 50, mode: 'reps' }] }])
+ st.workouts.push({ id: 'p', d: '2026-09-01', entries: [{ id: BENCH, target: { sets: 2, reps: 10, weight: 50 }, sets: [{ w: 50, r: 15, done: true }, { w: 50, r: 15, done: true }] }] })
+ const [e] = buildSessionEntries(st, st.routines[0])
+ expect(e.plan.policy).toBe('linear')
+ expect(reps(e)).toEqual([10, 10])
+ })
+
+ // Whatever the earlier session's target — the routine said 15 then, the user typed 15 over a
+ // 10, or it predates stamped targets — only a policy that moves reps may move them.
+ const priors = {
+ 'target 15': { sets: 2, reps: 15, weight: 50, mode: 'reps' },
+ 'target 10, did 15': { sets: 2, reps: 10, weight: 50, mode: 'reps' },
+ 'no target': null,
+ }
+ for (const [label, priorTarget] of Object.entries(priors)) {
+ for (const prog of POLICIES) {
+ it(`every policy at 2 × 10 after a logged 2 × 15 · prior ${label} · ${prog}`, () => {
+ const st = state([{ id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 50, mode: 'reps', prog }] }])
+ st.workouts.push({ id: 'p', d: '2026-09-01', entries: [{ id: BENCH, target: priorTarget, sets: [{ w: 50, r: 15, done: true }, { w: 50, r: 15, done: true }] }] })
+ const [e] = start(st, ['A'])
+ if (prog === 'double') expect(reps(e).every(r => r >= 8 && r <= 10)).toBe(true)
+ else expect(reps(e)).toEqual([10, 10])
+ })
+ }
+ }
+})
+
+describe('"Your last session" keeps the old carry-over', () => {
+ it('opens at the reps logged last time, judged against the plan', () => {
+ const st = state([{ id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 50 }] }], { startFrom: 'last' })
+ train(st, ['A'], { r: 15 })
+ const [e] = start(st, ['A'])
+ expect(reps(e)).toEqual([15, 15])
+ expect(e.target.reps).toBe(10)
+ })
+
+ it('still lets a policy that decides reps decide them', () => {
+ const st = state([{ id: 'A', name: 'A', ex: [{ id: BENCH, sets: 2, reps: 12, repsMin: 8, weight: 40, prog: 'double' }] }], { startFrom: 'last' })
+ train(st, ['A'], { r: 9 })
+ const [e] = start(st, ['A'])
+ expect(e.plan.kind).toBe('hold')
+ expect(reps(e)).toEqual([10, 10])
+ })
+})
diff --git a/frontend/src/lib/session-start.test.js b/frontend/src/lib/session-start.test.js
index b96633b7e..6b85b122b 100644
--- a/frontend/src/lib/session-start.test.js
+++ b/frontend/src/lib/session-start.test.js
@@ -46,6 +46,58 @@ describe('buildSessionEntries', () => {
expect(work.every(s => s.r === entry.target.reps && s.w === entry.target.weight)).toBe(true)
})
+ // The same invariant for every other way a loaded rep policy opens a session: what the rows
+ // say is the target the session is judged by, so doing exactly what is on the screen is a hit.
+ // Linear and Greyskull used to open at last session's reps while the stamped target kept the
+ // plan's, so a routine edited from 15 to 10 opened at 15 and read 15 ≥ 10 as a hit forever.
+ const history = (reps, extra = {}) => ({
+ unit: 'kg', exWeights: {}, routines: [],
+ workouts: [{ d: '2026-01-01', entries: [{ id: '0025', target: { sets: 2, reps: 15, weight: 40 }, sets: reps.map(r => ({ w: 40, r, done: true })) }] }],
+ ...extra,
+ })
+ // Greyskull has no hold: one failure resets it, so its miss case is a (non-Epley) deload.
+ for (const [prog, kind, reps] of [['linear', 'up', [15, 15]], ['linear', 'hold', [15, 9]], ['greyskull', 'up', [15, 15]], ['greyskull', 'deload', [15, 9]]]) {
+ it(`opens ${prog} ${kind} at the plan's reps, and completing the rows reads as a hit`, () => {
+ const cfg = { id: '0025', sets: 2, reps: 10, weight: 40, prog }
+ const [entry] = buildSessionEntries(history(reps), { id: 'r', prog, ex: [cfg] })
+ const work = entry.sets.filter(s => !isWarmupRow(s))
+ expect(entry.plan.kind).toBe(kind)
+ expect(entry.target.reps).toBe(10)
+ expect(work.map(s => s.r)).toEqual([10, 10])
+ expect(work.every(s => s.r === entry.target.reps && s.w === entry.target.weight)).toBe(true)
+ expect(readSession({ ...entry, sets: entry.sets.map(s => ({ ...s, done: true })) }, cfg).ok).toBe(true)
+ })
+ }
+
+ it('carries last session\'s reps instead when the profile starts from the last session', () => {
+ const cfg = { id: '0025', sets: 2, reps: 10, weight: 40, prog: 'linear' }
+ const [entry] = buildSessionEntries(history([15, 15], { startFrom: 'last' }), { id: 'r', prog: 'linear', ex: [cfg] })
+ expect(entry.sets.map(s => [s.w, s.r])).toEqual([[42.5, 15], [42.5, 15]])
+ expect(entry.target.reps).toBe(10)
+ })
+
+ it('warms up at the plan\'s reps, not at last session\'s', () => {
+ const cfg = { id: '0025', sets: 2, reps: 10, weight: 40, warmupSets: 1 }
+ const [entry] = buildSessionEntries(history([15, 15]), { id: 'r', prog: 'linear', ex: [cfg] })
+ expect(entry.sets.map(s => [isWarmupRow(s) ? 'warm' : 'work', s.r])).toEqual([['warm', 10], ['work', 10], ['work', 10]])
+ })
+
+ it('splits the plan\'s reps evenly per side', () => {
+ const cfg = { id: '0025', sets: 1, reps: 16, weight: 20, side: true, prog: 'linear' }
+ const side = (w, r) => ({ w, r, done: true })
+ const st = {
+ unit: 'kg', exWeights: {}, routines: [],
+ workouts: [{ d: '2026-01-01', entries: [{ id: '0025', target: { sets: 1, reps: 10, weight: 20, side: true }, sets: [
+ { w: 22.5, r: 10, done: true, sides: { L: side(22.5, 5), R: side(20, 5) } },
+ ] }] }],
+ }
+ const [entry] = buildSessionEntries(st, { id: 'r', ex: [cfg] })
+ const row = entry.sets[0]
+ expect(entry.plan.kind).toBe('up')
+ expect([row.sides.L.r, row.sides.R.r]).toEqual([8, 8])
+ expect(row.r).toBe(entry.target.reps)
+ })
+
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)
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 725b43eff..6d4430975 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -25,7 +25,7 @@ import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } fr
import { buildPlanBundle, parsePlan, mergePlan, printPlan, planPrintHTML } from './lib/plan-share.js'
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
import { exerciseHistory } from './lib/exercise-history.js'
-import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS, weightIncrement } from './lib/progression.js'
+import { policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS, weightIncrement } from './lib/progression.js'
import { normalizeRepRange } from './lib/rep-range.js'
import { MOBILE, shareExport, printHtml } from './lib/mobile.js'
import { buildCompletedWorkout } from './lib/finish-workout.js'
@@ -34,7 +34,7 @@ import { nextUnfinishedUnit } from './lib/supersetFlow.js'
import { swapActiveExercise } from './lib/active-exercise-swap.js'
import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'
import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'
-import { buildSessionEntries } from './lib/session-start.js'
+import { buildSessionEntries, buildPlannedEntry } from './lib/session-start.js'
import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'
@@ -1025,13 +1025,12 @@ export function swapActiveWorkoutExercise(index) {
// Same rows the add flow builds: last time's loads and, in a planned session, the
// prescription — swapping barbell for dumbbell bench must not start you at an empty bar.
const step = modeOf(full) === 'reps' ? weightIncrement(full, st.unit) : defaultIncrement(ex.id, st.unit)
- const plan = freestyle ? null : nextPrescription(st, full, slotRoutine)
- const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : { rid: current.rid }), ...(plan?.kind === 'off' ? { useTarget: true } : {}) })
+ const built = freestyle
+ ? { target: { ...cfg }, plan: null, sets: applyIntensifierPlan(buildSets(st, full, { step, preferLast: true }), full) }
+ : buildPlannedEntry(st, full, slotRoutine, { noProg: current.noProg === true })
const replacement = {
id: ex.id,
- target: { ...cfg },
- plan,
- sets: applyIntensifierPlan(freestyle ? built : applyPrescription(built, plan, step), full),
+ ...built,
...(current.rid ? { rid: current.rid } : {}),
}
diff --git a/frontend/src/sheets.plan-session.test.jsx b/frontend/src/sheets.plan-session.test.jsx
new file mode 100644
index 000000000..c3307538d
--- /dev/null
+++ b/frontend/src/sheets.plan-session.test.jsx
@@ -0,0 +1,79 @@
+// @vitest-environment happy-dom
+// "Saved as 2 × 10, the training day shows 2 × 15" (Discord report, #275), end to end through the
+// real store: beginWorkout → tick the rows → finishWorkout → edit the routine the way the routine
+// editor saves it → beginWorkout again. Nothing here calls the prescription directly: the rows are
+// what the workout screen would render.
+import { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { beginWorkout, finishWorkout } from './sheets.jsx'
+import { DEF, useStore } from './store/useStore.js'
+import { useUI } from './store/useUI.js'
+import { isWarmupRow } from './lib/workout-model.js'
+
+const BENCH = '0025'
+const clone = v => JSON.parse(JSON.stringify(v))
+const S = () => useStore.getState().S
+const upd = fn => act(() => useStore.getState().update(fn))
+const rowsOf = rid => S().active.entries.filter(e => e.rid === rid && e.id === BENCH)
+ .map(e => e.sets.filter(s => !isWarmupRow(s)).map(s => `${s.w}x${s.r}`))[0]
+
+function install(routines, extra = {}) {
+ const st = clone(DEF)
+ Object.assign(st, { routines, week: { 1: ['A'] }, active: null, workouts: [], weighIn: false }, extra)
+ useStore.setState({ S: st, user: null })
+}
+
+function startOn(day, rids) {
+ vi.setSystemTime(new Date(day + 'T17:00:00'))
+ act(() => beginWorkout(rids, null))
+}
+
+// Tick every row, optionally typing a rep count first (what the stepper would write), and finish.
+function trainActive(day, typedReps) {
+ vi.setSystemTime(new Date(day + 'T18:00:00'))
+ upd(s => s.active.entries.forEach(e => e.sets.forEach(x => {
+ if (!isWarmupRow(x) && typedReps != null) x.r = typedReps
+ x.done = true
+ })))
+ act(() => finishWorkout())
+ useUI.setState({ sheets: [] })
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] })
+ localStorage.clear()
+ useUI.setState({ sheets: [] })
+})
+afterEach(() => { vi.useRealTimers() })
+
+describe('what you plan is what you train', () => {
+ it('a routine edited from 2 × 15 to 2 × 10 opens at 10 on the next training day', () => {
+ install([{ id: 'A', name: 'Plan A', emoji: 'dumbbell', ex: [{ id: BENCH, sets: 2, reps: 15, weight: 50, mode: 'reps' }] }])
+ startOn('2026-09-07', ['A'])
+ expect(rowsOf('A')).toEqual(['50x15', '50x15'])
+ trainActive('2026-09-07')
+ expect(S().workouts[0].entries[0].target.reps).toBe(15)
+
+ upd(s => { s.routines[0].ex[0] = { ...s.routines[0].ex[0], reps: 10 } })
+ startOn('2026-09-14', ['A'])
+ expect(S().active.entries[0].target.reps).toBe(10)
+ expect(rowsOf('A').map(r => r.split('x')[1])).toEqual(['10', '10'])
+ })
+
+ it('logging 15 once on a 2 × 10 plan does not turn every later session into 15s', () => {
+ install([{ id: 'A', name: 'Plan A', emoji: 'dumbbell', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 50, mode: 'reps' }] }])
+ startOn('2026-09-07', ['A'])
+ expect(rowsOf('A')).toEqual(['50x10', '50x10'])
+ trainActive('2026-09-07', 15)
+ startOn('2026-09-14', ['A'])
+ expect(rowsOf('A')).toEqual(['52.5x10', '52.5x10'])
+ })
+
+ it('"Your last session" still carries the 15s over', () => {
+ install([{ id: 'A', name: 'Plan A', emoji: 'dumbbell', ex: [{ id: BENCH, sets: 2, reps: 10, weight: 50, mode: 'reps' }] }], { startFrom: 'last' })
+ startOn('2026-09-07', ['A'])
+ trainActive('2026-09-07', 15)
+ startOn('2026-09-14', ['A'])
+ expect(rowsOf('A')).toEqual(['52.5x15', '52.5x15'])
+ })
+})
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 00fc90d83..f1b69d2ea 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -82,6 +82,11 @@ export const DEF = {
// the session straight away; weight can still be logged from Home/Stats. Defaults on; an
// older profile without the key reads as on (`!== false`).
weighIn: true,
+ // Where a planned session's reps come from (Settings → During a workout, lib/session-start.js):
+ // 'plan' opens at the routine's own sets × reps and lets history and progression decide the
+ // weight; 'last' carries the reps over from the last session, the way it always worked before.
+ // Absent reads as 'plan' too, which is what the MCP bridge sees on a raw state file.
+ startFrom: 'plan',
}
const clone = o => JSON.parse(JSON.stringify(o))
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 993c0373d..1084d2bbc 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -285,6 +285,16 @@ export default function Settings() {
value={['list', 'compact'].includes(S.workoutView) ? S.workoutView : 'cards'}
onChange={v => update(s => { s.workoutView = v })} />
</Row>
+ {/* Whose reps a planned session opens with (lib/session-start.js). The plan's by default:
+ the routine is what you said you would do, and history and progression decide the
+ weight. The other choice is the old behaviour, reps carried over from last time.
+ Absent (an older profile) reads as the plan. */}
+ <SelectRow icon="clipboard" iconTint="var(--acc)" title={t('Planned sessions start from')}
+ value={S.startFrom === 'last' ? 'last' : 'plan'} onChange={v => update(s => { s.startFrom = v })}
+ options={[
+ { value: 'plan', label: t('Your plan'), subtitle: t('The routine’s sets and reps. Your history decides the weight.') },
+ { value: 'last', label: t('Your last session'), subtitle: t('The reps you logged last time in that routine, carried over.') },
+ ]} />
{/* The lean workout screen keeps the sets and one "more" button per exercise; each switch
brings one of the old always-visible button groups back for people who liked them. */}
<Row icon="wrench" iconTint="var(--purple)" title={t('Workout controls')} accessory="chevron"
diff --git a/frontend/src/views/Settings.startfrom.test.jsx b/frontend/src/views/Settings.startfrom.test.jsx
new file mode 100644
index 000000000..9becc351d
--- /dev/null
+++ b/frontend/src/views/Settings.startfrom.test.jsx
@@ -0,0 +1,104 @@
+// @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 Settings from './Settings.jsx'
+import { bindUI } from '../components/ui.jsx'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+const mocks = vi.hoisted(() => {
+ const state = { S: null }
+ state.snapshot = () => ({
+ S: state.S,
+ user: null,
+ update: mut => {
+ const next = structuredClone(state.S)
+ mut(next)
+ state.S = next
+ },
+ replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
+ signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
+ })
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
+vi.mock('../lib/api.js', () => ({
+ api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
+}))
+vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
+vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
+vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
+vi.mock('../sheets.jsx', () => ({
+ loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
+}))
+
+// The Settings view reads the build-time version constant at render time.
+globalThis.__APP_VERSION__ ??= 'test'
+
+// SelectRow opens its choices through the bound UI store; capture the sheet to render it here.
+let sheet = null
+bindUI({ getState: () => ({ openSheet: render => { sheet = render; return { close: () => {} } } }) })
+
+let host, root
+beforeEach(() => {
+ sheet = null
+ mocks.S = {
+ unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
+ gifSize: 'full', workouts: [], routines: [], exWeights: {},
+ }
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+})
+
+const mount = () => act(() => root.render(<Settings />))
+const row = () => [...host.querySelectorAll('.lrow')].find(r => r.textContent.includes('Planned sessions start from'))
+const choose = label => {
+ act(() => { row().click() })
+ expect(sheet).toBeTypeOf('function')
+ const box = document.createElement('div')
+ document.body.appendChild(box)
+ const sheetRoot = createRoot(box)
+ act(() => sheetRoot.render(sheet(() => {})))
+ const option = [...box.querySelectorAll('button.lrow')].find(b => b.querySelector('.lrow-t')?.textContent === label)
+ expect(option).toBeTruthy()
+ act(() => { option.click() })
+ act(() => sheetRoot.unmount())
+ box.remove()
+}
+
+describe('Settings — planned sessions start from', () => {
+ it('reads an older profile without the setting as the plan', () => {
+ mount()
+ expect(row()).toBeTruthy()
+ expect(row().textContent).toContain('Your plan')
+ })
+
+ it('switches to the last session and back, writing startFrom to the store', () => {
+ mount()
+ choose('Your last session')
+ expect(mocks.S.startFrom).toBe('last')
+ mount()
+ expect(row().textContent).toContain('Your last session')
+ choose('Your plan')
+ expect(mocks.S.startFrom).toBe('plan')
+ })
+})
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index 6ae1413d9..be5f2b5fe 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -16,8 +16,9 @@ import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWo
import { effortColor } from '../lib/effort.js'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
-import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement, stepWeight } from '../lib/progression.js'
+import { defaultIncrement, weightIncrement, stepWeight } from '../lib/progression.js'
import { progressionGuidance } from '../lib/progression-copy.js'
+import { buildPlannedEntry } from '../lib/session-start.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps, isSideSet, makeSideSet, setSideField, toggleSide, addSideDrop, removeSideDropAt, setSideDropAt, addSideCluster, removeSideClusterAt, setSideClusterAt } from '../lib/workout-model.js'
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'
@@ -796,20 +797,20 @@ function ActiveWorkout() {
if (!activeEntry || activeEntry.id !== entryId) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === activeEntry.rid)
- const step = modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : 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, rid: activeEntry.rid, useTarget: plan.kind === 'off' }), plan, step), full)
+ // rebuilt from the new config exactly the way the session start builds them (same reps
+ // source, same prescription, same stamped target), and only what you already logged is
+ // kept in place (done warm-ups first, then done work sets, then the fresh remainder).
+ const built = buildPlannedEntry(s, full, activeRoutine, { noProg: activeEntry.noProg === true })
+ const fresh = built.sets
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.target = built.target
+ activeEntry.plan = built.plan
activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)]
})
}, null, routine)
@@ -1079,15 +1080,15 @@ function ActiveWorkout() {
const seed = freestyle ? freestyleConfig(S, { id: ex.id, ...defaultConfig(ex.id) }) : null
const commit = cfg => update(s => {
const full = { ...cfg, id: ex.id }
- const plan = freestyle ? null : nextPrescription(s, full, routine)
- const sets = buildSets(s, full, {
- step: modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit),
- ...(freestyle ? { preferLast: true } : { rid: curRid }),
- ...(plan?.kind === 'off' ? { useTarget: true } : {})
- })
- const progressed = freestyle ? sets : applyPrescription(sets, plan, modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit))
+ // A planned session builds the exercise the way its routine would (prescription, reps
+ // source, target); freestyle reproduces what you did last time.
+ const built = freestyle
+ ? { target: { ...cfg }, plan: null, sets: applyIntensifierPlan(buildSets(s, full, {
+ step: modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit), preferLast: true,
+ }), full) }
+ : buildPlannedEntry(s, full, routine)
const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length)
- s.active.entries.splice(insertAt, 0, { id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full), ...(curRid ? { rid: curRid } : {}) })
+ s.active.entries.splice(insertAt, 0, { id: ex.id, ...built, ...(curRid ? { rid: curRid } : {}) })
s.active.cur = insertAt
useUI.getState().shiftRestOwner(insertAt, 1)
})
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx
index 452fcecf7..0f235b901 100644
--- a/frontend/src/views/Workout.test.jsx
+++ b/frontend/src/views/Workout.test.jsx
@@ -739,6 +739,37 @@ describe('progression guidance', () => {
})
})
+// Editing an exercise mid-session rebuilds its open rows the way the session start builds them:
+// the same reps source and the same stamped target, so saving "2 × 10" over a session carried at
+// 15 opens 10s, and the target the session is judged by says what the rows say.
+describe('progression settings rebuild the rows like a session start', () => {
+ const history = [{
+ d: '2026-08-27',
+ entries: [{ id: 'plain-bench', target: { sets: 2, reps: 15, weight: 40 }, sets: [{ w: 40, r: 15, done: true }, { w: 40, r: 15, done: true }] }],
+ }]
+ const plan = { policy: 'linear', kind: 'up', weight: 42.5, why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'] }
+ const saveTen = async state => {
+ await mount([exercise('plain-bench', [false, false], { plan, target: { mode: 'reps', sets: 2, reps: 15, weight: 40 } })], 0, state)
+ await pressProgression()
+ const save = mocks.exConfigSheet.mock.calls.at(-1)[2]
+ await act(async () => { save({ mode: 'reps', sets: 2, reps: 10, weight: 40, prog: 'linear' }) })
+ return mocks.S.active.entries[0]
+ }
+
+ it('opens the plan\'s reps and stamps the prescription into the target', async () => {
+ const saved = await saveTen({ workouts: history })
+ expect(saved.sets.map(s => [s.w, s.r])).toEqual([[42.5, 10], [42.5, 10]])
+ expect(saved.target).toMatchObject({ id: 'plain-bench', sets: 2, reps: 10, weight: 42.5 })
+ expect(saved.plan.kind).toBe('up')
+ })
+
+ it('carries last session\'s reps when the profile starts from the last session', async () => {
+ const saved = await saveTen({ workouts: history, startFrom: 'last' })
+ expect(saved.sets.map(s => s.r)).toEqual([15, 15])
+ expect(saved.target.reps).toBe(10)
+ })
+})
+
describe('effort cell (colour-coded RIR/RPE quick picker)', () => {
// A rep exercise whose sets can carry an effort rating. `rir` per set is optional — an
// unrated set simply omits the key, which is what the empty cell has to represent.
diff --git a/mcp/README.md b/mcp/README.md
index 18532ad38..b1f0b7604 100644
--- a/mcp/README.md
+++ b/mcp/README.md
@@ -84,9 +84,10 @@ Nine read-only tools in v1:
`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.
+60 kg" opens at 75 kg if the policy progressed or deloaded from that routine's last logged
+session. The routine's own weight is the last fallback the session builder consults, not the
+first; its reps hold unless a policy that moves reps moved them, or the profile starts planned
+sessions from the last session (`starts_from`). 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
diff --git a/mcp/src/tools.js b/mcp/src/tools.js
index 36d39fe9f..b748e32e4 100644
--- a/mcp/src/tools.js
+++ b/mcp/src/tools.js
@@ -16,7 +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'
+import { buildSessionEntries, startsFromLast } from '../../frontend/src/lib/session-start.js'
/* ---------- helpers ---------- */
@@ -414,28 +414,30 @@ 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) {
+// Where a number on the session screen actually came from. A routine's own weight is the LAST
+// fallback, not the first: buildSets() takes the weight of this routine's last session of the
+// exercise (any routine's, when this one never trained it), then the confirmed working weight,
+// and applyPrescription() then overwrites it with whatever the progression policy decided. The
+// reps are the routine's own unless the profile starts planned sessions from the last session
+// (startFrom 'last'), or a policy that moves reps moved them. 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, routine) {
// 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 last = lastEntryFor(S, cfg.id, routine && routine.id)
+ if (field === 'reps') return startsFromLast(S) && last ? 'last_session' : 'routine_plan'
+ if (last) return 'last_session'
+ const conf = (S.exWeights || {})[cfg.id]
+ return conf && conf.w > 0 ? 'confirmed_weight' : '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',
+ last_session: 'carried over from the last time this routine had this exercise (or any routine, if this one never has)',
routine_plan: "the routine's own target"
}
@@ -443,7 +445,7 @@ const SOURCE_TEXT = {
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.',
+ '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 progressed or deloaded from that routine\'s last logged session. The reps are the routine\'s own unless a policy that moves reps moved them, or the profile starts planned sessions from the last session (starts_from). 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.')
@@ -478,8 +480,8 @@ export const previewSession = {
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')
+ const wSrc = sourceOf(S, cfg, plan, 'weight', r)
+ const rSrc = sourceOf(S, cfg, plan, 'reps', r)
return {
position: i + 1,
id: cfg.id,
@@ -540,6 +542,9 @@ export const previewSession = {
routine_id: r.id,
routine_name: r.name,
unit,
+ // The profile's "Planned sessions start from" setting: 'plan' opens at the routine's own
+ // reps, 'last_session' carries them over from the last time.
+ starts_from: startsFromLast(S) ? 'last_session' : 'plan',
policy: policyFor(null, r, 'reps'),
policy_name: policyName(policyFor(null, r, 'reps')),
exercises,
diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js
index b6674a4b5..dbabaab25 100644
--- a/mcp/test/tools.test.js
+++ b/mcp/test/tools.test.js
@@ -754,23 +754,49 @@ describe('preview_session', () => {
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]
+ const fiveLastTime = [{
+ 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 }]
+ }]
+ }]
+
+ test('reps are the routine\'s own by default, whatever was logged last time', () => {
+ only({ id: '0025', sets: 2, reps: 12, weight: 60 }, { workouts: fiveLastTime })
+ const out = call('preview_session')
+ const e = out.exercises[0]
+ expect(out.starts_from).toBe('plan')
+ expect(e.opening_sets.map(s => s.r)).toEqual([12, 12])
+ expect(e.reps_source).toBe('routine_plan')
+ expect(e.changed).not.toContain('reps')
+ })
+
+ test('reps carry from the last session when the profile starts planned sessions from it', () => {
+ only({ id: '0025', sets: 2, reps: 12, weight: 60 }, { workouts: fiveLastTime })
+ S.startFrom = 'last'
+ _seedStateForTests(S)
+ const out = call('preview_session')
+ const e = out.exercises[0]
+ expect(out.starts_from).toBe('last_session')
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('the weight comes from this routine\'s own last session, not another routine\'s (#216)', () => {
+ only({ id: '0025', sets: 2, reps: 10, weight: 60 }, {
+ workouts: [
+ { id: 'w1', d: '2026-07-20', routineIds: ['r-preview'], name: 'Preview', entries: [{ id: '0025', rid: 'r-preview', target: { sets: 2, reps: 10, weight: 60 }, sets: [{ w: 60, r: 10, done: true }, { w: 60, r: 10, done: true }] }] },
+ { id: 'w2', d: '2026-07-22', routineIds: ['r-light'], name: 'Light', entries: [{ id: '0025', rid: 'r-light', target: { sets: 2, reps: 15, weight: 40 }, sets: [{ w: 40, r: 15, done: true }, { w: 40, r: 15, done: true }] }] },
+ ]
+ })
+ const e = call('preview_session').exercises[0]
+ expect(e.opening_sets.map(s => [s.w, s.r])).toEqual([[62.5, 10], [62.5, 10]])
+ expect(e.weight_source).toBe('progression')
+ })
+
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]