Skip to content

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

Rotation: a pass a sync merge left complete starts its next one

Duarte Santos1098fdc7f678
diff --git a/frontend/src/lib/rotation.js b/frontend/src/lib/rotation.js
index cce490f29..8dcdeb3c5 100644
--- a/frontend/src/lib/rotation.js
+++ b/frontend/src/lib/rotation.js
@@ -213,3 +213,19 @@ export function refillAfter(s, w, today = todayISO(), now = Date.now()) {
s.queue = newPass(rotate(seq, last), s.rotation.label || '', s.rotation.id, dayAfter(bound), sinceAfter(s, q, now))
return true
}
+
+/**
+ * A complete pass this app manages, refilled as the finish that completed it would have
+ * (refillAfter), taking the latest workout that credited it as that finish. For a copy that
+ * reached this state without a finish on this device: a sync merge that took both devices'
+ * sessions of the pass, or kept the other copy's queue over this one's refill. Returns true when
+ * it refilled; anything else (no managed pass, an incomplete one) is left alone.
+ */
+export function refillIfComplete(s, 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 last = creditWindow(s, q)
+ .sort((x, y) => (x.d === y.d ? (x.start || 0) - (y.start || 0) : x.d < y.d ? -1 : 1)).at(-1)
+ return last ? refillAfter(s, last, today, now) : false
+}
diff --git a/frontend/src/lib/rotation.test.js b/frontend/src/lib/rotation.test.js
index fa46c9a1c..95d4df30d 100644
--- a/frontend/src/lib/rotation.test.js
+++ b/frontend/src/lib/rotation.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { scheduleModeOf, queueRecovery, rotationIds, startPass, saveRotation, startNewPass, stopPass, refillAfter, chooseRotation, chooseFixedWeek } from './rotation.js'
+import { scheduleModeOf, queueRecovery, rotationIds, startPass, saveRotation, startNewPass, stopPass, refillAfter, refillIfComplete, chooseRotation, chooseFixedWeek } from './rotation.js'
import { queueNext, queueRemaining, queueView } from './queue.js'
import { effectiveRoutineIds } from './history.js'
@@ -381,3 +381,27 @@ describe('the How you train switch Plan and Settings share', () => {
expect(s.scheduleMode).toBe('week')
})
})
+
+describe('a complete managed pass left behind by a sync merge', () => {
+ const managed = (ids, workouts, over = {}) => S({
+ rotation: { id: 'r1', sequence: ['a', 'b', 'c'], label: 'My split' },
+ queue: pass(ids, { rotationId: 'r1' }),
+ workouts, ...over,
+ })
+
+ it('refills from the latest workout that credited it', () => {
+ // the phone's refill lost to the desktop's older queue: the pass is complete, nothing refilled it
+ const s = managed(['a', 'b', 'c'], [w('a', '2026-09-10'), w('c', '2026-09-11'), w('b', TODAY)])
+ expect(refillIfComplete(s, TODAY, NOW)).toBe(true)
+ expect(s.queue).toEqual({ ids: ['c', 'a', 'b'], since: NOW, startsOn: '2026-09-13', label: 'My split', rotationId: 'r1' })
+ })
+
+ it('leaves an incomplete pass, a planner queue and no queue alone', () => {
+ const open = managed(['a', 'b', 'c'], [w('a', TODAY)])
+ expect(refillIfComplete(open, TODAY, NOW)).toBe(false)
+ expect(open.queue.ids).toEqual(['a', 'b', 'c'])
+ const planner = managed(['a', 'b', 'c'], [w('a', '2026-09-10'), w('b', '2026-09-11'), w('c', TODAY)], { queue: pass(['a', 'b', 'c']) })
+ expect(refillIfComplete(planner, TODAY, NOW)).toBe(false)
+ expect(refillIfComplete(S(), TODAY, NOW)).toBe(false)
+ })
+})
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 9030ed8be..f691c9fba 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -7,6 +7,7 @@ import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
import { rememberDefaultLang } from '../lib/default-lang.js'
import { guestAllowed } from '../lib/guest.js'
import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'
+import { refillIfComplete } from '../lib/rotation.js'
import { mergeStates, localExtras, stampRoutines, stampCustomEx, stampDeletions, stampEdits, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } from '../lib/sync-merge.js'
import { convertStateUnit } from '../lib/units.js'
import { pendingRefCount, settleMedia, loadPending } from '../lib/media-owed.js'
@@ -522,6 +523,10 @@ export const useStore = create((set, get) => {
const ts = metaOf().base?.ts || 0
const merged = Object.assign(clone(DEF), mergeStates(local, remote))
merged.active = carryActive(local, merged)
+ // A pass of this app's rotation that the merge left complete (each copy finished a session of
+ // it, or one copy's refill lost to the other's older queue) starts its next pass here, as the
+ // finish that completed it would have (lib/rotation.js).
+ if (refillIfComplete(merged)) merged.edited = { ...(merged.edited || {}), queue: Date.now() }
persist(merged, false)
if (rev == null) dropSync()
else writeSync(rev, ts)
diff --git a/frontend/src/store/useStore.sync.test.jsx b/frontend/src/store/useStore.sync.test.jsx
index 37d2fbeb8..c0a1fba25 100644
--- a/frontend/src/store/useStore.sync.test.jsx
+++ b/frontend/src/store/useStore.sync.test.jsx
@@ -469,3 +469,29 @@ describe('removals and settings across a conflict', () => {
expect(sent.bodyweight.map(e => e.d)).toEqual(['2026-09-05'])
})
})
+
+describe('a rotation pass a merge leaves complete', () => {
+ it('starts its next pass, as the finish that completed it would have', async () => {
+ vi.useFakeTimers()
+ const now = Date.parse('2026-09-12T10:00:00')
+ vi.setSystemTime(now)
+ const plan = {
+ routines: [routine('a'), routine('b')],
+ rotation: { id: 'rot', sequence: ['a', 'b'], label: '' },
+ queue: { ids: ['a', 'b'], since: now - 5 * 86400000, startsOn: '2026-09-07', label: '', rotationId: 'rot' },
+ }
+ const done = (id, d) => ({ id: 'w-' + id, d, start: now - 86400000, routineIds: [id], routineId: id, name: id, entries: [] })
+ // this device trained A, the other trained B: each copy alone still has a session to go
+ signedIn({ ...clone(DEF), ...clone(plan), _ts: 300, workouts: [done('a', '2026-09-10')] })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))
+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: { ...clone(DEF), ...clone(plan), _ts: 200, workouts: [done('b', '2026-09-11')], _rev: 2 } }))
+ api.mockResolvedValueOnce({ ok: true, rev: 3 })
+
+ await useStore.getState().pushState()
+
+ const q = puts().at(-1).state.queue
+ expect(q.ids).toEqual(['a', 'b'])
+ expect(q.startsOn).toBe('2026-09-12')
+ expect(q.since).toBeGreaterThanOrEqual(now)
+ })
+})