From 47c1cc446fc4c1ca99de7f16ae1ef9e5779d2a9f Mon Sep 17 00:00:00 2001 From: Horus Gonzalez Date: Sun, 30 Aug 2026 14:31:56 -0600 Subject: [PATCH 01/28] Exercise picker: the "+" adds now instead of opening the detail sheet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "+" on a row in the exercise picker read as "add this now" but did the same thing as tapping the row — opened the detail/config sheet — so it added nothing until you'd scrolled past sets/reps and found the real "Add to routine"/"Add exercise" button there. The "+" now commits with the default config (or, mid-workout in freestyle, the same last-session-seeded config the sheet would have opened with) immediately, with a toast confirming what got added. Tapping the rest of the row is unchanged — it still opens the detail sheet, for setting sets/reps before adding. Both call sites (routine editor, and the mid-workout "Add exercise") get the same fix, since they share the one picker component. No new strings — reuses 'Add "{0}"' and '"{0}" added to {1}', both already translated in every locale. --- frontend/src/sheets.jsx | 9 ++++++++- frontend/src/views/RoutineEdit.jsx | 13 +++++++++++-- frontend/src/views/Workout.jsx | 13 ++++++++++--- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index b5c0bd9..4a328e8 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -502,7 +502,14 @@ function ExercisePicker({ onPick, close }) { } {f.slice(0, shown).map(e =>
onPick(e)}>
{exerciseNameFor(e)}
{t(e.tg || e.bp)} · {t(e.eq)}
- {usage[e.id] && } + {usage[e.id] && } + {/* A "+" glyph reads as "add this now" — it used to just open the same detail sheet as + tapping the row, so it added nothing until you'd scrolled past the sets/reps config + and found the real button. Now it does what it looks like: adds with the default + config right away. Tapping the row itself still opens the detail/config sheet, for + when you want to set sets/reps before adding. */} +
)} {f.length === 0 && bp === '★' &&
{t('Nothing chosen yet — add exercises and they’ll show up here.')}
} diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx index a8c492c..76ab810 100644 --- a/frontend/src/views/RoutineEdit.jsx +++ b/frontend/src/views/RoutineEdit.jsx @@ -1,11 +1,12 @@ import { useNavigate, useParams } from 'react-router-dom' import { useEffect } from 'react' import { useStore } from '../store/useStore.js' +import { useUI } from '../store/useUI.js' import { exOr } from '../lib/exercises.js' import { activeProfile, exAvailable } from '../lib/equipment.js' import { uid } from '../lib/format.js' import { t, exerciseNameFor } from '../lib/i18n.js' -import { supersetUnits, cleanupSg, exLine } from '../lib/history.js' +import { supersetUnits, cleanupSg, exLine, defaultConfig } from '../lib/history.js' import { Thumb } from '../components/Media.jsx' import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' @@ -20,6 +21,7 @@ export default function RoutineEdit() { const { id } = useParams() const S = useStore(s => s.S) const update = useStore(s => s.update) + const toast = useUI(s => s.toast) const r = S.routines.find(x => x.id === id) useEffect(() => { if (!r) nav('/plan') }, [!!r]) // Editing here has no explicit "save" — every field change persists immediately. A single @@ -111,7 +113,14 @@ export default function RoutineEdit() { })()}
{t('Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.')}
- +
- {A.entries.length > 0 && <>
From 63803ba2b022aa9fb1caa67a7fbdc309f6ec8c15 Mon Sep 17 00:00:00 2001 From: Manuel Date: Sun, 30 Aug 2026 17:07:59 +0200 Subject: [PATCH 02/28] fix: keep no-progression routine targets --- frontend/src/lib/history.test.js | 66 +++++++++++++++++++++++++++++++ frontend/src/lib/session-start.js | 2 +- frontend/src/views/Workout.jsx | 9 ++++- 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index f74c6a4..1ad7c69 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -501,6 +501,72 @@ describe('buildSets', () => { .toEqual([{ w: 40, r: 12, done: false }, { w: 40, r: 12, done: false }]) }) + it('uses the current routine target instead of another routine\'s bodyweight history', () => { + const S = { + exWeights: {}, + workouts: [{ + d: '2026-01-01', + routineId: 'routine-a', + entries: [{ + id: BW, + target: { sets: 2, reps: 15, weight: 0, bodyweight: true }, + sets: [{ w: 0, r: 15, done: true }, { w: 0, r: 15, done: true }] + }] + }] + } + const cfg = { id: BW, sets: 4, reps: 8, weight: 0, bodyweight: true, prog: 'off' } + + expect(buildSets(S, cfg, { useTarget: true })).toEqual([ + { w: 0, r: 8, done: false }, + { w: 0, r: 8, done: false }, + { w: 0, r: 8, done: false }, + { w: 0, r: 8, done: false } + ]) + + const reverseS = { + exWeights: {}, + workouts: [{ + d: '2026-01-02', + routineId: 'routine-b', + entries: [{ + id: BW, + target: { sets: 4, reps: 8, weight: 0, bodyweight: true }, + sets: [ + { w: 0, r: 8, done: true }, { w: 0, r: 8, done: true }, + { w: 0, r: 8, done: true }, { w: 0, r: 8, done: true } + ] + }] + }] + } + expect(buildSets(reverseS, { ...cfg, sets: 2, reps: 15 }, { useTarget: true })).toEqual([ + { w: 0, r: 15, done: false }, + { w: 0, r: 15, done: false } + ]) + }) + + it('preserves configured load, reps, duration and cardio targets when history is present', () => { + const repsS = { + exWeights: { [LIFT]: { w: 75 } }, + workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 75, r: 15, done: true }] }] }] + } + expect(buildSets(repsS, { id: LIFT, sets: 2, reps: 8, weight: 40 }, { useTarget: true })) + .toEqual([{ w: 40, r: 8, done: false }, { w: 40, r: 8, done: false }]) + + const timedS = { + exWeights: {}, + workouts: [{ d: '2026-01-02', entries: [{ id: LIFT, target: { mode: 'time' }, sets: [{ sec: 90, w: 20, done: true }] }] }] + } + expect(buildSets(timedS, { id: LIFT, mode: 'time', sets: 2, sec: 30, weight: 5 }, { useTarget: true })) + .toEqual([{ sec: 30, w: 5, done: false }, { sec: 30, w: 5, done: false }]) + + const cardioS = { + exWeights: {}, + workouts: [{ d: '2026-01-03', entries: [{ id: CARDIO, sets: [{ min: 45, speed: 10, done: true }] }] }] + } + expect(buildSets(cardioS, { id: CARDIO, sets: 2, min: 20, speed: 8 }, { useTarget: true })) + .toEqual([{ min: 20, speed: 8, done: false }, { min: 20, speed: 8, done: false }]) + }) + }) describe('applyIntensifierPlan', () => { diff --git a/frontend/src/lib/session-start.js b/frontend/src/lib/session-start.js index 5ca9f50..cf3dd1b 100644 --- a/frontend/src/lib/session-start.js +++ b/frontend/src/lib/session-start.js @@ -14,7 +14,7 @@ export function buildSessionEntries(st, r) { const entries = (r ? r.ex : []).map(cfg => { const plan = excluded ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r) const step = defaultIncrement(cfg.id, st.unit) - const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: excluded }), plan, step), cfg) + 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 { entries, excluded } diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index fafab26..290d7d1 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -662,12 +662,17 @@ function ActiveWorkout() { const routine = S.routines.find(r => r.id === A.routineId) const freestyle = !A.routineId // Freestyle has no routine prescription to apply: show the last target in the config - // sheet and carry its completed rows forward. A planned session keeps its existing path. + // sheet and carry its completed rows forward. A planned session uses its configured + // target when progression is off, while progression-enabled sessions keep their path. const seed = freestyle ? freestyleConfig(S, { id: ex.id, ...defaultConfig(ex.id) }) : null exConfigSheet(ex, null, cfg => update(s => { const full = { ...cfg, id: ex.id } const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId)) - const sets = buildSets(s, full, { step: defaultIncrement(ex.id, s.unit), ...(freestyle ? { preferLast: true } : {}) }) + const sets = buildSets(s, full, { + step: defaultIncrement(ex.id, s.unit), + ...(freestyle ? { preferLast: true } : {}), + ...(plan?.kind === 'off' ? { useTarget: true } : {}) + }) const progressed = freestyle ? sets : applyPrescription(sets, plan, defaultIncrement(ex.id, s.unit)) 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) }) From 1bec57bb3fd2aaf540bd95303798eb301471b780 Mon Sep 17 00:00:00 2001 From: Manuel Date: Mon, 31 Aug 2026 09:57:54 +0200 Subject: [PATCH 03/28] fix: use available width for exercise selector --- frontend/src/index.css | 2 +- frontend/src/views/Stats.test.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/frontend/src/index.css b/frontend/src/index.css index ca0528e..9b19998 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -262,7 +262,7 @@ h4.sec{ display:grid;grid-template-columns:minmax(0,1fr) auto;grid-template-rows:auto auto; } .lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1} -.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left} +.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;width:100%;max-width:none;text-align:left} .lrow.lrow-stack-value .lrow-c{grid-column:2;grid-row:1 / span 2;align-self:center} /* an (i) before a row's control: painted small and dim so the control stays the loud thing, but with a finger-sized target like everything else — the padding is the hit area and the diff --git a/frontend/src/views/Stats.test.js b/frontend/src/views/Stats.test.js index be90304..c0ce185 100644 --- a/frontend/src/views/Stats.test.js +++ b/frontend/src/views/Stats.test.js @@ -35,7 +35,8 @@ describe('Stats mixed-entry metric contract', () => { expect(uiSource).toContain('sheetTitle, stackedValue = false') expect(uiSource).toContain("className={stackedValue ? 'lrow-stack-value' : ''}") expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1}') - expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left}') + expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;width:100%;max-width:none;text-align:left}') + expect(cssSource).toContain('flex:0 1 auto;max-width:45%;min-width:0;') expect(cssSource).toContain('overflow:hidden;text-overflow:ellipsis;white-space:nowrap') }) }) From 3214dfde9d9edea65972fa30354488a225936c38 Mon Sep 17 00:00:00 2001 From: TheophileDiot Date: Mon, 31 Aug 2026 10:46:54 +0200 Subject: [PATCH 04/28] mcp: get_routine reports an exercise's own rest --- mcp/README.md | 2 +- mcp/src/tools.js | 5 ++++- mcp/test/tools.test.js | 11 +++++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/mcp/README.md b/mcp/README.md index 0cff276..7c15cab 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -72,7 +72,7 @@ Eight read-only tools in v1: | Tool | What it answers | |---|---| | `list_routines` | What routines are saved in my profile? (names + exercise counts) | -| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) | +| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight and rest per exercise) | | `get_week_plan` | What's on my plan this week, including today with any date-specific override? | | `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. | | `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. | diff --git a/mcp/src/tools.js b/mcp/src/tools.js index 3d20b40..c7b2323 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -105,7 +105,7 @@ export const listRoutines = { /** get_routine — the full exercise list for one routine, including set/rep targets. */ export const getRoutine = { name: 'get_routine', - description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.', + description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, any per-exercise custom increment you can override, and each exercise\'s own rest in seconds (absent means it inherits the global rest timer). Use routine_id from list_routines.', schema: { routine_id: z.string().min(1) }, handler: ({ routine_id }) => { const S = getState() @@ -138,6 +138,9 @@ export const getRoutine = { speed: mode === 'cardio' ? (cfg.speed || 0) : undefined, weight: cfg.weight != null ? cfg.weight : undefined, increment: cfg.inc != null ? cfg.inc : undefined, + // The exercise's own rest (issue #10). Absent means it inherits the global rest + // timer; a superset rests once, taking the longest its members ask for. + rest_sec: cfg.restSec > 0 ? cfg.restSec : undefined, policy: policyFor(cfg, r, mode), policy_override: cfg.prog || null, superset_group: cfg.sg || null, diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js index 7b6e480..6e36ee7 100644 --- a/mcp/test/tools.test.js +++ b/mcp/test/tools.test.js @@ -129,6 +129,17 @@ describe('get_routine', () => { expect(r.exercises[0]).toMatchObject({ reps: 8, reps_min: 8, reps_max: 12 }) }) + test('reports an exercise\'s own rest, and leaves it out when it inherits the timer', () => { + S.routines[0].ex[0].restSec = 180 + delete S.routines[0].ex[1]?.restSec + + const r = call('get_routine', { routine_id: S.routines[0].id }) + expect(r.exercises[0].rest_sec).toBe(180) + // An exercise with no rest of its own inherits the global timer. Absent says that; + // a zero would read as "no rest at all", which is a different prescription. + expect(JSON.parse(JSON.stringify(r)).exercises[1]).not.toHaveProperty('rest_sec') + }) + test('projects routine and exercise progression rules from prog', () => { S.routines[0].prog = 'greyskull' S.routines[0].ex[0].prog = 'double' From 5370e2184c23f49c21d8534a959e92756b972424 Mon Sep 17 00:00:00 2001 From: TheophileDiot Date: Mon, 31 Aug 2026 10:46:54 +0200 Subject: [PATCH 05/28] BodyMap tests: import the geometry before the first render, not inside the wait --- frontend/src/components/BodyMap.test.jsx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/frontend/src/components/BodyMap.test.jsx b/frontend/src/components/BodyMap.test.jsx index 1cc2b43..cc328bb 100644 --- a/frontend/src/components/BodyMap.test.jsx +++ b/frontend/src/components/BodyMap.test.jsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import React, { act } from 'react' import { createRoot } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import BodyMap, { BodyMapLegend } from './BodyMap.jsx' globalThis.IS_REACT_ACT_ENVIRONMENT = true @@ -9,6 +9,14 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true let container let root +// BodyMap fetches its ~90 KB of geometry with a dynamic import on first render, and the +// waitFor below allows one second for it. That is ample once the module is in the ESM +// registry and not always ample when it is not: on a loaded CI runner the first map render +// in this file paid the cold import and timed out, while every later test passed on the +// component's warm CACHE. Import it here so the wait covers rendering, not module loading, +// and the file stops depending on how fast the machine is. +beforeAll(() => import('../lib/body-paths.js')) + beforeEach(() => { container = document.createElement('div') document.body.appendChild(container) From 1224b05d347e401673b0daf8dfc6abdd15654081 Mon Sep 17 00:00:00 2001 From: Space_Hermes Date: Sun, 30 Aug 2026 21:09:38 +0200 Subject: [PATCH 06/28] fix(workout): make progression guidance actionable --- frontend/src/views/Workout.jsx | 53 +++++++++++++++++------------ frontend/src/views/Workout.test.jsx | 41 ++++++++++++++++++++++ 2 files changed, 73 insertions(+), 21 deletions(-) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index fafab26..8ebd552 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -441,28 +441,39 @@ function ActiveWorkout() { const state = useStore.getState().S const entry = state.active?.entries?.[idx] if (!entry) return + const activeId = state.active.id + const entryId = entry.id const routine = state.routines.find(r => r.id === state.active.routineId) - exConfigSheet(exOr(entry.id), entry.target, cfg => update(s => { - const activeEntry = s.active?.entries?.[idx] - if (!activeEntry) return - const full = { ...cfg, id: activeEntry.id } - const activeRoutine = s.routines.find(r => r.id === s.active.routineId) - const step = defaultIncrement(activeEntry.id, s.unit) - // A config without a set count keeps the rows the session already has. - if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1 - const plan = nextPrescription(s, full, activeRoutine) - // The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are - // rebuilt from the new config the way the session was, and only what you already logged - // is kept in place (done warm-ups first, then done work sets, then the fresh remainder). - const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full) - const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x)) - const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x)) - const freshWarm = fresh.filter(isWarmupRow) - const freshWork = fresh.filter(x => !isWarmupRow(x)) - activeEntry.target = { ...cfg } - activeEntry.plan = plan - activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)] - }), null, routine) + exConfigSheet(exOr(entryId), entry.target, cfg => { + // Store updates clone the state tree. If this exact object is no longer at the captured + // index, the list changed while the sheet was open; an id check alone cannot distinguish + // duplicate occurrences of the same exercise, so fail closed before cloning again. + const current = useStore.getState().S + if (current.active?.id !== activeId || current.active.entries?.[idx] !== entry) return + update(s => { + const activeEntry = s.active?.id === activeId ? s.active.entries?.[idx] : null + // The sheet may outlive its workout or entry. Never apply its result to whatever later + // happens to occupy the same index. + if (!activeEntry || activeEntry.id !== entryId) return + const full = { ...cfg, id: activeEntry.id } + const activeRoutine = s.routines.find(r => r.id === s.active.routineId) + const step = defaultIncrement(activeEntry.id, s.unit) + // A config without a set count keeps the rows the session already has. + if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1 + const plan = nextPrescription(s, full, activeRoutine) + // The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are + // rebuilt from the new config the way the session was, and only what you already logged + // is kept in place (done warm-ups first, then done work sets, then the fresh remainder). + const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full) + const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x)) + const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x)) + const freshWarm = fresh.filter(isWarmupRow) + const freshWork = fresh.filter(x => !isWarmupRow(x)) + activeEntry.target = { ...cfg } + activeEntry.plan = plan + activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)] + }) + }, null, routine) } // Remove a whole exercise from the session. The confirmation always asks first; in a diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index 72c0082..488eff4 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -477,6 +477,47 @@ describe('progression guidance', () => { expect(mocks.S.active.cur).toBe(0) }) + it('does not save into a different duplicate occurrence after the entry list shifts', async () => { + const plan = { + policy: 'linear', kind: 'up', weight: 62.5, + why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'], + } + const first = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 5, weight: 60, marker: 'first' } }) + const second = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 8, weight: 80, marker: 'second' } }) + const third = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 10, weight: 100, marker: 'third' } }) + await mount([first, second, third], 1) + await pressProgression() + const save = mocks.exConfigSheet.mock.calls[0][2] + + mocks.S.active.entries.splice(0, 1) + await act(async () => { save({ ...second.target, prog: 'double', repsMin: 6 }) }) + + expect(mocks.S.active.entries.map(entry => entry.target.marker)).toEqual(['second', 'third']) + expect(mocks.S.active.entries[0].target.prog).toBeUndefined() + expect(mocks.S.active.entries[1].target.prog).toBeUndefined() + }) + + it('does not save through a sheet left open from a replaced workout', async () => { + const plan = { + policy: 'linear', kind: 'up', weight: 62.5, + why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'], + } + const original = exercise('plain-bench', [false], { plan }) + await mount([original]) + await pressProgression() + const save = mocks.exConfigSheet.mock.calls[0][2] + const replacement = exercise('plain-bench', [false], { + plan, + target: { mode: 'reps', reps: 10, weight: 100, marker: 'replacement' }, + }) + mocks.S.active = { ...mocks.S.active, id: 'replacement-workout', entries: [replacement] } + + await act(async () => { save({ ...original.target, prog: 'double', repsMin: 6 }) }) + + expect(mocks.S.active.entries[0].target).toEqual(replacement.target) + expect(mocks.S.active.entries[0].target.prog).toBeUndefined() + }) + it('leaves the active entry unchanged when progression settings are cancelled', async () => { const entry = exercise('plain-bench', [true, false], { plan: { From 40ae5a6f9d637a4a392ac11ee3128be75b9890b3 Mon Sep 17 00:00:00 2001 From: Manuel Date: Mon, 31 Aug 2026 18:54:22 +0200 Subject: [PATCH 07/28] fix: use exercise weight step for workout controls --- frontend/src/lib/progression.js | 9 ++++++- frontend/src/lib/progression.test.js | 10 +++++++- frontend/src/views/Workout.jsx | 5 ++-- frontend/src/views/Workout.test.jsx | 38 ++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index 9b33cbd..4cc5547 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -61,6 +61,11 @@ export function defaultIncrement(exId, unit) { if (unit === 'lb') return heavy ? 10 : 5 return heavy ? 5 : 2.5 } +// Resolve the load step for reps-mode weight controls and progression. Timed exercises use +// `inc` for seconds, so their optional weight column must not call this helper. +export function weightIncrement(cfg, unit) { + return cfg && cfg.inc > 0 ? cfg.inc : defaultIncrement(cfg?.id, unit) +} export const DEFAULT_SEC_INCREMENT = 5 // Where adding another set of push-ups stops being progress and starts being a way to spend // an evening. Past this the honest advice is load or a harder variation (issue #33). @@ -167,7 +172,9 @@ export function nextPrescription(S, cfg, routine) { const mode = modeOf(cfg) const policy = policyFor(cfg, routine, mode) const unit = S.unit || 'kg' - const inc = cfg.inc > 0 ? cfg.inc : (mode === 'time' ? DEFAULT_SEC_INCREMENT : defaultIncrement(cfg.id, unit)) + const inc = mode === 'time' + ? (cfg.inc > 0 ? cfg.inc : DEFAULT_SEC_INCREMENT) + : weightIncrement(cfg, unit) if (policy === 'off') return { policy, kind: 'off' } const sessions = sessionsFor(S, cfg.id, cfg).filter(s => s.mode === mode) diff --git a/frontend/src/lib/progression.test.js b/frontend/src/lib/progression.test.js index be56e79..7b541cf 100644 --- a/frontend/src/lib/progression.test.js +++ b/frontend/src/lib/progression.test.js @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest' import { readSession, sessionsFor, stallCount, nextPrescription, applyPrescription, - policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS + policyFor, defaultIncrement, weightIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS } from './progression.js' import { EXDB } from './exercises.js' @@ -103,6 +103,14 @@ describe('defaultIncrement', () => { }) }) +describe('weightIncrement', () => { + it('uses a positive exercise override and otherwise the exercise/unit default', () => { + expect(weightIncrement({ id: LIFT, inc: 1 }, 'kg')).toBe(1) + expect(weightIncrement({ id: LIFT }, 'kg')).toBe(2.5) + expect(weightIncrement({ id: HEAVY, inc: 0 }, 'kg')).toBe(5) + }) +}) + describe('linear progression', () => { const cfg = { id: LIFT, sets: 3, reps: 5, weight: 60, prog: 'linear' } diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index fafab26..367f6bc 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -13,7 +13,7 @@ import Media from '../components/Media.jsx' import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { Button, Check, NumberField } from '../components/ui.jsx' -import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js' +import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement } from '../lib/progression.js' import { progressionGuidance } from '../lib/progression-copy.js' import { glyphOf } from '../lib/glyphs.js' import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js' @@ -119,7 +119,8 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov const cfg = { ...(entry.target || {}), id: entry.id } const bw = !cardio && isBw(cfg) const added = bw && entry.sets.some(s => s.w > 0) - const loadCol = { f: 'w', step: 2.5, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) } + const loadStep = mode === 'reps' ? weightIncrement(cfg, S.unit) : 2.5 + const loadCol = { f: 'w', step: loadStep, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) } // The reps column is the total in every mode, unilateral included — the stepper walks in // twos there so the number you land on is one you can actually split evenly. const repCol = { f: 'r', step: repStep(cfg), dec: false, hd: t('Reps') } diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index 72c0082..b547e87 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -401,6 +401,44 @@ describe('Workout add exercise flow', () => { }) }) +describe('active workout weight controls', () => { + const press = async (label, selector) => { + const control = container.querySelector(selector) + const button = control?.querySelector(`button[aria-label="${label}"]`) + expect(button).toBeTruthy() + await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) }) + await rerender() + } + + it('uses the configured reps weight step for manual increases and decreases, with the default fallback', async () => { + await mount([exercise('plain-bench', [false], { + target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false, inc: 1 }, + })]) + + await press('Increase', '.setrow .stp.w') + expect(mocks.S.active.entries[0].sets[0].w).toBe(61) + await press('Decrease', '.setrow .stp.w') + expect(mocks.S.active.entries[0].sets[0].w).toBe(60) + + await unmount() + await mount([exercise('plain-bench', [false])]) + await press('Increase', '.setrow .stp.w') + expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5) + }) + + it('keeps timed seconds and optional timed weight on their existing steps', async () => { + await mount([exercise('timed-plank', [false], { + target: { mode: 'time', sec: 30, weight: 60, bodyweight: false, inc: 1 }, + sets: [{ sec: 30, w: 60, done: false }], + })]) + + await press('Increase', '.setrow .stp.w') + expect(mocks.S.active.entries[0].sets[0].sec).toBe(35) + await press('Increase', '.setrow .stp.r') + expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5) + }) +}) + describe('Workout discard timer lifecycle', () => { it('preserves active timers while discard is awaiting confirmation', async () => { const timer = { left: 30, total: 90, endsAt: Date.now() + 30_000 } From 6fece171977196031e84f3dacbde02679903e76a Mon Sep 17 00:00:00 2001 From: Manuel Date: Mon, 31 Aug 2026 19:12:18 +0200 Subject: [PATCH 08/28] fix: align manual weight normalization --- frontend/src/lib/progression.js | 16 ++++++++++------ frontend/src/views/Workout.jsx | 11 ++++++----- frontend/src/views/Workout.test.jsx | 26 ++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 11 deletions(-) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index 4cc5547..593e73c 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -81,18 +81,22 @@ export function policyFor(cfg, routine, mode) { } const round1 = v => Math.round(v * 10) / 10 -// Snap to a loadable multiple of the step. -function snap(v, step) { +// Snap to a loadable multiple of the step. Manual weight controls use this same normalization +// so fractional increments produce the same number as automatic progression. +export function snapWeight(v, step) { if (!(step > 0)) return round1(v) return round1(Math.round(v / step) * step) } +export function stepWeight(value, step, direction) { + return Math.max(0, snapWeight((Number(value) || 0) + direction * step, step)) +} // Back off by DELOAD_FACTOR, landing on something you can actually load. Rounding to the // nearest step keeps the cut close to the intended 10 %, but on small weights the nearest // step can be the weight you started from — so a deload that did not actually reduce // anything takes one step down instead. Never goes below a single step. function deloadTo(cur, step) { - let next = snap(cur * DELOAD_FACTOR, step) - if (next >= cur) next = snap(cur - step, step) + let next = snapWeight(cur * DELOAD_FACTOR, step) + if (next >= cur) next = snapWeight(cur - step, step) return Math.max(step, next) } @@ -225,7 +229,7 @@ export function nextPrescription(S, cfg, routine) { const range = normalizeRepRange(cfg.reps || last.goal || 10, cfg.repsMin, repStep(cfg)) const top = range.reps const bottom = range.repsMin - if (last.ok) return { policy, kind: 'up', weight: snap(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] } + if (last.ok) return { policy, kind: 'up', weight: snapWeight(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] } if (stalls >= deloadAt) { const dw = deloadTo(w, inc) return { policy, kind: 'deload', weight: dw, reps: bottom, why: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit] } @@ -241,7 +245,7 @@ export function nextPrescription(S, cfg, routine) { const dbl = policy === 'greyskull' && last.goal > 0 && last.amrap >= last.goal * 2 const step = dbl ? inc * 2 : inc return { - policy, kind: 'up', weight: snap(w + step, inc), + policy, kind: 'up', weight: snapWeight(w + step, inc), why: dbl ? ['Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.', last.amrap, step, unit] : ['Every rep last time — {0} {1} more.', step, unit] diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 367f6bc..e571a42 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -13,7 +13,7 @@ import Media from '../components/Media.jsx' import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { Button, Check, NumberField } from '../components/ui.jsx' -import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement } from '../lib/progression.js' +import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement, stepWeight } from '../lib/progression.js' import { progressionGuidance } from '../lib/progression-copy.js' import { glyphOf } from '../lib/glyphs.js' import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js' @@ -140,6 +140,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov // with no ceiling, as they always did. const bump = (s, i, col, dir) => { if (col.eff) return onField(i, col.f, stepEffort(col.eff, s[col.f], dir)) + if (mode === 'reps' && col.f === 'w') return onField(i, col.f, stepWeight(s[col.f], col.step, dir)) onField(i, col.f, Math.max(0, Math.round(((s[col.f] || 0) + dir * col.step) * 100) / 100)) } // Uses the shared stepper markup so a set row picks up the same control styling @@ -155,11 +156,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov ) // A smaller stepper for a drop's weight/reps or a burst's reps — editing what the plan (or a // live "+ Drop"/"+ Burst" tap) already put on the row, not typing into a fresh field. - const miniStepper = (value, step, dec, onChange) => ( + const miniStepper = (value, step, dec, onChange, snapWeightStep = false) => (
- + - +
) return <> @@ -235,7 +236,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov {dropsOf(s).map((d, di) => (
{t('Drop {0}', di + 1)} - {miniStepper(d.w, 2.5, true, v => setDropField(i, di, 'w', v))} + {miniStepper(d.w, loadStep, true, v => setDropField(i, di, 'w', v), true)} {miniStepper(d.r, 1, false, v => setDropField(i, di, 'r', v))}
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index b547e87..ee73be5 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client' import { parseHTML } from 'linkedom' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import Workout from './Workout.jsx' +import { nextPrescription } from '../lib/progression.js' const mocks = vi.hoisted(() => { const state = { @@ -426,6 +427,31 @@ describe('active workout weight controls', () => { expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5) }) + it('matches automatic progression rounding for a fractional configured step', async () => { + const target = { mode: 'reps', sets: 1, reps: 5, weight: 60, bodyweight: false, inc: 1.25 } + const automatic = nextPrescription({ + unit: 'kg', + workouts: [{ d: '2026-08-30', entries: [{ id: 'plain-bench', target, sets: [{ w: 60, r: 5, done: true }] }] }], + }, { id: 'plain-bench', ...target }) + + await mount([exercise('plain-bench', [false], { target, sets: [{ w: 60, r: 5, done: false }] })]) + await press('Increase', '.setrow .stp.w') + + expect(automatic.weight).toBe(61.3) + expect(mocks.S.active.entries[0].sets[0].w).toBe(automatic.weight) + }) + + it('uses the configured reps weight step for drop-set weight controls', async () => { + await mount([exercise('plain-bench', [false], { + target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false, inc: 1 }, + sets: [{ w: 60, r: 5, done: false, type: 'dropset', drops: [{ w: 50, r: 5 }] }], + })]) + + await press('Increase', '.subrow .stp') + + expect(mocks.S.active.entries[0].sets[0].drops[0].w).toBe(51) + }) + it('keeps timed seconds and optional timed weight on their existing steps', async () => { await mount([exercise('timed-plank', [false], { target: { mode: 'time', sec: 30, weight: 60, bodyweight: false, inc: 1 }, From 19f09dcccc5e23b650774de93bfcdcecf6a70a89 Mon Sep 17 00:00:00 2001 From: Sebastian G Date: Mon, 17 Aug 2026 16:33:49 +0200 Subject: [PATCH 09/28] feat: add copy routine button to RoutineEdit view --- frontend/src/lib/routines.js | 12 +++++ frontend/src/lib/routines.test.js | 79 ++++++++++++++++++++++++++++++ frontend/src/views/RoutineEdit.jsx | 7 +++ 3 files changed, 98 insertions(+) create mode 100644 frontend/src/lib/routines.js create mode 100644 frontend/src/lib/routines.test.js diff --git a/frontend/src/lib/routines.js b/frontend/src/lib/routines.js new file mode 100644 index 0000000..7613b30 --- /dev/null +++ b/frontend/src/lib/routines.js @@ -0,0 +1,12 @@ +import { uid } from './format.js' + +/** + * Create a deep copy of a routine with a new id and a "(Copy)" suffix. + * All exercises and their configuration are preserved independently. + */ +export function copyRoutine(routine, suffix = 'Copy') { + const copy = structuredClone(routine) + copy.id = uid() + copy.name = routine.name + ' (' + suffix + ')' + return copy +} diff --git a/frontend/src/lib/routines.test.js b/frontend/src/lib/routines.test.js new file mode 100644 index 0000000..8c6912b --- /dev/null +++ b/frontend/src/lib/routines.test.js @@ -0,0 +1,79 @@ +import { describe, it, expect } from 'vitest' +import { copyRoutine } from './routines.js' + +const routine = { + id: 'r1', + name: 'Push Day', + emoji: 'arm', + prog: 'linear', + ex: [ + { id: 'ex1', sets: 3, reps: 10, weight: 60, sg: 'sg1' }, + { id: 'ex2', sets: 4, reps: 8, weight: 80, sg: 'sg1' }, + { id: 'ex3', sets: 3, reps: 12, weight: 20 } + ] +} + +describe('copyRoutine', () => { + it('returns a new routine with a different id', () => { + const copy = copyRoutine(routine) + expect(copy.id).not.toBe(routine.id) + expect(copy.id).toBeTruthy() + }) + + it('appends "(Copy)" to the name by default', () => { + const copy = copyRoutine(routine) + expect(copy.name).toBe('Push Day (Copy)') + }) + + it('uses a custom suffix when provided', () => { + const copy = copyRoutine(routine, 'Kopie') + expect(copy.name).toBe('Push Day (Kopie)') + }) + + it('deep-copies all exercises with their configuration', () => { + const copy = copyRoutine(routine) + expect(copy.ex).toHaveLength(3) + expect(copy.ex[0]).toEqual(routine.ex[0]) + expect(copy.ex[1]).toEqual(routine.ex[1]) + expect(copy.ex[2]).toEqual(routine.ex[2]) + }) + + it('preserves exercise ids (references to the global library)', () => { + const copy = copyRoutine(routine) + expect(copy.ex[0].id).toBe('ex1') + expect(copy.ex[1].id).toBe('ex2') + expect(copy.ex[2].id).toBe('ex3') + }) + + it('preserves superset groupings', () => { + const copy = copyRoutine(routine) + expect(copy.ex[0].sg).toBe('sg1') + expect(copy.ex[1].sg).toBe('sg1') + expect(copy.ex[2].sg).toBeUndefined() + }) + + it('preserves the emoji and progression settings', () => { + const copy = copyRoutine(routine) + expect(copy.emoji).toBe('arm') + expect(copy.prog).toBe('linear') + }) + + it('produces an independent copy — mutating it does not affect the original', () => { + const copy = copyRoutine(routine) + copy.name = 'Modified' + copy.ex[0].weight = 999 + copy.ex.push({ id: 'ex4', sets: 5, reps: 5 }) + + expect(routine.name).toBe('Push Day') + expect(routine.ex[0].weight).toBe(60) + expect(routine.ex).toHaveLength(3) + }) + + it('handles a routine with no exercises', () => { + const empty = { id: 'r2', name: 'Empty', emoji: 'dumbbell', ex: [] } + const copy = copyRoutine(empty) + expect(copy.ex).toEqual([]) + expect(copy.name).toBe('Empty (Copy)') + expect(copy.id).not.toBe('r2') + }) +}) diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx index 701b062..bedef96 100644 --- a/frontend/src/views/RoutineEdit.jsx +++ b/frontend/src/views/RoutineEdit.jsx @@ -11,6 +11,7 @@ import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../she import Icon from '../components/Icon.jsx' import { glyphOf } from '../lib/glyphs.js' import { Button, Row, SelectRow, Switch } from '../components/ui.jsx' +import { copyRoutine } from '../lib/routines.js' import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js' import BodyMap from '../components/BodyMap.jsx' import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js' @@ -425,6 +426,12 @@ export default function RoutineEdit() {
{t('Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.')}
+ +
+
{t('Set up your weekly routine to get going — or load a ready-made starter plan.')}
+
)} diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsx index 87ad651..e6950e3 100644 --- a/frontend/src/views/Plan.jsx +++ b/frontend/src/views/Plan.jsx @@ -2,7 +2,7 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js' import { t } from '../lib/i18n.js' -import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx' +import { dayAssignSheet, starterPlanSheet, planToolsSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { Button } from '../components/ui.jsx' import { tappable } from '../lib/use-sheet-keyboard.js' @@ -45,7 +45,7 @@ export default function Plan() {
{r.name}
{exCount(r.ex.length)}
)}
: <>
{t('No routines yet.')}
{t('Create one or load the starter plan.')}
- + }
diff --git a/frontend/src/views/Settings.gifsize.test.jsx b/frontend/src/views/Settings.gifsize.test.jsx index a544911..e3fa44d 100644 --- a/frontend/src/views/Settings.gifsize.test.jsx +++ b/frontend/src/views/Settings.gifsize.test.jsx @@ -41,7 +41,7 @@ vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false })) vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() })) vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null })) vi.mock('../sheets.jsx', () => ({ - loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), + starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), })) diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index 1845148..7a82c0b 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -11,7 +11,7 @@ import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js' import { DEMO, REPO } from '../lib/demo.js' import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js' import { ConnectSheet } from './MobileOnboarding.jsx' -import { loadStarterPlan, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx' +import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx' @@ -218,7 +218,7 @@ export default function Settings() { {/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
- + importRef.current.click()} /> diff --git a/frontend/src/views/starter-entry.test.jsx b/frontend/src/views/starter-entry.test.jsx new file mode 100644 index 0000000..5dab0a8 --- /dev/null +++ b/frontend/src/views/starter-entry.test.jsx @@ -0,0 +1,51 @@ +// @vitest-environment happy-dom +// Home and Plan both offer the starter plan to someone who has no routines yet. Both used to +// wire the button straight to the loader, which quietly handed the click event in as the plan +// id and loaded nothing at all — so both entry points are pinned here. +import React, { act } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createRoot } from 'react-dom/client' +import { useStore } from '../store/useStore.js' +import { starterPlanSheet } from '../sheets.jsx' +import Home from './Home.jsx' +import Plan from './Plan.jsx' + +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../sheets.jsx', () => ({ + starterPlanSheet: vi.fn(), bwSheet: vi.fn(), goalSheet: vi.fn(), dayOverrideSheet: vi.fn(), + calendarSheet: vi.fn(), startFlow: vi.fn(), bwDeltaColor: () => '', + dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(), +})) + +let host, root +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + starterPlanSheet.mockClear() + useStore.setState(s => ({ S: { ...s.S, routines: [], week: {}, active: null }, user: null })) + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() +}) + +const starterButton = () => [...host.querySelectorAll('button')].find(b => b.textContent === 'Load starter plan') + +describe.each([['Home', Home], ['Plan', Plan]])('%s empty state', (_name, View) => { + it('opens the starter plan chooser instead of loading one plan blind', () => { + act(() => root.render()) + const button = starterButton() + expect(button).toBeTruthy() + + act(() => { button.click() }) + expect(starterPlanSheet).toHaveBeenCalledTimes(1) + }) + + it('drops the offer once the user has routines', () => { + useStore.setState(s => ({ S: { ...s.S, routines: [{ id: 'r', name: 'Mine', emoji: 'star', ex: [] }] } })) + act(() => root.render()) + expect(starterButton()).toBeFalsy() + }) +}) diff --git a/frontend/src/views/week-start.test.jsx b/frontend/src/views/week-start.test.jsx index 34bf2a3..e05c0c5 100644 --- a/frontend/src/views/week-start.test.jsx +++ b/frontend/src/views/week-start.test.jsx @@ -44,7 +44,7 @@ vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false })) vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() })) vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null })) vi.mock('../sheets.jsx', () => ({ - loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), + starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(), })) From e57eac027fd874b9fc17cbdd5f5a03101dddc347 Mon Sep 17 00:00:00 2001 From: "sebastian.goendoer" Date: Thu, 3 Sep 2026 21:40:11 +0200 Subject: [PATCH 19/28] fix: read fresh store value in set-stepper bump to prevent stale closure in supersets In a superset both ExerciseBlock instances subscribe to the same store slice. When one member's field is updated the store clone invalidates all entry references, causing both instances to re-render. The +/- button handlers were closing over the set object from the previous render, so the first tap wrote the correct value but the replacement closure made the next tap operate on stale data -- requiring two taps per visible increment instead of one. Fix: read the current field value directly from the store at call time instead of relying on the render-time snapshot. --- frontend/src/views/Workout.jsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index a71bfc0..7206b16 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -139,8 +139,15 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov // The effort column walks its own scale — see stepEffort. Weight and reps step up from 0 // with no ceiling, as they always did. const bump = (s, i, col, dir) => { - if (col.eff) return onField(i, col.f, stepEffort(col.eff, s[col.f], dir)) - onField(i, col.f, Math.max(0, Math.round(((s[col.f] || 0) + dir * col.step) * 100) / 100)) + // Read the current value directly from the store rather than from the render-time snapshot. + // In a superset both ExerciseBlock instances share the same store subscription, so when one + // member's field changes the partner re-renders too, replacing the closure's `s` reference + // with a fresh clone before the next tap fires. Reading from the store avoids that stale- + // closure problem entirely and keeps every tap operating on the real current value. + const fresh = useStore.getState().S.active?.entries[entryIdx]?.sets[i] + const cur = fresh ? fresh[col.f] : s[col.f] + if (col.eff) return onField(i, col.f, stepEffort(col.eff, cur, dir)) + onField(i, col.f, Math.max(0, Math.round(((cur || 0) + dir * col.step) * 100) / 100)) } // Uses the shared stepper markup so a set row picks up the same control styling // as every other +/- field in the app. From e278051fae10e080cc1ff53616a0152486fc0811 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Patr=C3=B3n=20G=C3=B3mez?= Date: Fri, 4 Sep 2026 09:14:16 +0200 Subject: [PATCH 20/28] feat(workout): add configurable list view for active workouts --- frontend/src/index.css | 12 +++ frontend/src/lib/pt-br-locale.test.js | 4 +- frontend/src/locales/de.js | 6 ++ frontend/src/locales/es.js | 6 ++ frontend/src/locales/fr.js | 6 ++ frontend/src/locales/hi.js | 6 ++ frontend/src/locales/hu.js | 6 ++ frontend/src/locales/it.js | 6 ++ frontend/src/locales/ko.js | 6 ++ frontend/src/locales/pl.js | 6 ++ frontend/src/locales/pt.js | 6 ++ frontend/src/locales/ru.js | 6 ++ frontend/src/locales/th.js | 6 ++ frontend/src/locales/tr.js | 6 ++ frontend/src/locales/zh.js | 6 ++ frontend/src/store/useStore.js | 4 + frontend/src/views/Settings.jsx | 8 ++ .../src/views/Settings.workoutview.test.jsx | 89 +++++++++++++++++++ frontend/src/views/Workout.jsx | 76 ++++++++++++++-- frontend/src/views/Workout.test.jsx | 72 +++++++++++++++ 20 files changed, 332 insertions(+), 11 deletions(-) create mode 100644 frontend/src/views/Settings.workoutview.test.jsx diff --git a/frontend/src/index.css b/frontend/src/index.css index f017979..2f82ba4 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -1010,6 +1010,18 @@ h4.sec{ .ss-ex{position:relative} .ss-amp{text-align:center;font-size:15px;font-weight:600;color:var(--acc);margin:14px 0 8px} +/* --- workout list view: every unit stacked, the current one outlined --- */ +.workout-list{display:grid;gap:14px} +.wl-unit{ + border-radius:var(--r-lg);padding:14px 14px 4px; + background:var(--surface-2); +} +.wl-unit.cur{box-shadow:inset 0 0 0 1.5px var(--acc-line)} +.wl-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px} +@media (max-width:400px){ + .wl-unit{padding:10px 8px 2px} +} + /* --- home: today's session row --- */ .today-row{ display:flex;align-items:center;justify-content:space-between;gap:10px; diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index 294e2cc..be464ce 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -28,10 +28,10 @@ describe('Brazilian Portuguese locale', () => { const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(586) - expect(inherited).toHaveLength(553) + expect(inherited).toHaveLength(559) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list - expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('4a550b06e44cabd2b69834c15607220ca547854f2b0934843cadaa60a7f61a27') + expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('ae49ea702bb600947e67170a1ef61c0518a326724c83b8484ce7199f1393700b') }) test('does not leak European Portuguese UI terms', () => { diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 69b1651..d9dffa2 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -412,6 +412,12 @@ export default { 'Minimize': 'Verkleinern', 'Expand': 'Vergrössern', 'Exercise animations': 'Übungs-Animationen', + 'Workout view': 'Trainingsansicht', + 'Cards': 'Karten', + 'List': 'Liste', + 'Current': 'Aktuell', + 'Set current': 'Als aktuell markieren', + 'Move, swap and remove below act on the exercise marked {0}.': 'Verschieben, Tauschen und Entfernen unten wirken auf die als {0} markierte Übung.', 'Full': 'Gross', 'Small': 'Klein', 'Hidden': 'Versteckt', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 9ef7697..ae86711 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -394,6 +394,12 @@ export default { 'Minimize': 'Minimizar', 'Expand': 'Ampliar', 'Exercise animations': 'Animaciones de los ejercicios', + 'Workout view': 'Vista del entrenamiento', + 'Cards': 'Tarjetas', + 'List': 'Lista', + 'Current': 'Actual', + 'Set current': 'Marcar actual', + 'Move, swap and remove below act on the exercise marked {0}.': 'Mover, cambiar y eliminar actúan sobre el ejercicio marcado como {0}.', 'Full': 'Completa', 'Small': 'Pequeña', 'Hidden': 'Oculta', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 71e0570..0f21a94 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -394,6 +394,12 @@ export default { 'Minimize': 'Réduire', 'Expand': 'Agrandir', 'Exercise animations': 'Animations des exercices', + 'Workout view': 'Vue de l’entraînement', + 'Cards': 'Cartes', + 'List': 'Liste', + 'Current': 'En cours', + 'Set current': 'Marquer comme en cours', + 'Move, swap and remove below act on the exercise marked {0}.': 'Déplacer, échanger et supprimer ci-dessous s’appliquent à l’exercice marqué {0}.', 'Full': 'Grande', 'Small': 'Petite', 'Hidden': 'Masquée', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index b263f21..aeff5ec 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -394,6 +394,12 @@ export default { 'Minimize': 'छोटा करें', 'Expand': 'बड़ा करें', 'Exercise animations': 'व्यायाम एनिमेशन', + 'Workout view': 'वर्कआउट दृश्य', + 'Cards': 'कार्ड', + 'List': 'सूची', + 'Current': 'वर्तमान', + 'Set current': 'वर्तमान के रूप में चिह्नित करें', + 'Move, swap and remove below act on the exercise marked {0}.': 'नीचे दिए गए मूव, स्वैप और रिमूव {0} के रूप में चिह्नित व्यायाम पर लागू होते हैं।', 'Full': 'पूर्ण', 'Small': 'छोटा', 'Hidden': 'छिपा', diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index d07d8b1..51be7b4 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -404,6 +404,12 @@ export default { 'Minimize': 'Kicsinyítés', 'Expand': 'Kibontás', 'Exercise animations': 'Gyakorlat-animációk', + 'Workout view': 'Edzésnézet', + 'Cards': 'Kártyák', + 'List': 'Lista', + 'Current': 'Aktuális', + 'Set current': 'Megjelölés aktuálisként', + 'Move, swap and remove below act on the exercise marked {0}.': 'Az alábbi áthelyezés, csere és törlés a {0} jelölésű gyakorlatra vonatkozik.', 'Full': 'Teljes', 'Small': 'Kicsi', 'Hidden': 'Rejtett', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 1a4afd4..7ce1eca 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -394,6 +394,12 @@ export default { 'Minimize': 'Riduci', 'Expand': 'Ingrandisci', 'Exercise animations': 'Animazioni degli esercizi', + 'Workout view': 'Vista allenamento', + 'Cards': 'Schede', + 'List': 'Elenco', + 'Current': 'Corrente', + 'Set current': 'Imposta come corrente', + 'Move, swap and remove below act on the exercise marked {0}.': 'Spostamento, scambio e rimozione qui sotto agiscono sull’esercizio contrassegnato come {0}.', 'Full': 'Grande', 'Small': 'Piccola', 'Hidden': 'Nascosta', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index b00fc36..13b0965 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -394,6 +394,12 @@ export default { 'Minimize': '축소', 'Expand': '확대', 'Exercise animations': '운동 애니메이션', + 'Workout view': '운동 보기', + 'Cards': '카드', + 'List': '목록', + 'Current': '현재', + 'Set current': '현재 운동으로 설정', + 'Move, swap and remove below act on the exercise marked {0}.': '아래의 이동, 교체, 삭제는 {0} 표시된 운동에 적용됩니다.', 'Full': '전체', 'Small': '작게', 'Hidden': '숨김', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 32ba989..fd9a82b 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -394,6 +394,12 @@ export default { 'Minimize': 'Zmniejsz', 'Expand': 'Powiększ', 'Exercise animations': 'Animacje ćwiczeń', + 'Workout view': 'Widok treningu', + 'Cards': 'Karty', + 'List': 'Lista', + 'Current': 'Bieżące', + 'Set current': 'Ustaw jako bieżące', + 'Move, swap and remove below act on the exercise marked {0}.': 'Przenoszenie, zamiana i usuwanie poniżej dotyczą ćwiczenia oznaczonego {0}.', 'Full': 'Pełna', 'Small': 'Mała', 'Hidden': 'Ukryta', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index a4d63fe..e96424a 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -394,6 +394,12 @@ export default { 'Minimize': 'Minimizar', 'Expand': 'Ampliar', 'Exercise animations': 'Animações dos exercícios', + 'Workout view': 'Vista do treino', + 'Cards': 'Cartões', + 'List': 'Lista', + 'Current': 'Atual', + 'Set current': 'Marcar como atual', + 'Move, swap and remove below act on the exercise marked {0}.': 'Mover, trocar e remover abaixo atuam sobre o exercício marcado como {0}.', 'Full': 'Grande', 'Small': 'Pequena', 'Hidden': 'Oculta', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index a2478a2..88cc213 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -394,6 +394,12 @@ export default { 'Minimize': 'Свернуть', 'Expand': 'Развернуть', 'Exercise animations': 'Анимации упражнений', + 'Workout view': 'Вид тренировки', + 'Cards': 'Карточки', + 'List': 'Список', + 'Current': 'Текущее', + 'Set current': 'Сделать текущим', + 'Move, swap and remove below act on the exercise marked {0}.': 'Кнопки перемещения, замены и удаления ниже действуют на упражнение с пометкой {0}.', 'Full': 'Полная', 'Small': 'Малая', 'Hidden': 'Скрыта', diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index ea2b319..1826fd0 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -404,6 +404,12 @@ export default { 'Minimize': 'ย่อ', 'Expand': 'ขยาย', 'Exercise animations': 'ภาพเคลื่อนไหวท่าออกกำลังกาย', + 'Workout view': 'มุมมองการฝึก', + 'Cards': 'การ์ด', + 'List': 'รายการ', + 'Current': 'ปัจจุบัน', + 'Set current': 'ตั้งเป็นปัจจุบัน', + 'Move, swap and remove below act on the exercise marked {0}.': 'การย้าย สลับ และลบด้านล่างจะมีผลกับท่าที่ทำเครื่องหมาย {0} ไว้', 'Full': 'เต็ม', 'Small': 'เล็ก', 'Hidden': 'ซ่อน', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 6b69cf6..4471efd 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -394,6 +394,12 @@ export default { 'Minimize': 'Küçült', 'Expand': 'Büyüt', 'Exercise animations': 'Egzersiz animasyonları', + 'Workout view': 'Antrenman görünümü', + 'Cards': 'Kartlar', + 'List': 'Liste', + 'Current': 'Aktif', + 'Set current': 'Aktif olarak işaretle', + 'Move, swap and remove below act on the exercise marked {0}.': 'Aşağıdaki taşıma, değiştirme ve kaldırma işlemleri {0} olarak işaretli egzersiz için geçerlidir.', 'Full': 'Tam', 'Small': 'Küçük', 'Hidden': 'Gizli', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index ae6abb5..8d7eafd 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -394,6 +394,12 @@ export default { 'Minimize': '缩小', 'Expand': '放大', 'Exercise animations': '动作动画', + 'Workout view': '训练视图', + 'Cards': '卡片', + 'List': '列表', + 'Current': '当前', + 'Set current': '设为当前', + 'Move, swap and remove below act on the exercise marked {0}.': '下方的移动、替换和删除将作用于标记为{0}的动作。', 'Full': '完整', 'Small': '小', 'Hidden': '隐藏', diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index c032afa..3346031 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -14,6 +14,10 @@ export const DEF = { theme: 'dark', accent: 'lime', body: 'male', targetW: null, bodyweight: [], routines: [], week: {}, dayPlan: {}, exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full', + // How the active workout is laid out — 'cards' (one exercise at a time with Prev/Next) + // or 'list' (every exercise stacked and scrollable). Purely presentational: profiles + // written before this setting existed overlay onto DEF and keep the 'cards' behaviour. + workoutView: 'cards', // effort: which per-set effort scale is logged — 'none' | 'rir' | 'rpe'. null, not 'none', so // that a profile which never chose (loaded state is overlaid on DEF, on every path: local, // server pull, backup import) still falls back to the `showRir` boolean this replaced and diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index 5b94d06..c17826f 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -144,6 +144,14 @@ export default function Settings() { {/* ---------- during a workout ---------- */}
+ {/* One exercise at a time (cards with Prev/Next) or the whole session stacked as a + scrollable list. Legacy/unknown values read as cards. */} + + update(s => { s.workoutView = v })} /> + update(s => { s.restSec = v })} options={[{ value: 0, label: t('Off') }, ...[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))]} /> diff --git a/frontend/src/views/Settings.workoutview.test.jsx b/frontend/src/views/Settings.workoutview.test.jsx new file mode 100644 index 0000000..1817bd0 --- /dev/null +++ b/frontend/src/views/Settings.workoutview.test.jsx @@ -0,0 +1,89 @@ +// @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' + +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, shareExport: vi.fn(), syncReminder: vi.fn() })) +vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null })) +vi.mock('../sheets.jsx', () => ({ + loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), + importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), +})) + +// The Settings view reads the build-time version constant at render time. +globalThis.__APP_VERSION__ ??= 'test' + +let host, root +beforeEach(() => { + 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()) +const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label) + +describe('Settings — workout view', () => { + it('offers Cards / List and writes workoutView to the store', () => { + mount() + expect(segButton('Cards')).toBeTruthy() + expect(segButton('List')).toBeTruthy() + expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true') + act(() => { segButton('List').click() }) + expect(mocks.S.workoutView).toBe('list') + mount() + expect(segButton('List').getAttribute('aria-pressed')).toBe('true') + act(() => { segButton('Cards').click() }) + expect(mocks.S.workoutView).toBe('cards') + }) + + it('shows a legacy/absent value as Cards', () => { + delete mocks.S.workoutView + mount() + expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true') + expect(segButton('List').getAttribute('aria-pressed')).toBe('false') + }) +}) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index a71bfc0..2b24e9c 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -320,6 +320,12 @@ function ActiveWorkout() { const unit = A.entries.length ? unitOf(units, cur) : [] const unitIdx = units.findIndex(u => u === unit) const isSuperset = unit.length > 1 + // Cards show one unit at a time with Prev/Next + swipe; list stacks every unit so the + // whole session is visible and scrollable (Settings → During a workout → Workout view). + // Every set handler below is already entry-index parameterised, so list mode only changes + // what is rendered — completion, rest, top-weight and auto-advance share one path. + // Unknown/absent values read as cards, keeping every pre-existing profile as it was. + const listMode = S.workoutView === 'list' // Superset flow: center the actionable row when completing a set moves to the partner or // back to the first exercise of the next round. Entry-bound maps keep repeated exercise IDs // distinct, while each rendered set index identifies the existing row within that entry. @@ -360,13 +366,13 @@ function ActiveWorkout() { } }) useEffect(() => { - if (!isSuperset) return + if (!isSuperset || listMode) return const entry = A.entries[cur] const firstIncomplete = entry?.sets.findIndex(s => !s.done) ?? -1 const setIdx = firstIncomplete >= 0 ? firstIncomplete : (entry?.sets.length ?? 0) - 1 const el = (setIdx >= 0 && setRefs.current.get(entry)?.get(setIdx)) || exRefs.current.get(entry) if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'center' }) - }, [cur, isSuperset, A.entries.length]) + }, [cur, isSuperset, listMode, A.entries.length]) const total = A.entries.reduce((n, e) => n + e.sets.length, 0) const done = setsDoneActive(A) @@ -423,6 +429,17 @@ function ActiveWorkout() { }, true) } + // One prop object per entry so the card and list layouts share the exact same wiring. + const blockProps = idx => ({ + onToggle: i => toggle(idx, i), + onField: (i, f, v) => setField(idx, i, f, v), + onAddSet: () => addSet(idx), + onRemoveSet: () => removeSet(idx), + onAddWarmup: () => addWarmup(idx), + onRemoveSetAt: i => removeSetAt(idx, i), + onStartTimed: i => startTimed(idx, i), + onProgressionSettings: () => openProgressionSettings(idx), + }) const navigateUnit = direction => { const targetFor = active => { if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null @@ -437,6 +454,10 @@ function ActiveWorkout() { if (target != null) s.active.cur = target }) } + // List mode shows every unit at once, so the "current" exercise is chosen by tapping + // "Set current" on its header instead of Prev/Next. The bottom Move/Swap/Remove actions + // keep operating on it, and completing sets still advances it on its own. + const focusUnit = firstIdx => update(s => { if (s.active) s.active.cur = firstIdx }) const onSwipePointerDown = event => { if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return @@ -640,7 +661,43 @@ function ActiveWorkout() {
{A.backfill &&
{t('Logging a past workout — no rest timers.')}
} - {A.entries.length ? <> + {A.entries.length ? (listMode ? ( +
+ {units.map((u, ui) => { + const multi = u.length > 1 + const isCur = u.includes(cur) + return
+
+ {multi ? t('Superset {0} / {1}', ui + 1, units.length) : t('Exercise {0} / {1}', ui + 1, units.length)} + {isCur + ? {t('Current')} + : } +
+ {multi ? ( +
+
+ {t('Superset · do these back-to-back, rest when done')} + +
+ {u.map((idx, k) => { + const entry = A.entries[idx] + return
bindExRef(entry, el)} className="ss-ex" data-exidx={idx}> + {k > 0 &&
+
} + bindSetRef(entry, setIdx, el)} + {...blockProps(idx)} /> +
+ })} +
+ ) : ( + 0 ? () => pairAt(u[0] - 1, u[0]) : null} + onPairNext={u[0] < A.entries.length - 1 ? () => pairAt(u[0], u[0] + 1) : null} + {...blockProps(u[0])} /> + )} +
+ })} +
+ ) : <>
{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}
bindExRef(entry, el)} className="ss-ex" data-exidx={idx}> {k > 0 &&
+
} bindSetRef(entry, setIdx, el)} - onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} onProgressionSettings={() => openProgressionSettings(idx)} /> + {...blockProps(idx)} />
})} ) : ( - toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} onProgressionSettings={() => openProgressionSettings(cur)} /> + )} - :
{t('Freestyle workout — add your first exercise.')}
} + ) :
{t('Freestyle workout — add your first exercise.')}
}
-
+ {!listMode &&
-
-
+
} + {!listMode &&
} + {listMode && A.entries.length > 0 &&
{t('Move, swap and remove below act on the exercise marked {0}.', t('Current'))}
} )} +
+
+ + {!selected &&
{t('Choose a muscle to see exercises that train it.')}
} + + {selected && <> +
+

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

+ +
+
+ { setQ(e.target.value); setShown(40) }} /> +
+
1 ? 8 : 12 }}> + + {BODYPARTS.map(b => )} +
+ {eqOpts.length > 1 &&
+ + {eqOpts.map(x => )} +
} +
+ {exercises.slice(0, shown).map(e => { + const best = bestWeightFor(S, e.id) + const primary = musclesOf(e)[selected] === 1 + return
choose(e))}> + +
{exerciseNameFor(e)}
{t(primary ? 'Primary target' : 'Also trains')} · {t(e.tg || e.bp)} · {t(e.eq)}
+ {onPick ? : <> + {best > 0 && {fmtNum(best)}} + + } +
+ })} + {exercises.length === 0 &&
{t('No match')}
} +
+ {exercises.length > shown && <>
} + } + +} diff --git a/frontend/src/index.css b/frontend/src/index.css index 9963d97..cae7c55 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -438,6 +438,7 @@ h4.sec{ } .chip:active{background:var(--surface-2)} .chip.on{background:var(--acc);color:var(--on-acc);font-weight:500} +.chip.on .dim{color:color-mix(in srgb,var(--on-acc) 62%,transparent)} /* =========================== CONTROLS ==================================== */ diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index 2e75329..53a938a 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => { .sort(byCodeUnit) const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') - expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(603) + expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(610) expect(inherited).toHaveLength(565) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 2874b21..3e8cb9f 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -24,6 +24,13 @@ export default { 'Resume': 'Weiter', 'Stats': 'Statistik', 'Exercises': 'Übungen', + 'By muscle': 'Nach Muskel', + 'Explore muscles': 'Muskeln entdecken', + 'Choose a muscle to see exercises that train it.': 'Wähle einen Muskel, um Übungen zu sehen, die ihn trainieren.', + 'Exercises for {0}': 'Übungen für {0}', + 'Clear selection': 'Auswahl aufheben', + 'Primary target': 'Hauptmuskel', + 'Also trains': 'Trainiert auch', 'History': 'Verlauf', 'Settings': 'Einstellungen', 'Freestyle': 'Freies Training', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 0c4f8f0..16d3352 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -23,6 +23,13 @@ export default { 'Resume': 'Seguir', 'Stats': 'Progreso', 'Exercises': 'Ejercicios', + 'By muscle': 'Por músculo', + 'Explore muscles': 'Explorar músculos', + 'Choose a muscle to see exercises that train it.': 'Elige un músculo para ver los ejercicios que lo entrenan.', + 'Exercises for {0}': 'Ejercicios para {0}', + 'Clear selection': 'Borrar selección', + 'Primary target': 'Músculo principal', + 'Also trains': 'También trabaja', 'History': 'Historial', 'Settings': 'Ajustes', 'Freestyle': 'Libre', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 49dd9db..2e6b4f3 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -23,6 +23,13 @@ export default { 'Resume': 'Reprendre', 'Stats': 'Stats', 'Exercises': 'Exercices', + 'By muscle': 'Par muscle', + 'Explore muscles': 'Explorer les muscles', + 'Choose a muscle to see exercises that train it.': 'Choisissez un muscle pour voir les exercices qui le sollicitent.', + 'Exercises for {0}': 'Exercices pour {0}', + 'Clear selection': 'Effacer la sélection', + 'Primary target': 'Cible principale', + 'Also trains': 'Sollicite aussi', 'History': 'Historique', 'Settings': 'Réglages', 'Freestyle': 'Libre', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index ea3cc2d..7207eec 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -23,6 +23,13 @@ export default { 'Resume': 'जारी रखें', 'Stats': 'आँकड़े', 'Exercises': 'व्यायाम', + 'By muscle': 'मांसपेशी से', + 'Explore muscles': 'मांसपेशियाँ खोजें', + 'Choose a muscle to see exercises that train it.': 'उस मांसपेशी को प्रशिक्षित करने वाले व्यायाम देखने के लिए एक मांसपेशी चुनें।', + 'Exercises for {0}': '{0} के लिए व्यायाम', + 'Clear selection': 'चयन साफ़ करें', + 'Primary target': 'मुख्य लक्ष्य', + 'Also trains': 'यह भी प्रशिक्षित करता है', 'History': 'इतिहास', 'Settings': 'सेटिंग्स', 'Freestyle': 'फ्रीस्टाइल', diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index 7db3376..ed08bfe 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -25,6 +25,13 @@ export default { 'Resume': 'Folytatás', 'Stats': 'Statisztika', 'Exercises': 'Gyakorlatok', + 'By muscle': 'Izom szerint', + 'Explore muscles': 'Izmok felfedezése', + 'Choose a muscle to see exercises that train it.': 'Válassz izmot, hogy lásd a gyakorlatokat, amelyek edzik.', + 'Exercises for {0}': '{0} gyakorlatai', + 'Clear selection': 'Kijelölés törlése', + 'Primary target': 'Elsődleges célizom', + 'Also trains': 'Emellett edzi', 'History': 'Előzmények', 'Settings': 'Beállítások', 'Freestyle': 'Szabad edzés', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index ea66bc5..c1f25aa 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -23,6 +23,13 @@ export default { 'Resume': 'Riprendi', 'Stats': 'Statistiche', 'Exercises': 'Esercizi', + 'By muscle': 'Per muscolo', + 'Explore muscles': 'Esplora i muscoli', + 'Choose a muscle to see exercises that train it.': 'Scegli un muscolo per vedere gli esercizi che lo allenano.', + 'Exercises for {0}': 'Esercizi per {0}', + 'Clear selection': 'Cancella selezione', + 'Primary target': 'Muscolo principale', + 'Also trains': 'Allena anche', 'History': 'Cronologia', 'Settings': 'Impostazioni', 'Freestyle': 'Libero', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index a1834b0..cdacbea 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -23,6 +23,13 @@ export default { 'Resume': '이어하기', 'Stats': '통계', 'Exercises': '운동', + 'By muscle': '근육별', + 'Explore muscles': '근육 탐색', + 'Choose a muscle to see exercises that train it.': '운동하는 부위를 선택해 해당 근육을 훈련하는 운동을 확인하세요.', + 'Exercises for {0}': '{0} 운동', + 'Clear selection': '선택 지우기', + 'Primary target': '주요 목표', + 'Also trains': '함께 훈련', 'History': '기록', 'Settings': '설정', 'Freestyle': '자유 운동', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 1fd55c0..20d0dc7 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -23,6 +23,13 @@ export default { 'Resume': 'Wznów', 'Stats': 'Statystyki', 'Exercises': 'Ćwiczenia', + 'By muscle': 'Według mięśnia', + 'Explore muscles': 'Poznaj mięśnie', + 'Choose a muscle to see exercises that train it.': 'Wybierz mięsień, aby zobaczyć ćwiczenia, które go angażują.', + 'Exercises for {0}': 'Ćwiczenia na {0}', + 'Clear selection': 'Wyczyść wybór', + 'Primary target': 'Główny cel', + 'Also trains': 'Angażuje również', 'History': 'Historia', 'Settings': 'Ustawienia', 'Freestyle': 'Dowolny', diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js index a6060bd..84e058f 100644 --- a/frontend/src/locales/pt-BR.js +++ b/frontend/src/locales/pt-BR.js @@ -627,6 +627,15 @@ export const PT_BR_OVERRIDES = { 'Point the camera at the QR code': 'Aponte a câmera para o código QR', 'Camera is not available here — import a photo or type the code instead.': 'A câmera não está disponível aqui — importe uma foto ou digite o código.', 'Camera access was denied — allow it in your browser and try again.': 'O acesso à câmera foi negado — permita-o no navegador e tente de novo.', + +// --- muscle explorer --- + 'By muscle': 'Por músculo', + 'Explore muscles': 'Explorar músculos', + 'Choose a muscle to see exercises that train it.': 'Escolha um músculo para ver os exercícios que o treinam.', + 'Exercises for {0}': 'Exercícios para {0}', + 'Clear selection': 'Limpar seleção', + 'Primary target': 'Músculo principal', + 'Also trains': 'Também trabalha', } export default { ...pt, ...PT_BR_OVERRIDES } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 7336910..a63f558 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -23,6 +23,13 @@ export default { 'Resume': 'Retomar', 'Stats': 'Estatísticas', 'Exercises': 'Exercícios', + 'By muscle': 'Por músculo', + 'Explore muscles': 'Explorar músculos', + 'Choose a muscle to see exercises that train it.': 'Escolha um músculo para ver os exercícios que o treinam.', + 'Exercises for {0}': 'Exercícios para {0}', + 'Clear selection': 'Limpar seleção', + 'Primary target': 'Alvo principal', + 'Also trains': 'Também trabalha', 'History': 'Histórico', 'Settings': 'Definições', 'Freestyle': 'Livre', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index f296cae..aa9de8c 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -23,6 +23,13 @@ export default { 'Resume': 'Продолжить', 'Stats': 'Статистика', 'Exercises': 'Упражнения', + 'By muscle': 'По мышцам', + 'Explore muscles': 'Изучить мышцы', + 'Choose a muscle to see exercises that train it.': 'Выберите мышцу, чтобы увидеть упражнения, которые её тренируют.', + 'Exercises for {0}': 'Упражнения для {0}', + 'Clear selection': 'Очистить выбор', + 'Primary target': 'Основная мышца', + 'Also trains': 'Также тренирует', 'History': 'История', 'Settings': 'Настройки', 'Freestyle': 'Свободная', diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index 7ad3a61..2ef2469 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -25,6 +25,13 @@ export default { 'Resume': 'เล่นต่อ', 'Stats': 'สถิติ', 'Exercises': 'ท่าออกกำลังกาย', + 'By muscle': 'ตามกล้ามเนื้อ', + 'Explore muscles': 'สำรวจกล้ามเนื้อ', + 'Choose a muscle to see exercises that train it.': 'เลือกกล้ามเนื้อเพื่อดูท่าออกกำลังกายที่ฝึกกล้ามเนื้อนั้น', + 'Exercises for {0}': 'ท่าออกกำลังกายสำหรับ {0}', + 'Clear selection': 'ล้างการเลือก', + 'Primary target': 'กล้ามเนื้อหลัก', + 'Also trains': 'ฝึกกล้ามเนื้อนี้ด้วย', 'History': 'ประวัติ', 'Settings': 'ตั้งค่า', 'Freestyle': 'ฟรีสไตล์', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 225edf1..eb97cfe 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -23,6 +23,13 @@ export default { 'Resume': 'Devam et', 'Stats': 'İstatistik', 'Exercises': 'Egzersizler', + 'By muscle': 'Kasa göre', + 'Explore muscles': 'Kasları keşfet', + 'Choose a muscle to see exercises that train it.': 'Çalıştıran egzersizleri görmek için bir kas seçin.', + 'Exercises for {0}': '{0} için egzersizler', + 'Clear selection': 'Seçimi temizle', + 'Primary target': 'Ana hedef', + 'Also trains': 'Ayrıca çalıştırır', 'History': 'Geçmiş', 'Settings': 'Ayarlar', 'Freestyle': 'Serbest', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 4571116..084a7cd 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -23,6 +23,13 @@ export default { 'Resume': '继续', 'Stats': '统计', 'Exercises': '动作库', + 'By muscle': '按肌肉', + 'Explore muscles': '探索肌肉', + 'Choose a muscle to see exercises that train it.': '选择一块肌肉以查看训练它的动作。', + 'Exercises for {0}': '{0} 训练动作', + 'Clear selection': '清除选择', + 'Primary target': '主要目标', + 'Also trains': '同时训练', 'History': '历史', 'Settings': '设置', 'Freestyle': '自由训练', diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 8ccba30..fa846be 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -16,6 +16,7 @@ import Icon from './components/Icon.jsx' import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, MultiSelectRow } from './components/ui.jsx' import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js' import BodyMap from './components/BodyMap.jsx' +import MuscleExplorer from './components/MuscleExplorer.jsx' import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js' import { parseImport, mergeImport } from './lib/import-csv.js' import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js' @@ -712,6 +713,7 @@ function ExercisePicker({ onPick, close }) { const [eq, setEq] = useState('') // '' = any equipment const [showAll, setShowAll] = useState(false) const [shown, setShown] = useState(50) + const [byMuscle, setByMuscle] = useState(false) const searchRef = useRef(null) const bpStrip = useRef(null), eqStrip = useRef(null) const onSearchFocus = useSheetKeyboard(searchRef) @@ -729,8 +731,17 @@ function ExercisePicker({ onPick, close }) { const chosenCount = Object.keys(usage).length useRevealActiveChip(bpStrip, bp) useRevealActiveChip(eqStrip, eqOn) + if (byMuscle) return <> +

{t('Add exercise')}

+ +
+ + + return <> -

{t('Add exercise')}

+

{t('Add exercise')}

+ +
{/* .picker-search is what index.css keys the keyboard-aware sheet layout on: the sheet lifts above the keys and the search stays put while the list scrolls under it. */}
diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx index 5822a78..b591abb 100644 --- a/frontend/src/views/Library.jsx +++ b/frontend/src/views/Library.jsx @@ -1,4 +1,5 @@ import { useRef, useState } from 'react' +import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js' import { activeProfile, exAvailable } from '../lib/equipment.js' @@ -12,6 +13,7 @@ import { Button } from '../components/ui.jsx' import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js' export default function Library() { + const nav = useNavigate() const S = useStore(s => s.S) const [q, setQ] = useState('') const [bp, setBp] = useState('') @@ -30,7 +32,9 @@ export default function Library() { useRevealActiveChip(eqStrip, eqOn) return <> -

{t('Exercises')}

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

{t('Exercises')}

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

{t('Explore muscles')}

{t('Choose a muscle to see exercises that train it.')}
+ +
+ + + +} From 0f021aa06dc66db11a5c8171af989013e068c8cb Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Fri, 4 Sep 2026 16:57:42 +0200 Subject: [PATCH 23/28] mrbatch: pt-BR-Guard nachgezogen, Sheet-Mock kennt starterPlanSheet, Listenmodus folgt !92 (kein Auto-Weiterspringen) --- frontend/src/lib/pt-br-locale.test.js | 8 ++++---- frontend/src/views/Settings.workoutview.test.jsx | 2 +- frontend/src/views/Workout.test.jsx | 6 ++++-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index ce83fd8..2e82c54 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => { .sort(byCodeUnit) const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') - expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(603) - expect(inherited).toHaveLength(571) + expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(612) + expect(inherited).toHaveLength(583) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list - expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('1bc5c2825a8e797b2b8e129d1c06b6baca568e95ea9a1e43ae9dacae4bc98801') + expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('c7ddbc412a3e758704289b4414372f2cbc0e26be4c0a0d95676cb3316ecae85a') }) test('does not leak European Portuguese UI terms', () => { @@ -49,6 +49,6 @@ describe('Brazilian Portuguese locale', () => { expect(ptBR['resistance band']).toBe('faixa elástica') expect(ptBR.soleus).toBe('sóleo') expect(ptBR.Unpair).toBe('Desvincular') - expect(ptBR['Starter plan loaded — Mon Push · Wed Pull · Fri Legs']).toContain('Seg Push · Qua Pull') + expect(ptBR['Choose starter plan']).toBe('Escolha um plano inicial') }) }) diff --git a/frontend/src/views/Settings.workoutview.test.jsx b/frontend/src/views/Settings.workoutview.test.jsx index 1817bd0..a2c0405 100644 --- a/frontend/src/views/Settings.workoutview.test.jsx +++ b/frontend/src/views/Settings.workoutview.test.jsx @@ -41,7 +41,7 @@ vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false })) vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() })) vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null })) vi.mock('../sheets.jsx', () => ({ - loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), + loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), })) diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index dbabba0..da60275 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -888,7 +888,9 @@ describe('workout list view', () => { expect(focusButton(units()[0])).toBeTruthy() }) - it('completing a set in list mode advances the current exercise like cards do', async () => { + // Since !92 finishing an exercise no longer moves the current marker on its own (cards use + // Next, the list uses "Set current"); completion still starts the rest like cards do. + it('completing a set in list mode starts the rest and leaves the current marker in place, like cards do', async () => { await mount([ exercise('plain-bench', [false], { asked: true }), exercise('plain-row', [false], { asked: true }), @@ -897,7 +899,7 @@ describe('workout list view', () => { await toggleSet(0) expect(mocks.S.active.entries[0].sets[0].done).toBe(true) - expect(mocks.S.active.cur).toBe(1) + expect(mocks.S.active.cur).toBe(0) expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) }) From 6e9f5e7b9cc8d4b13cbe986de38dbd1350d484fe Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Fri, 4 Sep 2026 17:11:24 +0200 Subject: [PATCH 24/28] mrbatch: preview_session baut die Session ueber session-start.js (Progression aus, Deload-Routinen, Warm-up-Schritt), meldet auch Zeit/Cardio-Overrides; Rest-Toast auch nach verstecktem Ablauf --- frontend/src/store/useUI.js | 6 +++- mcp/README.md | 2 +- mcp/src/tools.js | 35 ++++++++++++++++------- mcp/test/tools.test.js | 55 +++++++++++++++++++++++++++++++++++-- 4 files changed, 84 insertions(+), 14 deletions(-) diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js index e93ea94..8841789 100644 --- a/frontend/src/store/useUI.js +++ b/frontend/src/store/useUI.js @@ -111,8 +111,12 @@ export const useUI = create((set, get) => ({ if (left <= 0) { if (seenLive) { beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5) - vibrate([200, 100, 200]); get().flashTimer(); get().toast(t('Rest over — next set!')) + vibrate([200, 100, 200]); get().flashTimer() } + // The toast stays even when the rest ran out while the app was hidden: a guest, or anyone + // without push permission, gets no notification, and a countdown that silently vanishes + // on reopen reads like a bug. Only the loud parts (beep, vibration, flash) are gated. + get().toast(t('Rest over — next set!')) maybeRestNotification(); get().stopRest(); return } if (left <= 3) beep(snd, 660, 0.1) diff --git a/mcp/README.md b/mcp/README.md index f710fee..18532ad 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -120,7 +120,7 @@ dependencies landed in `frontend/`, no public exports changed. cd mcp && npm test ``` -54 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture +58 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override, missing routine, zero-workout history, no synced state, superset links, three 1RM formulas. "Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent diff --git a/mcp/src/tools.js b/mcp/src/tools.js index 4b59324..453ff24 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -7,8 +7,7 @@ import { fmt, setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder } from './labels.js' import { - modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId, - buildSets, applyIntensifierPlan, lastEntryFor + modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId, lastEntryFor } from '../../frontend/src/lib/history.js' import { exOr } from '../../frontend/src/lib/exercises.js' import { isWarmupRow } from '../../frontend/src/lib/workout-model.js' @@ -16,7 +15,8 @@ import { estimate1RM, best1RM, e1rmSeries, DEFAULT_FORMULA, REP_CAP } from '../../frontend/src/lib/onerm.js' import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js' -import { policyFor, nextPrescription, applyPrescription } from '../../frontend/src/lib/progression.js' +import { policyFor } from '../../frontend/src/lib/progression.js' +import { buildSessionEntries } from '../../frontend/src/lib/session-start.js' /* ---------- helpers ---------- */ @@ -419,7 +419,10 @@ export const muscleBalance = { // 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) { - const decided = plan && plan.kind !== 'off' && plan.kind !== 'first' && plan[field] != null + // 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] @@ -460,16 +463,20 @@ export const previewSession = { } const unit = S.unit || 'kg' + // The same builder the app starts a session with (sheets.jsx beginWorkout → session-start.js): + // prescription, step, progression-off targets, deload routines and warm-up ramps all come from + // there, so the preview cannot drift from what the screen shows. + const built = buildSessionEntries(S, r).entries const exercises = (r.ex || []).map((cfg, i) => { const ex = exerciseOf(cfg.id, S) const mode = modeOf({ ...cfg, id: cfg.id }) - const plan = nextPrescription(S, cfg, r) - // Mirrors beginWorkout() exactly (sheets.jsx): build, apply the prescription, then stamp - // the intensifier. Anything less and the preview stops matching the real session. - const rows = applyIntensifierPlan(applyPrescription(buildSets(S, cfg), plan), cfg) + const plan = built[i].plan + const rows = built[i].sets const work = rows.filter(s => !isWarmupRow(s)) const openW = work.length ? (work[0].w || 0) : 0 const openR = work.length ? (work[0].r || 0) : 0 + const openSec = work.length ? (work[0].sec || 0) : 0 + const openMin = work.length ? (work[0].min || 0) : 0 const wSrc = sourceOf(S, cfg, plan, 'weight') const rSrc = sourceOf(S, cfg, plan, 'reps') return { @@ -514,11 +521,15 @@ export const previewSession = { // rep target moved, and saying which one moved saves the caller diffing it themselves. changed: [ ...(mode === 'reps' && cfg.weight != null && openW !== cfg.weight ? ['weight'] : []), - ...(mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps ? ['reps'] : []) + ...(mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps ? ['reps'] : []), + ...(mode === 'time' && (cfg.sec || 0) > 0 && openSec !== cfg.sec ? ['sec'] : []), + ...(mode === 'cardio' && (cfg.min || 0) > 0 && openMin !== cfg.min ? ['min'] : []) ], differs_from_plan: (mode === 'reps' && cfg.weight != null && openW !== cfg.weight) || - (mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps) + (mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps) || + (mode === 'time' && (cfg.sec || 0) > 0 && openSec !== cfg.sec) || + (mode === 'cardio' && (cfg.min || 0) > 0 && openMin !== cfg.min) } }) @@ -540,6 +551,10 @@ export const previewSession = { opening_weight: e.opening_sets.filter(s => s.phase === 'work')[0]?.w ?? null, planned_reps: e.planned.reps, opening_reps: e.opening_sets.filter(s => s.phase === 'work')[0]?.r ?? null, + planned_sec: e.planned.sec, + opening_sec: e.opening_sets.filter(s => s.phase === 'work')[0]?.sec ?? null, + planned_min: e.planned.min, + opening_min: e.opening_sets.filter(s => s.phase === 'work')[0]?.min ?? null, changed: e.changed, reason: e.prescription.why || e.weight_source_text })) diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js index 2320b6c..b6674a4 100644 --- a/mcp/test/tools.test.js +++ b/mcp/test/tools.test.js @@ -686,8 +686,10 @@ describe('preview_session', () => { // One routine, one exercise, scheduled for the pinned "today". Nothing from the demo seed, // so the arithmetic below is checkable by hand. - function only(cfg, { prog = 'off', workouts = [], exWeights = {} } = {}) { - S.routines = [{ id: 'r-preview', name: 'Preview', emoji: 'barbell', prog, ex: [cfg] }] + // Linear by default: with progression off the app opens the routine's own numbers (see the + // two tests at the end), so history-vs-plan precedence is only observable under a policy. + function only(cfg, { prog = 'linear', workouts = [], exWeights = {}, routine = {} } = {}) { + S.routines = [{ id: 'r-preview', name: 'Preview', emoji: 'barbell', prog, ex: [cfg], ...routine }] S.week = { [WD]: 'r-preview' } S.dayPlan = {} S.workouts = workouts @@ -792,6 +794,55 @@ describe('preview_session', () => { expect(r.exercises).toEqual([]) }) + test('with progression off the routine\'s own numbers open, whatever history says (matches session-start.js)', () => { + only({ id: '0025', sets: 3, reps: 8, weight: 50 }, { + prog: 'off', + exWeights: { '0025': { w: 72.5, d: '2026-07-20' } }, + workouts: [{ + id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview', + entries: [{ id: '0025', target: { id: '0025', sets: 3, reps: 5, weight: 60 }, sets: [{ w: 60, r: 5, done: true }] }] + }] + }) + const out = call('preview_session') + const e = out.exercises[0] + expect(e.prescription.kind).toBe('off') + expect(e.opening_sets.map(s => [s.w, s.r])).toEqual([[50, 8], [50, 8], [50, 8]]) + expect(e.weight_source).toBe('routine_plan') + expect(e.reps_source).toBe('routine_plan') + expect(e.differs_from_plan).toBe(false) + expect(out.overridden_count).toBe(0) + }) + + test('a deload routine (excludeFromProgression) opens its own numbers even under a policy', () => { + only({ id: '0025', sets: 3, reps: 5, weight: 50 }, { + prog: 'linear', routine: { excludeFromProgression: true }, + workouts: [{ + id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview', + entries: [{ id: '0025', target: { id: '0025', sets: 3, reps: 5, weight: 60 }, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] }] + }] + }) + const e = call('preview_session').exercises[0] + expect(e.prescription.kind).toBe('off') + expect(e.opening_sets.every(s => s.w === 50 && s.r === 5)).toBe(true) + expect(e.weight_source).toBe('routine_plan') + }) + + test('a timed exercise that progressed is listed as overridden too', () => { + only({ id: '0025', mode: 'time', sets: 3, sec: 30, inc: 10 }, { + prog: 'time', + workouts: [{ + id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview', + entries: [{ id: '0025', target: { id: '0025', mode: 'time', sets: 3, sec: 30 }, sets: [{ sec: 45, done: true }, { sec: 45, done: true }, { sec: 45, done: true }] }] + }] + }) + const out = call('preview_session') + const e = out.exercises[0] + expect(e.prescription.kind).toBe('up') + expect(e.changed).toEqual(['sec']) + expect(e.differs_from_plan).toBe(true) + expect(out.overridden[0].opening_sec).toBeGreaterThan(30) + }) + test('an unknown routine_id is an error, not an empty session', () => { only({ id: '0025', sets: 3, reps: 8, weight: 50 }) expect(() => call('preview_session', { routine_id: 'nope' })).toThrow(/no routine with id/) From 80cccdd2e09a55f959676873e51d3e298e07554c Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Fri, 4 Sep 2026 17:13:47 +0200 Subject: [PATCH 25/28] mrbatch (!87): Muskel-Explorer folgt dem Geraete-Profil wie Library/Picker, Zurueck-Pfeil links, Satz nicht doppelt, Library-Tab bleibt markiert --- frontend/src/components/MuscleExplorer.jsx | 19 +++++++++++++++++-- frontend/src/components/TabBar.jsx | 2 +- frontend/src/views/Muscles.jsx | 6 ++---- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/frontend/src/components/MuscleExplorer.jsx b/frontend/src/components/MuscleExplorer.jsx index d796a3b..e0cdfb6 100644 --- a/frontend/src/components/MuscleExplorer.jsx +++ b/frontend/src/components/MuscleExplorer.jsx @@ -1,6 +1,7 @@ import { useMemo, useState } from 'react' import { useStore } from '../store/useStore.js' import { BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js' +import { activeProfile, exAvailable } from '../lib/equipment.js' import { bestWeightFor } from '../lib/history.js' import { fmtNum } from '../lib/format.js' import { MUSCLES, MUSCLE_NAME, musclesOf } from '../lib/muscles.js' @@ -20,7 +21,14 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) { const [bp, setBp] = useState('') const [eq, setEq] = useState('') const [shown, setShown] = useState(40) - const catalog = useMemo(() => allExercises(S), [S.customEx]) + const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session + // Same rule as the Library and the picker: the active equipment profile narrows the catalogue + // (and the per-muscle counts) unless the user asks for everything. + const profile = activeProfile(S) + const catalog = useMemo(() => { + const all = allExercises(S) + return (profile && !showAll) ? all.filter(e => exAvailable(S, e)) : all + }, [S.customEx, S.equipFilterOn, S.activeEquipId, S.equipProfiles, showAll]) const counts = useMemo(() => Object.fromEntries(MUSCLES.map(m => [m, catalog.filter(e => musclesOf(e)[m]).length ])), [catalog]) @@ -33,6 +41,13 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) { const choose = ex => onPick ? onPick(ex) : onDetail(ex) return <> + {profile &&
+ + {showAll ? t('Showing all equipment') : t('Showing what you have in "{0}"', profile.name)} + +
}
@@ -43,7 +58,7 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) {
- {!selected &&
{t('Choose a muscle to see exercises that train it.')}
} + {!selected && onPick &&
{t('Choose a muscle to see exercises that train it.')}
} {selected && <>
diff --git a/frontend/src/components/TabBar.jsx b/frontend/src/components/TabBar.jsx index 156d4d7..d54e31c 100644 --- a/frontend/src/components/TabBar.jsx +++ b/frontend/src/components/TabBar.jsx @@ -13,7 +13,7 @@ export default function TabBar({ onStart }) { const isGuest = useStore(s => s.isGuest()) if (!user && !isGuest) return null const cur = loc.pathname.split('/')[1] || 'home' - const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') + const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') || (cur === 'muscles' && k === 'library') const startWorkout = () => { if (!S.active) { diff --git a/frontend/src/views/Muscles.jsx b/frontend/src/views/Muscles.jsx index 330a489..a1de3db 100644 --- a/frontend/src/views/Muscles.jsx +++ b/frontend/src/views/Muscles.jsx @@ -7,10 +7,8 @@ import Icon from '../components/Icon.jsx' export default function Muscles() { const nav = useNavigate() return <> -
-

{t('Explore muscles')}

{t('Choose a muscle to see exercises that train it.')}
- -
+
+

{t('Explore muscles')}

{t('Choose a muscle to see exercises that train it.')}
From 0cbd32c0f556023b970dd101cf4f40989989fbc4 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Fri, 4 Sep 2026 17:16:49 +0200 Subject: [PATCH 26/28] mrbatch: Listenmodus beendet den Workout nicht mehr zu frueh, Progression-Sheet speichert trotz Store-Clone, Progression-aus auch bei Swap/Sheet, Stepper snappt nur auf dem Raster, exWeights erst beim Abschluss Aus dem Subagenten-Test der Workout-MRs: - !96 x !92: toggle() beurteilte die Einheit des Markers statt die des angetippten Satzes; im Listenmodus kam "That's the whole workout!" nach einem Satz einer anderen Uebung. - !77: Identitaetsvergleich scheitert an jedem Store-Clone (auch der Stangengewicht-Stepper im Sheet selbst) -> Vergleich auf Workout-Id, Listenlaenge und Uebung am Index. - !71: useTarget bei Progression 'aus' auch fuer swapActiveWorkoutExercise und das Progression-Sheet im Workout. - !84: stepWeight snappt nur, wenn der Wert schon auf dem Schrittraster liegt (62.5 +5 -> 67.5, nicht 70; 61.3 +1.25 -> 62.5 wie die Progression). - !92: exWeights werden nur noch beim Abschluss geschrieben (doFinishWorkout), nicht beim Abhaken - ein korrigierter Tippfehler oder ein verworfener Workout wird nie zum "Best". --- frontend/src/lib/progression.js | 8 +++++++- frontend/src/sheets.jsx | 2 +- frontend/src/views/Workout.jsx | 20 ++++++++++++++------ frontend/src/views/Workout.test.jsx | 17 ++++++++++++++++- 4 files changed, 38 insertions(+), 9 deletions(-) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index 636af32..48f36cc 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -87,8 +87,14 @@ export function snapWeight(v, step) { if (!(step > 0)) return round1(v) return round1(Math.round(v / step) * step) } +// A tap moves by one step. Snapping to the grid keeps the number identical to what progression +// would prescribe (61.3 → 62.5 with a 1.25 step, not 62.55) — but only when the current value +// already sits on that grid; from 62.5 with a 5 kg step a tap gives 67.5, not 70. export function stepWeight(value, step, direction) { - return Math.max(0, snapWeight((Number(value) || 0) + direction * step, step)) + const v = Number(value) || 0 + const onGrid = step > 0 && Math.abs(v - Math.round(v / step) * step) <= 0.1 + const next = v + direction * step + return Math.max(0, onGrid ? snapWeight(next, step) : round1(next)) } // Back off by DELOAD_FACTOR, landing on something you can actually load. Rounding to the // nearest step keeps the cut close to the intended 10 %, but on small weights the nearest diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 3b698b1..3b3af2e 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -851,7 +851,7 @@ export function swapActiveWorkoutExercise(index) { const freestyle = !st.active?.routineId const step = defaultIncrement(ex.id, st.unit) const plan = freestyle ? null : nextPrescription(st, full, st.routines.find(r => r.id === st.active.routineId)) - const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}) }) + const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}), ...(plan?.kind === 'off' ? { useTarget: true } : {}) }) const replacement = { id: ex.id, target: { ...cfg }, diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index f8bb8d9..3ee32d3 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -490,13 +490,17 @@ function ActiveWorkout() { if (!entry) return const activeId = state.active.id const entryId = entry.id + const entryCount = state.active.entries.length const routine = state.routines.find(r => r.id === state.active.routineId) exConfigSheet(exOr(entryId), entry.target, cfg => { // Store updates clone the state tree. If this exact object is no longer at the captured // index, the list changed while the sheet was open; an id check alone cannot distinguish // duplicate occurrences of the same exercise, so fail closed before cloning again. + // Every store write clones the tree (the bar-weight stepper inside this very sheet does + // one), so object identity is useless here. Same workout, same list length and the same + // exercise at the captured index is what "nothing shifted" means. const current = useStore.getState().S - if (current.active?.id !== activeId || current.active.entries?.[idx] !== entry) return + if (current.active?.id !== activeId || current.active.entries?.length !== entryCount || current.active.entries?.[idx]?.id !== entryId) return update(s => { const activeEntry = s.active?.id === activeId ? s.active.entries?.[idx] : null // The sheet may outlive its workout or entry. Never apply its result to whatever later @@ -511,7 +515,7 @@ function ActiveWorkout() { // The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are // rebuilt from the new config the way the session was, and only what you already logged // is kept in place (done warm-ups first, then done work sets, then the fresh remainder). - const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full) + const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step, useTarget: plan.kind === 'off' }), plan, step), full) const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x)) const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x)) const freshWarm = fresh.filter(isWarmupRow) @@ -577,13 +581,17 @@ function ActiveWorkout() { checked = e.sets[i].done if (e.sets[i].done) { beep(S.sound, 1040, 0.12); vibrate(30) - const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done)) + // The unit that owns the ticked set — not the marked one. Since !92 the marker no longer + // follows a finished exercise, and in list mode any exercise can be worked on, so judging + // the marker's unit here declared the workout complete after one set elsewhere. + const ownUnit = unitOf(units, idx) + const unitDone = ownUnit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done)) if (unitDone) workoutDone = !nextUnfinishedUnit(A.entries, supersetUnits(A.entries), idx) if (e.sets.every(x => x.done)) { exJustDone = true - const mx = bestWeightForEntry(e) - e.topW = mx || null - if (!s.active.backfill && mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: todayISO() } } + // topW is captured now; exWeights only at the finish (doFinishWorkout), so a typo you + // correct before finishing, or a discarded workout, never becomes the remembered best. + e.topW = bestWeightForEntry(e) || null } } }, true) diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index da60275..ce1a157 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -219,7 +219,7 @@ describe('Workout set completion flow', () => { await toggleSet(0) expect(mocks.S.active.entries[0].topW).toBe(60) - expect(mocks.S.exWeights['plain-bench'].w).toBe(60) + expect(mocks.S.exWeights['plain-bench']).toBeUndefined() // written at the finish, not while ticking expect(mocks.topWeightSheet).not.toHaveBeenCalled() expect(mocks.S.active.cur).toBe(0) expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) @@ -903,6 +903,21 @@ describe('workout list view', () => { expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) }) + it('does not declare the workout complete after a set of a non-current exercise while sets remain', async () => { + // The marker stays on the finished bench (!92); ticking the first of three row sets must + // not open the completion sheet — the row's own unit still has two sets to go. + await mount([ + exercise('plain-bench', [true], { asked: true }), + exercise('plain-row', [false, false, false], { asked: true }), + ], 0, { workoutView: 'list' }) + + await toggleSet(1) + + expect(mocks.S.active.entries[1].sets[0].done).toBe(true) + expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() + expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number)) + }) + it('renders a superset as one grouped unit with its own unpair control', async () => { await mount([ exercise('bench', [false], { sg: 'g1', asked: true }), From dafc80f1d641a9dd8034a9b6e08977c96674d874 Mon Sep 17 00:00:00 2001 From: Konstantinos Thermos Date: Fri, 4 Sep 2026 18:46:39 +0300 Subject: [PATCH 27/28] Coach: the create schema requires a routine id and a week MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CREATE_SCHEMA is handed to OpenAI-compatible endpoints as a grammar to decode against, and it left both `routines[].id` and `week` optional. Small local models take that offer: llama3.2:3b and qwen2.5:3b both answer with routines that carry no id, and a week naming what they wrote into `name` instead. Nothing in the week then resolves, validate.js reports "the week schedules 0 days but 3 were asked for", the repair round produces the same answer again, and the job ends as `unusable` — "The Coach answered with something the app couldn't use." Requiring the two fields the week resolves through is enough. With them in the schema, llama3.2:3b produces a plan that passes validatePlan on the first attempt, against the payload that failed twice before. The validator is untouched; this only stops the grammar from offering an answer it can never accept. --- api/coach/core/schemas.js | 9 +++++++-- api/test/prompt-split.test.js | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/api/coach/core/schemas.js b/api/coach/core/schemas.js index 9779e73..072c58f 100644 --- a/api/coach/core/schemas.js +++ b/api/coach/core/schemas.js @@ -59,6 +59,11 @@ const EX_SCHEMA = { required: ['id', 'sets'] }; +// `week` and `routines[].id` are required, not optional: the week is the only thing that says +// which day trains which routine, and it points at a routine by id. A schema that leaves either +// out lets a small local model answer with routines that have no id and a week naming "r1" — +// grammar-valid, and something validate.js can only ever reject ("the week schedules 0 days but +// 3 were asked for"), through the repair round and out as a failed job. export const CREATE_SCHEMA = { type: 'object', properties: { @@ -75,7 +80,7 @@ export const CREATE_SCHEMA = { id: STR, name: STR, emoji: STR, prog: STR, why: STR, ex: { type: 'array', items: EX_SCHEMA } }, - required: ['name', 'ex'] + required: ['id', 'name', 'ex'] } }, customEx: { @@ -83,7 +88,7 @@ export const CREATE_SCHEMA = { items: { type: 'object', properties: { id: STR, n: STR, bp: STR, desc: STR }, required: ['id', 'n'] } } }, - required: ['coach_contract', 'routines'] + required: ['coach_contract', 'week', 'routines'] }; export const DEBRIEF_SCHEMA = { diff --git a/api/test/prompt-split.test.js b/api/test/prompt-split.test.js index 1b0072b..aea87c9 100644 --- a/api/test/prompt-split.test.js +++ b/api/test/prompt-split.test.js @@ -4,6 +4,7 @@ import { buildPrompt, buildPromptParts, taskOf } from '../coach/core/prompt.js'; import { SCHEMAS } from '../coach/core/schemas.js'; import { build, FULL_DETAIL_SESSIONS } from '../coach/core/payload.js'; import { chatCompletionsSpec } from '../coach/core/adapters/openai.js'; +import { validatePlan } from '../coach/core/validate.js'; const S = (workouts = []) => ({ lang: 'en', unit: 'kg', routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 8 }] }], @@ -48,6 +49,25 @@ test('every task has a flat schema — no $ref, no anyOf/oneOf (llama.cpp gramma assert.equal(taskOf('create', { refine: 'x' }), 'refine'); }); +test('the create schema requires what the week resolves through: a routine id, and a week', () => { + // A schema handed to a grammar-constrained decoder is the only thing standing between a small + // local model and an answer the validator can only reject. These two fields are where that + // showed: llama3.2:3b and qwen2.5:3b both answer with routines that carry no `id` and a week + // naming what they put in `name`, which costs a job and a repair round to find out. + assert.ok(SCHEMAS.create.properties.routines.items.required.includes('id')); + assert.ok(SCHEMAS.create.required.includes('week')); + assert.equal(SCHEMAS.refine, SCHEMAS.create); // refine reuses it, same guarantee + + const noId = { + coach_contract: 1, + routines: [{ name: 'r1', ex: [{ id: '0001', sets: 3, reps: 8 }] }], + week: { 1: 'r1' } + }; + const checked = validatePlan(noId, { daysPerWeek: 1 }); + assert.ok(!checked.ok); + assert.ok(checked.errors.some(e => e.includes('week[1] points at "r1"'))); +}); + test('older sessions in a review window are compacted, the recent ones keep full sets', () => { const many = Array.from({ length: FULL_DETAIL_SESSIONS + 4 }, (_, i) => workout('2026-08-' + String(i + 1).padStart(2, '0'))); const p = build(S(many), { handle: 'h1', kind: 'review' }); From 673054984510630b77547a2f17ccf568c55c7aa0 Mon Sep 17 00:00:00 2001 From: Konstantinos Thermos Date: Fri, 4 Sep 2026 18:58:23 +0300 Subject: [PATCH 28/28] Coach: cap the plan arrays in the schema, not only in the prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit create.md asks for "1-7 routines, each 3-12 exercises" and validate.js slices at MAX_ROUTINES / MAX_EX_PER_ROUTINE, but the schema the endpoint decodes against had no bound at all. A model that starts repeating itself never reaches the validator: qwen2.5:3b walks the library id by id, three sets of eight apiece, until it exhausts the 16k output limit — twelve minutes for an answer that arrives truncated, which the adapter turns into "the answer was cut off at the output limit" and a job that would already have hit COACH_JOB_TIMEOUT_MS. maxItems on the two arrays states the caps that already exist, where the decoder can enforce them. --- api/coach/core/schemas.js | 9 ++++++++- api/test/prompt-split.test.js | 7 +++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/api/coach/core/schemas.js b/api/coach/core/schemas.js index 072c58f..163b457 100644 --- a/api/coach/core/schemas.js +++ b/api/coach/core/schemas.js @@ -72,13 +72,20 @@ export const CREATE_SCHEMA = { summary: STR, basedOn: STR, week: { type: 'object' }, + // The caps are the validator's own (MAX_ROUTINES, MAX_EX_PER_ROUTINE), stated here as well + // because "1-7 routines, each 3-12 exercises" in create.md is only a request. A small model + // that starts repeating itself does not stop at a request: qwen2.5:3b walks the library id by + // id, three sets of eight apiece, until it hits the output limit — twelve minutes for an + // answer that arrives cut in half and cannot be parsed. maxItems ends that run at seven + // routines instead. routines: { type: 'array', + maxItems: 7, items: { type: 'object', properties: { id: STR, name: STR, emoji: STR, prog: STR, why: STR, - ex: { type: 'array', items: EX_SCHEMA } + ex: { type: 'array', maxItems: 20, items: EX_SCHEMA } }, required: ['id', 'name', 'ex'] } diff --git a/api/test/prompt-split.test.js b/api/test/prompt-split.test.js index aea87c9..deb80c3 100644 --- a/api/test/prompt-split.test.js +++ b/api/test/prompt-split.test.js @@ -68,6 +68,13 @@ test('the create schema requires what the week resolves through: a routine id, a assert.ok(checked.errors.some(e => e.includes('week[1] points at "r1"'))); }); +test('the create schema caps the two arrays the validator caps, so a repeating model stops', () => { + // validate.js slices at MAX_ROUTINES / MAX_EX_PER_ROUTINE; a model that never stops emitting + // otherwise runs to the output limit first and the answer arrives truncated and unparseable. + assert.equal(SCHEMAS.create.properties.routines.maxItems, 7); + assert.equal(SCHEMAS.create.properties.routines.items.properties.ex.maxItems, 20); +}); + test('older sessions in a review window are compacted, the recent ones keep full sets', () => { const many = Array.from({ length: FULL_DETAIL_SESSIONS + 4 }, (_, i) => workout('2026-08-' + String(i + 1).padStart(2, '0'))); const p = build(S(many), { handle: 'h1', kind: 'review' });