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.

fix(watch): a workout discarded on the phone is not saved to Apple Health (#776)

Duarte Santos19015f3141c0
diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swift
index 4ed295f1d..392abcb80 100644
--- a/frontend/ios/App/Watch/SessionStore.swift
+++ b/frontend/ios/App/Watch/SessionStore.swift
@@ -313,14 +313,19 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
let next = SessionCore.applySnapshot(before, snap)
self.state = next
if let ended = before.workout, next.workout == nil {
- // Ended on the phone (finished or discarded there): the session here ends too, and the
- // watch says so instead of quietly going back to the start screen.
- if !self.isDemo {
- self.summary = SessionCore.summary(ended, end: Date().timeIntervalSince1970 * 1000,
- startedAt: self.workoutSeenAt.map { $0.timeIntervalSince1970 * 1000 }, endedOnPhone: true)
+ // Ended on the phone: the session here ends too. Finished there, it is saved to Apple
+ // Health and the watch says so instead of quietly going back to the start screen.
+ // Discarded there (#776), nothing of it is saved, and there is nothing to sum up.
+ if SessionCore.discarded(ended.id, in: snap) {
+ self.health.end(save: false)
+ } else {
+ if !self.isDemo {
+ 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.ran(ended.id)
- self.health.end(save: true) { totals in self.addTotals(totals) }
self.dropClips()
self.stopHold()
self.skipRest()
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
index 4d6bd8316..963655698 100644
--- a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
@@ -16,6 +16,9 @@ struct Snapshot: Codable, Equatable {
/// 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]?
+ /// Workouts discarded on the phone lately (their ids): one of these that leaves the snapshot
+ /// was not finished, so the watch drops its Apple Health workout instead of saving it (#776).
+ var discarded: [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 13240c93f..a71e79592 100644
--- a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
@@ -222,6 +222,13 @@ enum SessionCore {
return (count, true)
}
+ /// Whether workout `wid`, gone from this snapshot, was discarded on the phone (not finished):
+ /// then nothing of it is saved to Apple Health (#776). An older phone never says: saved, as before.
+ static func discarded(_ wid: String?, in snap: Snapshot) -> Bool {
+ guard let wid = wid else { return false }
+ return snap.discarded?.contains(wid) ?? false
+ }
+
/// 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] {
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift
index 62bf917fd..17b12d2e5 100644
--- a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift
+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift
@@ -112,4 +112,17 @@ final class SessionCoreTests: XCTestCase {
let snap = try JSONDecoder().decode(Snapshot.self, from: Data(json.utf8))
XCTAssertEqual(SessionCore.applySnapshot(SessionState(), snap).workout?.entries.first?.sets.count, 1)
}
+
+ // #776: a workout discarded on the phone is not saved to Apple Health; finished, or from an
+ // older phone that does not say, it is.
+ func testADiscardedWorkoutIsToldApartFromAFinishedOne() throws {
+ var gone = snap(nil)
+ XCTAssertFalse(SessionCore.discarded("p1", in: gone))
+ gone.discarded = ["p0", "p1"]
+ XCTAssertTrue(SessionCore.discarded("p1", in: gone))
+ XCTAssertFalse(SessionCore.discarded("p2", in: gone))
+ XCTAssertFalse(SessionCore.discarded(nil, in: gone))
+ let json = #"{"v":1,"active":null,"discarded":["p1"]}"#
+ XCTAssertTrue(SessionCore.discarded("p1", in: try JSONDecoder().decode(Snapshot.self, from: Data(json.utf8))))
+ }
}
diff --git a/frontend/src/components/ErrorBoundary.jsx b/frontend/src/components/ErrorBoundary.jsx
index c2c0e9d68..e41eca160 100644
--- a/frontend/src/components/ErrorBoundary.jsx
+++ b/frontend/src/components/ErrorBoundary.jsx
@@ -1,6 +1,7 @@
import { Component } from 'react'
import { useStore } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
+import { markDiscarded } from '../lib/watch-sync.js'
import Icon from './Icon.jsx'
import { Button } from './ui.jsx'
@@ -31,6 +32,8 @@ export default class ErrorBoundary extends Component {
{active && <>
<div style={{ height: 8 }} />
<Button variant="danger" icon="trash" onClick={() => {
+ // The watch hears it was discarded, not finished (#776).
+ markDiscarded(useStore.getState().S.active?.id)
useStore.getState().update(s => { s.active = null })
location.reload()
}}>{t('Discard the running workout')}</Button>
diff --git a/frontend/src/lib/watch-sync.discard.test.js b/frontend/src/lib/watch-sync.discard.test.js
new file mode 100644
index 000000000..5586af7ac
--- /dev/null
+++ b/frontend/src/lib/watch-sync.discard.test.js
@@ -0,0 +1,71 @@
+// @vitest-environment happy-dom
+// A workout discarded on the phone while the watch runs it (#776): the snapshot names it, so the
+// watch drops its Apple Health workout instead of saving it as if it had been finished.
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('./health-sync.js', () => ({
+ loadHealth: async () => ({ on: true }),
+ onHealthChange: () => () => {},
+}))
+
+import { startWatchSync, markDiscarded, discardedFor, _setWatchPluginForTest, _resetWatchSync, DISCARDED_FOR_MS } from './watch-sync.js'
+
+beforeEach(() => { localStorage.clear(); _resetWatchSync() })
+
+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() {
+ return {
+ status: vi.fn(async () => ({ paired: true, installed: true })),
+ sendSnapshot: vi.fn(async () => ({ sent: true })),
+ sendClips: vi.fn(async () => ({})),
+ dropClips: vi.fn(async () => ({})),
+ openOnWatch: vi.fn(async () => ({ ok: true })),
+ drain: vi.fn(async () => ({ events: [] })),
+ ack: vi.fn(async () => ({})),
+ addListener: vi.fn(async () => ({ remove: () => {} })),
+ }
+}
+
+describe('discarded workouts, for the watch', () => {
+ const now = 1_800_000_000_000
+ it('remembers the newest few, for a while', () => {
+ markDiscarded('a', now)
+ markDiscarded('b', now + 1)
+ markDiscarded('a', now + 2)
+ markDiscarded(null, now)
+ expect(discardedFor(now + 3)).toEqual(['b', 'a'])
+ expect(discardedFor(now + 1 + DISCARDED_FOR_MS)).toEqual(['a'])
+ expect(discardedFor(now + 3 + DISCARDED_FOR_MS)).toEqual([])
+ for (let i = 0; i < 20; i++) markDiscarded('x' + i, now)
+ expect(discardedFor(now).length).toBeLessThanOrEqual(5)
+ })
+
+ it('goes out with the snapshot that ends the workout, a finished one does not', async () => {
+ vi.useFakeTimers()
+ try {
+ const b = bridge()
+ _setWatchPluginForTest(b)
+ const S0 = { unit: 'kg', workouts: [], routines: [], active: { id: 'w-1', start: Date.now() - 60e3, entries: [] } }
+ const st = store({ S: S0 })
+ const stop = await startWatchSync({ useStore: st, useUI: store({ timer: null }) })
+ await vi.runAllTimersAsync()
+ const last = () => JSON.parse(b.sendSnapshot.mock.calls.at(-1)[0].json)
+ expect(last().discarded).toBeUndefined()
+ markDiscarded('w-1')
+ st.setState({ S: { ...S0, active: null } })
+ await vi.runAllTimersAsync()
+ expect(last().active).toBe(null)
+ expect(last().discarded).toEqual(['w-1'])
+ stop()
+ } finally { vi.useRealTimers() }
+ })
+})
diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.js
index 70467135c..204b8006f 100644
--- a/frontend/src/lib/watch-sync.js
+++ b/frontend/src/lib/watch-sync.js
@@ -422,6 +422,30 @@ export function healthGoneFor (S, max = HEALTH_GONE_MAX) {
.map(([id]) => 'opengym-w-' + id)
}
+// Workouts discarded on the phone (#776), newest last: the snapshot names them for a while, so a
+// watch running one ends its Apple Health workout without saving it. Gone from the snapshot it
+// looks the same as a finished one. In localStorage, not S: a fact about this phone and its
+// watch, and it has to outlive the reload of "Discard the running workout" (ErrorBoundary).
+const DISCARDED_KEY = 'gym_watch_discarded'
+const DISCARDED_MAX = 5
+// Long enough for a watch out of range (or asleep in a bag) to hear it.
+export const DISCARDED_FOR_MS = 12 * 3600e3
+const readDiscarded = () => {
+ try { const v = JSON.parse(localStorage.getItem(DISCARDED_KEY)); return Array.isArray(v) ? v.filter(x => x && typeof x.id === 'string' && Number(x.at) > 0) : [] } catch { return [] }
+}
+
+/** The running workout `wid` is being discarded: call before it leaves S.active. */
+export function markDiscarded (wid, now = Date.now()) {
+ if (!wid || typeof wid !== 'string') return
+ const list = [...readDiscarded().filter(x => x.id !== wid), { id: wid, at: now }].slice(-DISCARDED_MAX)
+ try { localStorage.setItem(DISCARDED_KEY, JSON.stringify(list)) } catch { /* the watch then saves it, as before */ }
+}
+
+/** The ids of the workouts discarded here lately, oldest first. */
+export function discardedFor (now = Date.now()) {
+ return readDiscarded().filter(x => now - Number(x.at) < DISCARDED_FOR_MS).map(x => x.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
@@ -486,6 +510,9 @@ export async function startWatchSync ({ useStore, useUI }) {
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 }
+ // Discarded here: the watch drops its Apple Health workout instead of saving it (#776).
+ const discarded = discardedFor()
+ if (discarded.length) snap.discarded = discarded
const json = JSON.stringify(fitSnapshot(snap))
if (json !== lastSent) {
const r = await p.WatchBridge.sendSnapshot({ json })
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index 058fe85f6..40e11b651 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -40,7 +40,7 @@ import { routineChangesFromEntry, updateRoutineFromEntry } from '../lib/routines
import { sessionNoProg, setSessionNoProg, setEntryNoProg, joinSessionNoProg } from '../lib/session-noprog.js'
import { glyphOf } from '../lib/glyphs.js'
import { markAllSetsDone, sessionHistory } from '../lib/backfill.js'
-import { bindWatchActions } from '../lib/watch-sync.js'
+import { bindWatchActions, markDiscarded } from '../lib/watch-sync.js'
import { bestSetFor } from '../lib/exercise-history.js'
import { bindLiveActions } from '../lib/live-activity.js'
import { isWarmupRow, isFailureSet, toggleFailure, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps, isSideSet, makeSideSet, setSideField, toggleSide, addSideDrop, removeSideDropAt, setSideDropAt, addSideCluster, removeSideClusterAt, setSideClusterAt, WEIGHT_ORIGIN_MANUAL } from '../lib/workout-model.js'
@@ -1541,7 +1541,8 @@ function ActiveWorkout() {
// ⌄ that only leaves the screen (v1.3.11).
const discardWorkout = () => confirmSheet({
title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true,
- onConfirm: () => { update(s => { s.active = null }); stopRest(); stopWork(); nav('/home') },
+ // Named for the watch first: gone from its snapshot it would look finished, and be saved to Apple Health (#776).
+ onConfirm: () => { markDiscarded(useStore.getState().S.active?.id); update(s => { s.active = null }); stopRest(); stopWork(); nav('/home') },
})
// The header ⋯, in groups: the settings you change at the gym first (their own sheet, the same
// values as Settings), then what to add, what to change about this workout, and Discard last.
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx
index a1f91236f..23a449c70 100644
--- a/frontend/src/views/Workout.test.jsx
+++ b/frontend/src/views/Workout.test.jsx
@@ -8,6 +8,7 @@ import { nextPrescription } from '../lib/progression.js'
import { buildCombinedEntries } from '../lib/session-merge.js'
import { buildCompletedWorkout } from '../lib/finish-workout.js'
import { isWarmupRow } from '../lib/workout-model.js'
+import { discardedFor } from '../lib/watch-sync.js'
import { finishWorkout, finishWorkoutSheet } from '../sheets.jsx'
// A menu's actions in order, whether it came as one list or in groups (menuSheet `sections`).
@@ -891,6 +892,21 @@ describe('Workout discard timer lifecycle', () => {
expect(mocks.stopRest).toHaveBeenCalledOnce()
expect(mocks.stopWork).toHaveBeenCalledOnce()
})
+
+ // #776: gone from the watch's snapshot, a discarded workout looked finished and was saved to
+ // Apple Health. Discard names it for the watch first.
+ it('tells the watch the workout was discarded, not finished', async () => {
+ const kept = new Map()
+ vi.stubGlobal('localStorage', { getItem: k => kept.get(k) ?? null, setItem: (k, v) => kept.set(k, String(v)), removeItem: k => kept.delete(k) })
+ await mount([exercise('timed-plank', [false])])
+ const wid = mocks.S.active.id
+ expect(wid).toBeTruthy()
+ await requestDiscard()
+ expect(discardedFor()).not.toContain(wid)
+ await act(async () => { mocks.confirmSheet.mock.calls[0][0].onConfirm() })
+ expect(discardedFor()).toContain(wid)
+ vi.unstubAllGlobals()
+ })
})
// The live-presence "left" signal goes through lib/api.js beacon() (upstream's: the web app's