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.

Apple Watch: opens with a workout started on the iPhone; heart rate follows the phone's Apple Health switch

Duarte Santosebbd815fc9fc
diff --git a/frontend/ios/App/App/WatchBridgePlugin.swift b/frontend/ios/App/App/WatchBridgePlugin.swift
index 55a27a7d4..b2287deaa 100644
--- a/frontend/ios/App/App/WatchBridgePlugin.swift
+++ b/frontend/ios/App/App/WatchBridgePlugin.swift
@@ -1,6 +1,7 @@
import AVFoundation
import Capacitor
import Foundation
+import HealthKit
import ImageIO
import UniformTypeIdentifiers
import WatchConnectivity
@@ -28,6 +29,7 @@ import WatchConnectivity
* await WatchBridge.ack({ ids })
* WatchBridge.addListener('watchEvent', e => ...)
* await WatchBridge.sendClips({ wid, clips: [{ exId, path }] }) // the workout's animations
+ * await WatchBridge.openOnWatch() // { ok }: a workout started here opens the watch app
*
* Animations: only the running workout's, only as files sent with transferFile (the watch keeps
* them while that workout runs and deletes them after). Each is what this phone shows for that
@@ -46,6 +48,7 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
CAPPluginMethod(name: "drain", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "ack", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "sendClips", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "openOnWatch", returnType: CAPPluginReturnPromise),
]
private let queue = DispatchQueue(label: "ch.opengym.watch-events")
@@ -73,6 +76,27 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
])
}
+ /// A workout started on the phone: the watch app opens with it (Settings → Apple Watch, "Open on
+ /// the watch"). HealthKit wakes the watch app with a strength-training configuration, and the
+ /// watch starts its workout session (OpenGymWatchApp's delegate). Only with a paired watch that
+ /// has the app; anything else resolves { ok: false } and nothing happens.
+ @objc func openOnWatch(_ call: CAPPluginCall) {
+ guard WCSession.isSupported(), WCSession.default.activationState == .activated,
+ WCSession.default.isPaired, WCSession.default.isWatchAppInstalled,
+ HKHealthStore.isHealthDataAvailable() else {
+ call.resolve(["ok": false])
+ return
+ }
+ let config = HKWorkoutConfiguration()
+ config.activityType = .traditionalStrengthTraining
+ config.locationType = .indoor
+ WatchBridgePlugin.health.startWatchApp(with: config) { ok, _ in
+ call.resolve(["ok": ok])
+ }
+ }
+
+ private static let health = HKHealthStore()
+
@objc func sendSnapshot(_ call: CAPPluginCall) {
guard let json = call.getString("json") else {
call.reject("json is required")
diff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swift
index 0ff42674f..0a9212d6d 100644
--- a/frontend/ios/App/Watch/OpenGymWatchApp.swift
+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift
@@ -1,4 +1,6 @@
+import HealthKit
import SwiftUI
+import WatchKit
import WidgetKit
/*
@@ -15,18 +17,28 @@ import WidgetKit
*/
@main
struct OpenGymWatchApp: App {
- @StateObject private var store = SessionStore()
+ @WKApplicationDelegateAdaptor private var delegate: WatchAppDelegate
var body: some Scene {
WindowGroup {
RootView()
- .environmentObject(store)
+ .environmentObject(delegate.store)
.tint(Theme.accent)
.background(Color.black)
}
}
}
+/// Owns the session, so HealthKit's launch for a workout started on the iPhone (WatchBridgePlugin
+/// openOnWatch → startWatchApp) reaches it even before the first view is drawn.
+final class WatchAppDelegate: NSObject, WKApplicationDelegate {
+ let store = SessionStore()
+
+ func handle(_ workoutConfiguration: HKWorkoutConfiguration) {
+ store.openedForWorkout()
+ }
+}
+
enum Theme {
/// The app's default accent (frontend/src/index.css --green, dark).
static let accent = Color(red: 0x30 / 255, green: 0xd1 / 255, blue: 0x58 / 255)
@@ -445,26 +457,6 @@ struct HeartRateBadge: View {
}
}
-/// Off until switched on: then the workout runs as an Apple Health workout session (heart rate per
-/// set, the app kept awake with the wrist down) and is saved to Apple Health when it ends.
-struct HealthToggle: View {
- @ObservedObject var health: WorkoutManager
-
- var body: some View {
- Toggle(isOn: Binding(
- get: { health.enabled },
- set: { on in
- if on { health.requestAuthorization { ok in health.enabled = ok } } else { health.enabled = false }
- }
- )) {
- Label("Apple Health", systemImage: "heart.fill")
- }
- .tint(Theme.accent)
- .font(.footnote)
- .frame(minHeight: Theme.tap)
- }
-}
-
/* ---------- hidden: what arrived from the phone ---------- */
struct DebugView: View {
diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swift
index 8d8298546..a930c08f3 100644
--- a/frontend/ios/App/Watch/SessionStore.swift
+++ b/frontend/ios/App/Watch/SessionStore.swift
@@ -144,6 +144,22 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
return .idle
}
+ /// HealthKit opened the app for a workout started on the iPhone: the workout session starts
+ /// now (Apple expects one right away), for the workout the phone sent or is about to send.
+ func openedForWorkout() {
+ DispatchQueue.main.async {
+ self.log("opened by the phone for a workout")
+ if WCSession.isSupported(), let json = WCSession.default.receivedApplicationContext["snapshot"] as? String {
+ self.apply(json: json)
+ }
+ self.health.start(workoutId: self.state.workout?.id)
+ // Nothing came after all (the phone's workout was discarded at once): no session left running.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 60) {
+ if self.state.workout == nil { self.health.end(save: false) }
+ }
+ }
+ }
+
/* ---------- snapshots from the phone ---------- */
func apply(json: String) {
diff --git a/frontend/ios/App/Watch/WorkoutManager.swift b/frontend/ios/App/Watch/WorkoutManager.swift
index d94695115..fb2a2f021 100644
--- a/frontend/ios/App/Watch/WorkoutManager.swift
+++ b/frontend/ios/App/Watch/WorkoutManager.swift
@@ -2,8 +2,8 @@ import Foundation
import HealthKit
/*
- * Apple Health on the watch, behind its switch (on the watch's start screen, and in the phone's
- * Settings → Apple Watch, which wins when it is set): a strength-training workout session as soon
+ * Apple Health on the watch, behind the phone's Apple Health switch (Settings → Data on the iPhone,
+ * sent with every snapshot as settings.health): a strength-training workout session as soon
* as a workout starts here or is picked up from the phone, showing the live heart rate and keeping
* the watch app running with the wrist down (so the rest still taps the wrist on time), and the
* workout saved to Apple Health when it ends. Off, nothing of this runs and nothing is asked.
@@ -11,8 +11,9 @@ import HealthKit
* The heart rate arrives two ways at once, whichever is first: the workout builder's statistics
* and an anchored query on heart-rate samples, which carry their own time (the sets' and rests'
* heart rates are worked out from those times). Until the first reading: "measuring".
- * The permission is asked when the switch is turned on (or the phone turns it on), at the start
- * screen, never in the middle of the first set.
+ * The permission is asked when the phone's switch turns it on, at the start screen, never in the
+ * middle of the first set. A workout started on the iPhone can open the app (HealthKit's
+ * startWatchApp, WatchAppDelegate): the session starts then, and gets the workout's id when it comes.
*/
final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate, HKLiveWorkoutBuilderDelegate {
static let enabledKey = "healthEnabled"
@@ -82,12 +83,23 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
/// The workout's id, for Apple Health's sync identifier (the phone writes none of its own then).
private var workoutId: String?
+ /// The id the running session carries already.
+ private var tagged: String?
+
+ /// One workout in Apple Health, not two: the phone skips writing one with this sync id.
+ private func tag() {
+ guard let b = builder, let wid = workoutId, tagged != wid else { return }
+ tagged = wid
+ b.addMetadata([HKMetadataKeySyncIdentifier: "opengym-w-\(wid)", HKMetadataKeySyncVersion: 1]) { _, _ in }
+ }
/// A workout started here or picked up from the phone: the session starts now.
func start(workoutId wid: String? = nil) {
wanted = true
if let wid = wid { workoutId = wid }
- guard enabled, session == nil, HKHealthStore.isHealthDataAvailable() else { return }
+ // Already running (opened by the phone before its workout arrived): only the id to add.
+ if session != nil { tag(); return }
+ guard enabled, HKHealthStore.isHealthDataAvailable() else { return }
let config = HKWorkoutConfiguration()
config.activityType = .traditionalStrengthTraining
config.locationType = .indoor
@@ -104,10 +116,8 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
let now = Date()
s.startActivity(with: now)
b.beginCollection(withStart: now) { _, _ in }
- // One workout in Apple Health, not two: the phone skips writing one with this sync id.
- if let wid = workoutId {
- b.addMetadata([HKMetadataKeySyncIdentifier: "opengym-w-\(wid)", HKMetadataKeySyncVersion: 1]) { _, _ in }
- }
+ tagged = nil
+ tag()
startQuery(from: now)
running = true
} catch {
diff --git a/frontend/src/lib/watch-settings.js b/frontend/src/lib/watch-settings.js
index d0d3f8e77..8362f7d07 100644
--- a/frontend/src/lib/watch-settings.js
+++ b/frontend/src/lib/watch-settings.js
@@ -4,12 +4,15 @@
// (lib/watch-sync.js, `settings`); it reports back with a watchStatus event.
//
// enabled send workouts to the watch at all (off: the watch shows nothing to do)
-// health Apple Health on the watch: workout session, live heart rate, saved workouts
+// autoShow a workout started on the phone opens the watch app too (HealthKit's startWatchApp)
// restHaptics the wrist taps when a rest is over
// crown what the Digital Crown turns first on a set: 'reps' or 'weight'
+// Apple Health on the watch is not a choice of its own: it follows the phone's Apple Health switch
+// (Settings → Data, lib/health-sync.js), which the watch gets as `settings.health`. An older build's
+// `health` field in the stored prefs is left alone and not read.
export const WATCH_PREFS_KEY = 'gym_watch_v1'
export const WATCH_STATUS_KEY = 'gym_watch_status_v1'
-export const WATCH_DEFAULTS = Object.freeze({ enabled: true, health: false, restHaptics: true, crown: 'reps' })
+export const WATCH_DEFAULTS = Object.freeze({ enabled: true, autoShow: true, restHaptics: true, crown: 'reps' })
const listeners = new Set()
export const onWatchPrefs = fn => { listeners.add(fn); return () => listeners.delete(fn) }
@@ -21,7 +24,7 @@ export function readWatchPrefs(storage = globalThis.localStorage) {
const v = read(WATCH_PREFS_KEY, storage) || {}
return {
enabled: v.enabled !== false,
- health: v.health === true,
+ autoShow: v.autoShow !== false,
restHaptics: v.restHaptics !== false,
crown: v.crown === 'weight' ? 'weight' : 'reps',
}
@@ -48,5 +51,5 @@ export function writeWatchStatus(ev, storage = globalThis.localStorage) {
return next
}
-/** The choices as the watch reads them (WatchCore Model.swift WatchSettings). */
-export const settingsForWatch = (p = readWatchPrefs()) => ({ health: p.health, restHaptics: p.restHaptics, crown: p.crown })
+/** The choices as the watch reads them (WatchCore Model.swift WatchSettings); `health` is the phone's Apple Health switch. */
+export const settingsForWatch = (p = readWatchPrefs(), health = false) => ({ health: !!health, restHaptics: p.restHaptics, crown: p.crown })
diff --git a/frontend/src/lib/watch-settings.test.js b/frontend/src/lib/watch-settings.test.js
index e74238fa3..b85be1eef 100644
--- a/frontend/src/lib/watch-settings.test.js
+++ b/frontend/src/lib/watch-settings.test.js
@@ -11,7 +11,7 @@ describe('the choices', () => {
expect(readWatchPrefs()).toEqual({ ...WATCH_DEFAULTS })
const seen = vi.fn()
onWatchPrefs(seen)
- expect(writeWatchPrefs({ health: true, crown: 'weight', junk: 1 })).toEqual({ enabled: true, health: true, restHaptics: true, crown: 'weight' })
+ expect(writeWatchPrefs({ autoShow: false, crown: 'weight', junk: 1, health: true })).toEqual({ enabled: true, autoShow: false, restHaptics: true, crown: 'weight' })
expect(readWatchPrefs().crown).toBe('weight')
expect(seen).toHaveBeenCalled()
localStorage.setItem('gym_watch_v1', '{broken')
@@ -21,6 +21,10 @@ describe('the choices', () => {
it('go to the watch as its settings, and live outside the profile', () => {
writeWatchPrefs({ restHaptics: false })
expect(settingsForWatch()).toEqual({ health: false, restHaptics: false, crown: 'reps' })
+ // Apple Health on the watch is the phone's Apple Health switch, whatever an older build stored.
+ localStorage.setItem('gym_watch_v1', JSON.stringify({ health: true }))
+ expect(settingsForWatch().health).toBe(false)
+ expect(settingsForWatch(readWatchPrefs(), true).health).toBe(true)
expect(localStorage.getItem('gym_state_v1')).toBeNull()
})
})
diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.js
index 0fd9691bf..ea8293ae7 100644
--- a/frontend/src/lib/watch-sync.js
+++ b/frontend/src/lib/watch-sync.js
@@ -182,6 +182,8 @@ export function applyEvents (events, getState) {
if (ev.type === 'start') {
if (!A) {
if (!appHandlers) break
+ // Started at the wrist: the watch app is open already, nothing to open there (startWatchSync).
+ if (ev.wid) startedOnWatch.add(ev.wid)
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.
@@ -277,6 +279,23 @@ export function bindWatchActions (h) {
* 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.
*/
+// Workouts the watch started, so the phone doesn't open the watch app for them again.
+const startedOnWatch = new Set()
+/** How long after its start a workout that turns up still opens the watch app (not one restored on launch). */
+export const OPEN_ON_WATCH_WINDOW_MS = 2 * 60 * 1000
+
+/**
+ * Whether a workout that just appeared on the phone opens the watch app (Settings → Apple Watch,
+ * "Open on the watch"): a new live session started here a moment ago, not one the watch started,
+ * not a backfilled past one, and not one that came back with the app's saved state.
+ */
+export function shouldOpenOnWatch (prev, next, { prefs = readWatchPrefs(), now = Date.now(), fromWatch = startedOnWatch } = {}) {
+ if (!next || !next.id || (prev && prev.id === next.id)) return false
+ if (!prefs.enabled || !prefs.autoShow || next.backfill || fromWatch.has(next.id)) return false
+ const start = Number(next.start)
+ return Number.isFinite(start) && start > 0 && Math.abs(now - start) <= OPEN_ON_WATCH_WINDOW_MS
+}
+
export async function startWatchSync ({ useStore, useUI }) {
const p = await watchPlugin()
if (!p) return () => {}
@@ -300,6 +319,13 @@ export async function startWatchSync ({ useStore, useUI }) {
return linked
}
await checkLink()
+ // Apple Health on the watch follows the phone's own Apple Health switch (Settings → Data).
+ let healthOn = false, offHealth = () => {}
+ try {
+ const hs = await import('./health-sync.js')
+ healthOn = !!(await hs.loadHealth())?.on
+ offHealth = hs.onHealthChange(h => { if (!!h?.on !== healthOn) { healthOn = !!h?.on; schedule() } })
+ } catch { /* no Apple Health here: the watch measures nothing */ }
const send = async () => {
tm = null
if (!linked) return
@@ -310,7 +336,7 @@ export async function startWatchSync ({ useStore, useUI }) {
const snap = prefs.enabled
? buildSnapshot(S, { timer: useUI.getState().timer, ready: readyFor(S) })
: { v: SNAPSHOT_VERSION, unit: S.unit === 'lb' ? 'lb' : 'kg', active: null, ready: null }
- snap.settings = settingsForWatch(prefs)
+ snap.settings = settingsForWatch(prefs, healthOn)
const json = JSON.stringify(snap)
if (json !== lastSent) {
const r = await p.WatchBridge.sendSnapshot({ json })
@@ -326,7 +352,12 @@ export async function startWatchSync ({ useStore, useUI }) {
} catch { /* no watch, or not now: the next change tries again */ }
}
const schedule = () => { if (!linked) return; clearTimeout(tm); tm = setTimeout(send, SEND_DEBOUNCE_MS) }
- const offStore = useStore.subscribe((s, prev) => { if (s.S !== prev.S) schedule() })
+ const offStore = useStore.subscribe((s, prev) => {
+ if (s.S === prev.S) return
+ schedule()
+ // A workout started on the phone: the watch app opens with it (HealthKit's startWatchApp).
+ if (linked && shouldOpenOnWatch(prev.S?.active, s.S?.active)) Promise.resolve().then(() => p.WatchBridge.openOnWatch()).catch(() => {})
+ })
// The rest as the watch needs it changes when it starts, stops or is paused, not every second.
const restOf = t => (t ? `${t.endsAt}|${!!t.paused}|${!!t.ready}` : '')
const offUI = useUI.subscribe((s, prev) => { if (s.timer !== prev.timer && restOf(s.timer) !== restOf(prev.timer)) schedule() })
@@ -336,12 +367,12 @@ export async function startWatchSync ({ useStore, useUI }) {
document.addEventListener('visibilitychange', onVisible)
schedule()
drainWatchEvents()
- return () => { offStore(); offUI(); offPrefs(); sub?.remove?.(); document.removeEventListener('visibilitychange', onVisible); clearTimeout(tm) }
+ return () => { offStore(); offUI(); offPrefs(); offHealth(); 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; appHandlers = null; pluginP = null; getStateRef = null; draining = null }
+export function _resetWatchSync () { startedOnWatch.clear(); handlers = null; appHandlers = null; pluginP = null; getStateRef = null; draining = null }
/**
* Writes `fields` (heart rate) onto one set: in the running session when it is that workout, else in
diff --git a/frontend/src/lib/watch-sync.open.test.js b/frontend/src/lib/watch-sync.open.test.js
new file mode 100644
index 000000000..32c845c44
--- /dev/null
+++ b/frontend/src/lib/watch-sync.open.test.js
@@ -0,0 +1,125 @@
+// @vitest-environment happy-dom
+// The phone's side of "open on the watch": a workout started on the phone opens the watch app
+// (WatchBridge.openOnWatch, HealthKit's startWatchApp), and Apple Health on the watch follows the
+// phone's Apple Health switch.
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const health = vi.hoisted(() => ({ on: false, listeners: new Set() }))
+vi.mock('./health-sync.js', () => ({
+ loadHealth: async () => ({ on: health.on }),
+ onHealthChange: cb => { health.listeners.add(cb); return () => health.listeners.delete(cb) },
+}))
+
+import { shouldOpenOnWatch, startWatchSync, applyEvents, bindWatchAppActions, _setWatchPluginForTest, _resetWatchSync, OPEN_ON_WATCH_WINDOW_MS } from './watch-sync.js'
+import { WATCH_DEFAULTS, writeWatchPrefs } from './watch-settings.js'
+
+const now = 1_800_000_000_000
+const live = (over = {}) => ({ id: 'w-9', start: now - 1000, entries: [], ...over })
+
+beforeEach(() => { localStorage.clear(); _resetWatchSync(); health.on = false; health.listeners.clear() })
+
+describe('which workouts open the watch app', () => {
+ const prefs = { ...WATCH_DEFAULTS }
+ it('a new one started here a moment ago', () => {
+ expect(shouldOpenOnWatch(null, live(), { prefs, now })).toBe(true)
+ expect(shouldOpenOnWatch(live({ id: 'old' }), live(), { prefs, now })).toBe(true)
+ })
+ it('not the same one again, nor none', () => {
+ expect(shouldOpenOnWatch(live(), live({ cur: 2 }), { prefs, now })).toBe(false)
+ expect(shouldOpenOnWatch(live(), null, { prefs, now })).toBe(false)
+ })
+ it('not one restored at launch or synced in long after its start, nor a backfill', () => {
+ expect(shouldOpenOnWatch(null, live({ start: now - OPEN_ON_WATCH_WINDOW_MS - 1 }), { prefs, now })).toBe(false)
+ expect(shouldOpenOnWatch(null, live({ start: undefined }), { prefs, now })).toBe(false)
+ expect(shouldOpenOnWatch(null, live({ backfill: { durationMin: 60 } }), { prefs, now })).toBe(false)
+ })
+ it('not with the switch off, or with the watch off altogether', () => {
+ expect(shouldOpenOnWatch(null, live(), { prefs: { ...prefs, autoShow: false }, now })).toBe(false)
+ expect(shouldOpenOnWatch(null, live(), { prefs: { ...prefs, enabled: false }, now })).toBe(false)
+ })
+ it('not one the watch started itself', () => {
+ const start = vi.fn()
+ bindWatchAppActions({ start, patchSet: vi.fn() })
+ applyEvents([{ id: 'e1', type: 'start', wid: 'w-9', at: now, routineIds: [] }], () => ({ S: { active: null } }))
+ expect(start).toHaveBeenCalled()
+ expect(shouldOpenOnWatch(null, live(), { prefs, now })).toBe(false)
+ expect(shouldOpenOnWatch(null, live({ id: 'w-other' }), { prefs, now })).toBe(true)
+ })
+})
+
+// A store as small as zustand's: getState, setState, subscribe((s, prev)).
+function store(initial) {
+ let st = initial
+ const subs = new Set()
+ return {
+ getState: () => st,
+ setState: patch => { const prev = st; st = { ...st, ...patch }; subs.forEach(fn => fn(st, prev)) },
+ subscribe: fn => { subs.add(fn); return () => subs.delete(fn) },
+ }
+}
+
+function bridge({ installed = true } = {}) {
+ return {
+ status: vi.fn(async () => ({ paired: true, installed })),
+ sendSnapshot: vi.fn(async () => ({ sent: true })),
+ sendClips: vi.fn(async () => ({})),
+ openOnWatch: vi.fn(async () => ({ ok: true })),
+ drain: vi.fn(async () => ({ events: [] })),
+ ack: vi.fn(async () => ({})),
+ addListener: vi.fn(async () => ({ remove: () => {} })),
+ }
+}
+
+describe('startWatchSync', () => {
+ const S0 = { unit: 'kg', restSec: 90, workouts: [], routines: [], active: null }
+ const ui = store({ timer: null })
+
+ it('opens the watch app for a workout started on the phone, once', async () => {
+ const b = bridge()
+ _setWatchPluginForTest(b)
+ const st = store({ S: S0 })
+ const stop = await startWatchSync({ useStore: st, useUI: ui })
+ st.setState({ S: { ...S0, active: live({ start: Date.now() }) } })
+ st.setState({ S: { ...S0, active: live({ start: Date.now(), cur: 1 }) } })
+ await new Promise(r => setTimeout(r, 0))
+ expect(b.openOnWatch).toHaveBeenCalledTimes(1)
+ stop()
+ })
+
+ it('leaves the watch alone without the app on it, or with the switch off', async () => {
+ const b = bridge({ installed: false })
+ _setWatchPluginForTest(b)
+ const st = store({ S: S0 })
+ const stop = await startWatchSync({ useStore: st, useUI: ui })
+ st.setState({ S: { ...S0, active: live({ start: Date.now() }) } })
+ stop()
+ const b2 = bridge()
+ _setWatchPluginForTest(b2)
+ writeWatchPrefs({ autoShow: false })
+ const st2 = store({ S: S0 })
+ const stop2 = await startWatchSync({ useStore: st2, useUI: ui })
+ st2.setState({ S: { ...S0, active: live({ id: 'w-10', start: Date.now() }) } })
+ await new Promise(r => setTimeout(r, 0))
+ expect(b.openOnWatch).not.toHaveBeenCalled()
+ expect(b2.openOnWatch).not.toHaveBeenCalled()
+ stop2()
+ })
+
+ it('tells the watch the phone\'s Apple Health switch, and again when it changes', async () => {
+ vi.useFakeTimers()
+ try {
+ health.on = true
+ const b = bridge()
+ _setWatchPluginForTest(b)
+ const st = store({ S: S0 })
+ const stop = await startWatchSync({ useStore: st, useUI: ui })
+ await vi.runAllTimersAsync()
+ const sent = () => JSON.parse(b.sendSnapshot.mock.calls.at(-1)[0].json).settings
+ expect(sent().health).toBe(true)
+ health.listeners.forEach(fn => fn({ on: false }))
+ await vi.runAllTimersAsync()
+ expect(sent().health).toBe(false)
+ stop()
+ } finally { vi.useRealTimers() }
+ })
+})
diff --git a/frontend/src/views/WatchSettings.jsx b/frontend/src/views/WatchSettings.jsx
index 15289093d..a79a40327 100644
--- a/frontend/src/views/WatchSettings.jsx
+++ b/frontend/src/views/WatchSettings.jsx
@@ -1,25 +1,43 @@
// Settings → Apple Watch (iPhone app only): whether the watch app is there, and this phone's
// choices for it (lib/watch-settings.js), which the watch gets with every snapshot.
+//
+// Apple Health is one switch for phone and watch: the Apple Health card in Settings → Data. This
+// page only says what the watch makes of it (measuring, off, or not allowed there) and leads to it.
import { useEffect, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
import { t } from '../lib/i18n.js'
import { Section, Row, Switch, SelectRow } from '../components/ui.jsx'
import { readWatchPrefs, writeWatchPrefs, readWatchStatus, onWatchPrefs } from '../lib/watch-settings.js'
import { watchStatus } from '../lib/watch-sync.js'
+import { loadHealth, onHealthChange } from '../lib/health-sync.js'
export default function WatchSettingsPage() {
+ const nav = useNavigate()
const [prefs, setPrefs] = useState(readWatchPrefs)
const [status, setStatus] = useState(readWatchStatus)
const [link, setLink] = useState(null) // { paired, installed } from the phone, or null while asking
+ const [healthOn, setHealthOn] = useState(null) // the phone's Apple Health switch, null while reading
useEffect(() => onWatchPrefs(() => { setPrefs(readWatchPrefs()); setStatus(readWatchStatus()) }), [])
useEffect(() => { watchStatus().then(setLink).catch(() => setLink({ paired: false, installed: false })) }, [])
+ useEffect(() => {
+ let gone = false
+ loadHealth().then(h => { if (!gone) setHealthOn(!!h?.on) }).catch(() => { if (!gone) setHealthOn(false) })
+ const off = onHealthChange(h => setHealthOn(!!h?.on))
+ return () => { gone = true; off() }
+ }, [])
const set = patch => setPrefs(writeWatchPrefs(patch))
const linkLine = !link ? t('Checking…')
: !link.paired ? t('No Apple Watch paired with this iPhone')
: !link.installed ? t('openGym is not on your Apple Watch yet. Install it in the Watch app.')
: t('openGym is on your Apple Watch')
- const healthLine = status?.health === 'denied' ? t('Not allowed on the watch. Allow it in the Health app on your iPhone.')
- : t('Heart rate during the workout and next to each set, and the workout saved to Apple Health. The watch asks once.')
+ const denied = healthOn && status?.health === 'denied'
+ const healthValue = healthOn == null ? '' : denied ? t('Not allowed') : healthOn ? t('On') : t('Off')
+ const healthLine = denied ? t('Not allowed on the watch. Allow it in the Health app on your iPhone.')
+ : healthOn ? t('Heart rate during the workout and next to each set, and the workout saved to Apple Health. The watch asks once.')
+ : t('Turn on Apple Health and the watch measures your heart rate for every set.')
+ // The one Apple Health switch, on its own card in Settings → Data.
+ const openHealth = () => nav('/settings/data', { state: { find: 'Write to Apple Health' } })
return <>
<Section footer={linkLine}>
@@ -28,11 +46,14 @@ export default function WatchSettingsPage() {
</Row>
</Section>
{prefs.enabled && <>
- <Section footer={healthLine}>
- <Row icon="heart" iconTint="var(--red)" title={t('Apple Health on the watch')}>
- <Switch checked={prefs.health} onChange={v => set({ health: v })} aria-label={t('Apple Health on the watch')} />
+ <Section footer={t('Start a workout on the phone and openGym pops up on your wrist.')}>
+ <Row icon="bolt" iconTint="var(--green)" title={t('Open on the watch')}>
+ <Switch checked={prefs.autoShow} onChange={v => set({ autoShow: v })} aria-label={t('Open on the watch')} />
</Row>
</Section>
+ <Section footer={healthLine}>
+ <Row icon="heart" iconTint="var(--red)" title={t('Apple Health')} value={healthValue} accessory="chevron" onClick={openHealth} />
+ </Section>
<Section>
<Row icon="vibrate" iconTint="var(--indigo)" title={t('Tap the wrist when a rest is over')}>
<Switch checked={prefs.restHaptics} onChange={v => set({ restHaptics: v })} aria-label={t('Tap the wrist when a rest is over')} />
diff --git a/frontend/src/views/WatchSettings.test.jsx b/frontend/src/views/WatchSettings.test.jsx
new file mode 100644
index 000000000..8dbdac08f
--- /dev/null
+++ b/frontend/src/views/WatchSettings.test.jsx
@@ -0,0 +1,61 @@
+// @vitest-environment happy-dom
+// Settings → Apple Watch: one Apple Health story. The phone's Apple Health switch (Settings → Data)
+// is the one switch; this page says what the watch makes of it and leads there.
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { act } from 'react'
+import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'
+
+const mocks = vi.hoisted(() => ({ health: { on: false }, link: { paired: true, installed: true } }))
+vi.mock('../lib/health-sync.js', () => ({ loadHealth: async () => mocks.health, onHealthChange: () => () => {} }))
+vi.mock('../lib/watch-sync.js', () => ({ watchStatus: async () => mocks.link }))
+
+import WatchSettingsPage from './WatchSettings.jsx'
+import { readWatchPrefs, writeWatchStatus } from '../lib/watch-settings.js'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+let where = null
+function Where() { where = useLocation(); return null }
+
+async function mount() {
+ const el = document.createElement('div')
+ document.body.replaceChildren(el)
+ await act(async () => {
+ createRoot(el).render(<MemoryRouter initialEntries={['/settings/watch']}><Routes>
+ <Route path="/settings/watch" element={<WatchSettingsPage />} />
+ <Route path="*" element={<Where />} />
+ </Routes></MemoryRouter>)
+ })
+ return el
+}
+const row = (el, title) => [...el.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title)
+
+beforeEach(() => { localStorage.clear(); mocks.health = { on: false }; where = null })
+
+describe('Settings → Apple Watch', () => {
+ it('shows Apple Health as the phone has it, and leads to its switch', async () => {
+ const el = await mount()
+ expect(row(el, 'Apple Health').querySelector('.lrow-v').textContent).toBe('Off')
+ expect(el.textContent).toContain('Turn on Apple Health and the watch measures your heart rate for every set.')
+ expect(row(el, 'Apple Health').querySelector('[role="switch"]')).toBeNull()
+ await act(async () => { row(el, 'Apple Health').click() })
+ expect(where.pathname).toBe('/settings/data')
+ expect(where.state).toEqual({ find: 'Write to Apple Health' })
+ })
+
+ it('says when the watch was not allowed to', async () => {
+ mocks.health = { on: true }
+ writeWatchStatus({ health: 'denied' })
+ const el = await mount()
+ expect(row(el, 'Apple Health').querySelector('.lrow-v').textContent).toBe('Not allowed')
+ expect(el.textContent).toContain('Allow it in the Health app on your iPhone.')
+ })
+
+ it('has the switch for opening on the watch, on to begin with', async () => {
+ const el = await mount()
+ const sw = row(el, 'Open on the watch').querySelector('[role="switch"]')
+ expect(sw.getAttribute('aria-checked')).toBe('true')
+ await act(async () => { sw.click() })
+ expect(readWatchPrefs().autoShow).toBe(false)
+ })
+})