Restructure into a three-tab app with Progress, goals, and Meditation

The UX redesign's first landing (spec in UX-REDESIGN.md): ContentView
becomes a Today / Progress / Settings TabView, "Routine" replaces
"Split" in every user-facing string and view name (code-level types
keep their names), and workout starting moves to shared
WorkoutStarter / StartedWorkoutNavigator plumbing.

- New Progress tab: weekly goal streaks, workout trends, per-exercise
  weight progression, achievements, and the full history list
  (WorkoutLogsView -> WorkoutHistoryView).
- Goals: stable categories workouts roll up to, managed from Settings.
- New Meditation exercise + starter routine; timed sits record to
  Apple Health as Mind & Body sessions.

Claude-Session: https://claude.ai/code/session_012qw2itfzKyEJ1HpsFt8Ex4
This commit is contained in:
2026-07-11 07:53:01 -04:00
parent 5c201289fb
commit 6e440317c4
97 changed files with 5354 additions and 1291 deletions
@@ -34,9 +34,9 @@ final class WatchConnectivityBridge: NSObject {
/// Exclusive-edit lock pushed by the phone. While set, the watch parks the matching
/// run (popping out of its progress view) and blocks re-entry, so the phone owns the
/// edit and the watch can't clobber it with a stale optimistic write. `editingWorkoutID`
/// matches a run by its workout id; `editingSplitID` matches any run by its `splitID`.
/// matches a run by its workout id; `editingRoutineID` matches any run by its `routineID`.
private(set) var editingWorkoutID: String?
private(set) var editingSplitID: String?
private(set) var editingRoutineID: String?
/// Monotonic sequence stamped on each live-run frame we send. Bumped to stay ahead of any
/// frame we *receive*, so the two devices share one increasing per-run sequence and either
@@ -101,16 +101,16 @@ final class WatchConnectivityBridge: NSObject {
}
/// Apply the last application context the system holds for us (settings, edit
/// locks, and the authoritative splits + workouts sets). Idempotent, so it's safe
/// locks, and the authoritative routines + workouts sets). Idempotent, so it's safe
/// to call both eagerly at launch and again when activation completes.
private func applyReceivedContext() {
guard let session else { return }
let ctx = session.receivedApplicationContext
Self.log.info("applyReceivedContext: activation=\(session.activationState.rawValue) keys=\(ctx.keys.sorted().joined(separator: ","), privacy: .public)")
applyState(WCPayload.decodeSplits(ctx), workouts: WCPayload.decodeWorkouts(ctx))
applyState(WCPayload.decodeRoutines(ctx), workouts: WCPayload.decodeWorkouts(ctx))
applySettings(ctx)
editingWorkoutID = WCPayload.decodeEditingWorkoutID(ctx)
editingSplitID = WCPayload.decodeEditingSplitID(ctx)
editingRoutineID = WCPayload.decodeEditingRoutineID(ctx)
}
/// Apply a decoded state push. `nil` (decode failure the phone runs a build with
@@ -118,14 +118,14 @@ final class WatchConnectivityBridge: NSObject {
/// against a bogus empty set nor silently show stale data forever. The upsert/prune
/// itself is delegated to the pure, session-free `WatchCacheApplier` seam so the
/// apply/prune contract is unit-testable.
private func applyState(_ splits: [SplitDocument]?, workouts: [WorkoutDocument]?) {
guard WatchCacheApplier.apply(splits: splits, workouts: workouts, into: context) else {
Self.log.error("applyState: payload failed to decode (splits=\(splits == nil ? "failed" : "ok", privacy: .public), workouts=\(workouts == nil ? "failed" : "ok", privacy: .public)) — phone/watch build mismatch?")
private func applyState(_ routines: [RoutineDocument]?, workouts: [WorkoutDocument]?) {
guard WatchCacheApplier.apply(routines: routines, workouts: workouts, into: context) else {
Self.log.error("applyState: payload failed to decode (routines=\(routines == nil ? "failed" : "ok", privacy: .public), workouts=\(workouts == nil ? "failed" : "ok", privacy: .public)) — phone/watch build mismatch?")
schemaMismatch = true
return
}
schemaMismatch = false
Self.log.info("applyState: applied \(splits?.count ?? 0) splits, \(workouts?.count ?? 0) workouts")
Self.log.info("applyState: applied \(routines?.count ?? 0) routines, \(workouts?.count ?? 0) workouts")
lastSyncDate = Date()
onWorkoutsChanged?()
}
@@ -277,7 +277,7 @@ final class WatchConnectivityBridge: NSObject {
// MARK: - Cache apply/prune seam
/// The pure, session-free core of the phonewatch state apply: it upserts the authoritative
/// splits/workouts into the watch's SwiftData cache and prunes anything the phone no longer
/// routines/workouts into the watch's SwiftData cache and prunes anything the phone no longer
/// sends. Split out of `WatchConnectivityBridge` (which wraps `WCSession`) so the apply/prune
/// contract including the authoritative-empty prune and the nil-decode skip is unit-testable
/// against an in-memory `ModelContext` without a live WatchConnectivity session.
@@ -288,31 +288,31 @@ enum WatchCacheApplier {
/// applied, `false` when skipped, so the caller can log / stamp `lastSyncDate` accordingly.
@MainActor
@discardableResult
static func apply(splits: [SplitDocument]?, workouts: [WorkoutDocument]?, into context: ModelContext) -> Bool {
guard let splits, let workouts else { return false }
apply(splits: splits, workouts: workouts, into: context)
static func apply(routines: [RoutineDocument]?, workouts: [WorkoutDocument]?, into context: ModelContext) -> Bool {
guard let routines, let workouts else { return false }
apply(routines: routines, workouts: workouts, into: context)
return true
}
/// Upsert every split/workout the phone sent, then prune anything it *didn't*. Both sets are
/// Upsert every routine/workout the phone sent, then prune anything it *didn't*. Both sets are
/// authoritative, so an authoritative empty push clears rows the phone no longer has (a deleted
/// split; a run discarded/deleted on the phone, completed-and-aged-out, or otherwise dropped
/// routine; a run discarded/deleted on the phone, completed-and-aged-out, or otherwise dropped
/// from the ~24h window). On first launch the cache is empty, so the prune is a harmless no-op.
/// The watch never originates a split/workout, so pruning can't lose local-only data.
/// The watch never originates a routine/workout, so pruning can't lose local-only data.
@MainActor
static func apply(splits: [SplitDocument], workouts: [WorkoutDocument], into context: ModelContext) {
var liveSplitIDs = Set<String>()
for s in splits {
CacheMapper.upsertSplit(s, relativePath: s.relativePath, into: context)
liveSplitIDs.insert(s.id)
static func apply(routines: [RoutineDocument], workouts: [WorkoutDocument], into context: ModelContext) {
var liveRoutineIDs = Set<String>()
for s in routines {
CacheMapper.upsertRoutine(s, relativePath: s.relativePath, into: context)
liveRoutineIDs.insert(s.id)
}
var liveWorkoutIDs = Set<String>()
for w in workouts {
CacheMapper.upsertWorkout(w, relativePath: w.relativePath, into: context)
liveWorkoutIDs.insert(w.id)
}
if let allSplits = try? context.fetch(FetchDescriptor<Split>()) {
for s in allSplits where !liveSplitIDs.contains(s.id) { context.delete(s) }
if let allRoutines = try? context.fetch(FetchDescriptor<Routine>()) {
for s in allRoutines where !liveRoutineIDs.contains(s.id) { context.delete(s) }
}
if let allWorkouts = try? context.fetch(FetchDescriptor<Workout>()) {
for w in allWorkouts where !liveWorkoutIDs.contains(w.id) { context.delete(w) }
@@ -359,21 +359,21 @@ extension WatchConnectivityBridge: WCSessionDelegate {
}
nonisolated func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
let splits = WCPayload.decodeSplits(applicationContext)
let routines = WCPayload.decodeRoutines(applicationContext)
let workouts = WCPayload.decodeWorkouts(applicationContext)
let rest = WCPayload.decodeRestSeconds(applicationContext)
let done = WCPayload.decodeDoneCountdownSeconds(applicationContext)
let unit = WCPayload.decodeWeightUnit(applicationContext)
let editingWorkoutID = WCPayload.decodeEditingWorkoutID(applicationContext)
let editingSplitID = WCPayload.decodeEditingSplitID(applicationContext)
let editingRoutineID = WCPayload.decodeEditingRoutineID(applicationContext)
Task { @MainActor in
self.applyState(splits, workouts: workouts)
self.applyState(routines, workouts: workouts)
if let rest { UserDefaults.standard.set(rest, forKey: WCPayload.restSecondsKey) }
if let done { UserDefaults.standard.set(done, forKey: WCPayload.doneCountdownSecondsKey) }
if let unit { UserDefaults.standard.set(unit, forKey: WCPayload.weightUnitKey) }
// Absent keys mean "not editing" set unconditionally so the lock clears.
self.editingWorkoutID = editingWorkoutID
self.editingSplitID = editingSplitID
self.editingRoutineID = editingRoutineID
}
}
}
@@ -11,7 +11,7 @@ import SwiftData
/// Root of the watch app. The watch only runs the workouts that are currently
/// active on the phone there's no history browsing here. An "active" workout is a
/// cached one that isn't finished (`notStarted` or `inProgress`); a workout is
/// created on the phone as `notStarted` the moment a split is picked, and flips to
/// created on the phone as `notStarted` the moment a routine is picked, and flips to
/// `completed` once every exercise is done, at which point it drops off this list.
///
/// The root shows every active workout (most-recent first); picking one opens its
@@ -20,7 +20,7 @@ struct ActiveWorkoutGateView: View {
@Environment(WatchConnectivityBridge.self) private var bridge
@Query(sort: \Workout.start, order: .reverse) private var workouts: [Workout]
@Query private var splits: [Split]
@Query private var routines: [Routine]
/// Navigated workouts (depth 1). Held here rather than relying on implicit
/// `NavigationLink` destinations so we can pop back to the gate the moment the phone
@@ -31,17 +31,17 @@ struct ActiveWorkoutGateView: View {
workouts.filter { $0.status == .inProgress || $0.status == .notStarted }
}
private func split(for workout: Workout) -> Split? {
guard let id = workout.splitID else { return nil }
return splits.first { $0.id == id }
private func routine(for workout: Workout) -> Routine? {
guard let id = workout.routineID else { return nil }
return routines.first { $0.id == id }
}
/// True while the phone has this workout's exercise or the split it came from open
/// True while the phone has this workout's exercise or the routine it came from open
/// in an editor. The watch parks such a run and blocks re-entry so the phone owns the
/// edit and the watch can't forward a stale optimistic write over it.
private func isLockedForEditing(_ workout: Workout) -> Bool {
if let id = bridge.editingWorkoutID, id == workout.id { return true }
if let splitID = bridge.editingSplitID, splitID == workout.splitID { return true }
if let routineID = bridge.editingRoutineID, routineID == workout.routineID { return true }
return false
}
@@ -89,17 +89,17 @@ struct ActiveWorkoutGateView: View {
// pop back to the gate so re-entry rebuilds a fresh working copy. Also pop if the run
// we're inside was pruned (discarded/deleted on the phone, or aged out of the push).
.onChange(of: bridge.editingWorkoutID) { _, _ in popIfNavigatedRunUnavailable() }
.onChange(of: bridge.editingSplitID) { _, _ in popIfNavigatedRunUnavailable() }
.onChange(of: bridge.editingRoutineID) { _, _ in popIfNavigatedRunUnavailable() }
.onChange(of: workouts.map(\.id)) { _, _ in popIfNavigatedRunUnavailable() }
}
@ViewBuilder
private func row(for workout: Workout) -> some View {
if isLockedForEditing(workout) {
ActiveWorkoutRow(workout: workout, split: split(for: workout), editingOnPhone: true)
ActiveWorkoutRow(workout: workout, routine: routine(for: workout), editingOnPhone: true)
} else {
NavigationLink(value: ActiveWorkoutRoute(workoutID: workout.id)) {
ActiveWorkoutRow(workout: workout, split: split(for: workout))
ActiveWorkoutRow(workout: workout, routine: routine(for: workout))
}
}
}
@@ -135,7 +135,7 @@ struct ActiveWorkoutGateView: View {
private struct ActiveWorkoutRow: View {
let workout: Workout
let split: Split?
let routine: Routine?
/// When true, the phone is editing this run render it dimmed and non-tappable.
var editingOnPhone: Bool = false
@@ -144,13 +144,13 @@ private struct ActiveWorkoutRow: View {
var body: some View {
HStack(spacing: 10) {
Image(systemName: editingOnPhone ? "pencil" : (split?.systemImage ?? "figure.strengthtraining.traditional"))
Image(systemName: editingOnPhone ? "pencil" : (routine?.systemImage ?? "figure.strengthtraining.traditional"))
.font(.title3)
.foregroundStyle(split.map { Color.color(from: $0.color) } ?? .workTint)
.foregroundStyle(routine.map { Color.color(from: $0.color) } ?? .workTint)
.frame(width: 26)
VStack(alignment: .leading, spacing: 2) {
Text(workout.splitName ?? Split.unnamed)
Text(workout.routineName ?? Routine.unnamed)
.font(.headline)
.lineLimit(1)
@@ -163,11 +163,11 @@ struct ExerciseProgressView: View {
/// page-index math below depends on it.
private var showsReady: Bool { debugInitialPage == nil && !enteredViaFlow }
/// This split runs as a continuous flow finishing one exercise rests, then
/// This routine runs as a continuous flow finishing one exercise rests, then
/// auto-advances into the next rather than returning to the list per exercise.
private var autoAdvance: Bool { doc.autoAdvance == true }
/// Rest length for this run: the split's per-split override, else the global default.
/// Rest length for this run: the routine's per-routine override, else the global default.
/// Governs both between-set rests and (in flow mode) the between-exercise rest.
private var effectiveRest: Int { max(1, doc.restSeconds ?? restSeconds) }
+2 -2
View File
@@ -8,10 +8,10 @@
import SwiftUI
/// Thin coordinator that lets a single pushed run walk across exercises in a flow-mode
/// split (`autoAdvance`). It owns which log is on screen and swaps it when the running
/// routine (`autoAdvance`). It owns which log is on screen and swaps it when the running
/// `ExerciseProgressView` finishes an exercise; `.id(currentLogID)` rebuilds the child
/// fresh for each exercise, so the delicate per-exercise run/mirror machinery stays
/// exactly as it is. For a non-flow split it's transparent one exercise, unchanged.
/// exactly as it is. For a non-flow routine it's transparent one exercise, unchanged.
struct RunFlowView: View {
@Environment(WatchConnectivityBridge.self) private var bridge
@@ -35,16 +35,16 @@ struct WorkoutLogListView: View {
_doc = State(initialValue: WorkoutDocument(fromLive: workout) ?? .deletedPlaceholder)
}
/// The split this workout came from (read-only on the watch), used to offer
/// The routine this workout came from (read-only on the watch), used to offer
/// additional exercises that aren't logged yet. Fetched imperatively *not* via
/// `@Query` so the list body never observes the live `Split` or traverses its
/// `@Query` so the list body never observes the live `Routine` or traverses its
/// `exercises` relationship during a render. Doing so (a `@Query`-observed model
/// whose to-many relationship is read in `body`) drove a SwiftData re-render loop
/// that hung the watch. `availableExercises` is therefore only ever evaluated from
/// the picker sheet's closure, not from `body`.
private var split: Split? {
guard let splitID = doc.splitID else { return nil }
return CacheMapper.fetchSplit(id: splitID, in: modelContext)
private var routine: Routine? {
guard let routineID = doc.routineID else { return nil }
return CacheMapper.fetchRoutine(id: routineID, in: modelContext)
}
private var sortedLogs: [WorkoutLogDocument] {
@@ -52,9 +52,9 @@ struct WorkoutLogListView: View {
}
private var availableExercises: [Exercise] {
guard let split else { return [] }
guard let routine else { return [] }
let existingNames = Set(doc.logs.map { $0.exerciseName })
return split.exercisesArray.filter { !existingNames.contains($0.name) }
return routine.exercisesArray.filter { !existingNames.contains($0.name) }
}
var body: some View {
@@ -74,10 +74,10 @@ struct WorkoutLogListView: View {
}
}
// Gate on the *resolved* split, not the stale `splitID` string a split
// Gate on the *resolved* routine, not the stale `routineID` string a routine
// deleted on the phone leaves the id dangling, and offering Add Exercise
// against it would only show a misleading "All exercises added" picker.
if split != nil {
if routine != nil {
Section {
Button {
showingExercisePicker = true
@@ -96,13 +96,13 @@ struct WorkoutLogListView: View {
ContentUnavailableView(
"No Exercises",
systemImage: "figure.strengthtraining.traditional",
description: Text(split == nil
description: Text(routine == nil
? "No exercises in this workout."
: "Tap + to add exercises.")
)
}
}
.navigationTitle(doc.splitName ?? Split.unnamed)
.navigationTitle(doc.routineName ?? Routine.unnamed)
// Absorb phone edits while this screen is open (H1's watch-side gap):
// without this, the snapshot stays frozen at init, and the next watch
// tick made against a state that's missing the phone's edit would be
@@ -120,7 +120,7 @@ struct WorkoutLogListView: View {
}
}
.navigationDestination(item: $selectedLogID) { logID in
// RunFlowView hosts the run and, in a flow-mode split, auto-advances across
// RunFlowView hosts the run and, in a flow-mode routine, auto-advances across
// exercises. It owns the live-run mirror wiring (incoming-frame filter,
// `navigatedRunID`, and the parameterized live-ended signal) since the on-screen
// log advances during a flowing run.
@@ -61,7 +61,7 @@ enum SessionEndPlanner {
!isRunning && !activeIDs(in: workouts).isEmpty
}
/// The run whose split configures a self-started session: the most recently started
/// The run whose routine configures a self-started session: the most recently started
/// active one (ties broken by id for determinism).
static func runToStart(in workouts: [WorkoutDocument]) -> WorkoutDocument? {
let ids = activeIDs(in: workouts)
@@ -148,17 +148,17 @@ final class WorkoutSessionCoordinator {
}
/// Self-start a session when an active run has none (see `SessionEndPlanner.shouldStart`).
/// The activity type comes from the run's split so the saved Health workout is categorized
/// the same way a phone-launched one would be; a run whose split is gone (deleted, or not
/// The activity type comes from the run's routine so the saved Health workout is categorized
/// the same way a phone-launched one would be; a run whose routine is gone (deleted, or not
/// yet synced) falls back to traditional strength training.
private func startIfNeeded(workouts: [WorkoutDocument]) {
guard SessionEndPlanner.shouldStart(isRunning: sessionManager.isRunning, workouts: workouts),
let run = SessionEndPlanner.runToStart(in: workouts) else { return }
let split = run.splitID.flatMap { id in
(try? context.fetch(FetchDescriptor<Split>())).flatMap { $0.first { $0.id == id } }
let routine = run.routineID.flatMap { id in
(try? context.fetch(FetchDescriptor<Routine>())).flatMap { $0.first { $0.id == id } }
}
let configuration = HKWorkoutConfiguration()
configuration.activityType = split?.activityTypeEnum.hkActivityType ?? .traditionalStrengthTraining
configuration.activityType = routine?.activityTypeEnum.hkActivityType ?? .traditionalStrengthTraining
configuration.locationType = .indoor
sessionManager.start(with: configuration)
}