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
Watch sync: start and finish from the watch
Duarte Santos1a4569ed7e21
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 71da30f50..ccbc91fee 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -13,13 +13,13 @@ import { setNav, notePath, keyBefore } from './lib/nav.js'import { setSystemBarsLight } from './lib/system-bars.js'import { initBackButton } from './lib/back.js'import { installEdgeSwipeBack, BACK_PREVIEW_EVENT } from './lib/edge-swipe-back.js'-import { startWatchSync } from './lib/watch-sync.js'+import { startWatchSync, bindWatchAppActions } from './lib/watch-sync.js'import { useWakeLock } from './lib/wakelock.js'import { installViewportGuard } from './lib/viewport-guard.js'import { installChipDrag } from './lib/hchips.js'import { syncPushSubscription } from './lib/push.js'import { MOBILE, nativePlatform } from './lib/mobile.js'-import { exitWorkoutEdit, startFlow } from './sheets.jsx'+import { exitWorkoutEdit, startFlow, beginWorkout } from './sheets.jsx'import Icon from './components/Icon.jsx'import TabBar from './components/TabBar.jsx'import ErrorBoundary from './components/ErrorBoundary.jsx'@@ -328,7 +328,10 @@ export default function App() {if (!MOBILE) returnlet stop = null, gone = falsestartWatchSync({ useStore, useUI }).then(fn => { if (gone) fn(); else stop = fn })- return () => { gone = true; stop?.() }+ // A session started on the watch starts here as the phone's Start does, with the watch's id+ // and start time, and no weigh-in question (the lifter is at the watch, not here).+ const unbind = bindWatchAppActions({ start: (ids, opts) => beginWorkout(ids, null, opts) })+ return () => { gone = true; stop?.(); unbind() }}, [])return <HashRouter><Shell /></HashRouter>}diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.jsindex 84e630e14..8c27578cf 100644--- a/frontend/src/lib/watch-sync.js+++ b/frontend/src/lib/watch-sync.js@@ -17,62 +17,93 @@import { MOBILE, nativePlatform } from './mobile.js'import { EXIDX } from './exercises.js'import { exerciseNameFor } from './i18n.js'-import { modeOf, setLabel, lastEntryFor } from './history.js'+import { modeOf, setLabel, lastEntryFor, effectiveRoutineIds } from './history.js'import { isWarmupRow } from './workout-model.js'import { sessionHistory } from './backfill.js'+import { buildCombinedEntries, deriveSessionName } from './session-merge.js'+import { todayISO } from './format.js'export const SNAPSHOT_VERSION = 1const APPLIED_KEY = 'gym_watch_applied'const APPLIED_MAX = 300const SEND_DEBOUNCE_MS = 400+// Routines the watch can start besides today's: enough to choose from, small enough to send.+const READY_MAX = 8const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null)/* ---------- the snapshot ---------- */+// One exercise as the watch shows it.+function watchEntry (e, H) {+ const ex = EXIDX[e.id]+ const target = e.target || {}+ const mode = modeOf({ ...target, id: e.id })+ let last = null+ try {+ const l = H ? lastEntryFor(H, e.id, e.rid) : null+ if (l && Array.isArray(l.sets) && l.sets.length) last = l.sets.map(s => setLabel(e.id, s, l.target)).join(', ')+ } catch { last = null }+ return {+ id: e.id,+ name: ex ? exerciseNameFor(ex) : String(target.name || e.name || e.id),+ mode,+ restSec: num(target.restSec),+ last,+ sets: (e.sets || []).map(s => ({+ w: num(s.w), r: num(s.r), sec: num(s.sec), done: !!s.done, warmup: !!isWarmupRow(s),+ })),+ }+}++/**+ * What the watch can start by itself, the phone asleep: today's planned session and a few other+ * routines, each with its exercises built exactly as starting it on the phone builds them+ * (buildCombinedEntries, as sheets.jsx beginWorkout does).+ */+export function buildReady (S, today = todayISO()) {+ let H = null+ try { H = sessionHistory(S) } catch { H = null }+ const session = ids => {+ const { entries, routineIds, routines } = buildCombinedEntries(S, ids)+ if (!routines.length) return null+ return { routineIds, name: deriveSessionName(routines.map(r => r.name)) || '', entries: entries.map(e => watchEntry(e, H)) }+ }+ let todayIds = []+ try { todayIds = effectiveRoutineIds({ ...S, routines: S.routines || [], week: S.week || {}, dayPlan: S.dayPlan || {} }, today, today) || [] } catch { todayIds = [] }+ const planned = todayIds.length ? session(todayIds) : null+ const others = (S.routines || []).filter(r => r && !todayIds.includes(r.id)).slice(0, READY_MAX).map(r => session([r.id])).filter(Boolean)+ return { today: planned, others }+}+/** What the watch needs to run the session: plain data, no media (licence: text only). */-export function buildSnapshot(S, { timer = null } = {}) {+export function buildSnapshot(S, { timer = null, ready = null } = {}) {const A = S && S.active- if (!A || !Array.isArray(A.entries)) return { v: SNAPSHOT_VERSION, active: null }+ const unit = S && S.unit === 'lb' ? 'lb' : 'kg'+ if (!A || !Array.isArray(A.entries)) return { v: SNAPSHOT_VERSION, unit, active: null, ready }let H = nulltry { H = sessionHistory(S) } catch { H = null }return {v: SNAPSHOT_VERSION,+ unit,+ ready,active: {id: A.id || null,name: A.name || '',- unit: S.unit === 'lb' ? 'lb' : 'kg',+ unit,cur: Math.max(0, Math.min(A.entries.length - 1, A.cur || 0)),restSec: num(S.restSec) || 0,// a rest running on the phone, so the watch counts down the same onerest: timer && !timer.paused && !timer.ready && num(timer.endsAt) ? { endsAt: timer.endsAt } : null,- entries: A.entries.map(e => {- const ex = EXIDX[e.id]- const target = e.target || {}- const mode = modeOf({ ...target, id: e.id })- let last = null- try {- const l = H ? lastEntryFor(H, e.id, e.rid) : null- if (l && Array.isArray(l.sets) && l.sets.length) last = l.sets.map(s => setLabel(e.id, s, l.target)).join(', ')- } catch { last = null }- return {- id: e.id,- name: ex ? exerciseNameFor(ex) : String(target.name || e.name || e.id),- mode,- restSec: num(target.restSec),- last,- sets: (e.sets || []).map(s => ({- w: num(s.w), r: num(s.r), sec: num(s.sec), done: !!s.done, warmup: !!isWarmupRow(s),- })),- }- }),+ entries: A.entries.map(e => watchEntry(e, H)),},}}/* ---------- applying the watch's events ---------- */-let handlers = null+let handlers = null // the workout screen's: setDone, finish+let appHandlers = null // the app's: startconst readApplied = () => { try { return JSON.parse(localStorage.getItem(APPLIED_KEY)) || [] } catch { return [] } }const writeApplied = ids => { try { localStorage.setItem(APPLIED_KEY, JSON.stringify(ids.slice(-APPLIED_MAX))) } catch { /* the queue's ack is what counts */ } }@@ -83,22 +114,38 @@ function entryIndexOf (A, ev) {}/**- * Applies the events not applied yet, in order, through the bound actions. Returns the ids that- * are done with: applied now, applied before, or about a workout that is not running any more.- * Without bound actions (the workout screen is not there) nothing is done with and all stay queued.+ * Applies the events not applied yet, in order. Returns the ids that are done with: applied now,+ * applied before, or about a workout that is not running any more. An event whose actions are not+ * there yet (a set before the workout screen is open) stops the run: it and everything after it+ * stay queued, in order, for the next drain.+ *+ * start { routineIds, wid, at } the app starts that session with the watch's id and start+ * setDone { wid, exId, entryIdx, setIdx, w, r, at } the workout screen's own tick+ * finish { wid, at } the workout screen's own Finish and save*/export function applyEvents (events, getState) {- if (!handlers || !Array.isArray(events)) return []+ if (!Array.isArray(events)) return []const applied = readApplied()const done = []for (const ev of events) {if (!ev || typeof ev.id !== 'string') continueif (applied.includes(ev.id)) { done.push(ev.id); continue }const A = getState()?.S?.active- if (ev.type === 'setDone' && A && Array.isArray(A.entries) && (!ev.wid || ev.wid === A.id)) {+ const ours = A && Array.isArray(A.entries) && (!ev.wid || ev.wid === A.id)+ if (ev.type === 'start') {+ if (!A) {+ if (!appHandlers) break+ appHandlers.start(Array.isArray(ev.routineIds) ? ev.routineIds : [], { id: ev.wid || null, start: num(ev.at) })+ }+ // A workout already running on the phone is kept; one with the watch's id is this one.+ } else if (ev.type === 'setDone' && ours) {+ if (!handlers) breakconst idx = entryIndexOf(A, ev)const set = idx >= 0 ? A.entries[idx].sets?.[ev.setIdx] : null- if (set) handlers.setDone(idx, ev.setIdx, { w: num(ev.w), r: num(ev.r) })+ if (set) handlers.setDone(idx, ev.setIdx, { w: num(ev.w), r: num(ev.r), at: num(ev.at) })+ } else if (ev.type === 'finish' && ours) {+ if (!handlers) break+ handlers.finish()}// Applied, or meaningless now (another workout, a set that is gone): either way it is done.applied.push(ev.id)@@ -108,6 +155,13 @@ export function applyEvents (events, getState) {return done}+/** The app's own actions, for what needs no screen (starting a session). Returns the unbind. */+export function bindWatchAppActions (h) {+ appHandlers = h+ drainWatchEvents()+ return () => { if (appHandlers === h) appHandlers = null }+}+/* ---------- the native plugin ---------- */let pluginP = null@@ -154,19 +208,30 @@ export async function startWatchSync ({ useStore, useUI }) {if (!p) return () => {}getStateRef = () => useStore.getState()let lastSent = null, tm = null+ // The ready sessions only change with the plan, the log or the day: built again only then.+ let readyKey = null, ready = null+ const readyFor = S => {+ const key = [S.routines, S.week, S.dayPlan, S.workouts, S.exWeights, S.unit, todayISO()]+ if (!readyKey || key.some((v, i) => v !== readyKey[i])) {+ readyKey = key+ try { ready = buildReady(S) } catch { ready = null }+ }+ return ready+ }const send = async () => {tm = nulltry {const st = await p.WatchBridge.status()if (!st || !st.paired || !st.installed) return- const json = JSON.stringify(buildSnapshot(useStore.getState().S, { timer: useUI.getState().timer }))+ const S = useStore.getState().S+ const json = JSON.stringify(buildSnapshot(S, { timer: useUI.getState().timer, ready: readyFor(S) }))if (json === lastSent) returnconst r = await p.WatchBridge.sendSnapshot({ json })if (r && r.sent) lastSent = json} catch { /* no watch, or not now: the next change tries again */ }}const schedule = () => { clearTimeout(tm); tm = setTimeout(send, SEND_DEBOUNCE_MS) }- const offStore = useStore.subscribe((s, prev) => { if (s.S.active !== prev.S.active || s.S.unit !== prev.S.unit) schedule() })+ const offStore = useStore.subscribe((s, prev) => { if (s.S !== prev.S) schedule() })const offUI = useUI.subscribe((s, prev) => { if (s.timer !== prev.timer) schedule() })const sub = await p.WatchBridge.addListener('watchEvent', () => { drainWatchEvents() })const onVisible = () => { if (document.visibilityState === 'visible') { drainWatchEvents(); schedule() } }@@ -178,4 +243,4 @@ export async function startWatchSync ({ useStore, useUI }) {// Test seams.export function _setWatchPluginForTest (plugin, getState) { pluginP = Promise.resolve(plugin ? { WatchBridge: plugin } : null); getStateRef = getState || null }-export function _resetWatchSync () { handlers = null; pluginP = null; getStateRef = null; draining = null }+export function _resetWatchSync () { handlers = null; appHandlers = null; pluginP = null; getStateRef = null; draining = null }diff --git a/frontend/src/lib/watch-sync.test.js b/frontend/src/lib/watch-sync.test.jsindex 2f82db681..368f5ee67 100644--- a/frontend/src/lib/watch-sync.test.js+++ b/frontend/src/lib/watch-sync.test.js@@ -3,7 +3,7 @@// watch's events applied once each through the workout screen's own actions, drained from the// native queue and acknowledged only when done.import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { buildSnapshot, applyEvents, bindWatchActions, drainWatchEvents, _setWatchPluginForTest, _resetWatchSync, SNAPSHOT_VERSION } from './watch-sync.js'+import { buildSnapshot, buildReady, applyEvents, bindWatchActions, bindWatchAppActions, drainWatchEvents, _setWatchPluginForTest, _resetWatchSync, SNAPSHOT_VERSION } from './watch-sync.js'const state = (over = {}) => ({unit: 'kg', restSec: 90, workouts: [], routines: [],@@ -38,7 +38,7 @@ describe('the snapshot', () => {})it('says there is no workout when none runs, and no rest when it is paused or over', () => {- expect(buildSnapshot({ unit: 'kg' })).toEqual({ v: SNAPSHOT_VERSION, active: null })+ expect(buildSnapshot({ unit: 'kg' })).toEqual({ v: SNAPSHOT_VERSION, unit: 'kg', active: null, ready: null })expect(buildSnapshot(state(), { timer: { endsAt: 5, paused: true } }).active.rest).toBeNull()expect(buildSnapshot(state(), { timer: { endsAt: 5, ready: true } }).active.rest).toBeNull()expect(buildSnapshot(state({ unit: 'lb' })).active.unit).toBe('lb')@@ -59,7 +59,7 @@ describe('the events from the watch', () => {bindWatchActions({ setDone })expect(applyEvents([ev('a'), ev('a')], () => ({ S }))).toEqual(['a', 'a'])expect(setDone).toHaveBeenCalledTimes(1)- expect(setDone).toHaveBeenCalledWith(0, 1, { w: 62.5, r: 7 })+ expect(setDone).toHaveBeenCalledWith(0, 1, { w: 62.5, r: 7, at: 1 })// …and again later (a second drain, a restart of the page): still onceexpect(applyEvents([ev('a')], () => ({ S }))).toEqual(['a'])expect(setDone).toHaveBeenCalledTimes(1)@@ -72,7 +72,7 @@ describe('the events from the watch', () => {bindWatchActions({ setDone })expect(applyEvents([ev('moved'), ev('gone', { exId: '9999', entryIdx: 5 }), ev('other', { wid: 'w-2' })], () => ({ S }))).toEqual(['moved', 'gone', 'other'])expect(setDone).toHaveBeenCalledTimes(1)- expect(setDone).toHaveBeenCalledWith(1, 1, { w: 62.5, r: 7 })+ expect(setDone).toHaveBeenCalledWith(1, 1, { w: 62.5, r: 7, at: 1 })})it('wait in the queue while the workout screen is not there', () => {@@ -90,7 +90,7 @@ describe('the native queue', () => {const setDone = vi.fn()bindWatchActions({ setDone })await drainWatchEvents()- expect(setDone).toHaveBeenCalledWith(0, 1, { w: 60, r: 8 })+ expect(setDone).toHaveBeenCalledWith(0, 1, { w: 60, r: 8, at: null })expect(p.ack).toHaveBeenCalledWith({ ids: ['x1'] })})@@ -107,3 +107,47 @@ describe('the native queue', () => {expect(await drainWatchEvents()).toEqual([])})})++describe('starting and finishing on the watch', () => {+ const routines = [+ { id: 'r-push', name: 'Push', ex: [{ id: '0025', sets: 3, reps: 8, weight: 60 }] },+ { id: 'r-pull', name: 'Pull', ex: [{ id: '0001', sets: 2, reps: 10 }] },+ ]++ it('the phone keeps today\'s session and the other routines ready, built as Start builds them', () => {+ const S = { unit: 'kg', workouts: [], routines, week: { 2: 'r-push' }, dayPlan: {} }+ const ready = buildReady(S, '2026-10-13') // a Tuesday+ expect(ready.today).toMatchObject({ routineIds: ['r-push'], name: 'Push' })+ expect(ready.today.entries[0].sets).toHaveLength(3)+ expect(ready.others.map(o => o.routineIds)).toEqual([['r-pull']])+ const snap = buildSnapshot(S, { ready })+ expect(snap.active).toBeNull()+ expect(snap.ready.today.name).toBe('Push')+ })++ it('a start from the watch starts the session with the watch\'s id and time, once; the sets after it wait for the workout screen', () => {+ let S = { active: null }+ const start = vi.fn((ids, opts) => { S = { active: { id: opts.id, entries: [{ id: '0025', sets: [{ w: 60, r: 8, done: false }] }] } } })+ bindWatchAppActions({ start })+ const events = [+ { id: 's1', type: 'start', routineIds: ['r-push'], wid: 'watch-1', at: 1700000000000 },+ { id: 'd1', type: 'setDone', wid: 'watch-1', exId: '0025', entryIdx: 0, setIdx: 0, w: 60, r: 8, at: 1700000100000 },+ ]+ expect(applyEvents(events, () => ({ S }))).toEqual(['s1'])+ expect(start).toHaveBeenCalledWith(['r-push'], { id: 'watch-1', start: 1700000000000 })+ const setDone = vi.fn(), finish = vi.fn()+ bindWatchActions({ setDone, finish })+ expect(applyEvents([...events, { id: 'f1', type: 'finish', wid: 'watch-1', at: 1700000200000 }], () => ({ S }))).toEqual(['s1', 'd1', 'f1'])+ expect(start).toHaveBeenCalledTimes(1)+ expect(setDone).toHaveBeenCalledWith(0, 0, { w: 60, r: 8, at: 1700000100000 })+ expect(finish).toHaveBeenCalledTimes(1)+ })++ it('a start while another workout runs on the phone keeps that one', () => {+ const S = { active: { id: 'phone-1', entries: [] } }+ const start = vi.fn()+ bindWatchAppActions({ start })+ expect(applyEvents([{ id: 's2', type: 'start', routineIds: ['r'], wid: 'watch-2', at: 1 }], () => ({ S }))).toEqual(['s2'])+ expect(start).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex c82a0d80d..d7e31b863 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -2787,12 +2787,15 @@ export function startFlow(routineIds) {if (S().weighIn === false) { beginWorkout(routineIds, null); return }bwSheet({ required: true, onDone: bw => beginWorkout(routineIds, bw) })}-export function beginWorkout(routineIds, bw) {+// `opts` from the Apple Watch (lib/watch-sync.js): a session started there keeps the watch's id,+// so the sets ticked on it find it, and its start time, however late the phone hears of it.+export function beginWorkout(routineIds, bw, { id = null, start = null } = {}) {const st = S()const { entries, routineIds: rids, routines } = buildCombinedEntries(st, routineIds)+ const startAt = Number.isFinite(start) && start > 0 ? start : Date.now()update(s => {s.active = {- id: uid(), d: todayISO(), start: Date.now(),+ id: id || uid(), d: id && start ? isoOf(new Date(startAt)) : todayISO(), start: startAt,// A session tracks its routines as a list; per-entry `rid` carries which one each// exercise came from. No top-level `excludeFromProgression` — per-entry `noProg` does it.routineIds: rids,@@ -3375,6 +3378,9 @@ export function finishWorkoutSheet({ onDiscard } = {}) {],})}+// Finish and save without a question: the Apple Watch's Finish (lib/watch-sync.js) runs exactly+// what the phone's Finish and save runs.+export const finishWorkoutNow = () => doFinishWorkout()function doFinishWorkout() {const st = S()const A = st.activediff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex a9b3e00a4..c30d72fdb 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -26,7 +26,7 @@ import WorkoutThumb, { hasWorkoutMedia } from '../components/WorkoutThumb.jsx'import { workoutSettingsSheet } from '../components/WorkoutSettingsSheet.jsx'import { durationSheet } from '../components/DurationWheel.jsx'import { REST_MAX, fmtRest } from '../lib/duration.js'-import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, exitWorkoutEdit, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, renameWorkoutSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet, finishWorkoutSheet } from '../sheets.jsx'+import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, exitWorkoutEdit, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, renameWorkoutSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet, finishWorkoutSheet, finishWorkoutNow } from '../sheets.jsx'import { afterScrollRestore, scrollRestorePending } from '../components/Modals.jsx'import { effortColor } from '../lib/effort.js'import Elapsed from '../components/Elapsed.jsx'@@ -1758,12 +1758,16 @@ function ActiveWorkout() {// end-of-workout sheet). A row already ticked only takes the numbers.const toggleRef = useRef(toggle)toggleRef.current = toggle+ // The time is the watch's: the phone may hear of the set much later (lib/finish-workout.js+ // sessionEnd reads the sets' times). The watch's Finish runs the phone's Finish and save.useEffect(() => bindWatchActions({- setDone: (idx, i, { w, r }) => {+ setDone: (idx, i, { w, r, at }) => {if (useStore.getState().S.active?.editingWorkoutId) return // a saved workout being edited is not the sessionmutEntry(idx, en => { const set = en.sets[i]; if (!set) return; if (w != null) set.w = w; if (r != null) set.r = r })if (!useStore.getState().S.active?.entries?.[idx]?.sets?.[i]?.done) toggleRef.current(idx, i)+ if (at) mutEntry(idx, en => { const set = en.sets[i]; if (set?.done) set.at = at })},+ finish: () => { if (!useStore.getState().S.active?.editingWorkoutId) finishWorkoutNow() },}), [])// After the finished exercise folded away (toggle, above): the new current one is the next thingdiff --git a/frontend/src/views/Workout.watch.test.jsx b/frontend/src/views/Workout.watch.test.jsxindex d65f033e9..0cda06d6c 100644--- a/frontend/src/views/Workout.watch.test.jsx+++ b/frontend/src/views/Workout.watch.test.jsx@@ -57,4 +57,15 @@ describe('a set ticked on the watch', () => {act(() => { applyEvents([{ id: 'e2', type: 'setDone', wid: 'w-watch', exId: '0025', entryIdx: 0, setIdx: 0, w: 65, r: 6 }], () => useStore.getState()) })expect(useStore.getState().S.active.entries[0].sets[0]).toMatchObject({ w: 65, r: 6, done: true })})++ it('keeps the watch\'s time on the set, and the watch\'s Finish saves the workout like Finish and save', () => {+ const at = Date.now() - 60000+ act(() => { applyEvents([{ id: 'e3', type: 'setDone', wid: 'w-watch', exId: '0025', entryIdx: 0, setIdx: 0, w: 60, r: 8, at }], () => useStore.getState()) })+ expect(useStore.getState().S.active.entries[0].sets[0].at).toBe(at)+ act(() => { applyEvents([{ id: 'f1', type: 'finish', wid: 'w-watch', at: at + 1000 }], () => useStore.getState()) })+ const S = useStore.getState().S+ expect(S.active).toBeNull()+ expect(S.workouts.at(-1)).toMatchObject({ id: 'w-watch' })+ expect(S.workouts.at(-1).entries[0].sets[0]).toMatchObject({ w: 60, r: 8, done: true, at })+ })})