Files
workouts/Workouts/Connectivity/PhoneConnectivityBridge.swift
T
rzen 8ef0e96b31 Park the Watch run while iPhone edits an exercise or split
Publish an exclusive-edit lock (editingWorkoutID / editingSplitID) in the
phone→watch application context. While the phone has a workout's exercise
(ExerciseView) or a split (SplitDetailView) open in an editor, the watch pops
out of that run, blocks re-entry, and shows it as "Editing on iPhone" — so the
two devices never drive the same run at once and the watch can't clobber the
phone's edit with a stale optimistic write. The lock clears when the editor
closes; absent keys in the latest-wins context mean "not editing".

Claude-Session: https://claude.ai/code/session_01SCv7zvGFcKy47KSTnTLxRe
2026-06-20 19:54:31 -04:00

124 lines
5.0 KiB
Swift

import Foundation
import SwiftData
import WatchConnectivity
/// Phone side of the iPhoneWatch bridge. The phone owns iCloud Drive; the watch
/// is a thin remote that round-trips through it:
/// Phone Watch: pushes all splits + recent workouts as the latest
/// application context whenever the cache changes (local or remote).
/// Watch Phone: receives an updated `WorkoutDocument` and applies it via the
/// SyncEngine write path (file observer cache push back).
@MainActor
final class PhoneConnectivityBridge: NSObject {
private let container: ModelContainer
private let syncEngine: SyncEngine
private var session: WCSession?
/// Exclusive-edit lock published to the watch. While the phone has a workout's
/// exercise (or a split) open in an editor, the watch parks any matching run and
/// blocks re-entry so the two devices never drive the same run at once. Included in
/// every `pushAll` (the latest-wins context replaces wholesale, so a push that omitted
/// them would clear the lock prematurely).
private(set) var editingWorkoutID: String?
private(set) var editingSplitID: String?
private var context: ModelContext { container.mainContext }
init(container: ModelContainer, syncEngine: SyncEngine) {
self.container = container
self.syncEngine = syncEngine
super.init()
}
func activate() {
guard WCSession.isSupported() else { return }
let session = WCSession.default
session.delegate = self
session.activate()
self.session = session
// Push fresh state to the watch whenever the cache changes.
syncEngine.onCacheChanged = { [weak self] in self?.pushAll() }
}
/// Sends the current splits + most-recent workouts to the watch.
func pushAll() {
guard let session, session.activationState == .activated, session.isPaired,
session.isWatchAppInstalled else { return }
let splits = (try? context.fetch(FetchDescriptor<Split>(sortBy: [SortDescriptor(\.order)]))) ?? []
var wDesc = FetchDescriptor<Workout>(sortBy: [SortDescriptor(\.start, order: .reverse)])
wDesc.fetchLimit = 25
let workouts = (try? context.fetch(wDesc)) ?? []
let restSeconds = UserDefaults.standard.object(forKey: WCPayload.restSecondsKey) as? Int ?? 45
let doneCountdownSeconds = UserDefaults.standard.object(forKey: WCPayload.doneCountdownSecondsKey) as? Int ?? 5
let payload = WCPayload.encodeState(
splits: splits.map(SplitDocument.init(from:)),
workouts: workouts.map(WorkoutDocument.init(from:)),
restSeconds: restSeconds,
doneCountdownSeconds: doneCountdownSeconds,
editingWorkoutID: editingWorkoutID,
editingSplitID: editingSplitID
)
try? session.updateApplicationContext(payload)
}
/// Mark (or clear, with `nil`) the workout currently open in a phone exercise editor.
/// The watch parks that run and blocks re-entry until it clears. Pushes immediately so
/// the lock takes effect without waiting on a cache change.
func setEditingWorkout(_ id: String?) {
guard editingWorkoutID != id else { return }
editingWorkoutID = id
pushAll()
}
/// Mark (or clear, with `nil`) the split currently open in a phone editor. The watch
/// parks any active run sourced from that split (matched by `splitID`).
func setEditingSplit(_ id: String?) {
guard editingSplitID != id else { return }
editingSplitID = id
pushAll()
}
/// Parse the (non-Sendable) WC dictionary in the nonisolated delegate context,
/// then hop to the MainActor with only Sendable values.
nonisolated private func route(_ dict: [String: Any]) {
switch dict[WCPayload.typeKey] as? String {
case WCPayload.requestSyncType:
Task { @MainActor in self.pushAll() }
case WCPayload.workoutUpdateType:
if let doc = WCPayload.decodeWorkoutUpdate(dict) {
Task { @MainActor in await self.syncEngine.ingestFromWatch(doc) }
}
default:
break
}
}
}
// MARK: - WCSessionDelegate
extension PhoneConnectivityBridge: WCSessionDelegate {
nonisolated func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
Task { @MainActor in self.pushAll() }
}
nonisolated func sessionDidBecomeInactive(_ session: WCSession) {}
nonisolated func sessionDidDeactivate(_ session: WCSession) {
session.activate() // reactivate for a switched watch
}
nonisolated func sessionReachabilityDidChange(_ session: WCSession) {
if session.isReachable { Task { @MainActor in self.pushAll() } }
}
nonisolated func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {
route(message)
}
nonisolated func session(_ session: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) {
route(userInfo)
}
}