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
perf(watch): a workout nobody finishes pauses its Health session after 3 h idle
Duarte Santos4b9dc1f0976d
diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swiftindex c97978097..5eb9b740d 100644--- a/frontend/ios/App/Watch/SessionStore.swift+++ b/frontend/ios/App/Watch/SessionStore.swift@@ -131,11 +131,15 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN// The Apple Health session of a workout that was running when the app was killed is// recovered (WatchAppDelegate.handleActiveWorkoutRecovery); a new one starts only if// none came back by then, so one workout never becomes two.+ // A workout left open for hours (SensorPlan) starts no session until something happens in it.if let w = saved.workout {workoutSeenAt = w.start.map { Date(timeIntervalSince1970: $0 / 1000) }DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] inguard let self = self, self.state.workout?.id == w.id else { return }- self.health.start(workoutId: w.id)+ if !SensorPlan.idle(w, seen: nil, now: Date().timeIntervalSince1970 * 1000, busy: false) {+ self.health.start(workoutId: w.id)+ }+ self.armIdleCheck()}}}@@ -149,6 +153,48 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN}}+ /* ---------- the heart-rate sensor in a workout nobody finishes (SensorPlan) ---------- */++ /// The last thing that happened here or came from the phone in the running workout.+ private var activityAt: Date?+ private var idleCheck: DispatchWorkItem?++ /// Something happened in the workout: a paused session resumes (or one starts, for a restored+ /// workout that was idle at launch), and the idle check moves out.+ private func noteActivity() {+ guard !isDemo, let w = workout else { return }+ activityAt = Date()+ if health.paused { health.resume() } else { health.start(workoutId: w.id) }+ armIdleCheck()+ }++ /// One check, at the moment the workout would turn idle; nothing runs in between.+ private func armIdleCheck() {+ idleCheck?.cancel()+ idleCheck = nil+ guard !isDemo, let at = SensorPlan.checkAt(workout, seen: activityAt.map { $0.timeIntervalSince1970 * 1000 }) else { return }+ let item = DispatchWorkItem { [weak self] in+ guard let self = self, self.workout != nil else { return }+ let busy = self.restEndsAt != nil || self.holdEndsAt != nil+ if SensorPlan.idle(self.workout, seen: self.activityAt.map { $0.timeIntervalSince1970 * 1000 },+ now: Date().timeIntervalSince1970 * 1000, busy: busy) {+ self.log("idle \(Int(SensorPlan.idleLimitMs / 60000)) min: workout session paused")+ self.health.pause()+ } else if busy {+ // A rest or hold runs on: look again once it is surely over.+ self.idleCheck = nil+ let again = DispatchWorkItem { [weak self] in self?.armIdleCheck() }+ self.idleCheck = again+ DispatchQueue.main.asyncAfter(deadline: .now() + 300, execute: again)+ } else {+ self.armIdleCheck()+ }+ }+ idleCheck = item+ let delay = max(0, at - Date().timeIntervalSince1970 * 1000) / 1000 + 1+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)+ }+private func save() {if let data = try? JSONEncoder().encode(state) { UserDefaults.standard.set(data, forKey: SessionStore.stateKey) }}@@ -274,6 +320,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNself.summary = nilself.health.start(workoutId: next.workout?.id)}+ if next.workout != nil && next.workout != before.workout { self.noteActivity() }if let rest = snap.active?.rest, next.workout?.id == snap.active?.id {let end = Date(timeIntervalSince1970: rest.endsAt / 1000)if end != self.restEndsAt { self.startRest(until: end, notify: true) }@@ -330,6 +377,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNstate = nextsetStartedAt = nowpicked[ei] = nil+ noteActivity()let (to, rest) = SessionCore.next(after: state, entry: ei, set: si)if side != nil && !rest {Haptics.side() // the other side now@@ -352,6 +400,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNlet ei = entryIndexstate = SessionCore.skip(state, entry: ei, set: si)picked[ei] = nil+ noteActivity()if setIndex == nil {let (to, _) = SessionCore.next(after: state, entry: ei, set: si)state.entryIndex = to@@ -367,6 +416,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNguard entry?.isTimed == true, setIndex != nil, seconds > 0 else { return }ackRestOver()skipRest()+ noteActivity()let now = Date()let end = now.addingTimeInterval(seconds)holdStartedAt = now@@ -483,6 +533,8 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNrestAfter = nilloadTargets()health.start(workoutId: next.workout?.id)+ activityAt = now+ armIdleCheck()summary = nilHaptics.start()}diff --git a/frontend/ios/App/Watch/WorkoutManager.swift b/frontend/ios/App/Watch/WorkoutManager.swiftindex 741b99bc0..3c173ebf6 100644--- a/frontend/ios/App/Watch/WorkoutManager.swift+++ b/frontend/ios/App/Watch/WorkoutManager.swift@@ -116,6 +116,7 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegatesamples = []heartRate = nilcalories = nil+ paused = falselet now = Date()s.startActivity(with: now)b.beginCollection(withStart: now) { _, _ in }@@ -129,6 +130,23 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate}}+ /// Rested for a workout nobody finishes (SensorPlan): the session pauses, which lets the+ /// heart-rate sensor go back to its everyday rate. Nothing is lost: the builder keeps what it+ /// measured, and the workout is still saved when it ends. `resume()` picks it up again.+ private(set) var paused = false++ func pause() {+ guard let s = session, !paused, s.state == .running else { return }+ paused = true+ s.pause()+ }++ func resume() {+ guard paused else { return }+ paused = false+ session?.resume()+ }+/// The app was killed (or crashed) with a workout session running: watchOS kept the session and/// hands it back here, with everything it measured. Taken up as if never gone; a session this/// launch started meanwhile is dropped (one workout in Apple Health, not two).@@ -147,6 +165,7 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegateb.delegate = selfself.session = sself.builder = b+ self.paused = s.state == .pausedself.wanted = trueif let wid = wid { self.workoutId = wid }self.tagged = nil@@ -267,6 +286,7 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate}session = nilbuilder = nil+ paused = falseDispatchQueue.main.async {self.running = falseself.heartRate = nildiff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/SensorPlan.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/SensorPlan.swiftnew file mode 100644index 000000000..4c987e7ff--- /dev/null+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/SensorPlan.swift@@ -0,0 +1,46 @@+import Foundation++/*+ * When the watch's Apple Health workout session (and with it the heart-rate sensor at workout+ * rate) is allowed to rest. A workout that is never finished (left open on the phone, the watch+ * forgotten on the charger) used to keep the session, and the sensor, running for good.+ *+ * Idle = no set ticked, no rest or hold running, no change to the workout from the phone, and+ * no start, for `idleLimit`. Then the session is PAUSED, not ended: nothing measured so far is+ * lost, the workout is still saved to Apple Health when it ends, and the next set, rest or+ * phone change resumes it (WorkoutManager.pause/resume). A saved workout restored at launch that+ * is already idle does not start a new session until something happens in it.+ */+enum SensorPlan {+ /// Three hours without anything happening in the workout.+ static let idleLimitMs: Double = 3 * 3600 * 1000++ /// The latest moment anything happened in this workout (ms since 1970): its start, when this+ /// watch first had it or last saw it change, each ticked set (and side), the rest's end.+ static func lastActivity(_ w: ActiveWorkout, seen: Double?) -> Double? {+ var last: Double? = nil+ func take(_ t: Double?) { if let t = t, t > (last ?? -.infinity) { last = t } }+ take(w.start)+ take(seen)+ take(w.rest?.endsAt)+ for e in w.entries {+ for s in e.sets { take(s.at) }+ }+ return last+ }++ /// Whether the session should rest now. `busy`: a rest or hold runs on the watch.+ /// Without any known time there is nothing to measure idleness from: not idle.+ static func idle(_ w: ActiveWorkout?, seen: Double?, now: Double, busy: Bool) -> Bool {+ guard let w = w else { return false }+ if busy { return false }+ guard let last = lastActivity(w, seen: seen) else { return false }+ return now - last >= idleLimitMs+ }++ /// When to look again (ms since 1970): the moment the workout turns idle without new activity.+ static func checkAt(_ w: ActiveWorkout?, seen: Double?) -> Double? {+ guard let w = w, let last = lastActivity(w, seen: seen) else { return nil }+ return last + idleLimitMs+ }+}diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SensorPlanTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SensorPlanTests.swiftnew file mode 100644index 000000000..3540b9baf--- /dev/null+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SensorPlanTests.swift@@ -0,0 +1,66 @@+import XCTest+@testable import WatchCore++/// When the watch's workout session (the heart-rate sensor) rests in a workout nobody finishes.+final class SensorPlanTests: XCTestCase {+ let h: Double = 3600 * 1000++ func row(done: Bool = false, at: Double? = nil) -> SetRow {+ SetRow(w: 60, r: 8, sec: nil, done: done, warmup: false, at: at)+ }++ func workout(start: Double?, sets: [SetRow], rest: Double? = nil) -> ActiveWorkout {+ ActiveWorkout(id: "w1", name: "Push", unit: "kg", cur: 0, restSec: 90, rest: rest.map { RestInfo(endsAt: $0) },+ entries: [Entry(id: "0025", name: "Bench Press", mode: "reps", restSec: nil, last: nil, sets: sets),+ Entry(id: "0426", name: "Overhead Press", mode: "reps", restSec: nil, last: nil, sets: [row()])],+ start: start)+ }++ func testTheLastTickedSetIsTheLastActivity() {+ let w = workout(start: 1000, sets: [row(done: true, at: 5000), row(done: true, at: 9000), row()])+ XCTAssertEqual(SensorPlan.lastActivity(w, seen: nil), 9000)+ XCTAssertEqual(SensorPlan.lastActivity(w, seen: 20000), 20000)+ XCTAssertEqual(SensorPlan.lastActivity(workout(start: 1000, sets: [row()], rest: 7000), seen: nil), 7000)+ }++ func testAWorkoutLeftOpenTurnsIdleAfterTheLimitNotBefore() {+ let w = workout(start: 0, sets: [row(done: true, at: 10 * 60 * 1000), row()])+ let last = 10.0 * 60 * 1000+ XCTAssertFalse(SensorPlan.idle(w, seen: nil, now: last + 2 * h, busy: false))+ XCTAssertFalse(SensorPlan.idle(w, seen: nil, now: last + 3 * h - 1, busy: false))+ XCTAssertTrue(SensorPlan.idle(w, seen: nil, now: last + 3 * h, busy: false))+ XCTAssertEqual(SensorPlan.checkAt(w, seen: nil), last + 3 * h)+ }++ func testARunningRestOrHoldIsNeverIdle() {+ let w = workout(start: 0, sets: [row()])+ XCTAssertTrue(SensorPlan.idle(w, seen: nil, now: 10 * h, busy: false))+ XCTAssertFalse(SensorPlan.idle(w, seen: nil, now: 10 * h, busy: true))+ }++ func testANewTickOrAPhoneChangeMakesItActiveAgain() {+ var w = workout(start: 0, sets: [row(), row()])+ XCTAssertTrue(SensorPlan.idle(w, seen: nil, now: 4 * h, busy: false))+ // a change from the phone just now+ XCTAssertFalse(SensorPlan.idle(w, seen: 4 * h, now: 4 * h + 1, busy: false))+ // a set ticked just now+ w.entries[0].sets[0] = row(done: true, at: 4 * h)+ XCTAssertFalse(SensorPlan.idle(w, seen: nil, now: 4 * h + 1, busy: false))+ }++ func testNoWorkoutOrNoTimeIsNotIdle() {+ XCTAssertFalse(SensorPlan.idle(nil, seen: nil, now: 100 * h, busy: false))+ XCTAssertNil(SensorPlan.checkAt(nil, seen: nil))+ let w = workout(start: nil, sets: [row()])+ XCTAssertNil(SensorPlan.lastActivity(w, seen: nil))+ XCTAssertFalse(SensorPlan.idle(w, seen: nil, now: 100 * h, busy: false))+ }++ func testARestoredWorkoutFromYesterdayStartsIdle() {+ // Saved state from a workout started yesterday and never finished: at relaunch the+ // session does not start until something happens in it.+ let yesterday = 1_700_000_000_000.0+ let w = workout(start: yesterday, sets: [row(done: true, at: yesterday + 600_000), row()])+ XCTAssertTrue(SensorPlan.idle(w, seen: nil, now: yesterday + 20 * h, busy: false))+ }+}