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 Health: the watch takes out its own copies of workouts deleted in openGym

Duarte Santos67d42c5d2911
diff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swift
index 905d303a1..af3af9074 100644
--- a/frontend/ios/App/Watch/OpenGymWatchApp.swift
+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift
@@ -540,7 +540,7 @@ struct ValueEditor: View {
let unit: String
@State private var value: Double = 0
@FocusState private var focused: Bool
- @ScaledMetric(relativeTo: .largeTitle) private var size: CGFloat = 46
+ @ScaledMetric(relativeTo: .largeTitle) private var size: CGFloat = 54
private var step: Double {
switch field {
diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swift
index 0afa4bc79..6f5ab7c7c 100644
--- a/frontend/ios/App/Watch/SessionStore.swift
+++ b/frontend/ios/App/Watch/SessionStore.swift
@@ -261,6 +261,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
self.summary = SessionCore.summary(ended, end: Date().timeIntervalSince1970 * 1000,
startedAt: self.workoutSeenAt.map { $0.timeIntervalSince1970 * 1000 }, endedOnPhone: true)
}
+ self.ran(ended.id)
self.health.end(save: true) { totals in self.addTotals(totals) }
self.dropClips()
self.stopHold()
@@ -278,6 +279,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
if end != self.restEndsAt { self.startRest(until: end, notify: true) }
}
self.health.syncSetting(next.settings.health)
+ self.removeDeletedFromHealth(snap.healthGone)
self.loadTargets()
}
}
@@ -407,6 +409,37 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
summary = nil
}
+ /* ---------- workouts deleted in openGym, out of Apple Health ---------- */
+
+ private static let healthDeletedKey = "healthDeleted"
+ private var healthDeleting = false
+ /// The last few workouts that ran here (their Apple Health copy may still be being saved).
+ private var recentWorkouts: [String] = []
+ private func ran(_ wid: String?) {
+ guard let wid = wid else { return }
+ recentWorkouts = Array((recentWorkouts.filter { $0 != wid } + [wid]).suffix(3))
+ }
+
+ /// The copies this watch saved of workouts deleted in openGym: taken out once (the ids settled
+ /// are remembered), and the phone told, so it stops retrying what it could not delete itself.
+ private func removeDeletedFromHealth(_ gone: [String]?) {
+ guard !isDemo, !healthDeleting else { return }
+ let done = UserDefaults.standard.stringArray(forKey: SessionStore.healthDeletedKey) ?? []
+ let todo = SessionCore.healthToDelete(gone: gone, done: done)
+ guard !todo.isEmpty else { return }
+ healthDeleting = true
+ let recent = Set(recentWorkouts.map { "opengym-w-\($0)" })
+ health.deleteWorkouts(syncIds: todo, keepTrying: recent) { [weak self] settled in
+ guard let self = self else { return }
+ self.healthDeleting = false
+ guard !settled.isEmpty else { return }
+ let now = UserDefaults.standard.stringArray(forKey: SessionStore.healthDeletedKey) ?? []
+ UserDefaults.standard.set(SessionCore.healthDeleted(now, adding: settled), forKey: SessionStore.healthDeletedKey)
+ if let ev = SessionCore.healthDeletedEvent(settled, id: UUID().uuidString) { self.send(event: ev) }
+ self.log("removed from Apple Health: \(settled.count)")
+ }
+ }
+
/// The weigh-in before a workout started here (the phone's check-in), when the phone asks for one.
@Published private(set) var weighInFor: ReadySession?
/// The body weight on the weigh-in's crown.
@@ -462,6 +495,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
let (next, event) = SessionCore.finish(state, at: now, id: UUID().uuidString)
guard let ev = event else { return }
if let w = ended { summary = SessionCore.summary(w, end: now, startedAt: workoutSeenAt.map { $0.timeIntervalSince1970 * 1000 }) }
+ ran(ended?.id)
health.end(save: true) { [weak self] totals in self?.addTotals(totals) }
stopHold()
skipRest()
@@ -689,7 +723,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
if screen != "empty" { apply(json: screen == "idle" ? SessionStore.demoReadyJSON : SessionStore.demoJSON) }
DispatchQueue.main.async {
switch screen {
- case "set", "weight", "rest", "offline": self.picked[0] = 2
+ case "set", "weight", "rest", "offline", "edit-weight", "edit-reps": self.picked[0] = 2
case "hold": self.state.entryIndex = 1
case "bodyweight": self.state.entryIndex = 2
case "side": self.state.entryIndex = 3
diff --git a/frontend/ios/App/Watch/WorkoutManager.swift b/frontend/ios/App/Watch/WorkoutManager.swift
index a7382d8f3..9e974389c 100644
--- a/frontend/ios/App/Watch/WorkoutManager.swift
+++ b/frontend/ios/App/Watch/WorkoutManager.swift
@@ -158,6 +158,42 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
}
}
+ /// Takes out of Apple Health the workouts this app saved under these sync ids (workouts deleted
+ /// in openGym), with the calories saved along with them. Heart-rate readings are the watch's
+ /// sensors' own and stay, as with Apple's Workout app. `done` gets the ids that are settled:
+ /// removed, or with no copy of this app's to remove. Nothing settled when Health could not be
+ /// read or the delete was refused: the next snapshot tries again.
+ /// `keepTrying`: ids of workouts that ran here just now, whose copy may still be on its way
+ /// into Health (a workout deleted on the phone while the watch was still saving it): not
+ /// settled while no copy is found, so the next snapshot looks again.
+ func deleteWorkouts(syncIds ids: [String], keepTrying: Set<String> = [], done: @escaping ([String]) -> Void) {
+ guard HKHealthStore.isHealthDataAvailable(), !ids.isEmpty else { done([]); return }
+ let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeySyncIdentifier, allowedValues: ids)
+ let q = HKSampleQuery(sampleType: HKObjectType.workoutType(), predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { [weak self] _, found, error in
+ guard let self = self else { return }
+ if error != nil { DispatchQueue.main.async { done([]) }; return }
+ let me = Bundle.main.bundleIdentifier ?? ""
+ let mine = (found as? [HKWorkout] ?? []).filter { $0.sourceRevision.source.bundleIdentifier == me }
+ let held = Set(mine.compactMap { $0.metadata?[HKMetadataKeySyncIdentifier] as? String })
+ // Settled without a delete: no copy of this app's, and not one that may still come.
+ let nothing = ids.filter { !held.contains($0) && !keepTrying.contains($0) }
+ if mine.isEmpty { DispatchQueue.main.async { done(nothing) }; return }
+ let group = DispatchGroup()
+ if let kcal = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned) {
+ for w in mine {
+ group.enter()
+ self.store.deleteObjects(of: kcal, predicate: HKQuery.predicateForObjects(from: w)) { _, _, _ in group.leave() }
+ }
+ }
+ group.notify(queue: .global()) {
+ self.store.delete(mine) { ok, _ in
+ DispatchQueue.main.async { done(ok ? nothing + Array(held) : nothing) }
+ }
+ }
+ }
+ store.execute(q)
+ }
+
private func startQuery(from start: Date) {
guard let type = HKQuantityType.quantityType(forIdentifier: .heartRate) else { return }
let predicate = HKQuery.predicateForSamples(withStart: start, end: nil, options: .strictStartDate)
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
index f262b6a07..4d6bd8316 100644
--- a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
@@ -13,6 +13,9 @@ struct Snapshot: Codable, Equatable {
var active: ActiveWorkout?
var ready: Ready?
var settings: WatchSettings?
+ /// Apple Health sync ids of workouts deleted in openGym ("opengym-w-<id>", newest first): the
+ /// watch takes out the copies it saved itself, which the phone may not delete.
+ var healthGone: [String]?
}
/// What the watch can start by itself: today's planned session and a few other routines.
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
index b6c519212..13240c93f 100644
--- a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
@@ -222,6 +222,28 @@ enum SessionCore {
return (count, true)
}
+ /// Of the deleted workouts the phone names, the ones this watch has not taken out of Apple Health
+ /// yet (`done`: already removed, or found to have no copy of the watch's). Only workout ids.
+ static func healthToDelete(gone: [String]?, done: [String]) -> [String] {
+ let seen = Set(done)
+ var out: [String] = []
+ for id in gone ?? [] where id.hasPrefix("opengym-w-") && !seen.contains(id) && !out.contains(id) { out.append(id) }
+ return out
+ }
+
+ /// `done` with these ids added, the newest kept (a few hundred is plenty: the phone names at
+ /// most the last sixty deletions).
+ static func healthDeleted(_ done: [String], adding ids: [String]) -> [String] {
+ var out = done.filter { !ids.contains($0) }
+ out.append(contentsOf: ids)
+ return Array(out.suffix(300))
+ }
+
+ /// What the phone is told once they are out, so its own retries of them stop.
+ static func healthDeletedEvent(_ ids: [String], id: String) -> Event? {
+ ids.isEmpty ? nil : ["id": id, "type": "healthDeleted", "ids": ids]
+ }
+
/// The weigh-in before a workout started here, for the phone's body weight list.
static func weighIn(_ w: Double, at: Double, id: String) -> Event? {
guard w > 0, w < 700 else { return nil }
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SetTypesTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SetTypesTests.swift
index ecfc6fd0d..9d068adb5 100644
--- a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SetTypesTests.swift
+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SetTypesTests.swift
@@ -212,3 +212,30 @@ final class SettingsAndWeighInTests: XCTestCase {
XCTAssertNil(old.settings?.lang)
}
}
+
+/// Workouts deleted in openGym: the watch takes its own copies out of Apple Health, once.
+final class HealthDeleteTests: XCTestCase {
+ func testOnlyWorkoutIdsNotDoneYetOnceEach() {
+ let todo = SessionCore.healthToDelete(gone: ["opengym-w-a", "opengym-bw-2026-10-01", "opengym-w-b", "opengym-w-a"], done: ["opengym-w-b"])
+ XCTAssertEqual(todo, ["opengym-w-a"])
+ XCTAssertEqual(SessionCore.healthToDelete(gone: nil, done: []), [])
+ }
+
+ func testDoneIsKeptBoundedAndANewRoundIsANoOp() {
+ var done: [String] = []
+ done = SessionCore.healthDeleted(done, adding: ["opengym-w-a"])
+ done = SessionCore.healthDeleted(done, adding: ["opengym-w-a"])
+ XCTAssertEqual(done, ["opengym-w-a"])
+ XCTAssertEqual(SessionCore.healthToDelete(gone: ["opengym-w-a"], done: done), [])
+ let many = (0..<400).map { "opengym-w-\($0)" }
+ XCTAssertEqual(SessionCore.healthDeleted([], adding: many).count, 300)
+ let ev = SessionCore.healthDeletedEvent(["opengym-w-a"], id: "e")
+ XCTAssertEqual(ev?["type"] as? String, "healthDeleted")
+ XCTAssertNil(SessionCore.healthDeletedEvent([], id: "e"))
+ }
+
+ func testASnapshotWithTheListReads() throws {
+ let snap = try JSONDecoder().decode(Snapshot.self, from: Data(#"{"v":1,"healthGone":["opengym-w-x"]}"#.utf8))
+ XCTAssertEqual(snap.healthGone, ["opengym-w-x"])
+ }
+}
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 0213cd784..998c45ce3 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -347,6 +347,9 @@ export default function App() {
start: (ids, { bw = null, ...opts } = {}) => beginWorkout(ids, bw, opts),
// The watch's weigh-in: logged as the phone's check-in logs one (today's replaces today's).
weighIn: ({ w, at }) => useStore.getState().update(s => { logWeighIn(s, w, at) }),
+ // The watch removed its copies of deleted workouts from Apple Health: the phone's removal
+ // runs again, finds them gone and stops retrying them.
+ healthDeleted: () => { import('./lib/health-sync.js').then(m => m.syncHealth(useStore.getState().S)).catch(() => {}) },
patchSet: (where, fields, opts = {}) => useStore.getState().update(s => {
patchSetIn(s, where, fields, stampWorkout, { ...opts, recount: w => { w.vol = workoutVolume(w) } })
}),
diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.js
index 7eb689356..cb0a48b5d 100644
--- a/frontend/src/lib/watch-sync.js
+++ b/frontend/src/lib/watch-sync.js
@@ -256,6 +256,10 @@ export function applyEvents (events, getState) {
if (!appHandlers?.weighIn) break
appHandlers.weighIn({ w: num(ev.w), at: num(ev.at) || Date.now() })
}
+ } else if (ev.type === 'healthDeleted') {
+ // The watch took its copies of deleted workouts out of Apple Health: the phone's own removal
+ // (which kept retrying the ones it could not delete) runs again and now finds them gone.
+ if (appHandlers?.healthDeleted) appHandlers.healthDeleted(Array.isArray(ev.ids) ? ev.ids.filter(x => typeof x === 'string') : [])
} else if (ev.type === 'watchStatus') {
// What the watch says about itself, for Settings → Apple Watch. Never queued behind anything.
writeWatchStatus(ev)
@@ -390,6 +394,24 @@ export function fitSnapshot (snap, max = SNAPSHOT_MAX_BYTES) {
return out
}
+// How many deleted workouts the watch is told about at most (the newest deletions).
+export const HEALTH_GONE_MAX = 60
+
+/**
+ * The Apple Health sync ids of workouts deleted in openGym (S.deleted, newest first), for the watch
+ * to take its own copies out of Health: a workout the watch app saved is the watch's, and the phone
+ * may not delete it, nor the heart rate and calories saved with it (lib/health-connect.js goneIds
+ * names the same ids for the phone's own copies).
+ */
+export function healthGoneFor (S, max = HEALTH_GONE_MAX) {
+ const del = S?.deleted && typeof S.deleted === 'object' && S.deleted.workouts && typeof S.deleted.workouts === 'object' ? S.deleted.workouts : {}
+ return Object.entries(del)
+ .filter(([, at]) => Number(at) > 0)
+ .sort((a, b) => Number(b[1]) - Number(a[1]))
+ .slice(0, max)
+ .map(([id]) => 'opengym-w-' + id)
+}
+
/**
* What the watch takes from the app beyond its own settings: the app's language (the watch shows
* its words in it, whatever the watch itself is set to), and whether a workout starts with the
@@ -448,6 +470,8 @@ export async function startWatchSync ({ useStore, useUI }) {
? 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, healthOn), ...watchExtras(S) }
+ // With Apple Health on: the deleted workouts, so the watch removes the copies it saved.
+ if (healthOn) { const gone = healthGoneFor(S); if (gone.length) snap.healthGone = gone }
const json = JSON.stringify(fitSnapshot(snap))
if (json !== lastSent) {
const r = await p.WatchBridge.sendSnapshot({ json })
diff --git a/frontend/src/lib/watch-sync.settypes.test.js b/frontend/src/lib/watch-sync.settypes.test.js
index d0e0412ad..3f05db819 100644
--- a/frontend/src/lib/watch-sync.settypes.test.js
+++ b/frontend/src/lib/watch-sync.settypes.test.js
@@ -166,3 +166,22 @@ describe('the weigh-in from the watch', () => {
expect(watchExtras({})).toEqual({ lang: 'en', weighIn: true })
})
})
+
+describe('workouts deleted in openGym, for the watch\'s own copies in Apple Health', () => {
+ it('names the deleted workouts newest first, leaves add-backs out, and caps the list', async () => {
+ const { healthGoneFor } = await import('./watch-sync.js')
+ const S = { deleted: { workouts: { a: 100, b: 300, c: -5, d: 200 }, bodyweight: { '2026-10-01': 50 } } }
+ expect(healthGoneFor(S)).toEqual(['opengym-w-b', 'opengym-w-d', 'opengym-w-a'])
+ expect(healthGoneFor(S, 2)).toEqual(['opengym-w-b', 'opengym-w-d'])
+ expect(healthGoneFor({})).toEqual([])
+ })
+
+ it('the watch saying it removed them makes the phone sync Health again, once', () => {
+ const healthDeleted = vi.fn()
+ bindWatchAppActions({ start: vi.fn(), patchSet: vi.fn(), healthDeleted })
+ const ev = { id: 'hd1', type: 'healthDeleted', ids: ['opengym-w-b', 7] }
+ applyEvents([ev, ev], () => ({ S: { active: null } }))
+ expect(healthDeleted).toHaveBeenCalledTimes(1)
+ expect(healthDeleted).toHaveBeenCalledWith(['opengym-w-b'])
+ })
+})