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
rotation: the in-app sequence, its pass helpers, and the finish-workout refill, with tests
giulioleuci5ad4f774b164
diff --git a/frontend/src/lib/rotation.js b/frontend/src/lib/rotation.jsnew file mode 100644index 000000000..373292dc1--- /dev/null+++ b/frontend/src/lib/rotation.js@@ -0,0 +1,153 @@+// Rotation — the in-app half of the queue (lib/queue.js).+//+// S.rotation = null | { id: string, sequence: string[], label: string }+//+// `S.rotation` is a DEFINITION, never a live queue: what the calendar, the reminders and the MCP+// resolve is always `S.queue`. `scheduleModeOf` is Home/Plan's own display choice: a live queue+// always wins regardless of `S.scheduleMode` (an external writer never has to know the flag+// exists), and the flag itself exists only to hold Rotation selected — weekday grid hidden, both+// screens showing the rotation editor — from the moment it is chosen through to the first+// routine being added, since there is no queue yet at that point to derive anything from.+//+// OWNERSHIP — `S.queue.rotationId === S.rotation.id` marks a pass this app manages: only such a+// pass refills itself when it completes. A planner's queue omits `rotationId`, so it completes+// and waits for its writer; saving it from Plan's editor adopts it (stamps the id) and opts it+// into refill from that point on. The token also stops a stale saved rotation from reclaiming+// somebody else's queue that happens to hold the same routine ids.+//+// THE ONE-DAY BOUNDARY — a new pass created by a completion starts the day AFTER the workout+// that closed the old one. The done rule (queue.js) credits a workout dated on or after+// `startsOn` whose name matches the routine even when its `start` predates `since` — the+// fallback for an early or unreliable clock. Without the boundary the session that finished the+// old pass would immediately tick an item of the new one.++import { isoOf, todayISO, uid } from './format.js'+import { queueOf, queueView } from './queue.js'++const routineIdsOf = w => (Array.isArray(w?.routineIds) ? w.routineIds : (w?.routineId ? [w.routineId] : []))+const dayAfter = iso => { const d = new Date(iso + 'T12:00:00'); d.setDate(d.getDate() + 1); return isoOf(d) }++/** 'rotation' while a usable live queue exists, or once chosen with nothing built yet (S.scheduleMode). */+export const scheduleModeOf = S => (queueOf(S) || S?.scheduleMode === 'rotation') ? 'rotation' : 'week'++/** A queue payload arrived but is unusable (malformed, duplicate-only, all-deleted): Week + a fix-up in Plan. */+export const queueRecovery = S => S?.queue != null && !queueOf(S)++/** The saved sequence's routines that still exist, first occurrence of each — the ids a new pass gets. */+export const rotationIds = S => {+ const seq = Array.isArray(S?.rotation?.sequence) ? S.rotation.sequence : []+ const routines = Array.isArray(S?.routines) ? S.routines : []+ return seq.filter((id, i) => seq.indexOf(id) === i && routines.some(r => r.id === id))+}++const newPass = (ids, label, rotationId, startsOn, since) => ({ ids, since, startsOn, label, rotationId })++/** Workouts that could have credited `q`'s pass: dated on/after its startsOn, matching one of its ids. */+const creditWindow = (s, q) => (s.workouts || [])+ .filter(w => String(w.d || '') >= q.startsOn && routineIdsOf(w).some(id => q.ids.includes(id)))++/**+ * `now`, or later still when a workout already in the credit window would otherwise re-credit+ * the new pass — a backdated or future-clock finish, or one just written by the caller. The done+ * rule's first clause is `w.start >= since` with no date bound of its own, so `since` is the only+ * thing keeping an old pass's own workouts from also ticking the new one.+ */+const sinceAfter = (s, q, now) => Math.max(now, ...creditWindow(s, q).map(w => (w.start ?? 0) + 1))++/** Settings → Rotation with a saved rotation and no queue. False when nothing valid is left to start. */+export function startPass(s, today = todayISO(), now = Date.now()) {+ const ids = rotationIds(s)+ if (!ids.length) return false+ s.queue = newPass(ids, s.rotation.label || '', s.rotation.id, today, now)+ return true+}++/**+ * Plan's editor save: create the rotation on the first save, adopt an externally written queue,+ * or apply an ordinary edit. An edit keeps the running pass's `since`/`startsOn`, and the done+ * rule is by routine id since `since`, so progress already logged survives a reorder — and an id+ * added back after it was already trained today reads as done straight away.+ */+export function saveRotation(s, ids, label, today = todayISO(), now = Date.now()) {+ if (!ids.length) return+ const prev = queueOf(s)+ s.rotation = { id: s.rotation?.id ?? uid(), sequence: ids, label }+ s.queue = {+ ids,+ since: prev?.since ?? now,+ startsOn: prev?.startsOn ?? today,+ label,+ rotationId: s.rotation.id,+ }+ // A session dropped from the rotation leaves its future pin behind otherwise — dayPlan then+ // still resolves that date to a session the queue no longer has (pinState/queue.js).+ const removed = (prev?.ids || []).filter(id => !ids.includes(id))+ if (removed.length) {+ Object.keys(s.dayPlan || {}).forEach(iso => {+ if (iso >= today && removed.includes(s.dayPlan[iso])) delete s.dayPlan[iso]+ })+ }+ // An edit (e.g. removing the last session still to do) can leave the pass complete on the+ // spot — without this it would sit idle until a workout happened to reach refillAfter.+ if (queueView(s, today)?.complete) startNewPass(s, today, now)+}++/** The latest day a workout could have credited the current pass, or null. */+const lastCreditDay = s => {+ const q = queueOf(s)+ if (!q) return null+ const days = (s.workouts || [])+ .filter(w => routineIdsOf(w).some(id => q.ids.includes(id)) && String(w.d || '') >= q.startsOn)+ .map(w => w.d)+ return days.length ? days.sort().at(-1) : null+}++/**+ * Plan's "Start new pass": throw the current pass away and begin the saved sequence again. From+ * today — unless today's own workout closed the pass being replaced, which would otherwise be+ * credited twice (see THE ONE-DAY BOUNDARY above).+ */+export function startNewPass(s, today = todayISO(), now = Date.now()) {+ if (!s.rotation) return+ const ids = rotationIds(s)+ if (!ids.length) return+ const q = queueOf(s)+ const last = lastCreditDay(s)+ const startsOn = last && last >= today ? dayAfter(last) : today+ s.queue = newPass(ids, s.rotation.label || '', s.rotation.id, startsOn, q ? sinceAfter(s, q, now) : now)+}++/** Is `ids` some circular ordering of `seq`? (Both already normalized, so ids are unique.) */+const isCircular = (ids, seq) => {+ if (!ids.length || ids.length !== seq.length) return false+ const i = seq.indexOf(ids[0])+ return i >= 0 && ids.every((id, n) => seq[(i + n) % seq.length] === id)+}++/** `seq` rotated to begin just after `afterId`; unchanged when the id is not in it. */+const rotate = (seq, afterId) => {+ const i = seq.indexOf(afterId)+ return i < 0 ? seq : [...seq.slice(i + 1), ...seq.slice(0, i + 1)]+}++/**+ * Called with the state a finished workout has just been written into. Replaces a COMPLETE pass+ * this app manages with the next one and returns true; returns false — leaving `S.queue`+ * untouched — for an incomplete pass, a queue with no matching `rotationId`, or a managed pass+ * that no longer matches its rotation (the editor will resync it on the next save).+ *+ * The next pass is the rotation, rotated so it begins after the final queue id this workout+ * credited: `[A,B,C]` closed by C repeats as `[A,B,C]`, closed by B becomes `[C,A,B]`.+ */+export function refillAfter(s, w, today = todayISO(), now = Date.now()) {+ const q = queueOf(s)+ if (!q?.rotationId || !s.rotation?.id || q.rotationId !== s.rotation.id) return false+ if (!queueView(s, today)?.complete) return false+ const seq = rotationIds(s)+ if (!isCircular(q.ids, seq)) return false+ const credited = routineIdsOf(w)+ const last = q.ids.filter(id => credited.includes(id)).at(-1) ?? null+ const bound = [w.d, lastCreditDay(s)].filter(Boolean).sort().at(-1)+ s.queue = newPass(rotate(seq, last), s.rotation.label || q.label || '', s.rotation.id, dayAfter(bound), sinceAfter(s, q, now))+ return true+}diff --git a/frontend/src/lib/rotation.test.js b/frontend/src/lib/rotation.test.jsnew file mode 100644index 000000000..354355ece--- /dev/null+++ b/frontend/src/lib/rotation.test.js@@ -0,0 +1,232 @@+import { describe, it, expect } from 'vitest'+import { scheduleModeOf, queueRecovery, rotationIds, startPass, saveRotation, startNewPass, refillAfter } from './rotation.js'+import { queueRemaining, queueView } from './queue.js'++const routines = [{ id: 'a', name: 'A' }, { id: 'b', name: 'B' }, { id: 'c', name: 'C' }, { id: 'own', name: 'Core' }]+const TODAY = '2026-09-12'+const NOW = Date.parse(TODAY + 'T10:00:00')++// today/now are passed straight into the functions under test (see rotation.js), so none of+// this needs the system clock or fake timers at all.+const S = (over = {}) => ({ routines, workouts: [], week: {}, dayPlan: {}, queue: null, rotation: null, ...over })+// A finished workout on routine `id`, dated `d`. `start` defaults comfortably before NOW — not+// equal to it — so a fixture accidentally sitting exactly on a new pass's `since` never masks a+// real off-by-one in the boundary it's meant to test.+const w = (id, d, start = NOW - 1000) => ({ id: 'w-' + id + d, d, start, routineIds: [id], routineId: id, name: routines.find(r => r.id === id).name, entries: [] })+const pass = (ids, over = {}) => ({ ids, since: NOW - 86400000, startsOn: '2026-09-10', label: 'Rotation', ...over })++describe('the selected mode is derived from the live queue', () => {+ it('no usable queue is Fixed Week; a usable one is Rotation', () => {+ expect(scheduleModeOf(S())).toBe('week')+ expect(scheduleModeOf(S({ queue: pass(['a', 'b']) }))).toBe('rotation')+ // a saved rotation alone schedules nothing+ expect(scheduleModeOf(S({ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'Rotation' } }))).toBe('week')+ })++ it('a malformed queue is Week plus recovery, never Rotation', () => {+ const st = S({ queue: { ids: ['gone'], since: NOW } })+ expect(scheduleModeOf(st)).toBe('week')+ expect(queueRecovery(st)).toBe(true)+ expect(queueRecovery(S())).toBe(false)+ expect(queueRecovery(S({ queue: pass(['a']) }))).toBe(false)+ })+})++describe('starting a pass from a saved rotation', () => {+ it('starts today, from the rotation ids that still exist, stamped with the rotation id', () => {+ const s = S({ rotation: { id: 'r1', sequence: ['a', 'gone', 'b', 'a'], label: 'My split' } })+ expect(startPass(s, TODAY, NOW)).toBe(true)+ expect(s.queue).toEqual({ ids: ['a', 'b'], since: NOW, startsOn: TODAY, label: 'My split', rotationId: 'r1' })+ })++ it('does nothing when no rotation routine survives', () => {+ const s = S({ rotation: { id: 'r1', sequence: ['gone'], label: 'x' } })+ expect(startPass(s, TODAY, NOW)).toBe(false)+ expect(s.queue).toBe(null)+ })+})++describe('editing the sequence', () => {+ it('the first save creates the rotation and its pass', () => {+ const s = S()+ saveRotation(s, ['a', 'b', 'c'], 'My split', TODAY, NOW)+ expect(s.rotation.sequence).toEqual(['a', 'b', 'c'])+ expect(s.queue).toEqual({ ids: ['a', 'b', 'c'], since: NOW, startsOn: TODAY, label: 'My split', rotationId: s.rotation.id })+ })++ it('an ordinary edit keeps the pass, so logged progress survives', () => {+ const s = S({+ rotation: { id: 'r1', sequence: ['a', 'b', 'c'], label: 'My split' },+ queue: pass(['a', 'b', 'c'], { rotationId: 'r1' }),+ workouts: [w('a', '2026-09-11')],+ })+ saveRotation(s, ['c', 'b', 'a', 'own'], 'My split', TODAY, NOW)+ expect(s.queue.since).toBe(NOW - 86400000)+ expect(s.queue.startsOn).toBe('2026-09-10')+ expect(queueRemaining(s)).toEqual(['c', 'b', 'own']) // 'a' is still done+ expect(s.rotation.id).toBe('r1')+ })++ it('saving an externally written queue adopts it: same pass, now carrying the rotation id', () => {+ const s = S({ queue: pass(['a', 'b'], { label: 'US W1' }) }) // no rotationId+ saveRotation(s, ['a', 'b'], 'US W1', TODAY, NOW)+ expect(s.queue.since).toBe(NOW - 86400000)+ expect(s.queue.startsOn).toBe('2026-09-10')+ expect(s.queue.rotationId).toBe(s.rotation.id)+ })++ it('an edit that completes the pass on the spot starts the next one immediately', () => {+ const s = S({+ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' },+ queue: pass(['a', 'b'], { rotationId: 'r1' }),+ workouts: [w('a', '2026-09-11')], // 'a' already done; removing 'b' would finish the pass+ })+ saveRotation(s, ['a'], 'My split', TODAY, NOW)+ expect(s.rotation.sequence).toEqual(['a'])+ // completing on save immediately starts the next pass — today, since the credit that closed+ // the old one was logged yesterday, not today (the one-day boundary only pushes to tomorrow+ // when today's own workout is what completed the pass).+ expect(s.queue.startsOn).toBe(TODAY)+ expect(queueRemaining(s)).toEqual(['a'])+ })++ it('removing a session clears its future pin, but leaves past pins and pins on kept sessions alone', () => {+ const s = S({+ rotation: { id: 'r1', sequence: ['a', 'b', 'c'], label: 'My split' },+ queue: pass(['a', 'b', 'c'], { rotationId: 'r1' }),+ dayPlan: { '2026-09-11': 'b', '2026-09-12': 'c', '2026-09-14': 'a' },+ })+ saveRotation(s, ['a', 'b'], 'My split', TODAY, NOW) // drops 'c'+ expect(s.dayPlan).toEqual({ '2026-09-11': 'b', '2026-09-14': 'a' })+ })++ it('Start new pass rewinds to today, and to tomorrow when today closed the old one', () => {+ const base = { rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } }+ const stale = S({ ...base, queue: pass(['a', 'b'], { rotationId: 'r1' }), workouts: [w('a', '2026-09-10'), w('b', '2026-09-10')] })+ startNewPass(stale, TODAY, NOW)+ expect(stale.queue.startsOn).toBe(TODAY)+ // …but a pass closed by a workout dated today must not have that same workout credit the new one+ const fresh = S({ ...base, queue: pass(['a', 'b'], { rotationId: 'r1' }), workouts: [w('a', '2026-09-10'), w('b', TODAY)] })+ startNewPass(fresh, TODAY, NOW)+ expect(fresh.queue.startsOn).toBe('2026-09-13')+ expect(fresh.queue.since).toBe(NOW)+ })+})++describe('refilling a completed managed pass', () => {+ const managed = (ids, workouts) => S({+ rotation: { id: 'r1', sequence: ['a', 'b', 'c'], label: 'My split' },+ queue: pass(ids, { rotationId: 'r1' }),+ workouts,+ })++ it('completed in order refills in the same order, starting tomorrow', () => {+ const last = w('c', TODAY)+ const s = managed(['a', 'b', 'c'], [w('a', '2026-09-10'), w('b', '2026-09-11'), last])+ expect(refillAfter(s, last, TODAY, NOW)).toBe(true)+ expect(s.queue).toEqual({ ids: ['a', 'b', 'c'], since: NOW, startsOn: '2026-09-13', label: 'My split', rotationId: 'r1' })+ })++ it('the routine that closed the pass is the one the next pass ends with', () => {+ const last = w('b', TODAY)+ const s = managed(['a', 'b', 'c'], [w('c', '2026-09-10'), w('a', '2026-09-11'), last])+ expect(refillAfter(s, last, TODAY, NOW)).toBe(true)+ expect(s.queue.ids).toEqual(['c', 'a', 'b'])+ })++ it('a merged session credits every matching item; the last one in slot order sets the next pass', () => {+ const merged = { id: 'm', d: TODAY, start: NOW - 1000, routineIds: ['a', 'b'], routineId: 'a', name: 'A + B', entries: [] }+ const s = managed(['c', 'a', 'b'], [w('c', '2026-09-10'), merged])+ expect(refillAfter(s, merged, TODAY, NOW)).toBe(true)+ expect(s.queue.ids).toEqual(['c', 'a', 'b']) // 'b' closed it, so the next pass ends on 'b'+ })++ it('an incomplete pass is left alone', () => {+ const last = w('a', TODAY)+ const s = managed(['a', 'b', 'c'], [last])+ expect(refillAfter(s, last, TODAY, NOW)).toBe(false)+ expect(s.queue.since).toBe(NOW - 86400000)+ })++ it('a queue without a matching rotationId is never rewritten', () => {+ const last = w('b', TODAY)+ const s = S({+ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' },+ queue: pass(['a', 'b'], { label: 'US W1' }), // an external planner's pass+ workouts: [w('a', '2026-09-11'), last],+ })+ expect(refillAfter(s, last, TODAY, NOW)).toBe(false)+ expect(s.queue.rotationId).toBe(undefined)+ expect(s.queue.since).toBe(NOW - 86400000)+ })++ it('a queue and a rotation both missing their ids never match by accident', () => {+ // Hardening for the boundary case `!q?.rotationId || !s.rotation?.id`: two undefineds must+ // never read as equal and let an unrelated pass rewrite over someone else's queue.+ const last = w('b', TODAY)+ const s = S({+ rotation: { sequence: ['a', 'b'], label: 'My split' }, // no id+ queue: pass(['a', 'b']), // no rotationId+ workouts: [w('a', '2026-09-11'), last],+ })+ expect(refillAfter(s, last, TODAY, NOW)).toBe(false)+ })++ it('a managed pass that no longer matches its rotation waits for the editor', () => {+ const last = w('b', TODAY)+ const s = S({+ rotation: { id: 'r1', sequence: ['a', 'b', 'c'], label: 'My split' },+ queue: pass(['a', 'b'], { rotationId: 'r1' }), // not a circular ordering of a,b,c+ workouts: [w('a', '2026-09-11'), last],+ })+ expect(refillAfter(s, last, TODAY, NOW)).toBe(false)+ })++ it('there is no queue to refill without one', () => {+ expect(refillAfter(S(), w('a', TODAY), TODAY, NOW)).toBe(false)+ })++ it('a backfilled finish dated before other logged workouts still starts the new pass after the latest of them', () => {+ const backfilled = w('c', '2026-09-08')+ const s = managed(['a', 'b', 'c'], [w('a', '2026-09-10'), w('b', '2026-09-11'), backfilled])+ expect(refillAfter(s, backfilled, TODAY, NOW)).toBe(true)+ expect(s.queue.startsOn).toBe('2026-09-12')+ })++ it('a workout logged with a clock ahead of now does not re-credit the new pass', () => {+ // The bug: `since = Date.now()` at refill time sits before a workout whose own clock (a+ // backfilled entry, or a device a few minutes fast) already reads later — that workout then+ // reads as done in the pass that has not even started yet.+ const last = w('c', TODAY, NOW - 1000)+ const skewed = w('a', '2026-09-11', NOW + 5 * 60000) // "logged" five minutes ahead of now+ const s = managed(['a', 'b', 'c'], [skewed, w('b', '2026-09-11'), last])+ expect(refillAfter(s, last, TODAY, NOW)).toBe(true)+ expect(queueRemaining(s)).toEqual(['a', 'b', 'c'])+ expect(queueView(s, TODAY).waiting).toBe(true)+ })+})++describe('the finished-workout boundary', () => {+ it('refills from the workout the finish screen actually writes', async () => {+ const { buildCompletedWorkout } = await import('./finish-workout.js')+ const active = {+ id: 'w1', d: TODAY, start: NOW, routineIds: ['b'], name: 'B',+ entries: [{ id: '0025', sets: [{ w: 60, reps: 5, done: true }] }],+ }+ const done = buildCompletedWorkout(active)+ const s = S({+ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' },+ queue: pass(['a', 'b'], { rotationId: 'r1' }),+ workouts: [w('a', '2026-09-11')],+ })+ s.workouts.push(done) // what doFinishWorkout does, in order+ expect(refillAfter(s, done, TODAY, NOW)).toBe(true)+ expect(s.queue.ids).toEqual(['a', 'b'])+ expect(s.queue.startsOn).toBe('2026-09-13')+ // Nothing is due until tomorrow — not because both sessions happen to read as already done+ // (the masked bug: `since` landing exactly on a same-day workout's own `start`), but because+ // the pass has not started yet.+ expect(queueRemaining(s)).toEqual(['a', 'b'])+ expect(queueView(s, TODAY).waiting).toBe(true)+ })+})diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex ca44b4d98..c691697b5 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -35,6 +35,7 @@ import { normalizeRepRange } from './lib/rep-range.js'import { MOBILE, shareExport, printHtml } from './lib/mobile.js'import { speedUnitOf, toSpeed, fromSpeed } from './lib/speed.js'import { buildCompletedWorkout } from './lib/finish-workout.js'+import { refillAfter } from './lib/rotation.js'import { isWarmupRow, hasCompletedWork } from './lib/workout-model.js'import { saveSessionAsRoutine } from './lib/session-routines.js'import { nextUnfinishedUnit } from './lib/supersetFlow.js'@@ -2702,6 +2703,9 @@ function doFinishWorkout() {s.workouts.push(w)}s.active = null+ // A rotation pass this app manages starts its next pass the moment the last session lands+ // (lib/rotation.js). A planner's queue is left alone: it completes and waits for its writer.+ refillAfter(s, w)})useStore.getState().autoBackupNow()useUI.getState().stopRest()diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 344d9578b..2b7c853db 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -75,7 +75,15 @@ export const DEF = {unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, soundOnSilent: false, timerFlash: false, timedSetOvertime: false, keepAwake: true, lang: 'en',theme: 'dark', accent: 'lime', body: 'male', targetW: null,bodyweight: [], routines: [], week: {}, dayPlan: {},- queue: null, // a planner's floating week (lib/queue.js) — written only through the API, never by the app+ queue: null, // a planner's floating week (lib/queue.js) — via the API, or by this rotation feature (below)+ // The in-app rotation's reusable definition — { id, sequence, label } (lib/rotation.js). Never+ // a live queue: it only ever feeds `queue`, and `queue.rotationId` says the pass is managed here.+ rotation: null,+ // null | 'week' | 'rotation' — which of the two scheduling screens Home/Plan show. A live+ // queue always wins regardless of this (scheduleModeOf, lib/rotation.js): the flag exists only+ // to keep Rotation selected, and the weekday grid hidden, from the moment it's chosen in+ // Settings/Plan through to the first routine being added — there's no queue yet to derive it from.+ scheduleMode: null,exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',// Stats activity heatmap metric. Profiles without this key continue to open on time.heatmapMetric: 'time',