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
Health: a run is a run in Apple Health, on the watch and in Health Connect (#799)
Duarte Santosb03178faf1cc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9619efd38..faaa0c86f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -65,6 +65,10 @@ per muscle. Settings → Workout → Fine-tuning turns it off.- **Heart rate for sets you tick on the phone.** With the Apple Watch running the session, a setticked on the phone now gets its heart rate from the watch too, not just the ones ticked onthe wrist.+- **A run is a run in Apple Health** (#799, thanks @svillar). A workout that was only running+ used to land in Apple Health as strength training, from the watch every time. Now runs, walks,+ rows, rides, jump rope, HIIT, yoga and stretching each get their own type, on the iPhone, the+ Apple Watch and in Health Connect. Lift anything at all and it's strength training, as before.- **Back means back.** A page's own back button now brings you back where you were scrolled,just like the edge swipe, and Body measurements goes back to Stats instead of Home. The titlesbeside those back buttons all sit the same distance from them now (#704, #763, #764, thanksdiff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.javaindex 94b5091dd..8e7da346f 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java@@ -413,6 +413,12 @@ public class HealthConnectPlugin extends Plugin {case "biking_stationary": return ExerciseSessionRecord.EXERCISE_TYPE_BIKING_STATIONARY;case "elliptical": return ExerciseSessionRecord.EXERCISE_TYPE_ELLIPTICAL;case "stair_climbing_machine": return ExerciseSessionRecord.EXERCISE_TYPE_STAIR_CLIMBING_MACHINE;+ case "biking": return ExerciseSessionRecord.EXERCISE_TYPE_BIKING;+ case "rowing": return ExerciseSessionRecord.EXERCISE_TYPE_ROWING_MACHINE;+ case "hiit": return ExerciseSessionRecord.EXERCISE_TYPE_HIGH_INTENSITY_INTERVAL_TRAINING;+ case "yoga": return ExerciseSessionRecord.EXERCISE_TYPE_YOGA;+ case "flexibility": return ExerciseSessionRecord.EXERCISE_TYPE_STRETCHING;+ // Health Connect has no jump rope and no mixed cardio: those are "other", as before.default: return ExerciseSessionRecord.EXERCISE_TYPE_OTHER_WORKOUT;}}diff --git a/frontend/ios/App/App/AppleHealthPlugin.swift b/frontend/ios/App/App/AppleHealthPlugin.swiftindex c7a7744f4..1051d81e8 100644--- a/frontend/ios/App/App/AppleHealthPlugin.swift+++ b/frontend/ios/App/App/AppleHealthPlugin.swift@@ -176,10 +176,12 @@ public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {[HKMetadataKeySyncIdentifier: id, HKMetadataKeySyncVersion: NSNumber(value: Int64(Date().timeIntervalSince1970 * 1000))]}- private static let activityTypes: [String: HKWorkoutActivityType] = [+ /// lib/health-connect.js SESSION_TYPES; also the watch's workout type (WatchBridgePlugin).+ static let activityTypes: [String: HKWorkoutActivityType] = ["strength_training": .traditionalStrengthTraining, "walking": .walking, "running": .running,- "biking_stationary": .cycling, "elliptical": .elliptical, "stair_climbing_machine": .stairClimbing,- "other_workout": .other,+ "biking_stationary": .cycling, "biking": .cycling, "elliptical": .elliptical, "stair_climbing_machine": .stairClimbing,+ "rowing": .rowing, "jump_rope": .jumpRope, "hiit": .highIntensityIntervalTraining, "mixed_cardio": .mixedCardio,+ "yoga": .yoga, "flexibility": .flexibility, "other_workout": .other,]private func saveSession(_ s: [String: Any]) async throws {diff --git a/frontend/ios/App/App/WatchBridgePlugin.swift b/frontend/ios/App/App/WatchBridgePlugin.swiftindex b9129cc5c..adce2b4b4 100644--- a/frontend/ios/App/App/WatchBridgePlugin.swift+++ b/frontend/ios/App/App/WatchBridgePlugin.swift@@ -81,9 +81,10 @@ 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.+ /// the watch"). HealthKit wakes the watch app with the workout's planned type (the page's+ /// `type`, else strength training), 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,@@ -92,7 +93,8 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {return}let config = HKWorkoutConfiguration()- config.activityType = .traditionalStrengthTraining+ // The type the page planned (lib/health-connect.js plannedType, #799): a run opens as a run.+ config.activityType = AppleHealthPlugin.activityTypes[call.getString("type") ?? ""] ?? .traditionalStrengthTrainingconfig.locationType = .indoorWatchBridgePlugin.health.startWatchApp(with: config) { ok, _ incall.resolve(["ok": ok])diff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swiftindex aba6b285b..5c7835014 100644--- a/frontend/ios/App/Watch/OpenGymWatchApp.swift+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift@@ -44,7 +44,7 @@ final class WatchAppDelegate: NSObject, WKApplicationDelegate {let store = SessionStore()func handle(_ workoutConfiguration: HKWorkoutConfiguration) {- store.openedForWorkout()+ store.openedForWorkout(workoutConfiguration.activityType)}/// Relaunched after being killed mid-workout: the Apple Health session watchOS kept running.diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swiftindex 9d58e9fea..b14001f4d 100644--- a/frontend/ios/App/Watch/SessionStore.swift+++ b/frontend/ios/App/Watch/SessionStore.swift@@ -1,4 +1,5 @@import Foundation+import HealthKitimport UIKitimport UserNotificationsimport WatchConnectivity@@ -141,7 +142,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNDispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] inguard let self = self, self.state.workout?.id == w.id else { return }if !SensorPlan.idle(w, seen: nil, now: Date().timeIntervalSince1970 * 1000, busy: false) {- self.health.start(workoutId: w.id)+ self.health.start(workoutId: w.id, type: w.healthType)}self.armIdleCheck()}@@ -168,7 +169,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNprivate func noteActivity() {guard !isDemo, let w = workout else { return }activityAt = Date()- if health.paused { health.resume() } else { health.start(workoutId: w.id) }+ if health.paused { health.resume() } else { health.start(workoutId: w.id, type: w.healthType) }armIdleCheck()}@@ -281,13 +282,13 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN/// 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() {+ func openedForWorkout(_ opened: HKWorkoutActivityType? = nil) {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)+ self.health.start(workoutId: self.state.workout?.id, type: self.state.workout?.healthType, opened: opened)// 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) }@@ -335,7 +336,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNself.workoutSeenAt = Date()self.picked = [:]self.summary = nil- self.health.start(workoutId: next.workout?.id)+ self.health.start(workoutId: next.workout?.id, type: next.workout?.healthType)}if next.workout != nil && next.workout != before.workout { self.noteActivity() }// Sets ticked on the phone: their heart rate from this watch's readings (Discord fuckdv).@@ -574,7 +575,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNworkoutSeenAt = nowrestAfter = nilloadTargets()- health.start(workoutId: next.workout?.id)+ health.start(workoutId: next.workout?.id, type: next.workout?.healthType)activityAt = nowarmIdleCheck()summary = nildiff --git a/frontend/ios/App/Watch/WorkoutManager.swift b/frontend/ios/App/Watch/WorkoutManager.swiftindex 3c173ebf6..876cca9d9 100644--- a/frontend/ios/App/Watch/WorkoutManager.swift+++ b/frontend/ios/App/Watch/WorkoutManager.swift@@ -3,10 +3,11 @@ import HealthKit/** 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.+ * sent with every snapshot as settings.health): a workout session (of the type the phone planned,+ * strength training unless it says otherwise: a run is a run, #799) 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.** 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'@@ -95,15 +96,25 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegateb.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) {+ /// The phone's names for a workout's type (lib/health-connect.js SESSION_TYPES, #799).+ static let activityTypes: [String: HKWorkoutActivityType] = [+ "strength_training": .traditionalStrengthTraining, "walking": .walking, "running": .running,+ "biking_stationary": .cycling, "biking": .cycling, "elliptical": .elliptical, "stair_climbing_machine": .stairClimbing,+ "rowing": .rowing, "jump_rope": .jumpRope, "hiit": .highIntensityIntervalTraining, "mixed_cardio": .mixedCardio,+ "yoga": .yoga, "flexibility": .flexibility, "other_workout": .other,+ ]++ /// A workout started here or picked up from the phone: the session starts now, as the type the+ /// phone planned (a run is a run in Apple Health), else as the type HealthKit opened the app+ /// with, else strength training. A session already running keeps its type.+ func start(workoutId wid: String? = nil, type: String? = nil, opened: HKWorkoutActivityType? = nil) {wanted = trueif let wid = wid { workoutId = wid }// 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.activityType = type.flatMap { WorkoutManager.activityTypes[$0] } ?? opened ?? .traditionalStrengthTrainingconfig.locationType = .indoordo {let s = try HKWorkoutSession(healthStore: store, configuration: config)diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swiftindex 963655698..e668ab8e7 100644--- a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift@@ -31,6 +31,8 @@ struct ReadySession: Codable, Equatable {var routineIds: [String]var name: Stringvar entries: [Entry]+ /// Apple Health's workout type for it (lib/health-connect.js plannedType, #799); none from an older phone.+ var healthType: String?}struct ActiveWorkout: Codable, Equatable {@@ -43,6 +45,8 @@ struct ActiveWorkout: Codable, Equatable {var entries: [Entry]/// When it started (ms since 1970), for the summary's duration.var start: Double?+ /// Apple Health's workout type for it (#799); none: strength training, as before.+ var healthType: String?}struct RestInfo: Codable, Equatable {diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swiftindex 87dd652f1..c5659a013 100644--- a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift@@ -290,7 +290,7 @@ enum SessionCore {/// A ready session started here, with the body weight just weighed in (or none).static func start(_ s0: SessionState, _ session: ReadySession, wid: String, at: Double, id: String, bw: Double? = nil) -> (SessionState, Event) {var s = s0- s.workout = ActiveWorkout(id: wid, name: session.name, unit: s.unit, cur: 0, restSec: s.restSec, rest: nil, entries: session.entries, start: at)+ s.workout = ActiveWorkout(id: wid, name: session.name, unit: s.unit, cur: 0, restSec: s.restSec, rest: nil, entries: session.entries, start: at, healthType: session.healthType)s.startedHere = wids.pending = [:]s.skipped = nildiff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swiftindex 9bab51019..9a8a4f9af 100644--- a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift@@ -90,6 +90,17 @@ final class SessionCoreTests: XCTestCase {XCTAssertTrue(s.workout?.entries[0].sets[0].done ?? false, "with the tick made before it heard")}+ /// #799: a run planned on the phone is a run in Apple Health, also when the watch starts it.+ func testTheWorkoutTypeComesWithTheSessionAndAnOlderPhoneSendsNone() throws {+ var ready = ReadySession(routineIds: ["r1"], name: "Run", entries: [])+ ready.healthType = "running"+ XCTAssertEqual(SessionCore.start(SessionState(), ready, wid: "watch-1", at: 100, id: "s1").0.workout?.healthType, "running")+ let old = try JSONDecoder().decode(Snapshot.self, from: Data(#"{"v":1,"active":{"id":"p1","name":"Push","unit":"kg","cur":0,"restSec":90,"entries":[]}}"#.utf8))+ XCTAssertNil(old.active?.healthType)+ let run = try JSONDecoder().decode(Snapshot.self, from: Data(#"{"v":1,"active":{"id":"p1","name":"Run","unit":"kg","cur":0,"restSec":90,"entries":[],"healthType":"running"}}"#.utf8))+ XCTAssertEqual(SessionCore.applySnapshot(SessionState(), run).workout?.healthType, "running")+ }+func testAnotherWorkoutOnThePhoneStartsClean() {var s = SessionCore.applySnapshot(SessionState(), snap(workout("p1", sets: [row(60, 8)])))s = SessionCore.tick(s, entry: 0, set: 0, w: 60, r: 8, at: 1, id: "e1").0diff --git a/frontend/src/lib/health-connect.js b/frontend/src/lib/health-connect.jsindex 7f09c05d3..13901f8a8 100644--- a/frontend/src/lib/health-connect.js+++ b/frontend/src/lib/health-connect.js@@ -8,16 +8,19 @@import { workoutText } from './workout-text.js'import { modeForEntry, hasCompletedWork } from './workout-model.js'import { isoOf } from './format.js'+import { EXIDX } from './exercises.js'const LB_PER_KG = 2.2046226218// Health Connect refuses a title or notes over 1000 characters (ExerciseSessionRecord).export const TEXT_MAX = 1000-// The session type Health Connect files a workout under. A workout with any strength work in it is-// strength training: ten minutes on the treadmill before the squats do not make it a walk. One that-// is all cardio takes the machine's type when the catalogue says which machine it is, and "other"-// when it does not (a custom exercise, burpees, cardio on two different machines).-// The native side maps each name to its ExerciseSessionRecord.EXERCISE_TYPE_* constant.+// The session type Health Connect (and Apple Health) files a workout under. A workout with any+// strength work in it is strength training: ten minutes on the treadmill before the squats do not+// make it a walk. One that is all cardio takes the type of what was done when the catalogue says+// (the machine, else the move's name: a run, a row, burpees and jacks as HIIT), stretching at the+// end of a run leaves it a run, and cardio of two kinds is mixed cardio (#799).+// The native side maps each name to its ExerciseSessionRecord.EXERCISE_TYPE_* constant, and to an+// HKWorkoutActivityType on the iPhone and the watch (AppleHealthPlugin, WorkoutManager).const CARDIO_TYPES = {'3666': 'walking', // walking on incline treadmill'0685': 'running', '0684': 'running', '3656': 'running',@@ -25,14 +28,66 @@ const CARDIO_TYPES = {'2141': 'elliptical', '2331': 'elliptical','2311': 'stair_climbing_machine',}-export const SESSION_TYPES = ['strength_training', 'walking', 'running', 'biking_stationary', 'elliptical', 'stair_climbing_machine', 'other_workout']+export const SESSION_TYPES = ['strength_training', 'walking', 'running', 'biking_stationary', 'biking', 'elliptical', 'stair_climbing_machine',+ 'rowing', 'jump_rope', 'hiit', 'mixed_cardio', 'yoga', 'flexibility', 'other_workout']+// Catalogue cardio by its name, first match wins: the treadmill before the bike ("run on treadmill"+// is filed with the stationary bike), the bike before the run ("assault bike run").+const BY_NAME = [+ [/treadmill/, n => (/walk/.test(n) ? 'walking' : 'running')],+ [/\b(bike|bicycle|cycl\w*|aquabike)\b/, (n, ex) => (ex.eq === 'stationary bike' ? 'biking_stationary' : 'biking')],+ [/jump rope|skip rope|\bskipping\b/, () => 'jump_rope'],+ [/\brow(ing)?\b/, () => 'rowing'],+ [/\b(walk\w*|marching)\b/, () => 'walking'],+ [/\b(run|running|jog|sprints?|trot)\b/, () => 'running'],+ [/burpee|jacks?\b|mountain climber|squat thrust|battling rope|tuck jump|star jump|hiit|circuit|tabata/, () => 'hiit'],+]+const CARDIO_EQ = { 'elliptical machine': 'elliptical', 'stepmill machine': 'stair_climbing_machine' }++/** What one exercise counts as for the session type: one of SESSION_TYPES. */+export function exerciseType(entry) {+ const id = String(entry?.id ?? '')+ if (CARDIO_TYPES[id]) return CARDIO_TYPES[id]+ const ex = EXIDX[id]+ if (ex?.cat === 'yoga') return 'yoga'+ if (ex?.cat === 'stretching' || ex?.cat === 'mobility') return 'flexibility'+ // Cardio by the catalogue, whether it is logged as minutes or as reps (burpees count reps, #717).+ if (ex && (ex.cat === 'cardio' || ex.cat === 'plyometrics' || ex.bp === 'cardio')) {+ if (CARDIO_EQ[ex.eq]) return CARDIO_EQ[ex.eq]+ const n = String(ex.n || '').toLowerCase()+ const hit = BY_NAME.find(([re]) => re.test(n))+ return hit ? hit[1](n, ex) : 'mixed_cardio'+ }+ // A custom exercise logged as cardio: nothing says which.+ return modeForEntry(entry) === 'cardio' ? 'other_workout' : 'strength_training'+}++const CALM = new Set(['yoga', 'flexibility'])++function typeOf(entries) {+ if (!entries.length) return 'other_workout'+ const types = new Set(entries.map(exerciseType))+ if (types.has('strength_training')) return 'strength_training'+ // The stretches after a run or a row: still that run. Only stretching: yoga if any yoga.+ const moving = [...types].filter(x => !CALM.has(x))+ if (!moving.length) return types.has('yoga') ? 'yoga' : 'flexibility'+ if (moving.length === 1) return moving[0]+ // Two kinds of cardio, or cardio the catalogue does not place next to one it does.+ return moving.includes('other_workout') ? 'other_workout' : 'mixed_cardio'+}++/** The type of a finished workout, from the exercises with something done in them. */export function sessionType(w) {- const done = (w?.entries || []).filter(e => (e.sets || []).some(hasCompletedWork))- if (!done.length) return 'other_workout'- if (done.some(e => modeForEntry(e) !== 'cardio')) return 'strength_training'- const types = new Set(done.map(e => CARDIO_TYPES[e.id] || 'other_workout'))- return types.size === 1 ? [...types][0] : 'other_workout'+ return typeOf((w?.entries || []).filter(e => (e.sets || []).some(hasCompletedWork)))+}++/**+ * The type a workout is set to be, before anything is done (the watch's workout session, #799).+ * Null for one with nothing in it yet: the watch keeps its strength training then.+ */+export function plannedType(entries) {+ const planned = (entries || []).filter(e => e && e.id != null)+ return planned.length ? typeOf(planned) : null}const clip = s => (s.length > TEXT_MAX ? s.slice(0, TEXT_MAX - 1) + '…' : s)diff --git a/frontend/src/lib/health-connect.test.js b/frontend/src/lib/health-connect.test.jsindex d31032b54..cef08099e 100644--- a/frontend/src/lib/health-connect.test.js+++ b/frontend/src/lib/health-connect.test.js@@ -1,5 +1,7 @@import { describe, expect, it } from 'vitest'-import { goneIds, healthRecords, planSync, recordKey, sessionRecord, sessionType, SESSION_TYPES, TEXT_MAX, weightRecord, writtenIds } from './health-connect.js'+import { readFileSync } from 'node:fs'+import { EXIDX } from './exercises.js'+import { exerciseType, goneIds, healthRecords, planSync, plannedType, recordKey, sessionRecord, sessionType, SESSION_TYPES, TEXT_MAX, weightRecord, writtenIds } from './health-connect.js'// #200: what the Android app writes to Health Connect, worked out from the state alone.const nameOf = e => ({ '0025': 'barbell bench press', '3666': 'walking on incline treadmill', '2138': 'stationary bike run v. 3' })[e.id] || e.id@@ -17,14 +19,55 @@ describe('sessionType', () => {expect(sessionType(workout([treadmill]))).toBe('walking')expect(sessionType(workout([bike]))).toBe('biking_stationary')})- it('is "other" for cardio on two machines, or on one the catalogue does not place', () => {- expect(sessionType(workout([treadmill, bike]))).toBe('other_workout')+ it('is mixed cardio for cardio on two machines, "other" for one the catalogue does not place', () => {+ expect(sessionType(workout([treadmill, bike]))).toBe('mixed_cardio')expect(sessionType(workout([{ ...treadmill, id: 'custom-rower' }]))).toBe('other_workout')+ expect(sessionType(workout([treadmill, { ...treadmill, id: 'custom-rower' }]))).toBe('other_workout')})it('ignores exercises with no set done', () => {const skipped = { ...strength, sets: [{ w: 60, r: 8, done: false }] }expect(sessionType(workout([treadmill, skipped]))).toBe('walking')})+ // #799: a running-only session went to Apple Health as strength training.+ const cardio = (id, extra = {}) => ({ id, target: { mode: 'cardio' }, sets: [{ min: 20, speed: 8, done: true }], ...extra })+ const reps = id => ({ id, target: { mode: 'reps' }, sets: [{ r: 20, done: true }] })+ it.each([+ ['5216', 'running'], // sprint+ ['4004', 'running'], // place jog+ ['2197', 'running'], // run on treadmill (filed with the stationary bike)+ ['2259', 'walking'], // walking on treadmill+ ['2258', 'walking'],+ ['1161', 'rowing'], // rowing (with rowing machine)+ ['3893', 'biking_stationary'], // assault bike run+ ['5214', 'biking'], // riding outdoor bicycle+ ['2192', 'elliptical'],+ ['2612', 'jump_rope'],+ ['6100', 'jump_rope'], // bodyweight skipping+ ['3384', 'hiit'], // battling ropes power slam+ ['3037', 'mixed_cardio'], // butt kicks: cardio, no machine, no name to go by+ ])('files cardio %s as %s', (id, type) => {+ expect(sessionType(workout([cardio(id)]))).toBe(type)+ })+ it('counts burpees and jacks as HIIT also when they are logged as reps', () => {+ expect(sessionType(workout([reps('1160'), reps('3094')]))).toBe('hiit')+ expect(exerciseType(reps('0630'))).toBe('hiit') // mountain climber+ })+ it('keeps a strength move named like cardio strength (bent over row)', () => {+ expect(exerciseType(reps('0027'))).toBe('strength_training')+ expect(sessionType(workout([reps('0027'), cardio('0685')]))).toBe('strength_training')+ })+ it('files yoga and stretching, and leaves a run with a stretch after it a run', () => {+ const yoga = Object.values(EXIDX).find(e => e.cat === 'yoga').id+ const stretch = Object.values(EXIDX).find(e => e.cat === 'stretching').id+ expect(sessionType(workout([reps(yoga)]))).toBe('yoga')+ expect(sessionType(workout([reps(stretch)]))).toBe('flexibility')+ expect(sessionType(workout([reps(stretch), reps(yoga)]))).toBe('yoga')+ expect(sessionType(workout([cardio('0685'), reps(stretch)]))).toBe('running')+ expect(sessionType(workout([strength, reps(stretch)]))).toBe('strength_training')+ })+ it('still files a strength move logged as minutes as "other"', () => {+ expect(sessionType(workout([cardio('0025')]))).toBe('other_workout')+ })it('only ever answers a type the native side knows', () => {for (const w of [workout([]), workout([strength]), workout([treadmill]), workout([bike, treadmill])]) {expect(SESSION_TYPES).toContain(sessionType(w))@@ -32,6 +75,31 @@ describe('sessionType', () => {})})+// Each name has its own type on the native side; a name it does not know is filed as "other".+describe('the native tables', () => {+ const src = f => readFileSync(new URL(f, import.meta.url), 'utf8')+ it.each([['../../ios/App/App/AppleHealthPlugin.swift'], ['../../ios/App/Watch/WorkoutManager.swift']])('%s knows every type', f => {+ const s = src(f)+ for (const name of SESSION_TYPES) expect(s).toContain(`"${name}": .`)+ })+ it('Health Connect knows every type it has a constant for', () => {+ const s = src('../../android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java')+ for (const name of SESSION_TYPES.filter(n => !['jump_rope', 'mixed_cardio', 'other_workout'].includes(n))) {+ expect(s).toContain(`case "${name}": return`)+ }+ })+})++describe('plannedType', () => {+ it('types a planned session before any set is done, for the watch (#799)', () => {+ const plan = id => ({ id, target: { mode: 'cardio', min: 30 }, sets: [{ min: 30, speed: 10, done: false }] })+ expect(plannedType([plan('0685')])).toBe('running')+ expect(plannedType([plan('0685'), { id: '0025', target: { mode: 'reps' }, sets: [{ w: 60, r: 8 }] }])).toBe('strength_training')+ expect(plannedType([])).toBeNull()+ expect(plannedType(undefined)).toBeNull()+ })+})+describe('sessionRecord', () => {it('carries the workout id, its times, the name and the sets as text', () => {const rec = sessionRecord(workout([strength], { note: 'Felt strong.' }), { unit: 'kg', nameOf })diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.jsindex 204b8006f..5c8ada0b6 100644--- a/frontend/src/lib/watch-sync.js+++ b/frontend/src/lib/watch-sync.js@@ -28,6 +28,7 @@ import { buildCombinedEntries, deriveSessionName } from './session-merge.js'import { todayISO, exerciseNameText } from './format.js'import { sanitizeHr } from './heart-rate.js'import { readWatchPrefs, settingsForWatch, writeWatchStatus, onWatchPrefs } from './watch-settings.js'+import { plannedType } from './health-connect.js'export const SNAPSHOT_VERSION = 1const APPLIED_KEY = 'gym_watch_applied'@@ -123,10 +124,13 @@ export function buildReady (S, today = todayISO()) {try {const { entries, routineIds, routines } = buildCombinedEntries(S, ids)if (!routines.length) return null+ const healthType = plannedType(entries)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)),+ // Apple Health's workout type on the watch: a run is a run (#799)+ ...(healthType ? { healthType } : {}),}} catch { return null }}@@ -145,6 +149,7 @@ export function buildSnapshot(S, { timer = null, ready = null } = {}) {if (!A || !Array.isArray(A.entries)) return { v: SNAPSHOT_VERSION, unit, restSec, active: null, ready }let H = nulltry { H = sessionHistory(S) } catch { H = null }+ const healthType = plannedType(A.entries)return {v: SNAPSHOT_VERSION,unit,@@ -161,6 +166,8 @@ export function buildSnapshot(S, { timer = null, ready = null } = {}) {// 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.filter(e => e && e.id != null).map(e => watchEntry(e, H, S)),+ // Apple Health's workout type on the watch: a run is a run (#799)+ ...(healthType ? { healthType } : {}),},}}@@ -538,7 +545,7 @@ export async function startWatchSync ({ useStore, useUI }) {if (s.S === prev.S) returnschedule()// 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(() => {})+ if (linked && shouldOpenOnWatch(prev.S?.active, s.S?.active)) Promise.resolve().then(() => p.WatchBridge.openOnWatch({ type: plannedType(s.S.active.entries) || undefined })).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}` : '')diff --git a/frontend/src/lib/watch-sync.open.test.js b/frontend/src/lib/watch-sync.open.test.jsindex fe40a7f04..ec7dc43de 100644--- a/frontend/src/lib/watch-sync.open.test.js+++ b/frontend/src/lib/watch-sync.open.test.js@@ -83,6 +83,19 @@ describe('startWatchSync', () => {st.setState({ S: { ...S0, active: live({ start: Date.now(), cur: 1 }) } })await new Promise(r => setTimeout(r, 0))expect(b.openOnWatch).toHaveBeenCalledTimes(1)+ expect(b.openOnWatch).toHaveBeenCalledWith({ type: undefined }) // nothing in it yet: strength training+ stop()+ })++ it('opens the watch app as a run for a run (#799)', async () => {+ const b = bridge()+ _setWatchPluginForTest(b)+ const st = store({ S: S0 })+ const stop = await startWatchSync({ useStore: st, useUI: ui })+ const entries = [{ id: '0685', target: { mode: 'cardio', min: 30 }, sets: [{ min: 30, speed: 10 }] }]+ st.setState({ S: { ...S0, active: live({ start: Date.now(), entries }) } })+ await new Promise(r => setTimeout(r, 0))+ expect(b.openOnWatch).toHaveBeenCalledWith({ type: 'running' })stop()})diff --git a/frontend/src/lib/watch-sync.test.js b/frontend/src/lib/watch-sync.test.jsindex 48b27f671..ad45d1aae 100644--- a/frontend/src/lib/watch-sync.test.js+++ b/frontend/src/lib/watch-sync.test.js@@ -151,6 +151,17 @@ describe('starting and finishing on the watch', () => {expect(snap.ready.today.name).toBe('Push')})+ // #799: the watch's Apple Health workout used to be strength training whatever was planned.+ it('tells the watch which Apple Health type each session is', () => {+ const run = { id: 'r-run', name: 'Run', ex: [{ id: '0685', mode: 'cardio', min: 30, speed: 10 }] }+ const S = { unit: 'kg', workouts: [], routines: [...routines, run], week: { 2: 'r-run' }, dayPlan: {} }+ const ready = buildReady(S, '2026-10-13')+ expect(ready.today.healthType).toBe('running')+ expect(ready.others.map(o => o.healthType)).toEqual(['strength_training', 'strength_training'])+ const active = { id: 'w1', name: 'Run', entries: [{ id: '0685', target: { mode: 'cardio', min: 30 }, sets: [{ min: 30, speed: 10 }] }] }+ expect(buildSnapshot({ ...S, active }).active.healthType).toBe('running')+ })+// 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', () => {