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
Follow-up to !140: a role's exercise choice survives sync, the one made last wins
Duarte Santosfe9987497a0f
diff --git a/frontend/src/lib/structuralBalance.js b/frontend/src/lib/structuralBalance.jsindex 805d940dc..1af493edc 100644--- a/frontend/src/lib/structuralBalance.js+++ b/frontend/src/lib/structuralBalance.js@@ -121,10 +121,27 @@ export function overrideKey(template, role) {return `${template.id}:${role.id}`}+// One role's override as S.balanceOverrides stores it: `{ id, _ts }`, the chosen exercise and+// when it was chosen, with `id: null` once the role is back on its default. The clear is kept+// as a stamped entry rather than deleted so it can win a sync against the other device's older+// choice (lib/sync-merge.js keeps whichever side set a role last). A bare id string is how the+// first builds of this screen stored it, and still reads as that exercise.+export function overrideIdOf(value) {+ if (typeof value === 'string') return value || null+ return value && typeof value.id === 'string' && value.id ? value.id : null+}++// `overrides` with the role under `key` set to `exId`, or back on its default for null.+export function withOverride(overrides, key, exId, now = Date.now()) {+ return { ...(overrides || {}), [key]: { id: exId || null, _ts: now } }+}++const overrideFor = (S, template, role) => overrideIdOf(S.balanceOverrides?.[overrideKey(template, role)])+// The exercise ids to resolve "current" from: the user's chosen override if one exists for this// role, otherwise the role's curated whitelist.export function exerciseIdsFor(S, template, role) {- const override = S.balanceOverrides?.[overrideKey(template, role)]+ const override = overrideFor(S, template, role)return override ? [override] : role.exerciseIds}@@ -159,7 +176,7 @@ function evaluateRole(template, role, currentByRoleId, bodyweightKg, S) {// normalized to "% of the rep target" by the time it gets there.const targetPct = targetFor(role, S)const classifyTarget = role.evaluationMode === EVALUATION_MODES.REP_COUNT ? 100 : targetPct- const override = S.balanceOverrides?.[overrideKey(template, role)]+ const override = overrideFor(S, template, role)// Which exercise this role is set to, whether or not it has ever been logged — the view needs// it to name the role's exercise (and to show an override back to the user who chose it).const configuredExerciseId = override || role.exerciseIds[0] || nulldiff --git a/frontend/src/lib/structuralBalance.test.js b/frontend/src/lib/structuralBalance.test.jsindex 4ef712227..3708d2045 100644--- a/frontend/src/lib/structuralBalance.test.js+++ b/frontend/src/lib/structuralBalance.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { computeBalance, classify, ratioFor, resolveCurrent, resolveCurrentReps, targetFor, overrideKey } from './structuralBalance.js'+import { computeBalance, classify, ratioFor, resolveCurrent, resolveCurrentReps, targetFor, overrideKey, overrideIdOf, withOverride } from './structuralBalance.js'import { TEMPLATES, EVALUATION_MODES, BALANCE_STATUSES, BORDERLINE_BAND_PCT } from './structuralBalanceTemplates.js'const NOW = Date.parse('2026-01-15T00:00:00Z')@@ -362,6 +362,34 @@ describe('exercise override', () => {})})+// How an override is stored: `{ id, _ts }`, a clear as `id: null` (see sync-merge.js).+describe('stored overrides', () => {+ const template = TEMPLATES.atg+ const key = overrideKey(template, findRole(template, 'nordicCurl'))+ const logged = { unit: 'kg', workouts: [workoutAt('3193', NOW, [setDone(0, 1)]), workoutAt('0599', NOW, [setDone(40, 1)])] }+ const nordic = overrides => computeBalance({ ...logged, balanceOverrides: overrides }, template).find(r => r.roleId === 'nordicCurl')++ it('withOverride stamps a choice and a clear, leaving the other roles alone', () => {+ const set = withOverride({ other: { id: '0001', _ts: 1 } }, key, '0599', 1234)+ expect(set).toEqual({ other: { id: '0001', _ts: 1 }, [key]: { id: '0599', _ts: 1234 } })+ expect(withOverride(set, key, null, 2000)[key]).toEqual({ id: null, _ts: 2000 })+ expect(withOverride(undefined, key, '0599', 5)).toEqual({ [key]: { id: '0599', _ts: 5 } })+ })++ it('reads a stamped choice, a cleared one as the default, and the first builds\' bare id', () => {+ expect(overrideIdOf({ id: '0599', _ts: 3 })).toBe('0599')+ expect(overrideIdOf({ id: null, _ts: 3 })).toBe(null)+ expect(overrideIdOf('0599')).toBe('0599')+ expect(overrideIdOf(undefined)).toBe(null)+ expect(overrideIdOf('')).toBe(null)++ expect(nordic({ [key]: { id: '0599', _ts: 3 } })).toMatchObject({ isOverridden: true, mappedExerciseId: '0599' })+ const cleared = nordic({ [key]: { id: null, _ts: 9 } })+ expect(cleared).toMatchObject({ isOverridden: false, configuredExerciseId: '3193', mappedExerciseId: '3193' })+ expect(nordic({ [key]: '0599' })).toMatchObject({ isOverridden: true, mappedExerciseId: '0599' })+ })+})+describe('computeBalance — full template end-to-end (Poliquin)', () => {it('resolves every role in order, mixing logged and unlogged roles', () => {const template = TEMPLATES.poliquindiff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex f8e55c176..2a59377c0 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -16,7 +16,9 @@* - favEx: ordered set union, the newer copy first* - exWeights: union by exercise, the better `w` for that exercise — larger for an ordinary* lift, smaller on an assistance machine (a PR logged on the other device must not be- * forgotten, whichever way it runs); exNotes, barWeights, balanceOverrides: key union+ * forgotten, whichever way it runs); exNotes, barWeights: key union+ * - balanceOverrides: key union; of a key both have, the entry set last by its own `_ts`, a+ * clear included (mergeStampedMap), the newer copy's on a tie* - `_ts`: the later of the two; `_rev` dropped (the server sets it); `active` left to the caller** Known limit: with no record of what each side deleted, an entry removed on one device inside@@ -77,6 +79,25 @@ function mergeExWeights(n = {}, o = {}) {return out}+const stampOf = v => (v && typeof v === 'object' ? Number(v._ts) || 0 : 0)+const isMap = v => !!v && typeof v === 'object' && !Array.isArray(v)++/**+ * A settings map whose entries carry their own edit time (`{ …, _ts }`), such as the Structural+ * Balance overrides: every key of either side, and of a key both have, the entry set last — the+ * same rule a routine follows. Taking the newer copy's entry lost a choice made on one device+ * whenever the other had since logged a set; a plain key union brought a cleared entry back+ * from the side that still had it. So a clear is written as a stamped entry, not a delete, and+ * wins like any other edit. On a tie, or with `prefer`, the newer (preferred) side's entry stays.+ */+export function mergeStampedMap(newer, older, prefer) {+ const n = isMap(newer) ? newer : {}+ const o = isMap(older) ? older : {}+ const out = { ...o, ...n }+ if (!prefer) for (const k of Object.keys(o)) if (k in n && stampOf(o[k]) > stampOf(n[k])) out[k] = o[k]+ return out+}+// `prefer` names the side whose settings, plan and per-exercise config win regardless of `_ts`:// on sign-in the server's profile is the truth and the device only contributes the entries it// logged while signed out. Without it the newer copy decides, as for a conflict between devices.@@ -104,9 +125,10 @@ export function mergeStates(a, b, { prefer } = {}) {out.bodyweight = mergeBodyweight(n.bodyweight, o.bodyweight).map(clone)if (list(n.favEx).length || list(o.favEx).length) out.favEx = [...new Set([...list(n.favEx), ...list(o.favEx)])]out.exWeights = clone(mergeExWeights(n.exWeights, o.exWeights))- for (const f of ['exNotes', 'barWeights', 'balanceOverrides']) {+ for (const f of ['exNotes', 'barWeights']) {if (n[f] || o[f]) out[f] = clone({ ...(o[f] || {}), ...(n[f] || {}) })}+ if (n.balanceOverrides || o.balanceOverrides) out.balanceOverrides = clone(mergeStampedMap(n.balanceOverrides, o.balanceOverrides, prefer))out._ts = Math.max(a._ts || 0, b._ts || 0)delete out._revreturn outdiff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.jsindex 613483c0b..d46eea8e3 100644--- a/frontend/src/lib/sync-merge.test.js+++ b/frontend/src/lib/sync-merge.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { localExtras, mergeBodyweight, mergeStates, newerOf, stampRoutines, unionById } from './sync-merge.js'+import { localExtras, mergeBodyweight, mergeStampedMap, mergeStates, newerOf, stampRoutines, unionById } from './sync-merge.js'const workout = (id, d = '2026-09-01', start = 1) => ({ id, d, start, entries: [] })const routine = (id, name = id) => ({ id, name, ex: [] })@@ -199,3 +199,55 @@ describe('routines keep the version edited last', () => {expect(again.map(x => x._ts)).toEqual([1000, 99, 1000])})})++// Structural Balance's per-role exercise choices. Each carries the time it was made and a clear+// is a stamped `id: null`, so the choice made last survives a conflict either way round — the+// newer copy's map used to win wholesale (a role picked on the phone vanished once the desktop+// logged a set), and a plain key union brought a cleared role back from the other device.+describe('balanceOverrides keep the choice made last', () => {+ const pick = (id, ts) => ({ id, _ts: ts })++ it('a role chosen on the older copy survives the newer copy\'s earlier choice', () => {+ const phone = base({ _ts: 100, balanceOverrides: { 'poliquin:dips': pick('0009', 90) } })+ const desk = base({ _ts: 200, restSec: 60, workouts: [workout('w2')], balanceOverrides: { 'poliquin:dips': pick('0251', 20) } })+ for (const m of [mergeStates(phone, desk), mergeStates(desk, phone)]) {+ expect(m.restSec).toBe(60)+ expect(m.balanceOverrides['poliquin:dips']).toEqual(pick('0009', 90))+ }+ })++ it('a clear is not undone by the other device\'s older choice, and a later choice beats a clear', () => {+ const cleared = base({ _ts: 100, balanceOverrides: { 'atg:pullups': pick(null, 80) } })+ const stale = base({ _ts: 300, balanceOverrides: { 'atg:pullups': pick('0017', 40) } })+ expect(mergeStates(cleared, stale).balanceOverrides['atg:pullups']).toEqual(pick(null, 80))+ expect(mergeStates(stale, cleared).balanceOverrides['atg:pullups']).toEqual(pick(null, 80))+ const later = base({ _ts: 50, balanceOverrides: { 'atg:pullups': pick('0652', 95) } })+ expect(mergeStates(cleared, later).balanceOverrides['atg:pullups']).toEqual(pick('0652', 95))+ })++ it('roles set on different devices are all kept; a tie or an unstamped entry goes to the newer copy', () => {+ const a = base({ _ts: 100, balanceOverrides: { 'poliquin:dips': pick('0009', 10), 'atg:nordicCurl': '0599' } })+ const b = base({ _ts: 200, balanceOverrides: { 'poliquin:barbellCurl': pick('0031', 30), 'atg:nordicCurl': '3193' } })+ const m = mergeStates(a, b)+ expect(Object.keys(m.balanceOverrides).sort()).toEqual(['atg:nordicCurl', 'poliquin:barbellCurl', 'poliquin:dips'])+ expect(m.balanceOverrides['atg:nordicCurl']).toBe('3193')+ expect(mergeStampedMap({ k: pick('x', 5) }, { k: pick('y', 5) }).k.id).toBe('x')+ })++ it('prefer keeps the preferred side\'s choice; one side without the map keeps the other\'s', () => {+ const server = base({ _ts: 10, balanceOverrides: { 'poliquin:dips': pick('0251', 5) } })+ const local = base({ _ts: 90, balanceOverrides: { 'poliquin:dips': pick('0009', 80), 'atg:pullups': pick('0017', 80) } })+ const m = mergeStates(server, local, { prefer: 'a' })+ expect(m.balanceOverrides).toEqual({ 'poliquin:dips': pick('0251', 5), 'atg:pullups': pick('0017', 80) })+ const bare = base({ _ts: 500 })+ expect(mergeStates(bare, local).balanceOverrides).toEqual(local.balanceOverrides)+ expect(mergeStates(bare, base({ _ts: 1 })).balanceOverrides).toBeUndefined()+ })++ it('the merged map is a copy, not the input', () => {+ const a = base({ _ts: 100, balanceOverrides: { k: pick('x', 1) } })+ const m = mergeStates(a, base({ _ts: 50 }))+ m.balanceOverrides.k.id = 'changed'+ expect(a.balanceOverrides.k.id).toBe('x')+ })+})diff --git a/frontend/src/store/useStore.balance-sync.test.jsx b/frontend/src/store/useStore.balance-sync.test.jsxnew file mode 100644index 000000000..2c672cb53--- /dev/null+++ b/frontend/src/store/useStore.balance-sync.test.jsx@@ -0,0 +1,108 @@+// @vitest-environment happy-dom++/* Structural Balance's per-role exercise choices (S.balanceOverrides) through the store's own+ sync paths. Each choice carries the time it was made, and "Use default exercise" is a stamped+ clear rather than a delete, so a conflict keeps whichever device chose last — a clear included —+ instead of handing the whole map to the copy that happened to be newer. */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))+const { toast } = vi.hoisted(() => ({ toast: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast }) } }))++import { api } from '../lib/api.js'+import { DEF, useStore } from './useStore.js'+import { withOverride } from '../lib/structuralBalance.js'++const DIPS = 'poliquin:dips'+const PULLUPS = 'atg:pullups'+const clone = value => JSON.parse(JSON.stringify(value))+const httpError = (status, data = {}) => Object.assign(new Error(data.error || 'HTTP ' + status), { status, data })+const netError = () => new TypeError('Failed to fetch')+const puts = () => api.mock.calls.filter(([, o]) => o?.method === 'PUT').map(([, o]) => JSON.parse(o.body))+const USER = { id: 'user-1', name: 'One' }+const fresh = { offline: false, pending: false, auth: false, lastError: null, lastSynced: 0, server: null }+const signedIn = S => useStore.setState({ S, user: USER, ready: true, sync: { ...fresh } })+// What the screen's "Change exercise" and "Use default exercise" write.+const choose = (key, id) => useStore.getState().update(s => { s.balanceOverrides = withOverride(s.balanceOverrides, key, id) })++beforeEach(() => {+ localStorage.clear()+ localStorage.setItem('gym_owner', USER.id)+ api.mockReset(); toast.mockReset()+ useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh } })+})+afterEach(() => {+ localStorage.clear()+ useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh } })+})++describe('a role chosen here and a conflict with the other device', () => {+ it('keeps the choice and the clear made here over the older ones in a newer copy', async () => {+ const shared = { ...clone(DEF), _ts: 100, balanceOverrides: { [PULLUPS]: { id: '0017', _ts: 90 } } }+ signedIn(clone(shared))+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ choose(DIPS, '0009')+ choose(PULLUPS, null)+ // The other device logged a set after that, and had picked the dips machine long before.+ const there = { ...clone(shared), _ts: Date.now() + 60_000, restSec: 45, workouts: [{ id: 'w9', d: '2026-09-20', start: 1, entries: [] }] }+ there.balanceOverrides[DIPS] = { id: '0251', _ts: 50 }+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: { ...there, _rev: 2 } }))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })++ await useStore.getState().pushState()++ expect(puts()).toHaveLength(2)+ for (const S of [puts()[1].state, useStore.getState().S]) {+ expect(S.restSec).toBe(45) // settings: the newer copy+ expect(S.workouts.map(w => w.id)).toEqual(['w9'])+ expect(S.balanceOverrides[DIPS].id).toBe('0009') // chosen here, later+ expect(S.balanceOverrides[PULLUPS].id).toBe(null) // cleared here, later+ }+ })++ it('takes the other device\'s choice when it was made after the one here', async () => {+ signedIn({ ...clone(DEF), _ts: 100 })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ choose(DIPS, '0009')+ const mine = useStore.getState().S.balanceOverrides[DIPS]._ts+ const there = { ...clone(DEF), _ts: 50, balanceOverrides: { [DIPS]: { id: '2364', _ts: mine + 1_000 } } }+ api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: { ...there, _rev: 2 } }))+ api.mockResolvedValueOnce({ ok: true, rev: 3 })++ await useStore.getState().pushState()++ expect(puts()[1].state.balanceOverrides[DIPS].id).toBe('2364')+ expect(useStore.getState().S.balanceOverrides[DIPS].id).toBe('2364')+ })+})++describe('a role chosen before a forced sign-out', () => {+ it('is kept aside and comes back on the next sign-in over the server\'s older choice', async () => {+ signedIn({ ...clone(DEF), _ts: 100 })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockResolvedValueOnce({ rev: 1 }) // a check in step: the fingerprint of rev 1 is taken+ window.dispatchEvent(new Event('online'))+ await new Promise(r => setTimeout(r, 10))++ choose(DIPS, '0009')+ const chosen = clone(useStore.getState().S.balanceOverrides[DIPS])+ expect(useStore.getState().unsyncedChanges()).toEqual({ owed: true, count: 1 })++ api.mockReset()+ api.mockRejectedValue(netError())+ expect(await useStore.getState().signOut({ force: true })).toMatchObject({ owed: true, stashed: true })+ expect(useStore.getState().S.balanceOverrides).toEqual({})++ const server = { ...clone(DEF), _ts: 50, _rev: 2, balanceOverrides: { [DIPS]: { id: '0251', _ts: 20 }, [PULLUPS]: { id: '0017', _ts: 30 } } }+ api.mockReset()+ api.mockImplementation(async (path, o) => (o?.method === 'PUT' ? { ok: true, rev: 3 } : { state: clone(server), rev: 2 }))+ useStore.getState().setUser(USER)+ await useStore.getState().adoptProfile(async () => false)++ for (const S of [useStore.getState().S, puts().at(-1).state]) {+ expect(S.balanceOverrides[DIPS]).toEqual(chosen)+ expect(S.balanceOverrides[PULLUPS]).toEqual({ id: '0017', _ts: 30 })+ }+ })+})diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 54e229622..08a872a6f 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -104,8 +104,9 @@ export const DEF = {startFrom: 'plan',// Structural Balance (views/StructuralBalance.jsx): which built-in ratio template is active,// and per-role exercise overrides keyed by `${templateId}:${roleId}` — see- // lib/structuralBalance.js's overrideKey(). An override replaces that role's curated- // exercise-id whitelist with a single user-chosen exercise id.+ // lib/structuralBalance.js's overrideKey(). An override (`{ id, _ts }`, `id: null` once+ // cleared) replaces that role's curated exercise-id whitelist with a single user-chosen+ // exercise id; the stamp is what lets a sync keep the choice made last (lib/sync-merge.js).balanceTemplate: DEFAULT_TEMPLATE_ID, balanceOverrides: {},}const clone = o => JSON.parse(JSON.stringify(o))diff --git a/frontend/src/views/StructuralBalance.jsx b/frontend/src/views/StructuralBalance.jsxindex b29d65bf0..b47ec34ef 100644--- a/frontend/src/views/StructuralBalance.jsx+++ b/frontend/src/views/StructuralBalance.jsx@@ -6,7 +6,7 @@ import { t, exerciseNameFor } from '../lib/i18n.js'import Icon from '../components/Icon.jsx'import { Button, Segmented } from '../components/ui.jsx'import { exercisePicker } from '../sheets.jsx'-import { computeBalance, overrideKey } from '../lib/structuralBalance.js'+import { computeBalance, overrideKey, withOverride } from '../lib/structuralBalance.js'import { balanceStatusView } from '../lib/structuralBalance-view.js'import { TEMPLATES, TEMPLATE_LIST, DEFAULT_TEMPLATE_ID, EVALUATION_MODES } from '../lib/structuralBalanceTemplates.js'@@ -28,13 +28,9 @@ export default function StructuralBalance() {const results = useMemo(() => computeBalance(S, template), [S, template])const setOverride = (role, exId) => update(s => {- s.balanceOverrides = { ...s.balanceOverrides, [overrideKey(template, role)]: exId }- })- const clearOverride = role => update(s => {- const next = { ...s.balanceOverrides }- delete next[overrideKey(template, role)]- s.balanceOverrides = next+ s.balanceOverrides = withOverride(s.balanceOverrides, overrideKey(template, role), exId)})+ const clearOverride = role => setOverride(role, null)const changeExercise = role => {const picker = exercisePicker(ex => { setOverride(role, ex.id); picker.close() })}diff --git a/frontend/src/views/StructuralBalance.test.jsx b/frontend/src/views/StructuralBalance.test.jsxindex 254806938..3c781a96b 100644--- a/frontend/src/views/StructuralBalance.test.jsx+++ b/frontend/src/views/StructuralBalance.test.jsx@@ -85,7 +85,9 @@ describe('StructuralBalance view', () => {const pickerView = picker.render(picker.close)act(() => pickerView.props.onPick({ id: '0043' })) // barbell full squat — deliberately not in inclineBench's whitelist- expect(useStore.getState().S.balanceOverrides['poliquin:inclineBench']).toBe('0043')+ const chosen = useStore.getState().S.balanceOverrides['poliquin:inclineBench']+ expect(chosen.id).toBe('0043')+ expect(chosen._ts).toBeGreaterThan(0)const updatedRow = host.querySelector('[data-role-id="inclineBench"]')expect(updatedRow.textContent).toContain('Custom')@@ -93,6 +95,12 @@ describe('StructuralBalance view', () => {const resetBtn = [...updatedRow.querySelectorAll('button')].find(b => b.textContent.includes('Use default exercise'))expect(resetBtn).toBeTruthy()act(() => resetBtn.click())- expect(useStore.getState().S.balanceOverrides['poliquin:inclineBench']).toBeUndefined()+ // Cleared as a stamped entry, so the clear can win a sync against the other device's choice.+ const cleared = useStore.getState().S.balanceOverrides['poliquin:inclineBench']+ expect(cleared.id).toBe(null)+ expect(cleared._ts).toBeGreaterThanOrEqual(chosen._ts)+ const resetRow = host.querySelector('[data-role-id="inclineBench"]')+ expect(resetRow.textContent).not.toContain('Custom')+ expect([...resetRow.querySelectorAll('button')].some(b => b.textContent.includes('Use default exercise'))).toBe(false)})})