Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Log a past workout: the session is built from the workouts before its day, so a missed Monday logged after Friday no longer opens at Friday's progression, and its last-time and best-set lines read from before that day too (#284)
Duarte Santosc808195a477e
diff --git a/frontend/src/lib/backfill.js b/frontend/src/lib/backfill.jsindex 8d250004d..3bf26aa6a 100644--- a/frontend/src/lib/backfill.js+++ b/frontend/src/lib/backfill.js@@ -18,6 +18,28 @@ export const backfillStart = (iso, time = '18:00') => {// A live session ends when you tap finish; a logged one ends when you said it did.export const backfillEnd = active => active.start + Math.max(1, active.backfill?.durationMin || 60) * 60000+// The history a session logged into the past is built from (#284): only what came before it.+// Built from the whole log, "Log this workout" for a missed Monday opened at the weights Friday's+// session had progressed to and saved them as Monday's — a spike on the chart, and a best set dated+// days before it was lifted. A session sits where insertChronological files it, so everything filed+// ahead of that spot is its past: earlier days, and earlier the same day. The workout it replaces+// is not, since that one is gone once this is saved. A confirmed working weight (exWeights) dated+// after the day is later progression as well; one with no date is kept, nothing says when it came.+// A view for reading only: the lists are new, everything else is S's own.+export function historyAsOf(S, { d, start = 0, replaceId = null }) {+ const filedBefore = w => (w.d || '') < d || ((w.d || '') === d && (w.start || 0) <= start)+ const workouts = (S.workouts || []).filter(w => filedBefore(w) && !(replaceId && w.id === replaceId))+ const exWeights = Object.fromEntries(Object.entries(S.exWeights || {}).filter(([, kept]) => !kept?.d || kept.d <= d))+ return { ...S, workouts, exWeights }+}++// The history the running session is built from and held against: as of its own day while it is+// logged into the past, and the whole log for a live one (S itself, so that costs nothing).+export const sessionHistory = S => {+ const A = S?.active+ return A?.backfill ? historyAsOf(S, { d: A.d, start: A.start, replaceId: A.backfill.replaceId }) : S+}+// The workouts array is chronological (History reverses it), so a past workout cannot just be// pushed — it goes where its date and start time put it, after anything from the same moment.export function insertChronological(workouts, w) {diff --git a/frontend/src/lib/backfill.test.js b/frontend/src/lib/backfill.test.jsindex 78a8372c3..9dbe5f867 100644--- a/frontend/src/lib/backfill.test.js+++ b/frontend/src/lib/backfill.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { workoutsOn, backfillStart, backfillEnd, insertChronological, completeBackfill, markAllSetsDone } from './backfill.js'+import { workoutsOn, backfillStart, backfillEnd, insertChronological, completeBackfill, markAllSetsDone, historyAsOf, sessionHistory } from './backfill.js'const w = (id, d, start = 0) => ({ id, d, start })@@ -58,6 +58,48 @@ describe('completeBackfill', () => {})})+// #284: a missed Monday logged on Saturday opened at Friday's progression and saved it as Monday's.+// What a session logged into the past is built from is the history filed ahead of it.+describe('historyAsOf', () => {+ const list = [w('a', '2026-01-01', 10), w('b', '2026-01-05', 10), w('c', '2026-01-05', 20), w('d', '2026-01-09', 10)]+ const S = { unit: 'kg', workouts: list, exWeights: { bench: { w: 100, d: '2026-01-09' }, row: { w: 60, d: '2026-01-02' }, curl: { w: 12 } } }++ it('keeps what is filed ahead of the session: earlier days, and earlier the same day', () => {+ expect(historyAsOf(S, { d: '2026-01-05', start: 15 }).workouts.map(x => x.id)).toEqual(['a', 'b'])+ expect(historyAsOf(S, { d: '2026-01-05', start: 20 }).workouts.map(x => x.id)).toEqual(['a', 'b', 'c'])+ expect(historyAsOf(S, { d: '2026-01-03' }).workouts.map(x => x.id)).toEqual(['a'])+ expect(historyAsOf(S, { d: '2025-12-31' }).workouts).toEqual([])+ })++ it('leaves out the workout being replaced', () => {+ expect(historyAsOf(S, { d: '2026-01-05', start: 30, replaceId: 'b' }).workouts.map(x => x.id)).toEqual(['a', 'c'])+ })++ it('drops a working weight confirmed after the day, and keeps one that carries no date', () => {+ expect(historyAsOf(S, { d: '2026-01-05', start: 15 }).exWeights).toEqual({ row: { w: 60, d: '2026-01-02' }, curl: { w: 12 } })+ })++ it('reads without writing: S keeps its history, and everything else comes through', () => {+ const view = historyAsOf(S, { d: '2026-01-03' })+ expect(S.workouts).toHaveLength(4)+ expect(Object.keys(S.exWeights)).toHaveLength(3)+ expect(view.unit).toBe('kg')+ expect(historyAsOf({}, { d: '2026-01-03' })).toMatchObject({ workouts: [], exWeights: {} })+ })+})++describe('sessionHistory', () => {+ const list = [w('a', '2026-01-01', 10), w('b', '2026-01-05', 10), w('d', '2026-01-09', 10)]++ it('is the whole state for a live session, and the history before the day for a logged one', () => {+ const live = { workouts: list, exWeights: {}, active: { d: '2026-01-10', start: 99 } }+ expect(sessionHistory(live)).toBe(live)+ const past = { workouts: list, exWeights: {}, active: { d: '2026-01-05', start: 50, backfill: { durationMin: 60, replaceId: 'b' } } }+ expect(sessionHistory(past).workouts.map(x => x.id)).toEqual(['a'])+ expect(sessionHistory({ workouts: list })).toEqual({ workouts: list })+ })+})+// #284: a past session that went as planned is logged with one tap instead of one per set.describe('markAllSetsDone', () => {it('ticks every row, warm-ups and both sides of a unilateral set included, and stamps the top weight', () => {diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex 6d048a872..c1aea72b4 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -38,7 +38,7 @@ import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheetimport { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'import { buildSessionEntries, buildPlannedEntry, builtOutOfProgression } from './lib/session-start.js'import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'-import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'+import { workoutsOn, backfillStart, backfillEnd, completeBackfill, historyAsOf, sessionHistory } from './lib/backfill.js'import { moveWorkout, sameWorkout, startTimeOf, durationMinOf, setWorkoutDuration } from './lib/workout-date.js'import { editCompletedSession } from './lib/session-edit.js'import { stampWorkout } from './lib/sync-merge.js'@@ -1095,10 +1095,12 @@ export function swapActiveWorkoutExercise(index) {const freestyle = !slotRoutine// Same rows the add flow builds: last time's loads and, in a planned session, the// prescription — swapping barbell for dumbbell bench must not start you at an empty bar.+ // Built from what came before the session's day when it is logged into the past (sessionHistory).const step = modeOf(full) === 'reps' ? weightIncrement(full, st.unit) : defaultIncrement(ex.id, st.unit)+ const past = sessionHistory(st)const built = freestyle- ? { target: { ...cfg }, plan: null, sets: applyIntensifierPlan(buildSets(st, full, { step, preferLast: true }), full) }- : buildPlannedEntry(st, full, slotRoutine, { noProg: builtOutOfProgression(current, slotRoutine) })+ ? { target: { ...cfg }, plan: null, sets: applyIntensifierPlan(buildSets(past, full, { step, preferLast: true }), full) }+ : buildPlannedEntry(past, full, slotRoutine, { noProg: builtOutOfProgression(current, slotRoutine) })const replacement = {id: ex.id,...built,@@ -2131,12 +2133,16 @@ export function logPastWorkoutSheet(initial) {// A backfilled session is built the way a live one is (buildCombinedEntries → buildPlannedEntry),// so its entries carry the same stamps: the routine list, per-entry rid and the plan, no// top-level routineId. One routine from the picker, or every routine of a missed combined day.+// Only from the history before that day (historyAsOf): a session logged later must not hand its+// progression back to the day it skipped.function beginBackfill({ iso, time, durationMin, routineIds, replaceId }) {const st = S()- const { entries, routineIds: rids, routines } = buildCombinedEntries(st, routineIds || [])+ const start = backfillStart(iso, time)+ const past = historyAsOf(st, { d: iso, start, replaceId })+ const { entries, routineIds: rids, routines } = buildCombinedEntries(past, routineIds || [])update(s => {s.active = {- id: uid(), d: iso, start: backfillStart(iso, time),+ id: uid(), d: iso, start,routineIds: rids,name: routines.length ? deriveSessionName(routines.map(r => r.name)) : t('Freestyle'),bw: null, cur: 0, entries,@@ -2160,7 +2166,7 @@ function AddRoutineToSession({ close }) {if (!active) return nullconst inSession = new Set([].concat(active.routineIds || []))const add = r => {- const entries = buildSessionEntries(st, r).map(e => ({ ...e, rid: r.id }))+ const entries = buildSessionEntries(sessionHistory(st), r).map(e => ({ ...e, rid: r.id }))update(s => {if (!s.active) returns.active.entries.push(...entries)diff --git a/frontend/src/sheets.missed-day.test.jsx b/frontend/src/sheets.missed-day.test.jsxindex 92d32478f..7b66a9a52 100644--- a/frontend/src/sheets.missed-day.test.jsx+++ b/frontend/src/sheets.missed-day.test.jsx@@ -117,6 +117,24 @@ describe('logging a missed planned day', () => {expect(w.entries[0].planned).toMatchObject({ sets: 2, reps: 10 })})+ // Review of #284: Monday missed, the routine trained again on Tuesday, Monday logged on+ // Wednesday. Built from the whole log, Monday opened at the weight Tuesday had progressed to and+ // was saved with it, filed ahead of Tuesday: a spike on the chart and a best set dated a day early.+ it('builds a missed day from the sessions before it, not from one logged after it', () => {+ const pushed = (id, d, w) => ({+ id, d, start: new Date(d + 'T18:00:00').getTime(), end: new Date(d + 'T19:00:00').getTime(), name: 'Push',+ routineIds: ['A'], prs: [], entries: [{ id: BENCH, rid: 'A', target: { sets: 2, reps: 10, weight: w, mode: 'reps' },+ planned: { sets: 2, reps: 10, weight: 50 }, sets: [{ w, r: 10, done: true }, { w, r: 10, done: true }] }],+ })+ install({ workouts: [pushed('fri', '2026-09-11', 50), pushed('tue', '2026-09-15', 52.5)] })+ dayOverrideSheet('2026-09-14')+ tapInTopSheet('Log this workout')+ tapInTopSheet('Continue')+ const bench = S().active.entries.find(e => e.id === BENCH)+ expect(bench.sets.filter(s => s.phase !== 'warmup').map(s => s.w)).toEqual([52.5, 52.5])+ expect(bench.target.weight).toBe(52.5)+ })+it('still refuses while a workout is running', () => {const toast = vi.fn()useUI.setState({ toast })diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex bc7e68d08..e7b95d000 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -22,7 +22,7 @@ import { defaultIncrement, weightIncrement, stepWeight } from '../lib/progressioimport { progressionGuidance } from '../lib/progression-copy.js'import { buildPlannedEntry, plannedConfigOf, builtOutOfProgression } from '../lib/session-start.js'import { glyphOf } from '../lib/glyphs.js'-import { markAllSetsDone } from '../lib/backfill.js'+import { markAllSetsDone, sessionHistory } from '../lib/backfill.js'import { bestSetFor } from '../lib/exercise-history.js'import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps, isSideSet, makeSideSet, setSideField, toggleSide, addSideDrop, removeSideDropAt, setSideDropAt, addSideCluster, removeSideClusterAt, setSideClusterAt, WEIGHT_ORIGIN_MANUAL } from '../lib/workout-model.js'import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'@@ -149,9 +149,12 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSiconst mode = modeOf({ ...(entry.target || {}), id: entry.id })const cardio = mode === 'cardio'const timed = mode === 'time'+ // The history the rows were built from: before the session's day when it is logged into the+ // past (sessionHistory), so "last time", the best set and the Best chip are not from later on.+ const H = sessionHistory(S)// The routine's own last session of this exercise (or any, for a routine that has none), the// same one the rows and the progression line were built from (#216).- const last = lastEntryFor(S, entry.id, entry.rid)+ const last = lastEntryFor(H, entry.id, entry.rid)const standingNote = exNoteFor(S, entry.id)// Only worth surfacing while there is still work left: once the exercise is finished, a note// telling you what to do in it is behind you, and the block is already long.@@ -159,8 +162,8 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi// The number is the heaviest logged set, or the working weight you kept.// On an assistance machine the best is the least help, and a 0 on either side means "nothing// logged" rather than a record (issue #232).- const bestHist = bestWeightFor(S, entry.id)- const bestKept = (S.exWeights[entry.id] || {}).w || 0+ const bestHist = bestWeightFor(H, entry.id)+ const bestKept = (H.exWeights[entry.id] || {}).w || 0const best = cardio ? 0: bestHist > 0 && bestKept > 0 ? betterWeight(entry.id, bestHist, bestKept) : Math.max(bestHist, bestKept)// What the progression policy decided for this session, and why (issue #17). Computed when@@ -192,7 +195,7 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi// the number to beat. Tapping the line switches between the two, and the choice is the// profile's (S.logRef), so every exercise and the next session follow it.const refBest = S.logRef === 'best'- const ref = refBest ? bestSetFor(S, entry.id, mode) : last+ const ref = refBest ? bestSetFor(H, entry.id, mode) : last// An exercise logged before only in another mode (reps then, a hold today) has a last time but// no best set to hold today's rows against. The line stays and says so: gone, it took the// switch back to "Last time" with it, reachable then only from Settings or another card.@@ -917,11 +920,12 @@ function ActiveWorkout() {if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1// The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are// rebuilt from the new config exactly the way the session start builds them (same reps- // source, same prescription, same stamped target), and only what you already logged is+ // source, same prescription, same stamped target, and in a workout logged into the past the+ // same history from before its day), and only what you already logged is// kept in place (done warm-ups first, then done work sets, then the fresh remainder).// Without a prescription only in a routine kept out of progression: an exercise kept out// by hand keeps its prescription, so its Undo leaves the numbers it should count at.- const built = buildPlannedEntry(s, full, activeRoutine, { noProg: builtOutOfProgression(activeEntry, activeRoutine) })+ const built = buildPlannedEntry(sessionHistory(s), full, activeRoutine, { noProg: builtOutOfProgression(activeEntry, activeRoutine) })const fresh = built.setsconst doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x))const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x))@@ -1308,16 +1312,18 @@ function ActiveWorkout() {// Freestyle has no routine prescription to apply: show the last target in the config// 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+ const seed = freestyle ? freestyleConfig(sessionHistory(S), { id: ex.id, ...defaultConfig(ex.id) }) : nullconst commit = cfg => update(s => {const full = { ...cfg, id: ex.id }// A planned session builds the exercise the way its routine would (prescription, reps// source, target); freestyle reproduces what you did last time.+ // Read from before the session's day when it is logged into the past (sessionHistory).+ const past = sessionHistory(s)const built = freestyle- ? { target: { ...cfg }, plan: null, sets: applyIntensifierPlan(buildSets(s, full, {+ ? { target: { ...cfg }, plan: null, sets: applyIntensifierPlan(buildSets(past, full, {step: modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit), preferLast: true,}), full) }- : buildPlannedEntry(s, full, routine, { noProg })+ : buildPlannedEntry(past, full, routine, { noProg })const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length)s.active.entries.splice(insertAt, 0, { id: ex.id, ...built, ...(curRid ? { rid: curRid } : {}), ...(noProg ? { noProg: true } : {}) })s.active.cur = insertAtdiff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsxindex 97cff728e..bc492847e 100644--- a/frontend/src/views/Workout.test.jsx+++ b/frontend/src/views/Workout.test.jsx@@ -576,6 +576,19 @@ describe('adding an exercise to a block kept out of progression', () => {expect(added.sets.map(s => s.w)).toEqual([102.5])})+ // #284 review: an exercise added to a workout logged into the past is built from what came+ // before that day, like the rest of it, not from a session logged after it.+ it('builds an exercise added to a workout logged into the past from the history before its day', async () => {+ const later = [...history, {+ d: '2026-08-31', routineIds: ['main'],+ entries: [{ id: BENCH, rid: 'main', target: { sets: 1, reps: 5, weight: 102.5 }, sets: [{ w: 102.5, r: 5, done: true }] }],+ }]+ const past = { d: '2026-08-29', start: Date.parse('2026-08-29T18:00:00'), backfill: { durationMin: 60, replaceId: null } }+ await mount([exercise('row', [false], { rid: 'main' })], 0, { routines, workouts: later, active: past })+ await addExerciseThroughSheets({ id: BENCH }, { mode: 'reps', sets: 1, reps: 5, weight: 40 })+ expect(mocks.S.active.entries[1].sets.map(s => s.w)).toEqual([102.5])+ })+it('does not pass on an exercise kept out by hand for today (its ⋯ menu)', async () => {await mount([exercise('row', [false], { rid: 'main', noProg: true })], 0, { routines, workouts: history })await addExerciseThroughSheets({ id: BENCH }, { mode: 'reps', sets: 1, reps: 5, weight: 40 })@@ -1953,6 +1966,19 @@ describe('the reference line: last time or best set', () => {expect(line().textContent).toMatch(/^Last time \(.+\): 0:30$/)})+ // #284 review: a workout logged into the past is held against what came before its day, the+ // history its rows were built from, not against a session logged after it.+ it('reads the history before the day of a workout logged into the past', async () => {+ const later = [...history, session('2026-08-28', 'A', 90, 3)]+ const past = { d: '2026-08-25', start: Date.parse('2026-08-25T18:00:00'), backfill: { durationMin: 60, replaceId: null } }+ await mount([exercise('plain-bench', [false], { rid: 'A' })], 0, { workouts: later, active: past })+ expect(line().textContent).toMatch(/^Last time \(.+\): 60×10$/)+ await act(async () => { line().dispatchEvent(new dom.Event('click', { bubbles: true })) })+ await rerender()+ expect(line().textContent).toMatch(/^Best set \(.+\): 80×5$/)+ expect(container.textContent).toContain('Best: 80 kg')+ })+// The text is the reference; the name also says what a tap does, after the text it shows.it('names the switch a tap makes', async () => {await mount([exercise('plain-bench', [false], { rid: 'A' })], 0, { workouts: history })