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: the running workout goes to the watch, its ticks come back
Duarte Santosbe48580957f2
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex b97e709bd..71da30f50 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -13,6 +13,7 @@ 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 { useWakeLock } from './lib/wakelock.js'import { installViewportGuard } from './lib/viewport-guard.js'import { installChipDrag } from './lib/hchips.js'@@ -321,5 +322,13 @@ export default function App() {}, [])// iOS: swipe from the left edge for the page's own back button (lib/edge-swipe-back.js)useEffect(() => installEdgeSwipeBack(), [])+ // iPhone app with an Apple Watch: the running workout goes to the watch, its ticks come back+ // (lib/watch-sync.js). Nothing at all on the web, on Android, or without a paired watch.+ useEffect(() => {+ if (!MOBILE) return+ let stop = null, gone = false+ startWatchSync({ useStore, useUI }).then(fn => { if (gone) fn(); else stop = fn })+ return () => { gone = true; stop?.() }+ }, [])return <HashRouter><Shell /></HashRouter>}diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.jsnew file mode 100644index 000000000..84e630e14--- /dev/null+++ b/frontend/src/lib/watch-sync.js@@ -0,0 +1,181 @@+// The Apple Watch link, the page's side (native: ios/App/App/WatchBridgePlugin.swift, the watch+// app: ios/App/Watch).+//+// Phone → watch: while a workout runs, a snapshot of it (each exercise by name, its sets with+// weight, reps and done, the rest, where you are) goes to the watch whenever it changes. The watch+// then runs the session on its own: the phone's page sleeps once the phone is locked in a pocket.+//+// Watch → phone: what happened on the watch comes back as small events ({ id, type: 'setDone',+// wid, exId, entryIdx, setIdx, w, r, at }). They are applied through the workout screen's own+// actions (bindWatchActions), the same ones a tap on the phone runs (rest timer, the high-water+// mark, the end-of-workout sheet), never a second copy of them. Each event is applied once, by its+// id, and only then acknowledged, which takes it out of the native queue; until the workout screen+// is there to apply it, it waits in that queue.+//+// The iPhone app only. Without a paired watch with the app on it, nothing is sent and nothing+// arrives: the phone behaves exactly as before.+import { MOBILE, nativePlatform } from './mobile.js'+import { EXIDX } from './exercises.js'+import { exerciseNameFor } from './i18n.js'+import { modeOf, setLabel, lastEntryFor } from './history.js'+import { isWarmupRow } from './workout-model.js'+import { sessionHistory } from './backfill.js'++export const SNAPSHOT_VERSION = 1+const APPLIED_KEY = 'gym_watch_applied'+const APPLIED_MAX = 300+const SEND_DEBOUNCE_MS = 400++const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null)++/* ---------- the snapshot ---------- */++/** What the watch needs to run the session: plain data, no media (licence: text only). */+export function buildSnapshot(S, { timer = null } = {}) {+ const A = S && S.active+ if (!A || !Array.isArray(A.entries)) return { v: SNAPSHOT_VERSION, active: null }+ let H = null+ try { H = sessionHistory(S) } catch { H = null }+ return {+ v: SNAPSHOT_VERSION,+ active: {+ id: A.id || null,+ name: A.name || '',+ unit: S.unit === 'lb' ? 'lb' : 'kg',+ 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 one+ rest: 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),+ })),+ }+ }),+ },+ }+}++/* ---------- applying the watch's events ---------- */++let handlers = null+const 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 */ } }++/** The entry an event means: by position when it still holds that exercise, else by the exercise. */+function entryIndexOf (A, ev) {+ if (A.entries[ev.entryIdx] && A.entries[ev.entryIdx].id === ev.exId) return ev.entryIdx+ return A.entries.findIndex(e => e.id === ev.exId)+}++/**+ * 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.+ */+export function applyEvents (events, getState) {+ if (!handlers || !Array.isArray(events)) return []+ const applied = readApplied()+ const done = []+ for (const ev of events) {+ if (!ev || typeof ev.id !== 'string') continue+ if (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 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) })+ }+ // Applied, or meaningless now (another workout, a set that is gone): either way it is done.+ applied.push(ev.id)+ done.push(ev.id)+ }+ writeApplied(applied)+ return done+}++/* ---------- the native plugin ---------- */++let pluginP = null+// Inside an object: a Capacitor plugin proxy answers `then`, so a promise must never resolve with+// the bare proxy (lib/rest-alert.js, the Coach hang #42).+const watchPlugin = () => pluginP || (pluginP = (async () => {+ if (!MOBILE || (await nativePlatform()) !== 'ios') return null+ const { registerPlugin } = await import('@capacitor/core')+ return { WatchBridge: registerPlugin('WatchBridge') }+})().catch(() => null))++let getStateRef = null+let draining = null++/** Takes what the watch sent from the native queue, applies it, and acknowledges what is done. */+export function drainWatchEvents () {+ if (draining) return draining+ draining = (async () => {+ try {+ const p = await watchPlugin()+ if (!p || !getStateRef) return []+ const { events = [] } = (await p.WatchBridge.drain()) || {}+ const done = applyEvents(events, getStateRef)+ if (done.length) await p.WatchBridge.ack({ ids: done })+ return done+ } catch { return [] } finally { draining = null }+ })()+ return draining+}++/** The workout screen hands over its own actions while it is mounted. Returns the unbind. */+export function bindWatchActions (h) {+ handlers = h+ drainWatchEvents()+ return () => { if (handlers === h) handlers = null }+}++/**+ * Started once by the app. Sends a snapshot whenever the workout or its rest changes (debounced,+ * and only what differs from the last one sent), drains the queue when the app comes back.+ */+export async function startWatchSync ({ useStore, useUI }) {+ const p = await watchPlugin()+ if (!p) return () => {}+ getStateRef = () => useStore.getState()+ let lastSent = null, tm = null+ const send = async () => {+ tm = null+ try {+ 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 }))+ if (json === lastSent) return+ const 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 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() } }+ document.addEventListener('visibilitychange', onVisible)+ schedule()+ drainWatchEvents()+ return () => { offStore(); offUI(); sub?.remove?.(); document.removeEventListener('visibilitychange', onVisible); clearTimeout(tm) }+}++// 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 }diff --git a/frontend/src/lib/watch-sync.test.js b/frontend/src/lib/watch-sync.test.jsnew file mode 100644index 000000000..2f82db681--- /dev/null+++ b/frontend/src/lib/watch-sync.test.js@@ -0,0 +1,109 @@+// @vitest-environment happy-dom+// The Apple Watch link, the page's side: the snapshot the watch runs a session from, and the+// 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'++const state = (over = {}) => ({+ unit: 'kg', restSec: 90, workouts: [], routines: [],+ active: {+ id: 'w-1', name: 'Push day', cur: 1, d: '2026-10-13',+ entries: [+ { id: '0025', target: { sets: 2, reps: 8, weight: 60 }, sets: [{ w: 60, r: 8, done: true }, { w: 60, r: 8, done: false }] },+ { id: '0001', target: { sets: 1, reps: 10, restSec: 120 }, sets: [{ w: 20, r: 10, done: false, phase: 'warmup' }] },+ ],+ },+ ...over,+})++beforeEach(() => { localStorage.clear(); _resetWatchSync() })+afterEach(() => _resetWatchSync())++describe('the snapshot', () => {+ it('carries what the watch needs to run the session, and nothing else', () => {+ const snap = buildSnapshot(state(), { timer: { endsAt: 1760000000000 } })+ expect(snap.v).toBe(SNAPSHOT_VERSION)+ expect(snap.active).toMatchObject({ id: 'w-1', name: 'Push day', unit: 'kg', cur: 1, restSec: 90, rest: { endsAt: 1760000000000 } })+ expect(snap.active.entries).toHaveLength(2)+ const [a, b] = snap.active.entries+ expect(a).toMatchObject({ id: '0025', mode: 'reps', restSec: null, last: null })+ expect(typeof a.name).toBe('string')+ expect(a.name.length).toBeGreaterThan(0)+ expect(a.sets).toEqual([{ w: 60, r: 8, sec: null, done: true, warmup: false }, { w: 60, r: 8, sec: null, done: false, warmup: false }])+ expect(b.restSec).toBe(120)+ expect(b.sets[0].warmup).toBe(true)+ // plain data only: no media, no image or animation paths+ expect(JSON.stringify(snap)).not.toMatch(/\.(gif|webp|png|jpg|mp4)|media|img/i)+ })++ 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(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')+ })++ it('names the last time of an exercise when the history has one', () => {+ const S = state({ workouts: [{ id: 'old', d: '2026-10-01', entries: [{ id: '0025', target: { sets: 2, reps: 8 }, sets: [{ w: 55, r: 8, done: true }, { w: 55, r: 7, done: true }] }] }] })+ expect(buildSnapshot(S).active.entries[0].last).toMatch(/55/)+ })+})++describe('the events from the watch', () => {+ const ev = (id, over = {}) => ({ id, type: 'setDone', wid: 'w-1', exId: '0025', entryIdx: 0, setIdx: 1, w: 62.5, r: 7, at: 1, ...over })++ it('go through the workout screen\'s own action, once each', () => {+ const S = state()+ const setDone = vi.fn()+ 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 })+ // …and again later (a second drain, a restart of the page): still once+ expect(applyEvents([ev('a')], () => ({ S }))).toEqual(['a'])+ expect(setDone).toHaveBeenCalledTimes(1)+ })++ it('find their exercise when the phone moved it, and drop what no longer exists', () => {+ const S = state()+ S.active.entries.reverse()+ const setDone = vi.fn()+ 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 })+ })++ it('wait in the queue while the workout screen is not there', () => {+ expect(applyEvents([ev('a')], () => ({ S: state() }))).toEqual([])+ })+})++describe('the native queue', () => {+ const plugin = events => ({ drain: vi.fn(async () => ({ events })), ack: vi.fn(async () => {}) })++ it('is drained when the workout screen binds, and acknowledged only for what was done', async () => {+ const S = state()+ const p = plugin([{ id: 'x1', type: 'setDone', wid: 'w-1', exId: '0025', entryIdx: 0, setIdx: 1, w: 60, r: 8 }])+ _setWatchPluginForTest(p, () => ({ S }))+ const setDone = vi.fn()+ bindWatchActions({ setDone })+ await drainWatchEvents()+ expect(setDone).toHaveBeenCalledWith(0, 1, { w: 60, r: 8 })+ expect(p.ack).toHaveBeenCalledWith({ ids: ['x1'] })+ })++ it('without the workout screen nothing is acknowledged: the events stay for later', async () => {+ const p = plugin([{ id: 'x1', type: 'setDone', wid: 'w-1', exId: '0025', entryIdx: 0, setIdx: 1 }])+ _setWatchPluginForTest(p, () => ({ S: state() }))+ expect(await drainWatchEvents()).toEqual([])+ expect(p.ack).not.toHaveBeenCalled()+ })++ it('off the iPhone app there is no plugin and nothing happens', async () => {+ _setWatchPluginForTest(null, () => ({ S: state() }))+ bindWatchActions({ setDone: vi.fn() })+ expect(await drainWatchEvents()).toEqual([])+ })+})diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex b684b1566..a9b3e00a4 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -39,6 +39,7 @@ import { routineChangesFromEntry, updateRoutineFromEntry } from '../lib/routinesimport { sessionNoProg, setSessionNoProg, setEntryNoProg, joinSessionNoProg } from '../lib/session-noprog.js'import { glyphOf } from '../lib/glyphs.js'import { markAllSetsDone, sessionHistory } from '../lib/backfill.js'+import { bindWatchActions } from '../lib/watch-sync.js'import { bestSetFor } from '../lib/exercise-history.js'import { isWarmupRow, isFailureSet, toggleFailure, 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, canMoveActiveWorkoutEntry, moveActiveWorkoutEntry } from '../lib/active-workout-order.js'@@ -1752,6 +1753,18 @@ function ActiveWorkout() {onFocusProgress?.({ unitDone: freshUnitDone })}}+ // The Apple Watch ticks sets through this same toggle (lib/watch-sync.js): the weight and reps it+ // logged go into the row first, then the tick runs as if tapped here (rest, high-water mark, the+ // end-of-workout sheet). A row already ticked only takes the numbers.+ const toggleRef = useRef(toggle)+ toggleRef.current = toggle+ useEffect(() => bindWatchActions({+ setDone: (idx, i, { w, r }) => {+ if (useStore.getState().S.active?.editingWorkoutId) return // a saved workout being edited is not the session+ mutEntry(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)+ },+ }), [])// After the finished exercise folded away (toggle, above): the new current one is the next thing// to do, so if it now sits under the header or low on the screen with little more than its titlediff --git a/frontend/src/views/Workout.watch.test.jsx b/frontend/src/views/Workout.watch.test.jsxnew file mode 100644index 000000000..d65f033e9--- /dev/null+++ b/frontend/src/views/Workout.watch.test.jsx@@ -0,0 +1,60 @@+// @vitest-environment happy-dom+// A set ticked on the Apple Watch runs the workout screen's own tick (lib/watch-sync.js): the+// weight and reps from the watch go into the row, the row is done, and the rest starts, exactly+// as a tap on the phone does it. Applied once, however often the event arrives.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { MemoryRouter } from 'react-router-dom'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Workout, { _resetHintQuiet } from './Workout.jsx'+import { DEF, useStore } from '../store/useStore.js'+import { useUI } from '../store/useUI.js'+import { applyEvents, _resetWatchSync } from '../lib/watch-sync.js'++vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), beacon: vi.fn(), appBase: () => '/' }))++globalThis.IS_REACT_ACT_ENVIRONMENT = true+const clone = v => JSON.parse(JSON.stringify(v))+let root, container++beforeEach(() => {+ _resetHintQuiet(); _resetWatchSync()+ vi.useFakeTimers()+ localStorage.clear()+ useUI.getState().stopRest()+ useUI.setState({ sheets: [], toastMsg: '', timer: null, work: null, swipeHint: null })+ const S = clone(DEF)+ S.hints = { swipeSets: true }+ S.restSec = 90+ S.active = { id: 'w-watch', d: '2026-10-13', start: Date.now(), name: 'Watch test', cur: 0,+ entries: [{ id: '0025', target: { sets: 2, reps: 8, weight: 60 }, sets: [{ w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }] }] }+ useStore.setState({ S, user: null })+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container)+ act(() => root.render(<MemoryRouter><Workout /></MemoryRouter>))+})+afterEach(() => {+ act(() => root.unmount()); container.remove()+ useUI.getState().stopRest()+ vi.clearAllTimers(); vi.useRealTimers()+})++describe('a set ticked on the watch', () => {+ it('takes the watch\'s numbers, is ticked by the screen\'s own tick, and starts the rest', () => {+ const ev = { id: 'e1', type: 'setDone', wid: 'w-watch', exId: '0025', entryIdx: 0, setIdx: 0, w: 62.5, r: 7, at: 1 }+ act(() => { applyEvents([ev, ev], () => useStore.getState()) })+ const set = useStore.getState().S.active.entries[0].sets[0]+ expect(set).toMatchObject({ w: 62.5, r: 7, done: true })+ expect(typeof set.at).toBe('number')+ expect(useUI.getState().timer).toBeTruthy() // the rest the tap would have started+ expect(useStore.getState().S.active.entries[0].sets[1].done).toBe(false)+ act(() => { applyEvents([ev], () => useStore.getState()) })+ expect(useStore.getState().S.active.entries[0].sets[0].done).toBe(true) // not toggled back off+ })++ it('a row already ticked on the phone only takes the numbers', () => {+ act(() => { useStore.getState().update(s => { s.active.entries[0].sets[0].done = true }) })+ 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 })+ })+})