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
fix(watch): the watch hears the phone after a late link, a reinstall and odd routines (TestFlight)
Duarte Santosd19ef668e357
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9076835de..2eb4f9ccc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,9 @@ tiny body, faint where the session is headed and lit up where you've already ticlayout and without moving a single set row (#670). Tap it for the big map and done/planned setsper muscle. Settings → Workout → Fine-tuning turns it off.+- **Apple Watch keeps up.** The watch could miss the phone right after launch and then hear+ nothing until you reopened the app, a freshly installed watch app could wait for your next change+ before it got your routines, and one odd routine could hide all of them. All fixed.- **Faster on long histories.** Home and Stats do far less work per open (Stats about a thirdless on 800 workouts), the main script a start parses is a quarter smaller, the installed web app stops askingthe server about every file on each launch, and other languages load their words in one godiff --git a/frontend/ios/App/App/WatchBridgePlugin.swift b/frontend/ios/App/App/WatchBridgePlugin.swiftindex 0ca29ba40..b9129cc5c 100644--- a/frontend/ios/App/App/WatchBridgePlugin.swift+++ b/frontend/ios/App/App/WatchBridgePlugin.swift@@ -112,7 +112,10 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {call.resolve(["sent": false])return}- let payload: [String: Any] = ["snapshot": json]+ // Stamped: iOS does not deliver an application context equal to the last one, and the page+ // sends the same snapshot again on purpose when the watch app was (re)installed. The watch+ // reads only "snapshot".+ let payload: [String: Any] = ["snapshot": json, "at": Date().timeIntervalSince1970]do {try s.updateApplicationContext(payload)} catch {diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.jsindex 7998677b9..70467135c 100644--- a/frontend/src/lib/watch-sync.js+++ b/frontend/src/lib/watch-sync.js@@ -90,7 +90,9 @@ function watchEntry (e, H, S) {} catch { last = null }const best = S ? bestFor(S, e.id, mode) : nullreturn {- id: e.id,+ // A string always: the watch reads the whole snapshot or nothing (WatchCore Model.swift), and+ // one id that came in as a number (an import) would leave it with nothing at all.+ id: String(e.id),// Title-cased as on the phone; the watch has no CSS to do it (lib/format.js exerciseNameText).name: ex ? exerciseNameText(ex) : String(target.name || e.name || e.id),mode,@@ -116,10 +118,17 @@ function watchEntry (e, H, S) {export function buildReady (S, today = todayISO()) {let H = nulltry { H = sessionHistory(S) } catch { H = null }+ // One routine that cannot be built is left out, not the whole list with it.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, S)) }+ try {+ const { entries, routineIds, routines } = buildCombinedEntries(S, ids)+ if (!routines.length) return null+ return {+ routineIds: routineIds.map(String),+ name: String(deriveSessionName(routines.map(r => r.name)) || ''),+ entries: entries.filter(e => e && e.id != null).map(e => watchEntry(e, H, S)),+ }+ } catch { return null }}let todayIds = []try { todayIds = effectiveRoutineIds({ ...S, routines: S.routines || [], week: S.week || {}, dayPlan: S.dayPlan || {} }, today, today) || [] } catch { todayIds = [] }@@ -151,7 +160,7 @@ export function buildSnapshot(S, { timer = null, ready = null } = {}) {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 => watchEntry(e, H, S)),+ entries: A.entries.filter(e => e && e.id != null).map(e => watchEntry(e, H, S)),},}}@@ -448,7 +457,11 @@ export async function startWatchSync ({ useStore, useUI }) {// change. Without one nothing below runs at all: no snapshot, no clips, no bridge call per tick.let linked = falseconst checkLink = async () => {+ const was = linkedtry { const st = await p.WatchBridge.status(); linked = !!(st && st.paired && st.installed) } catch { linked = false }+ // A watch that is new here (the app just installed on it, or reinstalled): it has nothing yet,+ // so the snapshot goes again even when it is the same as the last one sent.+ if (linked && !was) lastSent = nullreturn linked}await checkLink()@@ -511,9 +524,14 @@ export async function startWatchSync ({ useStore, useUI }) {const sub = await p.WatchBridge.addListener('watchEvent', () => { drainWatchEvents() })// The link itself changed (the session finished activating after launch, a watch was paired, the// app was installed on it): asked again, and the snapshot sent when there is a watch now.- const subLink = await Promise.resolve(p.WatchBridge.addListener('watchState', () => { checkLink().then(() => schedule()) })).catch(() => null)+ // Sent again even when unchanged: a reinstalled watch app starts with nothing.+ const subLink = await Promise.resolve(p.WatchBridge.addListener('watchState', () => { checkLink().then(() => { lastSent = null; schedule() }) })).catch(() => null)const onVisible = () => { if (document.visibilityState === 'visible') { drainWatchEvents(); checkLink().then(() => schedule()) } }document.addEventListener('visibilitychange', onVisible)+ // Asked once more now that the listeners are there: the link may have come up (watchState) while+ // the first answer above was on its way, and that event had no one to hear it. Without this the+ // watch heard nothing until the app went to the background and came back.+ if (!linked) await checkLink()schedule()drainWatchEvents()return () => { offStore(); offUI(); offPrefs(); offHealth(); offLang(); sub?.remove?.(); subLink?.remove?.(); document.removeEventListener('visibilitychange', onVisible); clearTimeout(tm) }diff --git a/frontend/src/lib/watch-sync.open.test.js b/frontend/src/lib/watch-sync.open.test.jsindex 3eed2bda7..fe40a7f04 100644--- a/frontend/src/lib/watch-sync.open.test.js+++ b/frontend/src/lib/watch-sync.open.test.js@@ -126,6 +126,41 @@ describe('startWatchSync', () => {} finally { vi.useRealTimers() }})+ // The link came up (WCSession activated) while the first status() was on its way: that+ // watchState event had no listener yet. The watch heard nothing until the app was reopened.+ it('sends to the watch when the link comes up during startup, before anyone listened', async () => {+ vi.useFakeTimers()+ try {+ const b = bridge()+ b.status.mockResolvedValueOnce({ activated: false, paired: false, installed: false })+ _setWatchPluginForTest(b)+ const stop = await startWatchSync({ useStore: store({ S: S0 }), useUI: ui })+ await vi.runAllTimersAsync()+ expect(b.sendSnapshot).toHaveBeenCalled()+ stop()+ } finally { vi.useRealTimers() }+ })++ // A watch app installed or reinstalled while the phone app runs starts with nothing: the same+ // snapshot goes again (the native side stamps it, so iOS delivers it although it is unchanged).+ it('sends the same snapshot again when the watch link changes', async () => {+ vi.useFakeTimers()+ try {+ const b = bridge()+ const heard = {}+ b.addListener = vi.fn(async (name, fn) => { heard[name] = fn; return { remove: () => {} } })+ _setWatchPluginForTest(b)+ const stop = await startWatchSync({ useStore: store({ S: S0 }), useUI: ui })+ await vi.runAllTimersAsync()+ expect(b.sendSnapshot).toHaveBeenCalledTimes(1)+ heard.watchState({ installed: true })+ await vi.runAllTimersAsync()+ expect(b.sendSnapshot).toHaveBeenCalledTimes(2)+ expect(b.sendSnapshot.mock.calls[1][0].json).toBe(b.sendSnapshot.mock.calls[0][0].json)+ stop()+ } finally { vi.useRealTimers() }+ })+it('tells the watch the phone\'s Apple Health switch, and again when it changes', async () => {vi.useFakeTimers()try {diff --git a/frontend/src/lib/watch-sync.test.js b/frontend/src/lib/watch-sync.test.jsindex 3b7ac8fe0..48b27f671 100644--- a/frontend/src/lib/watch-sync.test.js+++ b/frontend/src/lib/watch-sync.test.js@@ -151,6 +151,16 @@ describe('starting and finishing on the watch', () => {expect(snap.ready.today.name).toBe('Push')})+ // The watch reads a snapshot whole or not at all: one odd routine must not cost it the others,+ // and an id that came in as a number must still reach it as text.+ it('one routine that cannot be built is left out, and every id goes as text', () => {+ const odd = [{ id: 'r-odd', name: 'Odd' }, { id: 7, name: 'Imported', ex: [{ id: 25, sets: 1, reps: 5 }] }, ...routines]+ const ready = buildReady({ unit: 'kg', workouts: [], routines: odd, week: { 2: 'r-push' }, dayPlan: {} }, '2026-10-13')+ expect(ready.today).toMatchObject({ routineIds: ['r-push'] })+ expect(ready.others.map(o => o.routineIds)).toEqual([['7'], ['r-pull']])+ expect(ready.others[0].entries[0].id).toBe('25')+ })+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 }] }] } } })