Record per-set actuals and drive the chart and volume from them

Every completed set now writes a SetEntry (reps/weight or seconds),
pre-filled from the plan by transition(to:) so the list checkbox, both
run flows, and One More all capture for free; reset clears, skip keeps
partials. The rest and finish pages show the just-done set as a pill
that opens a stepper sheet for correcting reps and weight (2.5 lb /
1.25 kg steps). The Weight Progression chart plots the top-set actual
weight and workout volume sums recorded sets, both falling back to the
plan for legacy logs via effectiveSetEntries.

Storage side of UX #3 rides along: plan weights are Double now.
Schema bumps: SplitDocument 2→3, WorkoutDocument 3→4 (a fractional
weight fails an older Int decode, and a rewrite would strip the
irreplaceable actuals), SwiftData cache 4→5. A per-log updatedAt is
reserved for the future cross-device log merge.

Claude-Session: https://claude.ai/code/session_01HJDQQDA9QdP8zByg43H5v3
This commit is contained in:
2026-07-08 12:48:37 -04:00
parent c05e83cff7
commit 394ec0989e
24 changed files with 1193 additions and 77 deletions
+10 -2
View File
@@ -28,13 +28,21 @@ extension WorkoutActivityType {
}
}
/// Σ sets×reps×weight across weighted logs the app-native "how much work" number.
/// Σ reps×weight across weighted logs the app-native "how much work" number.
/// Computed in the stored weight unit (display-only units never change the value).
/// Sums recorded per-set actuals when a log has them (via `effectiveSetEntries`,
/// which also synthesizes plan entries for completed legacy logs identical to
/// the old sets×reps×weight formula); a legacy log with no entries at all falls
/// back to that plan formula unchanged.
enum WorkoutVolume {
static func total(_ logs: [WorkoutLogDocument]) -> Double {
logs.reduce(0) { sum, log in
guard LoadType(rawValue: log.loadType) == .weight else { return sum }
return sum + Double(log.sets * log.reps * log.weight)
let entries = log.effectiveSetEntries
guard !entries.isEmpty else {
return sum + Double(log.sets * log.reps) * log.weight
}
return sum + entries.reduce(0) { $0 + Double($1.reps ?? 0) * ($1.weight ?? 0) }
}
}
}
+70 -4
View File
@@ -35,7 +35,10 @@ struct SplitDocument: Codable, Sendable, Equatable, Identifiable {
// added. Removing required fields means older apps can no longer decode new
// files, so the forward-gate must quarantine them rather than let an older app
// silently rewrite them.
static let currentSchemaVersion = 2
// Bumped 23 when `ExerciseDocument.weight` went Int Double: an older app
// decoding a fractional weight (e.g. 45.5) into `Int` fails, so it must
// quarantine rather than rewrite.
static let currentSchemaVersion = 3
var relativePath: String { "Splits/\(id).json" }
}
@@ -46,7 +49,7 @@ struct ExerciseDocument: Codable, Sendable, Equatable, Identifiable {
var order: Int
var sets: Int
var reps: Int
var weight: Int
var weight: Double // unit-less; fractional since schema v3 (Int weights decode natively)
var loadType: Int
var durationSeconds: Int // total seconds (0 when not a timed exercise)
/// Ordered, user-defined comfort settings for machine-based exercises (seat
@@ -64,6 +67,15 @@ struct MachineSetting: Codable, Sendable, Equatable {
var value: String // "4", "3rd hole", "45°" free-form; machine dials aren't uniformly numeric
}
/// One performed set. Which fields are set follows the log's `LoadType`:
/// weight reps + weight; none (bodyweight) reps; duration seconds.
struct SetEntry: Codable, Sendable, Equatable {
var reps: Int? = nil
var weight: Double? = nil
var seconds: Int? = nil
var completedAt: Date
}
// MARK: - Workout
struct WorkoutDocument: Codable, Sendable, Equatable, Identifiable {
@@ -90,7 +102,12 @@ struct WorkoutDocument: Codable, Sendable, Equatable, Identifiable {
// `WorkoutLogDocument` and `machineSettings` was added to it. Dropping a
// required field means older apps can no longer decode new files, so the
// forward-gate must quarantine them.
static let currentSchemaVersion = 3
// Bumped 34 when `WorkoutLogDocument.weight` went Int Double and per-set
// actuals (`setEntries`) were added: an older app decoding a fractional weight
// into `Int` fails, and one rewriting the file would strip `setEntries`
// the recorded actuals are irreplaceable (same rationale as the v2 `metrics`
// bump), so older apps must quarantine.
static let currentSchemaVersion = 4
var relativePath: String { Self.relativePath(id: id, start: start) }
@@ -153,7 +170,7 @@ struct WorkoutLogDocument: Codable, Sendable, Equatable, Identifiable {
var order: Int
var sets: Int
var reps: Int
var weight: Int
var weight: Double // unit-less plan snapshot; fractional since schema v4
var loadType: Int
var durationSeconds: Int // total seconds (0 when not a timed exercise)
var currentStateIndex: Int
@@ -168,6 +185,14 @@ struct WorkoutLogDocument: Codable, Sendable, Equatable, Identifiable {
/// Optional additions absent in files written before they existed.
var startedAt: Date? = nil
var completedAt: Date? = nil
/// Per-set actuals, in set order. `nil` legacy file / nothing recorded;
/// entries are appended as sets complete (pre-filled from the plan) and only
/// diverge from it when the user adjusts one. Cleared on reset to `.notStarted`.
var setEntries: [SetEntry]? = nil
/// Reserved for the per-log merge H1's conflict resolution needs (a log edited
/// on two devices merges by the newer `updatedAt`). Nothing writes it yet;
/// absent in older files.
var updatedAt: Date? = nil
}
extension WorkoutLogDocument {
@@ -204,17 +229,58 @@ extension WorkoutLogDocument {
status = newStatus.rawValue
switch newStatus {
case .notStarted:
// A full reset the run never happened, so recorded actuals go too.
startedAt = nil
completedAt = nil
setEntries = nil
case .inProgress:
if startedAt == nil { startedAt = Date() }
completedAt = nil
case .completed:
if completedAt == nil { completedAt = Date() }
// Sets that completed without an explicit record (list checkbox,
// completeExercise) get plan-default entries; recorded ones are kept.
fillSetEntries(upTo: sets, at: completedAt ?? Date())
case .skipped:
// A skipped log keeps its partial entries "End Workout, keeping
// progress" must not discard the sets that were done.
completedAt = nil
}
}
/// Append plan-default entries for sets that completed without an explicit
/// record, up to `count` in total. Only the missing tail is filled entries
/// already recorded are never overwritten and a zero `count` on a log with
/// no entries leaves `setEntries` nil (nothing was performed).
mutating func fillSetEntries(upTo count: Int, at date: Date) {
var entries = setEntries ?? []
guard entries.count < count else { return }
while entries.count < count {
entries.append(planSetEntry(completedAt: date))
}
setEntries = entries
}
/// One plan-default entry, shaped by the log's `LoadType`:
/// weight reps + weight; none (bodyweight) reps; duration seconds.
func planSetEntry(completedAt date: Date) -> SetEntry {
switch LoadType(rawValue: loadType) ?? .weight {
case .weight: SetEntry(reps: reps, weight: weight, completedAt: date)
case .none: SetEntry(reps: reps, completedAt: date)
case .duration: SetEntry(seconds: durationSeconds, completedAt: date)
}
}
/// The entries read paths consume the single fallback rule for legacy files:
/// recorded actuals when any exist, else plan-synthesized entries for a
/// *completed* log (what `fillSetEntries` would have recorded), else empty
/// (an unfinished log with nothing recorded performed nothing).
var effectiveSetEntries: [SetEntry] {
if let setEntries, !setEntries.isEmpty { return setEntries }
guard status == WorkoutStatus.completed.rawValue else { return [] }
let date = completedAt ?? date
return (0..<max(0, sets)).map { _ in planSetEntry(completedAt: date) }
}
}
// MARK: - Workout health metrics
+14 -5
View File
@@ -59,7 +59,7 @@ final class Exercise {
var order: Int = 0
var sets: Int = 0
var reps: Int = 0
var weight: Int = 0
var weight: Double = 0
var loadType: Int = LoadType.weight.rawValue
var durationTotalSeconds: Int = 0
// Machine comfort settings stored directly as an optional Codable array
@@ -70,7 +70,7 @@ final class Exercise {
var split: Split?
init(id: String, name: String, order: Int, sets: Int, reps: Int, weight: Int,
init(id: String, name: String, order: Int, sets: Int, reps: Int, weight: Double,
loadType: Int, durationTotalSeconds: Int, machineSettings: [MachineSetting]? = nil) {
self.id = id
self.name = name
@@ -223,7 +223,7 @@ final class WorkoutLog {
var order: Int = 0
var sets: Int = 0
var reps: Int = 0
var weight: Int = 0
var weight: Double = 0
var loadType: Int = LoadType.weight.rawValue
var durationTotalSeconds: Int = 0
var currentStateIndex: Int = 0
@@ -235,14 +235,21 @@ final class WorkoutLog {
var machineSettings: [MachineSetting]?
var startedAt: Date?
var completedAt: Date?
// Per-set actuals stored directly as an optional Codable array, same
// pattern as `machineSettings`. `nil` legacy file / nothing recorded.
var setEntries: [SetEntry]?
// Mirrors the document's per-log `updatedAt` (named to dodge a future
// SwiftData column collision). Reserved for H1's per-log merge; unused.
var logUpdatedAt: Date?
var workout: Workout?
init(id: String, exerciseName: String, order: Int, sets: Int, reps: Int, weight: Int,
init(id: String, exerciseName: String, order: Int, sets: Int, reps: Int, weight: Double,
loadType: Int, durationTotalSeconds: Int, currentStateIndex: Int,
statusRaw: String, notes: String?, date: Date,
machineSettings: [MachineSetting]? = nil,
startedAt: Date? = nil, completedAt: Date? = nil) {
startedAt: Date? = nil, completedAt: Date? = nil,
setEntries: [SetEntry]? = nil, logUpdatedAt: Date? = nil) {
self.id = id
self.exerciseName = exerciseName
self.order = order
@@ -258,6 +265,8 @@ final class WorkoutLog {
self.machineSettings = machineSettings
self.startedAt = startedAt
self.completedAt = completedAt
self.setEntries = setEntries
self.logUpdatedAt = logUpdatedAt
}
var status: WorkoutStatus {
+11 -2
View File
@@ -81,8 +81,8 @@ enum MetricSource: String, Codable, Sendable {
case phoneEstimate
}
/// Display unit for weights. The stored weight values are plain integers and are
/// never rewritten when this changes switching only relabels what's shown.
/// Display unit for weights. The stored weight values are unit-less numbers and
/// are never rewritten when this changes switching only relabels what's shown.
enum WeightUnit: String, CaseIterable, Codable, Sendable {
case lb
case kg
@@ -101,6 +101,15 @@ enum WeightUnit: String, CaseIterable, Codable, Sendable {
}
}
/// Render a stored weight value with the current unit's label, trimming a
/// trailing ".0" so whole values stay clean: "45 lb", "42.5 kg".
func format(_ value: Double) -> String {
let text = value.truncatingRemainder(dividingBy: 1) == 0
? String(Int(value))
: String(value)
return "\(text) \(abbreviation)"
}
/// Render a stored weight value with the current unit's label, e.g. "135 lb".
func format(_ value: Int) -> String { "\(value) \(abbreviation)" }
}
+6 -2
View File
@@ -38,7 +38,8 @@ extension WorkoutLogDocument {
durationSeconds: log.durationTotalSeconds, currentStateIndex: log.currentStateIndex,
status: log.statusRaw, notes: log.notes, date: log.date,
machineSettings: log.machineSettings,
startedAt: log.startedAt, completedAt: log.completedAt)
startedAt: log.startedAt, completedAt: log.completedAt,
setEntries: log.setEntries, updatedAt: log.logUpdatedAt)
}
}
@@ -167,7 +168,8 @@ enum CacheMapper {
weight: d.weight, loadType: d.loadType, durationTotalSeconds: d.durationSeconds,
currentStateIndex: d.currentStateIndex, statusRaw: d.status,
notes: d.notes, date: d.date, machineSettings: d.machineSettings,
startedAt: d.startedAt, completedAt: d.completedAt)
startedAt: d.startedAt, completedAt: d.completedAt,
setEntries: d.setEntries, logUpdatedAt: d.updatedAt)
}
private static func apply(_ d: WorkoutLogDocument, to l: WorkoutLog) {
@@ -185,5 +187,7 @@ enum CacheMapper {
l.machineSettings = d.machineSettings
l.startedAt = d.startedAt
l.completedAt = d.completedAt
l.setEntries = d.setEntries
l.logUpdatedAt = d.updatedAt
}
}
@@ -10,7 +10,9 @@ enum WorkoutsModelContainer {
/// 3: added `categoryRaw` to `Exercise`.
/// 4: removed the weight-reminder columns and `categoryRaw` from `Exercise` and
/// the `completed` column from `WorkoutLog`; added `machineSettings` to both.
static let currentSchemaVersion = 4
/// 5: `weight` went Int Double on `Exercise` and `WorkoutLog`; added
/// `setEntries` and `logUpdatedAt` to `WorkoutLog`.
static let currentSchemaVersion = 5
private static let schemaVersionKey = "Workouts.persistenceSchemaVersion"
private static let identityTokenKey = "Workouts.iCloudIdentityToken"
+18 -6
View File
@@ -54,7 +54,7 @@ enum ScreenshotSeed {
for (eIndex, e) in s.3.enumerated() {
let isDuration = e.0 == "Plank"
let ex = Exercise(id: ULID.make(), name: e.0, order: eIndex, sets: e.1, reps: e.2,
weight: e.3, loadType: (isDuration ? LoadType.duration : .weight).rawValue,
weight: Double(e.3), loadType: (isDuration ? LoadType.duration : .weight).rawValue,
durationTotalSeconds: isDuration ? 45 : 0)
ex.split = split
context.insert(ex)
@@ -64,7 +64,7 @@ enum ScreenshotSeed {
let upper = splits[0]
// ---- Past finished sessions (Lat Pull Down trend for the chart) --------
let liftTrend = [95, 100, 105, 110]
let liftTrend: [Double] = [95, 100, 105, 110]
for (i, w) in liftTrend.enumerated() {
let date = daysAgo((liftTrend.count - i) * 4)
let workout = Workout(id: ULID.make(), splitID: nil, splitName: upper.0, start: date,
@@ -72,11 +72,12 @@ enum ScreenshotSeed {
createdAt: date, updatedAt: date, jsonRelativePath: "")
context.insert(workout)
for (eIndex, e) in upper.3.enumerated() {
let weight = e.0 == "Lat Pull Down" ? w : e.3
let weight = e.0 == "Lat Pull Down" ? w : Double(e.3)
let log = WorkoutLog(id: ULID.make(), exerciseName: e.0, order: eIndex, sets: e.1,
reps: e.2, weight: weight, loadType: LoadType.weight.rawValue,
durationTotalSeconds: 0, currentStateIndex: e.1,
statusRaw: WorkoutStatus.completed.rawValue, notes: nil, date: date)
statusRaw: WorkoutStatus.completed.rawValue, notes: nil, date: date,
setEntries: actualEntries(sets: e.1, reps: e.2, weight: weight, at: date))
log.workout = workout
context.insert(log)
}
@@ -91,10 +92,12 @@ enum ScreenshotSeed {
let progress = [(4, WorkoutStatus.completed), (2, .inProgress), (0, .notStarted), (0, .notStarted)]
for (eIndex, e) in upper.3.enumerated() {
let (idx, status) = progress[eIndex]
let weight = e.0 == "Lat Pull Down" ? 110 : Double(e.3)
let log = WorkoutLog(id: ULID.make(), exerciseName: e.0, order: eIndex, sets: e.1, reps: e.2,
weight: e.0 == "Lat Pull Down" ? 110 : e.3, loadType: LoadType.weight.rawValue,
weight: weight, loadType: LoadType.weight.rawValue,
durationTotalSeconds: 0, currentStateIndex: idx,
statusRaw: status.rawValue, notes: nil, date: today)
statusRaw: status.rawValue, notes: nil, date: today,
setEntries: idx > 0 ? actualEntries(sets: idx, reps: e.2, weight: weight, at: today) : nil)
log.workout = workout
context.insert(log)
}
@@ -102,5 +105,14 @@ enum ScreenshotSeed {
try? context.save()
return workout
}
/// Plausible per-set actuals for a weighted log: plan values, with the last
/// set a couple of reps short so screenshots show real-looking variation.
private static func actualEntries(sets: Int, reps: Int, weight: Double, at date: Date) -> [SetEntry] {
(0..<sets).map { i in
SetEntry(reps: i == sets - 1 ? max(1, reps - 2) : reps, weight: weight,
completedAt: date.addingTimeInterval(Double(i) * 150))
}
}
}
#endif