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
Apple Health: what is deleted in openGym goes from Health, and only that
Duarte Santos28bf0164f2c4
diff --git a/frontend/ios/App/App/AppleHealthPlugin.swift b/frontend/ios/App/App/AppleHealthPlugin.swiftindex d22883632..0fb48274c 100644--- a/frontend/ios/App/App/AppleHealthPlugin.swift+++ b/frontend/ios/App/App/AppleHealthPlugin.swift@@ -13,7 +13,8 @@ import UIKit** A workout the Apple Watch app already saved for the same session (same sync identifier, the* watch as its source) is left as it is: it has the heart rate in it, and a second copy would count- * the session twice.+ * the session twice. Removing takes that copy out too, and says which ids Apple Health still holds+ * afterwards, so lib/health-sync.js keeps them and tries again rather than forgetting them.*/@objc(AppleHealthPlugin)public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {@@ -92,9 +93,10 @@ public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {let weights = (call.getArray("weights") as? [String]) ?? []Task {do {- if !sessions.isEmpty { try await self.delete(HKObjectType.workoutType(), ids: sessions) }- if !weights.isEmpty { try await self.delete(self.bodyMass, ids: weights) }- call.resolve()+ var left: [String] = []+ if !sessions.isEmpty { left += try await self.delete(HKObjectType.workoutType(), ids: sessions) }+ if !weights.isEmpty { left += try await self.delete(self.bodyMass, ids: weights) }+ call.resolve(["left": left])} catch {self.fail(call, error)}@@ -161,12 +163,24 @@ public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {start: at, end: at, metadata: syncMetadata(id))}- private func delete(_ type: HKObjectType, ids: [String]) async throws {+ /// Deletes every sample with one of these sync identifiers, the Apple Watch app's copy of a+ /// workout included, and answers the ids Apple Health still holds afterwards (one it would not+ /// let this app delete), so the next sync tries them again instead of forgetting them.+ private func delete(_ type: HKObjectType, ids: [String]) async throws -> [String] {let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeySyncIdentifier, allowedValues: ids)try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) instore.deleteObjects(of: type, predicate: predicate) { _, _, error inif let error = error { cont.resume(throwing: error) } else { cont.resume() }}}+ guard let sampleType = type as? HKSampleType else { return [] }+ let still: [HKSample] = await withCheckedContinuation { cont in+ let q = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { _, found, error in+ // Not allowed to read: nothing to check against, the delete above is all there is.+ cont.resume(returning: error == nil ? (found ?? []) : [])+ }+ store.execute(q)+ }+ return Array(Set(still.compactMap { $0.metadata?[HKMetadataKeySyncIdentifier] as? String }))}}diff --git a/frontend/src/lib/health-connect.js b/frontend/src/lib/health-connect.jsindex ffc72cb9b..51aacacd7 100644--- a/frontend/src/lib/health-connect.js+++ b/frontend/src/lib/health-connect.js@@ -106,14 +106,35 @@ export function recordKey(rec) {return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)}+/**+ * The record ids openGym has on record as deleted: a workout or a weigh-in day removed on this+ * device or on another one whose removal synced in (S.deleted, lib/sync-merge.js stampDeletions;+ * a negative stamp is an add-back), and everything a "Reset everything" wiped (S.resetIds).+ * Only these are taken out of Health: a copy that merely lacks a workout (signed out, a guest+ * copy, a state not loaded yet) never empties Apple Health or Health Connect.+ */+export function goneIds(S) {+ const out = new Set()+ const del = S?.deleted && typeof S.deleted === 'object' ? S.deleted : {}+ for (const [k, at] of Object.entries(del.workouts || {})) if (Number(at) > 0) out.add('opengym-w-' + k)+ for (const [k, at] of Object.entries(del.bodyweight || {})) if (Number(at) > 0) out.add('opengym-bw-' + k)+ const reset = S?.resetIds && typeof S.resetIds === 'object' ? S.resetIds : {}+ for (const k of Array.isArray(reset.workouts) ? reset.workouts : []) out.add('opengym-w-' + k)+ // A weigh-in is named by its day and time there ("2026-09-17|1758…"); Health knows it by day.+ for (const k of Array.isArray(reset.bodyweight) ? reset.bodyweight : []) out.add('opengym-bw-' + String(k).split('|')[0])+ return out+}+/*** What a sync has to do, given the records now and `written`, what this phone wrote before* ({ [id]: { k: 'session' | 'weight', h: recordKey } }). New and changed records are written,* records that are gone from openGym (a deleted workout, a removed weigh-in) are removed.- * Returns { sessions, weights, remove: { sessions: [id], weights: [id] }, written } — `written`- * being what the phone has written once the sync went through.+ * With `gone` (goneIds), only a record on record as deleted is removed; one that is merely+ * missing stays written, and goes once its deletion arrives. Returns { sessions, weights,+ * remove: { sessions: [id], weights: [id] }, written } — `written` being what the phone has+ * written once the sync went through.*/-export function planSync({ sessions, weights }, written = {}) {+export function planSync({ sessions, weights }, written = {}, gone = null) {const next = {}const out = { sessions: [], weights: [], remove: { sessions: [], weights: [] } }const take = (list, k, into) => {@@ -128,6 +149,7 @@ export function planSync({ sessions, weights }, written = {}) {take(weights, 'weight', out.weights)for (const [id, was] of Object.entries(written || {})) {if (next[id]) continue+ if (gone && !gone.has(id)) { next[id] = was; continue }if (was?.k === 'session') out.remove.sessions.push(id)else if (was?.k === 'weight') out.remove.weights.push(id)}diff --git a/frontend/src/lib/health-connect.test.js b/frontend/src/lib/health-connect.test.jsindex 17364f046..d31032b54 100644--- a/frontend/src/lib/health-connect.test.js+++ b/frontend/src/lib/health-connect.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { healthRecords, planSync, recordKey, sessionRecord, sessionType, SESSION_TYPES, TEXT_MAX, weightRecord, writtenIds } from './health-connect.js'+import { goneIds, healthRecords, planSync, 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@@ -119,6 +119,20 @@ describe('planSync', () => {expect(plan.remove).toEqual({ sessions: ['opengym-w-w1'], weights: ['opengym-bw-2026-09-17'] })expect(plan.written).toEqual({})})+ it('with the deletions on record, removes only those and keeps the merely missing as written', () => {+ const { written } = planSync(records(), {})+ const plan = planSync({ sessions: [], weights: [] }, written, new Set(['opengym-bw-2026-09-17']))+ expect(plan.remove).toEqual({ sessions: [], weights: ['opengym-bw-2026-09-17'] })+ expect(Object.keys(plan.written)).toEqual(['opengym-w-w1'])+ })+ it('goneIds reads removals, add-backs and a reset', () => {+ const ids = goneIds({+ deleted: { workouts: { a: 5, b: -6 }, bodyweight: { '2026-09-01': 7 }, routines: { r: 9 } },+ resetIds: { workouts: ['c'], bodyweight: ['2026-09-02|123', '2026-09-03|'] },+ })+ expect([...ids].sort()).toEqual(['opengym-bw-2026-09-01', 'opengym-bw-2026-09-02', 'opengym-bw-2026-09-03', 'opengym-w-a', 'opengym-w-c'])+ expect(goneIds(null).size).toBe(0)+ })it('writes one record for two workouts that share an id', () => {const twice = { sessions: [...records().sessions, { ...records().sessions[0], title: 'Copy' }], weights: [] }expect(planSync(twice, {}).sessions.map(s => s.title)).toEqual(['Push'])diff --git a/frontend/src/lib/health-sync.js b/frontend/src/lib/health-sync.jsindex 895034597..a272e7b96 100644--- a/frontend/src/lib/health-sync.js+++ b/frontend/src/lib/health-sync.js@@ -13,7 +13,7 @@//// The web build never gets here (MOBILE is a build-time flag).import { MOBILE, nativePlatform, readJsonFile, writeJsonFile } from './mobile.js'-import { healthRecords, planSync, writtenIds } from './health-connect.js'+import { healthRecords, planSync, writtenIds, goneIds } from './health-connect.js'import { exerciseNameFor } from './i18n-core.js'import { EXIDX } from './exercises.js'import { speedUnitOf } from './speed.js'@@ -105,7 +105,7 @@ export function syncHealth(S) {async function syncOnce(S, h) {const p = await plugin()if (!p) return h- const plan = planSync(healthRecords(S, { nameOf, speedUnit: speedUnitOf(S) }), h.written)+ const plan = planSync(healthRecords(S, { nameOf, speedUnit: speedUnitOf(S) }), h.written, goneIds(S))const nothing = !plan.sessions.length && !plan.weights.length && !plan.remove.sessions.length && !plan.remove.weights.lengthif (nothing) {if (!h.error) return h@@ -125,8 +125,15 @@ async function syncOnce(S, h) {const kept = Object.fromEntries(Object.entries(h.written).filter(([id]) => !plan.written[id]))out.written = { ...kept, ...plan.written }}- if (plan.remove.sessions.length || plan.remove.weights.length) await p.HC.remove(plan.remove)- out = { ...out, written: plan.written, at: Date.now(), error: null }+ let written = plan.written+ if (plan.remove.sessions.length || plan.remove.weights.length) {+ // Apple Health answers what it could not take out (`left`: one the watch saved that the+ // phone may not delete): kept as written, so the next sync tries again.+ const res = await p.HC.remove(plan.remove)+ const left = Array.isArray(res?.left) ? res.left : []+ if (left.length) written = { ...written, ...Object.fromEntries(left.filter(id => h.written[id]).map(id => [id, h.written[id]])) }+ }+ out = { ...out, written, at: Date.now(), error: null }} catch (e) {out.error = e?.code === 'permission' ? 'permission' : e?.code === 'unavailable' ? 'unavailable' : 'failed'}diff --git a/frontend/src/lib/health-sync.test.js b/frontend/src/lib/health-sync.test.jsindex 3d5fc126e..2cd75a7c7 100644--- a/frontend/src/lib/health-sync.test.js+++ b/frontend/src/lib/health-sync.test.js@@ -28,7 +28,11 @@ vi.mock('@capacitor/core', () => ({h.calls.push(['write', arg])if (h.fail) throw Object.assign(new Error('refused'), { code: h.fail })},- remove: async arg => { h.calls.push(['remove', arg]) },+ remove: async arg => {+ h.calls.push(['remove', arg])+ if (h.removeFail) throw Object.assign(new Error('refused'), { code: h.removeFail })+ return h.left ? { left: h.left } : undefined+ },openSettings: async () => {},setEnabled: async ({ on }) => { h.calls.push(['setEnabled', on]) },}),@@ -45,7 +49,7 @@ const file = () => JSON.parse(h.files.get('opengym-health.json') || 'null')let hsbeforeEach(async () => {vi.resetModules()- h.files.clear(); h.calls = []; h.status = { status: 'available', granted: false }; h.grant = true; h.fail = null; h.platform = 'android'; h.plugins = []+ h.files.clear(); h.calls = []; h.status = { status: 'available', granted: false }; h.grant = true; h.fail = null; h.removeFail = null; h.left = null; h.platform = 'android'; h.plugins = []hs = await import('./health-sync.js')})@@ -98,7 +102,7 @@ describe('keeping in step', () => {expect(writes().map(w => w.sessions.map(s => s.id))).toEqual([['opengym-w-w2']])h.calls = []- await hs.syncHealth(state([workout('w2', 18)]))+ await hs.syncHealth({ ...state([workout('w2', 18)]), deleted: { workouts: { w1: at(20, 9) } } })expect(writes()).toEqual([])expect(removes()).toEqual([{ sessions: ['opengym-w-w1'], weights: [] }])expect(Object.keys(file().written)).toEqual(['opengym-w-w2'])@@ -127,6 +131,87 @@ describe('keeping in step', () => {})})+// The owner, TestFlight: a workout or a weigh-in deleted in openGym goes from Apple Health too,+// wherever the deletion was made, and nothing else ever does.+describe('deleting in openGym', () => {+ const bw = (d, w) => ({ d: `2026-09-${d}`, w, t: at(d, 7) })+ it('takes a deleted workout and a removed weigh-in out, and rewrites an edited one', async () => {+ await hs.enableHealth(state([workout('w1', 17), workout('w2', 18)], [bw(17, 80), bw(18, 79)]))+ h.calls = []+ const edited = { ...workout('w2', 18), name: 'Push, heavier' }+ await hs.syncHealth({ ...state([edited], [bw(18, 79)]), deleted: { workouts: { w1: at(20, 9) }, bodyweight: { '2026-09-17': at(20, 9) } } })+ expect(writes().map(w => w.sessions.map(s => s.title))).toEqual([['Push, heavier']])+ expect(removes()).toEqual([{ sessions: ['opengym-w-w1'], weights: ['opengym-bw-2026-09-17'] }])+ expect(Object.keys(file().written).sort()).toEqual(['opengym-bw-2026-09-18', 'opengym-w-w2'])+ })++ it('a copy that merely lacks them (signed out, not loaded yet) removes nothing', async () => {+ await hs.enableHealth(state([workout('w1', 17)], [bw(17, 80)]))+ h.calls = []+ await hs.syncHealth(state([], []))+ expect(removes()).toEqual([])+ expect(Object.keys(file().written).sort()).toEqual(['opengym-bw-2026-09-17', 'opengym-w-w1'])+ // …and back with them, nothing is written twice.+ await hs.syncHealth(state([workout('w1', 17)], [bw(17, 80)]))+ expect(h.calls).toEqual([])+ })++ it('a deletion made on another device goes when it syncs in, even after a copy without the workout', async () => {+ await hs.enableHealth(state([workout('w1', 17), workout('w2', 18)]))+ await hs.syncHealth(state([workout('w2', 18)])) // the merge has not brought the record yet+ expect(removes()).toEqual([])+ await hs.syncHealth({ ...state([workout('w2', 18)]), deleted: { workouts: { w1: at(21, 9) } } })+ expect(removes()).toEqual([{ sessions: ['opengym-w-w1'], weights: [] }])+ })++ it('a deletion while it was off goes once it is on again', async () => {+ await hs.enableHealth(state([workout('w1', 17)]))+ await hs.disableHealth({ removeWritten: false })+ h.calls = []+ const after = { ...state([]), deleted: { workouts: { w1: at(21, 9) } } }+ await hs.syncHealth(after)+ expect(h.calls.filter(c => c[0] === 'remove')).toEqual([])+ await hs.enableHealth(after)+ expect(removes()).toEqual([{ sessions: ['opengym-w-w1'], weights: [] }])+ expect(file().written).toEqual({})+ })++ it('an add-back (a negative stamp) is not a deletion, and an entry this phone never wrote is skipped', async () => {+ await hs.enableHealth(state([workout('w1', 17)]))+ h.calls = []+ await hs.syncHealth({ ...state([]), deleted: { workouts: { w1: -at(21, 9), old: at(21, 9) } } })+ expect(removes()).toEqual([])+ })++ it('"Reset everything" takes out what it wiped', async () => {+ await hs.enableHealth(state([workout('w1', 17)], [bw(17, 80)]))+ h.calls = []+ await hs.syncHealth({ ...state([]), resetAt: at(22, 9), resetIds: { workouts: ['w1'], bodyweight: ['2026-09-17|' + at(17, 7)] } })+ expect(removes()).toEqual([{ sessions: ['opengym-w-w1'], weights: ['opengym-bw-2026-09-17'] }])+ })++ it('a refused removal is tried again on the next sync, and one Apple Health kept is not forgotten', async () => {+ await hs.enableHealth(state([workout('w1', 17), workout('w2', 18)]))+ const gone = { ...state([]), deleted: { workouts: { w1: at(21, 9), w2: at(21, 9) } } }+ h.removeFail = 'permission'+ await hs.syncHealth(gone)+ expect(file().error).toBe('permission')+ expect(Object.keys(file().written).sort()).toEqual(['opengym-w-w1', 'opengym-w-w2'])+ h.removeFail = null+ h.left = ['opengym-w-w2'] // say the watch's copy stayed+ h.calls = []+ await hs.syncHealth(gone)+ expect(removes()).toEqual([{ sessions: ['opengym-w-w1', 'opengym-w-w2'], weights: [] }])+ expect(Object.keys(file().written)).toEqual(['opengym-w-w2'])+ expect(file().error).toBeNull()+ h.left = null+ h.calls = []+ await hs.syncHealth(gone)+ expect(removes()).toEqual([{ sessions: ['opengym-w-w2'], weights: [] }])+ expect(file().written).toEqual({})+ })+})+describe('turning it off', () => {it('can leave what it wrote in Health Connect', async () => {await hs.enableHealth(state([workout('w1', 17)]))