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.

Watch sync: every kind of set (holds, bodyweight, per-side, supersets, skips) and a workout summary

Duarte Santosa07bbad23729
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/ClipCodec.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/ClipCodec.swift
index d911773c3..e0308ae47 100644
--- a/frontend/ios/App/WatchCore/Sources/WatchCore/ClipCodec.swift
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/ClipCodec.swift
@@ -1,3 +1,5 @@
+// ImageIO only exists on Apple platforms; the session logic is also tested on Linux.
+#if canImport(ImageIO)
import CoreGraphics
import Foundation
import ImageIO
@@ -92,3 +94,4 @@ enum ClipCodec {
return false
}
}
+#endif
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
index 9c68d95e9..da813f54b 100644
--- a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
@@ -35,6 +35,8 @@ struct ActiveWorkout: Codable, Equatable {
var restSec: Double
var rest: RestInfo?
var entries: [Entry]
+ /// When it started (ms since 1970), for the summary's duration.
+ var start: Double?
}
struct RestInfo: Codable, Equatable {
@@ -44,10 +46,48 @@ struct RestInfo: Codable, Equatable {
struct Entry: Codable, Equatable {
var id: String
var name: String
+ /// "reps", "time" (a hold, `sec` per set) or "cardio" (logged on the phone).
var mode: String
var restSec: Double?
var last: String?
var sets: [SetRow]
+ /// No load of its own: `w` is added weight, shown only when there is some.
+ var bodyweight: Bool?
+ /// Unilateral: each set is done one side at a time (`sides`).
+ var perSide: Bool?
+ /// A superset: neighbours with the same group are done in turns, the rest after each round.
+ var group: String?
+ /// The best set before this workout, for the PRs at the finish.
+ var best: BestSet?
+ /// Assisted (a lighter weight is the better one).
+ var assisted: Bool?
+
+ var isTimed: Bool { mode == "time" }
+ var isCardio: Bool { mode == "cardio" }
+ var isBodyweight: Bool { bodyweight == true }
+}
+
+struct BestSet: Codable, Equatable {
+ var w: Double?
+ var r: Double?
+ var sec: Double?
+}
+
+/// One side of a per-side set.
+struct SideRow: Codable, Equatable {
+ var w: Double?
+ var r: Double?
+ var done: Bool
+}
+
+struct Sides: Codable, Equatable {
+ var L: SideRow
+ var R: SideRow
+
+ subscript(_ side: String) -> SideRow {
+ get { side == "R" ? R : L }
+ set { if side == "R" { R = newValue } else { L = newValue } }
+ }
}
struct SetRow: Codable, Equatable {
@@ -58,6 +98,16 @@ struct SetRow: Codable, Equatable {
var warmup: Bool
/// When it was ticked (ms since 1970), on whichever side ticked it: the later tick wins.
var at: Double?
+ /// A per-side set's two sides; `done` is both of them.
+ var sides: Sides?
+
+ /// The side up next on a per-side set ("L", then "R"), or nil.
+ var sideUp: String? {
+ guard let s = sides else { return nil }
+ if !s.L.done { return "L" }
+ if !s.R.done { return "R" }
+ return nil
+ }
}
/// The phone's Settings → Apple Watch (frontend lib/watch-settings.js).
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
index 24483e6a2..bf68c4024 100644
--- a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
@@ -37,6 +37,8 @@ struct PendingTick: Codable, Equatable {
var w: Double?
var r: Double?
var at: Double
+ /// A hold's seconds.
+ var sec: Double?
}
struct SessionState: Codable, Equatable {
@@ -53,12 +55,17 @@ struct SessionState: Codable, Equatable {
var pending: [String: PendingTick] = [:]
/// The exercise on screen.
var entryIndex = 0
+ /// Sets passed over here ("exerciseId#setIndex"), not done: the next one comes up instead.
+ /// Optional, like every field added later, so a state saved by an older build still loads.
+ var skipped: [String]?
}
typealias Event = [String: Any]
enum SessionCore {
- static func key(_ exId: String, _ si: Int) -> String { "\(exId)#\(si)" }
+ static func key(_ exId: String, _ si: Int, _ side: String? = nil) -> String {
+ side.map { "\(exId)#\(si)#\($0)" } ?? "\(exId)#\(si)"
+ }
/// A snapshot from the phone, over what the watch has.
static func applySnapshot(_ s0: SessionState, _ snap: Snapshot) -> SessionState {
@@ -87,20 +94,36 @@ enum SessionCore {
if !same {
// Another workout (or the first one this watch sees): its own position, no old ticks.
s.pending = [:]
+ s.skipped = nil
s.entryIndex = next.cur
}
// The watch's ticks the phone has not shown yet win; the later tick wins on a set both changed.
for (ei, e) in next.entries.enumerated() {
for (si, row) in e.sets.enumerated() {
let k = key(e.id, si)
- guard let p = s.pending[k] else { continue }
- if row.done && (row.at ?? .infinity) >= p.at {
- s.pending[k] = nil // the phone has it (or a later change of its own)
- } else {
- next.entries[ei].sets[si].done = true
- next.entries[ei].sets[si].w = p.w ?? row.w
- next.entries[ei].sets[si].r = p.r ?? row.r
- next.entries[ei].sets[si].at = p.at
+ if let p = s.pending[k] {
+ if row.done && (row.at ?? .infinity) >= p.at {
+ s.pending[k] = nil // the phone has it (or a later change of its own)
+ } else {
+ next.entries[ei].sets[si].done = true
+ next.entries[ei].sets[si].w = p.w ?? row.w
+ next.entries[ei].sets[si].r = p.r ?? row.r
+ if let sec = p.sec { next.entries[ei].sets[si].sec = sec }
+ next.entries[ei].sets[si].at = p.at
+ }
+ }
+ // A per-side set: each side by itself, the same way.
+ for side in ["L", "R"] {
+ let ks = key(e.id, si, side)
+ guard let p = s.pending[ks] else { continue }
+ let have = next.entries[ei].sets[si]
+ if have.sides?[side].done == true && (row.at ?? .infinity) >= p.at {
+ s.pending[ks] = nil
+ } else if have.sides != nil {
+ next.entries[ei].sets[si] = markSide(have, side, w: p.w, r: p.r, at: p.at)
+ } else {
+ s.pending[ks] = nil // no longer a per-side set on the phone
+ }
}
}
}
@@ -109,31 +132,103 @@ enum SessionCore {
return s
}
- /// A set ticked here: the state with it done, and the event for the phone.
- static func tick(_ s0: SessionState, entry ei: Int, set si: Int, w: Double, r: Double, at: Double, id: String, hr: [String: Double]? = nil) -> (SessionState, Event?) {
+ /// One side of a per-side set done, the row's own numbers following both sides (as the phone's
+ /// syncSideAggregate: reps the sum, weight the heavier, done when both are).
+ static func markSide(_ row0: SetRow, _ side: String, w: Double?, r: Double?, at: Double) -> SetRow {
+ guard var sides = row0.sides else { return row0 }
+ var row = row0
+ var one = sides[side]
+ one.done = true
+ if let w = w { one.w = w }
+ if let r = r { one.r = r }
+ sides[side] = one
+ row.sides = sides
+ row.done = sides.L.done && sides.R.done
+ row.r = (sides.L.r ?? 0) + (sides.R.r ?? 0)
+ row.w = max(sides.L.w ?? 0, sides.R.w ?? 0)
+ row.at = max(row0.at ?? 0, at)
+ return row
+ }
+
+ /// A set ticked here: the state with it done, and the event for the phone. `side` ticks one
+ /// side of a per-side set; `sec` is a hold's seconds; a cardio tick carries no numbers.
+ static func tick(_ s0: SessionState, entry ei: Int, set si: Int, side: String? = nil, w: Double?, r: Double?, sec: Double? = nil,
+ at: Double, id: String, hr: [String: Double]? = nil) -> (SessionState, Event?) {
guard var workout = s0.workout, workout.entries.indices.contains(ei), workout.entries[ei].sets.indices.contains(si) else { return (s0, nil) }
var s = s0
let e = workout.entries[ei]
- workout.entries[ei].sets[si].done = true
- workout.entries[ei].sets[si].w = w
- workout.entries[ei].sets[si].r = r
- workout.entries[ei].sets[si].at = at
+ let oneSide = side.flatMap { e.sets[si].sides != nil ? $0 : nil }
+ if let side = oneSide {
+ workout.entries[ei].sets[si] = markSide(e.sets[si], side, w: w, r: r, at: at)
+ } else {
+ workout.entries[ei].sets[si].done = true
+ if let w = w { workout.entries[ei].sets[si].w = w }
+ if let r = r { workout.entries[ei].sets[si].r = r }
+ if let sec = sec { workout.entries[ei].sets[si].sec = sec }
+ workout.entries[ei].sets[si].at = at
+ }
s.workout = workout
- s.pending[key(e.id, si)] = PendingTick(w: w, r: r, at: at)
+ s.pending[key(e.id, si, oneSide)] = PendingTick(w: w, r: r, at: at, sec: sec)
var event: Event = [
"id": id, "type": "setDone", "wid": workout.id ?? "", "exId": e.id,
- "entryIdx": ei, "setIdx": si, "w": w, "r": r, "at": at,
+ "entryIdx": ei, "setIdx": si, "at": at,
]
+ if let w = w { event["w"] = w }
+ if let r = r { event["r"] = r }
+ if let sec = sec { event["sec"] = sec }
+ if let side = oneSide { event["side"] = side }
if let hr = hr { event["hr"] = hr }
return (s, event)
}
+ /// A set passed over here: not done, the next one comes up (a tap on its dot brings it back).
+ static func skip(_ s0: SessionState, entry ei: Int, set si: Int) -> SessionState {
+ guard let w = s0.workout, w.entries.indices.contains(ei), w.entries[ei].sets.indices.contains(si) else { return s0 }
+ var s = s0
+ let k = key(w.entries[ei].id, si)
+ s.skipped = Array(Set((s.skipped ?? []) + [k])).sorted()
+ return s
+ }
+
+ static func isSkipped(_ s: SessionState, _ exId: String, _ si: Int) -> Bool {
+ s.skipped?.contains(key(exId, si)) ?? false
+ }
+
+ /// Where to go after a set of exercise `ei` (set `si`) was done, and whether a rest comes first.
+ /// per-side set with a side to go the same exercise, no rest (the other side now)
+ /// superset the next exercise of the group in turn; the rest only
+ /// after the last one of a round
+ /// otherwise this exercise while it has sets to do, then the next one
+ /// that has; after the last, the Finish page (index = count)
+ static func next(after s: SessionState, entry ei: Int, set si: Int) -> (entry: Int, rest: Bool) {
+ guard let w = s.workout, w.entries.indices.contains(ei) else { return (s.entryIndex, false) }
+ let count = w.entries.count
+ if w.entries[ei].sets.indices.contains(si), w.entries[ei].sets[si].sideUp != nil { return (ei, false) }
+ let open: (Int) -> Bool = { setIndex(s, entry: $0) != nil }
+ if let g = w.entries[ei].group {
+ var lo = ei, hi = ei
+ while lo > 0 && w.entries[lo - 1].group == g { lo -= 1 }
+ while hi + 1 < count && w.entries[hi + 1].group == g { hi += 1 }
+ if hi > lo {
+ let members = Array(lo...hi)
+ let inTurn = members.filter { $0 > ei } + members.filter { $0 <= ei }
+ if let n = inTurn.first(where: open) { return (n, n <= ei) }
+ if let n = ((hi + 1)..<count).first(where: open) ?? (0..<lo).first(where: open) { return (n, true) }
+ return (count, true)
+ }
+ }
+ if open(ei) { return (ei, true) }
+ if let n = ((ei + 1)..<count).first(where: open) ?? (0..<ei).first(where: open) { return (n, true) }
+ return (count, true)
+ }
+
/// A ready session started here.
static func start(_ s0: SessionState, _ session: ReadySession, wid: String, at: Double, id: String) -> (SessionState, Event) {
var s = s0
- s.workout = ActiveWorkout(id: wid, name: session.name, unit: s.unit, cur: 0, restSec: s.restSec, rest: nil, entries: session.entries)
+ s.workout = ActiveWorkout(id: wid, name: session.name, unit: s.unit, cur: 0, restSec: s.restSec, rest: nil, entries: session.entries, start: at)
s.startedHere = wid
s.pending = [:]
+ s.skipped = nil
s.entryIndex = 0
return (s, ["id": id, "type": "start", "routineIds": session.routineIds, "wid": wid, "at": at])
}
@@ -144,6 +239,7 @@ enum SessionCore {
var s = s0
s.workout = nil
s.pending = [:]
+ s.skipped = nil
s.startedHere = nil
if let wid = w.id { s.finishedHere = Array((s.finishedHere + [wid]).suffix(5)) }
return (s, ["id": id, "type": "finish", "wid": w.id ?? "", "at": at])
@@ -154,7 +250,8 @@ enum SessionCore {
guard let w = s.workout, w.entries.indices.contains(ei) else { return nil }
let sets = w.entries[ei].sets
if let p = picked, sets.indices.contains(p), !sets[p].done { return p }
- return sets.firstIndex { !$0.done }
+ let exId = w.entries[ei].id
+ return sets.indices.first { !sets[$0].done && !isSkipped(s, exId, $0) }
}
/// Sets done and sets in all, for the complication's ring.
@@ -163,4 +260,61 @@ enum SessionCore {
let all = w.entries.flatMap { $0.sets }.filter { !$0.warmup }
return (all.filter { $0.done }.count, all.count)
}
+
+ /// The workout as the summary shows it at its end (here, or on the phone).
+ static func summary(_ w: ActiveWorkout, end: Double, startedAt: Double? = nil, endedOnPhone: Bool = false) -> WorkoutSummary {
+ var sets = 0, volume = 0.0
+ var prs: [String] = []
+ for e in w.entries {
+ let work = e.sets.filter { !$0.warmup }
+ for row in work {
+ if let sides = row.sides {
+ for one in [sides.L, sides.R] where one.done { volume += (one.w ?? 0) * (one.r ?? 0) }
+ if row.done { sets += 1 }
+ } else if row.done {
+ sets += 1
+ if !e.isTimed && !e.isCardio { volume += (row.w ?? 0) * (row.r ?? 0) }
+ }
+ }
+ if let best = e.best, beatsBest(e, work.filter { $0.done }, best) { prs.append(e.name) }
+ }
+ let from = w.start ?? startedAt
+ return WorkoutSummary(name: w.name, unit: w.unit, duration: from.map { max(0, (end - $0) / 1000) },
+ sets: sets, volume: volume, prs: prs, endedOnPhone: endedOnPhone)
+ }
+
+ /// Whether one of these done sets beats the best before this workout: a heavier weight (a
+ /// lighter one when assisted), or more reps at the same; a longer hold. No history, no PR.
+ static func beatsBest(_ e: Entry, _ done: [SetRow], _ best: BestSet) -> Bool {
+ if e.isTimed {
+ guard let b = best.sec, b > 0 else { return false }
+ return done.contains { ($0.sec ?? 0) > b }
+ }
+ guard !e.isCardio, let bw = best.w, let br = best.r, bw > 0 || br > 0 else { return false }
+ let assisted = e.assisted == true
+ return done.contains { row in
+ let w = row.w ?? 0, r = row.r ?? 0
+ if w != bw { return w > 0 && (assisted ? w < bw : w > bw) }
+ return r > br
+ }
+ }
+}
+
+/// The end of a workout, on one screen: how long, how much, and what was a first.
+struct WorkoutSummary: Codable, Equatable {
+ var name: String
+ var unit: String
+ /// Seconds.
+ var duration: Double?
+ /// Work sets done (a per-side set once both sides are).
+ var sets: Int
+ var volume: Double
+ /// The exercises with a personal record in this workout.
+ var prs: [String]
+ var hrAvg: Double?
+ var hrMax: Double?
+ /// Active kilocalories, from the Apple Health workout.
+ var calories: Double?
+ /// The phone ended it (finished or discarded there) while the watch had it running.
+ var endedOnPhone: Bool
}
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/ClipCodecTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/ClipCodecTests.swift
index e90ab9783..a1ee477b1 100644
--- a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/ClipCodecTests.swift
+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/ClipCodecTests.swift
@@ -1,3 +1,5 @@
+// ImageIO only exists on Apple platforms; the session logic is also tested on Linux.
+#if canImport(ImageIO)
import XCTest
@testable import WatchCore
@@ -53,3 +55,4 @@ final class ClipCodecTests: XCTestCase {
XCTAssertFalse(ClipCodec.makeGif(from: junk, to: junk.appendingPathExtension("gif")))
}
}
+#endif
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SetTypesTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SetTypesTests.swift
new file mode 100644
index 000000000..93e526914
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SetTypesTests.swift
@@ -0,0 +1,179 @@
+import XCTest
+@testable import WatchCore
+
+/// Every kind of set the phone can send, through the watch's session: holds, bodyweight, per-side,
+/// warm-ups, supersets, skipped sets, cardio; and the summary at the end.
+final class SetTypesTests: XCTestCase {
+ func row(_ w: Double?, _ r: Double?, sec: Double? = nil, done: Bool = false, warmup: Bool = false, at: Double? = nil) -> SetRow {
+ SetRow(w: w, r: r, sec: sec, done: done, warmup: warmup, at: at)
+ }
+
+ func sideRow(_ w: Double, _ r: Double) -> SetRow {
+ var s = row(w, r * 2)
+ s.sides = Sides(L: SideRow(w: w, r: r, done: false), R: SideRow(w: w, r: r, done: false))
+ return s
+ }
+
+ func entry(_ id: String, _ name: String, mode: String = "reps", sets: [SetRow], group: String? = nil) -> Entry {
+ Entry(id: id, name: name, mode: mode, restSec: nil, last: nil, sets: sets, group: group)
+ }
+
+ func state(_ entries: [Entry], start: Double? = 0) -> SessionState {
+ let w = ActiveWorkout(id: "w1", name: "Mixed", unit: "kg", cur: 0, restSec: 90, rest: nil, entries: entries, start: start)
+ return SessionCore.applySnapshot(SessionState(), Snapshot(v: 1, unit: "kg", restSec: 90, active: w, ready: nil, settings: nil))
+ }
+
+ func testAHoldIsTickedWithItsSeconds() {
+ let s0 = state([entry("plank", "Plank", mode: "time", sets: [row(nil, nil, sec: 45), row(nil, nil, sec: 45)])])
+ XCTAssertTrue(s0.workout!.entries[0].isTimed)
+ let (s, ev) = SessionCore.tick(s0, entry: 0, set: 0, w: nil, r: nil, sec: 38, at: 10, id: "h1")
+ XCTAssertEqual(s.workout?.entries[0].sets[0].sec, 38)
+ XCTAssertEqual(ev?["sec"] as? Double, 38)
+ XCTAssertNil(ev?["w"])
+ XCTAssertNil(ev?["r"])
+ // an old snapshot keeps the watch's seconds until the phone has them
+ let back = SessionCore.applySnapshot(s, Snapshot(v: 1, unit: "kg", restSec: 90, active: s0.workout, ready: nil, settings: nil))
+ XCTAssertEqual(back.workout?.entries[0].sets[0].sec, 38)
+ XCTAssertEqual(SessionCore.setIndex(back, entry: 0), 1)
+ }
+
+ func testBodyweightCountsOnlyTheAddedWeight() {
+ var e = entry("pullup", "Pull-up", sets: [row(0, 10), row(5, 8)])
+ e.bodyweight = true
+ var s = state([e])
+ XCTAssertTrue(s.workout!.entries[0].isBodyweight)
+ s = SessionCore.tick(s, entry: 0, set: 0, w: 0, r: 10, at: 1, id: "a").0
+ s = SessionCore.tick(s, entry: 0, set: 1, w: 5, r: 8, at: 2, id: "b").0
+ let sum = SessionCore.summary(s.workout!, end: 60_000)
+ XCTAssertEqual(sum.sets, 2)
+ XCTAssertEqual(sum.volume, 40)
+ }
+
+ func testAPerSideSetIsDoneOneSideAtATime() {
+ var e = entry("split", "Split squat", sets: [sideRow(20, 8), sideRow(20, 8)])
+ e.perSide = true
+ var s = state([e, entry("calf", "Calf raise", sets: [row(40, 12)])])
+ XCTAssertEqual(s.workout?.entries[0].sets[0].sideUp, "L")
+ let (s1, ev) = SessionCore.tick(s, entry: 0, set: 0, side: "L", w: 20, r: 8, at: 5, id: "l")
+ XCTAssertEqual(ev?["side"] as? String, "L")
+ XCTAssertFalse(s1.workout!.entries[0].sets[0].done, "one side is not the set")
+ XCTAssertEqual(s1.workout?.entries[0].sets[0].sideUp, "R")
+ // the other side next, on the same exercise, without a rest between
+ let n = SessionCore.next(after: s1, entry: 0, set: 0)
+ XCTAssertEqual(n.entry, 0)
+ XCTAssertFalse(n.rest)
+ s = SessionCore.tick(s1, entry: 0, set: 0, side: "R", w: 20, r: 7, at: 6, id: "r").0
+ let row0 = s.workout!.entries[0].sets[0]
+ XCTAssertTrue(row0.done)
+ XCTAssertEqual(row0.r, 15)
+ XCTAssertEqual(SessionCore.setIndex(s, entry: 0), 1)
+ // an old snapshot keeps both sides the watch did
+ let back = SessionCore.applySnapshot(s, Snapshot(v: 1, unit: "kg", restSec: 90, active: state([e]).workout, ready: nil, settings: nil))
+ XCTAssertEqual(back.workout?.entries[0].sets[0].sides?.R.r, 7)
+ XCTAssertTrue(back.workout!.entries[0].sets[0].done)
+ // and the phone having them confirms them
+ var phone = state([e]).workout!
+ phone.entries[0].sets[0] = row0
+ let confirmed = SessionCore.applySnapshot(back, Snapshot(v: 1, unit: "kg", restSec: 90, active: phone, ready: nil, settings: nil))
+ XCTAssertNil(confirmed.pending["split#0#L"])
+ XCTAssertNil(confirmed.pending["split#0#R"])
+ XCTAssertEqual(SessionCore.summary(s.workout!, end: 1).volume, 300) // 20×8 + 20×7
+ }
+
+ func testWarmUpsAreNotWorkSets() {
+ var s = state([entry("bench", "Bench", sets: [row(40, 10, warmup: true), row(60, 8)])])
+ XCTAssertEqual(SessionCore.progress(s).total, 1)
+ s = SessionCore.tick(s, entry: 0, set: 0, w: 40, r: 10, at: 1, id: "w").0
+ XCTAssertEqual(SessionCore.progress(s).done, 0)
+ XCTAssertEqual(SessionCore.summary(s.workout!, end: 1).volume, 0)
+ XCTAssertEqual(SessionCore.setIndex(s, entry: 0), 1)
+ }
+
+ func testASupersetGoesInTurnsAndRestsAfterTheRound() {
+ let s0 = state([
+ entry("curl", "Curl", sets: [row(12, 10), row(12, 10)], group: "a"),
+ entry("push", "Pushdown", sets: [row(20, 12), row(20, 12)], group: "a"),
+ entry("raise", "Lateral raise", sets: [row(8, 15)]),
+ ])
+ var s = SessionCore.tick(s0, entry: 0, set: 0, w: 12, r: 10, at: 1, id: "1").0
+ var n = SessionCore.next(after: s, entry: 0, set: 0)
+ XCTAssertEqual(n.entry, 1, "on to the partner")
+ XCTAssertFalse(n.rest, "no rest inside a round")
+ s = SessionCore.tick(s, entry: 1, set: 0, w: 20, r: 12, at: 2, id: "2").0
+ n = SessionCore.next(after: s, entry: 1, set: 0)
+ XCTAssertEqual(n.entry, 0, "back to the first for the next round")
+ XCTAssertTrue(n.rest, "the rest after the round")
+ s = SessionCore.tick(s, entry: 0, set: 1, w: 12, r: 10, at: 3, id: "3").0
+ s = SessionCore.tick(s, entry: 1, set: 1, w: 20, r: 12, at: 4, id: "4").0
+ n = SessionCore.next(after: s, entry: 1, set: 1)
+ XCTAssertEqual(n.entry, 2, "the superset done: the next exercise")
+ s = SessionCore.tick(s, entry: 2, set: 0, w: 8, r: 15, at: 5, id: "5").0
+ XCTAssertEqual(SessionCore.next(after: s, entry: 2, set: 0).entry, 3, "all done: the Finish page")
+ }
+
+ func testASkippedSetIsPassedOverNotDone() {
+ var s = state([entry("bench", "Bench", sets: [row(60, 8), row(60, 8), row(60, 8)])])
+ s = SessionCore.skip(s, entry: 0, set: 0)
+ XCTAssertEqual(SessionCore.setIndex(s, entry: 0), 1)
+ XCTAssertFalse(s.workout!.entries[0].sets[0].done)
+ // picked by hand, it is back
+ XCTAssertEqual(SessionCore.setIndex(s, entry: 0, picked: 0), 0)
+ // a new workout forgets it
+ let other = ActiveWorkout(id: "w2", name: "Other", unit: "kg", cur: 0, restSec: 90, rest: nil, entries: s.workout!.entries)
+ let s2 = SessionCore.applySnapshot(s, Snapshot(v: 1, unit: "kg", restSec: 90, active: other, ready: nil, settings: nil))
+ XCTAssertNil(s2.skipped)
+ XCTAssertEqual(SessionCore.summary(s.workout!, end: 1).sets, 0)
+ }
+
+ func testCardioIsTickedWithoutNumbers() {
+ let s0 = state([entry("run", "Treadmill", mode: "cardio", sets: [row(nil, nil)])])
+ let (s, ev) = SessionCore.tick(s0, entry: 0, set: 0, w: nil, r: nil, at: 1, id: "c")
+ XCTAssertTrue(s.workout!.entries[0].sets[0].done)
+ XCTAssertNil(ev?["w"])
+ XCTAssertNil(ev?["r"])
+ }
+
+ func testTheSummaryCountsTimeVolumeAndRecords() {
+ var bench = entry("bench", "Bench", sets: [row(40, 10, warmup: true), row(80, 5), row(80, 6)])
+ bench.best = BestSet(w: 80, r: 5, sec: nil)
+ var row1 = entry("row", "Row", sets: [row(60, 8)])
+ row1.best = BestSet(w: 70, r: 8, sec: nil)
+ var assist = entry("dip", "Assisted dip", sets: [row(20, 8)])
+ assist.best = BestSet(w: 25, r: 8, sec: nil)
+ assist.assisted = true
+ var plank = entry("plank", "Plank", mode: "time", sets: [row(nil, nil, sec: 60)])
+ plank.best = BestSet(w: nil, r: nil, sec: 50)
+ let fresh = entry("new", "New thing", sets: [row(100, 1)])
+ var s = state([bench, row1, assist, plank, fresh], start: 1_000)
+ for (ei, si) in [(0, 0), (0, 1), (0, 2), (1, 0), (2, 0), (3, 0), (4, 0)] {
+ let r = s.workout!.entries[ei].sets[si]
+ s = SessionCore.tick(s, entry: ei, set: si, w: r.w, r: r.r, sec: r.sec, at: 2, id: "\(ei)\(si)").0
+ }
+ let sum = SessionCore.summary(s.workout!, end: 1_000 + 45 * 60_000)
+ XCTAssertEqual(sum.duration, 45 * 60)
+ XCTAssertEqual(sum.sets, 6, "warm-ups are not counted")
+ let expected: Double = 400 + 480 + 480 + 160 + 100 // 80×5, 80×6, 60×8, 20×8, 100×1
+ XCTAssertEqual(sum.volume, expected)
+ XCTAssertEqual(sum.prs, ["Bench", "Assisted dip", "Plank"], "more reps at the best weight, lighter assistance, a longer hold; no history is no PR")
+ XCTAssertFalse(sum.endedOnPhone)
+ }
+
+ func testAnOlderPhoneWithoutTheNewFieldsStillReads() throws {
+ let json = #"{"v":1,"active":{"id":"w","name":"A","unit":"kg","cur":0,"restSec":90,"entries":[{"id":"x","name":"X","mode":"reps","sets":[{"w":1,"r":2,"done":false,"warmup":false}]}]}}"#
+ let snap = try JSONDecoder().decode(Snapshot.self, from: Data(json.utf8))
+ XCTAssertNil(snap.active?.start)
+ XCTAssertNil(snap.active?.entries[0].group)
+ XCTAssertNil(snap.active?.entries[0].sets[0].sides)
+ let newer = #"{"v":1,"active":{"id":"w","name":"A","unit":"kg","cur":0,"restSec":90,"start":5,"entries":[{"id":"x","name":"X","mode":"reps","perSide":true,"group":"g","best":{"w":10,"r":5},"sets":[{"w":1,"r":2,"done":false,"warmup":false,"sides":{"L":{"w":1,"r":1,"done":true},"R":{"w":1,"r":1,"done":false}}}]}]}}"#
+ let snap2 = try JSONDecoder().decode(Snapshot.self, from: Data(newer.utf8))
+ XCTAssertEqual(snap2.active?.entries[0].sets[0].sideUp, "R")
+ XCTAssertEqual(snap2.active?.start, 5)
+ }
+
+ func testAStateSavedByTheLastBuildStillLoads() throws {
+ let saved = #"{"settings":{},"unit":"kg","restSec":90,"finishedHere":[],"pending":{"x#0":{"w":1,"r":2,"at":3}},"entryIndex":0}"#
+ let s = try JSONDecoder().decode(SessionState.self, from: Data(saved.utf8))
+ XCTAssertNil(s.skipped)
+ XCTAssertNil(s.pending["x#0"]?.sec)
+ }
+}
diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.js
index ea8293ae7..b3fbb44c2 100644
--- a/frontend/src/lib/watch-sync.js
+++ b/frontend/src/lib/watch-sync.js
@@ -15,12 +15,13 @@
// The iPhone app only. Without a paired watch with the app on it, nothing is sent and nothing
// arrives: the phone behaves exactly as before.
import { MOBILE, nativePlatform } from './mobile.js'
-import { EXIDX, gifSrc, figureOf } from './exercises.js'
+import { EXIDX, gifSrc, figureOf, isAssisted } from './exercises.js'
import { packId, packDrawingId } from './anim-quality.js'
import { getState as animPacks } from './anim-packs.js'
import { exerciseNameFor } from './i18n.js'
-import { modeOf, setLabel, lastEntryFor, effectiveRoutineIds } from './history.js'
-import { isWarmupRow } from './workout-model.js'
+import { modeOf, setLabel, lastEntryFor, effectiveRoutineIds, isBw, isPerSide } from './history.js'
+import { isWarmupRow, isSideSet, syncSideAggregate } from './workout-model.js'
+import { bestSetFor } from './exercise-history.js'
import { sessionHistory } from './backfill.js'
import { buildCombinedEntries, deriveSessionName } from './session-merge.js'
import { todayISO } from './format.js'
@@ -35,30 +36,67 @@ const SEND_DEBOUNCE_MS = 400
const READY_MAX = 8
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null)
+// One side of a per-side set, from the watch: 'L', 'R', or none (the whole set).
+const sideOf = v => (v === 'L' || v === 'R' ? v : null)
+// What a tick of a hold (`sec`) or of one side carries besides the numbers; nothing for a plain set.
+const extraOf = ev => ({ ...(num(ev.sec) != null ? { sec: num(ev.sec) } : {}), ...(sideOf(ev.side) ? { side: sideOf(ev.side) } : {}) })
/* ---------- the snapshot ---------- */
-// One exercise as the watch shows it.
-function watchEntry (e, H) {
+// The best set before today, per exercise and mode, for the watch's PRs at the finish. Worked out
+// once per history (S.workouts), not on every tick of the running session.
+let bestCache = { workouts: null, map: new Map() }
+function bestFor (S, id, mode) {
+ if (mode !== 'reps' && mode !== 'time') return null
+ if (bestCache.workouts !== S?.workouts) bestCache = { workouts: S?.workouts, map: new Map() }
+ const key = id + '|' + mode
+ if (!bestCache.map.has(key)) {
+ let b = null
+ try { b = bestSetFor(S, id, mode)?.set || null } catch { b = null }
+ bestCache.map.set(key, b ? (mode === 'time' ? { sec: num(b.sec), w: num(b.w) } : { w: num(b.w), r: num(b.r) }) : null)
+ }
+ return bestCache.map.get(key)
+}
+
+const sideRow = v => ({ w: num(v?.w), r: num(v?.r), done: v?.done === true })
+
+// One set as the watch shows it. A per-side set (a unilateral exercise) carries its two sides,
+// each ticked on its own; `done` is both.
+function watchSet (s) {
+ return {
+ w: num(s.w), r: num(s.r), sec: num(s.sec), done: !!s.done, warmup: !!isWarmupRow(s),
+ // when it was ticked: of two ticks of the same set (phone and watch), the later wins
+ ...(num(s.at) ? { at: num(s.at) } : {}),
+ ...(isSideSet(s) ? { sides: { L: sideRow(s.sides.L), R: sideRow(s.sides.R) } } : {}),
+ }
+}
+
+// One exercise as the watch shows it. Only optional fields were added over time (bodyweight,
+// perSide, group, best, assisted), so an older watch app reads a newer phone's snapshot.
+function watchEntry (e, H, S) {
const ex = EXIDX[e.id]
const target = e.target || {}
- const mode = modeOf({ ...target, id: e.id })
+ const cfg = { ...target, id: e.id }
+ const mode = modeOf(cfg)
let last = null
try {
const l = H ? lastEntryFor(H, e.id, e.rid) : null
if (l && Array.isArray(l.sets) && l.sets.length) last = l.sets.map(s => setLabel(e.id, s, l.target)).join(', ')
} catch { last = null }
+ const best = S ? bestFor(S, e.id, mode) : null
return {
id: e.id,
name: ex ? exerciseNameFor(ex) : String(target.name || e.name || e.id),
mode,
restSec: num(target.restSec),
last,
- sets: (e.sets || []).map(s => ({
- w: num(s.w), r: num(s.r), sec: num(s.sec), done: !!s.done, warmup: !!isWarmupRow(s),
- // when it was ticked: of two ticks of the same set (phone and watch), the later wins
- ...(num(s.at) ? { at: num(s.at) } : {}),
- })),
+ sets: (e.sets || []).map(watchSet),
+ ...(isBw(cfg) ? { bodyweight: true } : {}),
+ ...(isPerSide(cfg) ? { perSide: true } : {}),
+ // a superset: the exercises next to each other with the same group, done in turns
+ ...(e.sg ? { group: String(e.sg) } : {}),
+ ...(best ? { best } : {}),
+ ...(mode === 'reps' && isAssisted(e.id) ? { assisted: true } : {}),
}
}
@@ -73,7 +111,7 @@ export function buildReady (S, today = todayISO()) {
const session = ids => {
const { entries, routineIds, routines } = buildCombinedEntries(S, ids)
if (!routines.length) return null
- return { routineIds, name: deriveSessionName(routines.map(r => r.name)) || '', entries: entries.map(e => watchEntry(e, H)) }
+ return { routineIds, name: deriveSessionName(routines.map(r => r.name)) || '', entries: entries.map(e => watchEntry(e, H, S)) }
}
let todayIds = []
try { todayIds = effectiveRoutineIds({ ...S, routines: S.routines || [], week: S.week || {}, dayPlan: S.dayPlan || {} }, today, today) || [] } catch { todayIds = [] }
@@ -98,12 +136,14 @@ export function buildSnapshot(S, { timer = null, ready = null } = {}) {
active: {
id: A.id || null,
name: A.name || '',
+ // when it started (ms), for the watch's summary at the finish
+ ...(num(A.start) ? { start: num(A.start) } : {}),
unit,
cur: Math.max(0, Math.min(A.entries.length - 1, A.cur || 0)),
restSec: num(S.restSec) || 0,
// a rest running on the phone, so the watch counts down the same one
rest: timer && !timer.paused && !timer.ready && num(timer.endsAt) ? { endsAt: timer.endsAt } : null,
- entries: A.entries.map(e => watchEntry(e, H)),
+ entries: A.entries.map(e => watchEntry(e, H, S)),
},
}
}
@@ -189,10 +229,10 @@ export function applyEvents (events, getState) {
// A workout already running on the phone is kept; one with the watch's id is this one.
} else if (ev.type === 'setDone' && saved) {
if (!appHandlers) break
- const fields = { done: true, ...(num(ev.w) != null ? { w: num(ev.w) } : {}), ...(num(ev.r) != null ? { r: num(ev.r) } : {}), ...(num(ev.at) ? { at: num(ev.at) } : {}) }
+ const fields = { done: true, ...(num(ev.w) != null ? { w: num(ev.w) } : {}), ...(num(ev.r) != null ? { r: num(ev.r) } : {}), ...(num(ev.sec) != null ? { sec: num(ev.sec) } : {}), ...(num(ev.at) ? { at: num(ev.at) } : {}) }
const hr = sanitizeHr(ev.hr)
if (hr) fields.hr = hr
- appHandlers.patchSet({ wid: ev.wid, exId: ev.exId, entryIdx: ev.entryIdx, setIdx: ev.setIdx }, fields, { ifNewer: num(ev.at) })
+ appHandlers.patchSet({ wid: ev.wid, exId: ev.exId, entryIdx: ev.entryIdx, setIdx: ev.setIdx, ...(sideOf(ev.side) ? { side: sideOf(ev.side) } : {}) }, fields, { ifNewer: num(ev.at) })
} else if (ev.type === 'setDone' && ours) {
if (!handlers) {
// The tick is the workout screen's to apply: open it, and the queue drains when it binds.
@@ -201,7 +241,7 @@ export function applyEvents (events, getState) {
}
const idx = entryIndexOf(A, ev)
const set = idx >= 0 ? A.entries[idx].sets?.[ev.setIdx] : null
- if (set) handlers.setDone(idx, ev.setIdx, { w: num(ev.w), r: num(ev.r), at: num(ev.at), hr: sanitizeHr(ev.hr) })
+ if (set) handlers.setDone(idx, ev.setIdx, { w: num(ev.w), r: num(ev.r), at: num(ev.at), hr: sanitizeHr(ev.hr), ...extraOf(ev) })
} else if (ev.type === 'watchStatus') {
// What the watch says about itself, for Settings → Apple Watch. Never queued behind anything.
writeWatchStatus(ev)
@@ -380,7 +420,22 @@ export function _resetWatchSync () { startedOnWatch.clear(); handlers = null; ap
* (lib/sync-merge.js: of two copies of a workout the one edited last wins). Only these optional
* fields are ever added; nothing is removed or renamed.
*/
-export function patchSetIn (s, { wid, exId, entryIdx, setIdx }, fields, stamp, { ifNewer = null, recount = null } = {}) {
+export function patchSetIn (s, { wid, exId, entryIdx, setIdx, side = null }, fields, stamp, { ifNewer = null, recount = null } = {}) {
+ // One side of a per-side set: that side takes the numbers and the tick, the row's own w/r/done
+ // follow from both sides (lib/workout-model.js syncSideAggregate).
+ const write = (set, f) => {
+ if (side && isSideSet(set)) {
+ const { w, r, done, ...rest } = f
+ const one = { ...set.sides[side] }
+ if (w != null) one.w = w
+ if (r != null) one.r = r
+ if (done) one.done = true
+ set.sides = { ...set.sides, [side]: one }
+ const agg = syncSideAggregate(set)
+ for (const k of Object.keys(set)) if (!(k in agg)) delete set[k]
+ Object.assign(set, agg, rest)
+ } else Object.assign(set, f)
+ }
const find = w => {
if (!w || !Array.isArray(w.entries)) return null
const i = w.entries[entryIdx] && w.entries[entryIdx].id === exId ? entryIdx : w.entries.findIndex(e => e && e.id === exId)
@@ -388,7 +443,7 @@ export function patchSetIn (s, { wid, exId, entryIdx, setIdx }, fields, stamp, {
}
if (s.active && s.active.id === wid) {
const set = find(s.active)
- if (set) Object.assign(set, fields)
+ if (set) write(set, fields)
return !!set
}
const w = (s.workouts || []).find(x => x && x.id === wid)
@@ -403,7 +458,7 @@ export function patchSetIn (s, { wid, exId, entryIdx, setIdx }, fields, stamp, {
if (fields.restHr) f.restHr = fields.restHr
if (!Object.keys(f).length) return false
}
- Object.assign(set, f)
+ write(set, f)
if (recount) recount(w)
if (stamp) stamp(w)
return true
diff --git a/frontend/src/lib/watch-sync.settypes.test.js b/frontend/src/lib/watch-sync.settypes.test.js
new file mode 100644
index 000000000..277cb9857
--- /dev/null
+++ b/frontend/src/lib/watch-sync.settypes.test.js
@@ -0,0 +1,91 @@
+// @vitest-environment happy-dom
+// Every kind of set reaches the watch with what it needs, and comes back right: bodyweight,
+// per-side (two sides, each ticked on its own), holds (seconds), supersets (group), warm-ups,
+// the best set before today (the watch's PRs) and the workout's start (its summary).
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { buildSnapshot, applyEvents, bindWatchAppActions, patchSetIn, _resetWatchSync } from './watch-sync.js'
+
+beforeEach(() => { localStorage.clear(); _resetWatchSync() })
+
+const sideRow = (Ld = false) => ({ w: 20, r: 16, done: false, sides: { L: { w: 20, r: 8, done: Ld }, R: { w: 20, r: 8, done: false } } })
+
+const S = () => ({
+ unit: 'kg', restSec: 90, routines: [],
+ workouts: [{ id: 'old', d: '2026-10-01', start: 1, entries: [
+ { id: '0025', target: { sets: 1, reps: 8 }, sets: [{ w: 80, r: 5, done: true }, { w: 85, r: 3, done: true }] },
+ { id: 'plank', target: { mode: 'time', sec: 30 }, sets: [{ sec: 50, done: true }] },
+ ] }],
+ active: {
+ id: 'w-1', name: 'Mixed', cur: 0, d: '2026-10-14', start: 1_800_000_000_000,
+ entries: [
+ { id: '0025', target: { sets: 2, reps: 8, weight: 80 }, sets: [{ w: 40, r: 10, done: false, phase: 'warmup' }, { w: 80, r: 6, done: false }] },
+ { id: 'plank', target: { mode: 'time', sec: 45 }, sets: [{ sec: 45, done: false }] },
+ { id: 'pull', target: { sets: 1, reps: 8, bodyweight: true }, sets: [{ w: 0, r: 8, done: false }] },
+ { id: 'split', target: { sets: 1, reps: 16, side: true }, sets: [sideRow(true)] },
+ { id: 'curl', sg: 'g1', target: { sets: 1, reps: 10 }, sets: [{ w: 12, r: 10, done: false }] },
+ { id: 'push', sg: 'g1', target: { sets: 1, reps: 12 }, sets: [{ w: 25, r: 12, done: false }] },
+ { id: '1431', target: { sets: 1, reps: 8 }, sets: [{ w: 30, r: 8, done: false }] },
+ ],
+ },
+})
+
+describe('the snapshot carries every kind of set', () => {
+ const snap = buildSnapshot(S())
+ const [bench, plank, pull, split, curl, push, assisted] = snap.active.entries
+
+ it('the workout\'s start, for the summary', () => { expect(snap.active.start).toBe(1_800_000_000_000) })
+ it('warm-ups marked, and the best set before today', () => {
+ expect(bench.sets[0].warmup).toBe(true)
+ expect(bench.sets[1].warmup).toBe(false)
+ expect(bench.best).toEqual({ w: 85, r: 3 })
+ })
+ it('holds with their seconds and their longest one', () => {
+ expect(plank.mode).toBe('time')
+ expect(plank.sets[0].sec).toBe(45)
+ expect(plank.best).toEqual({ sec: 50, w: null })
+ })
+ it('bodyweight', () => { expect(pull.bodyweight).toBe(true); expect(bench.bodyweight).toBeUndefined() })
+ it('per-side sets with both sides', () => {
+ expect(split.perSide).toBe(true)
+ expect(split.sets[0].sides).toEqual({ L: { w: 20, r: 8, done: true }, R: { w: 20, r: 8, done: false } })
+ expect(bench.sets[1].sides).toBeUndefined()
+ })
+ it('supersets by their group, only where there is one', () => {
+ expect(curl.group).toBe('g1')
+ expect(push.group).toBe('g1')
+ expect(bench.group).toBeUndefined()
+ })
+ it('assisted exercises, where lighter is better', () => {
+ expect(assisted.assisted).toBe(true)
+ expect(bench.assisted).toBeUndefined()
+ })
+ it('no best for an exercise never done before', () => { expect(curl.best).toBeUndefined() })
+})
+
+describe('ticks of every kind', () => {
+ it('a per-side tick for a workout the phone already saved goes into that side', () => {
+ const s = { active: null, workouts: [{ id: 'w-old', entries: [{ id: 'split', sets: [sideRow()] }] }] }
+ const stamp = vi.fn()
+ expect(patchSetIn(s, { wid: 'w-old', exId: 'split', entryIdx: 0, setIdx: 0, side: 'L' }, { done: true, w: 22.5, r: 8, at: 5 }, stamp)).toBe(true)
+ const row = s.workouts[0].entries[0].sets[0]
+ expect(row.sides.L).toMatchObject({ w: 22.5, r: 8, done: true })
+ expect(row).toMatchObject({ done: false, r: 16, w: 22.5, at: 5 })
+ patchSetIn(s, { wid: 'w-old', exId: 'split', entryIdx: 0, setIdx: 0, side: 'R' }, { done: true, w: 20, r: 7, at: 6 }, stamp)
+ expect(s.workouts[0].entries[0].sets[0]).toMatchObject({ done: true, r: 15 })
+ expect(stamp).toHaveBeenCalledTimes(2)
+ })
+
+ it('side and seconds reach the app\'s handler for a saved workout, and nothing extra for a plain set', () => {
+ const patchSet = vi.fn()
+ bindWatchAppActions({ start: vi.fn(), patchSet })
+ const getState = () => ({ S: { active: null, workouts: [{ id: 'w-old', entries: [] }] } })
+ applyEvents([
+ { id: 'a', type: 'setDone', wid: 'w-old', exId: 'split', entryIdx: 0, setIdx: 0, side: 'L', w: 20, r: 8, at: 1 },
+ { id: 'b', type: 'setDone', wid: 'w-old', exId: 'plank', entryIdx: 1, setIdx: 0, sec: 40, at: 2 },
+ { id: 'c', type: 'setDone', wid: 'w-old', exId: '0025', entryIdx: 2, setIdx: 0, w: 60, r: 8, side: 'X', at: 3 },
+ ], getState)
+ expect(patchSet.mock.calls[0][0]).toMatchObject({ side: 'L' })
+ expect(patchSet.mock.calls[1][1]).toMatchObject({ sec: 40, done: true })
+ expect(patchSet.mock.calls[2][0].side).toBeUndefined()
+ })
+})
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index 72fbb3f0c..e7a1a13ba 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -1787,17 +1787,31 @@ function ActiveWorkout({ onActionChange }) {
// The time is the watch's: the phone may hear of the set much later (lib/finish-workout.js
// sessionEnd reads the sets' times). The watch's Finish runs the phone's Finish and save.
useEffect(() => bindWatchActions({
- setDone: (idx, i, { w, r, at, hr }) => {
+ setDone: (idx, i, { w, r, sec, side, at, hr }) => {
if (useStore.getState().S.active?.editingWorkoutId) return // a saved workout being edited is not the session
const now = useStore.getState().S.active?.entries?.[idx]?.sets?.[i]
+ // One side of a per-side set (a unilateral exercise): that side's numbers and its own tick.
+ const oneSide = side && isSideSet(now) ? side : null
+ const wasDone = oneSide ? now.sides[oneSide].done : now?.done
// The same set ticked here after the watch did: the later tick wins, the heart rate still lands.
- if (now?.done && at && Number(now.at) > at) {
+ if (wasDone && at && Number(now.at) > at) {
if (hr) mutEntry(idx, en => { if (en.sets[i]) en.sets[i].hr = hr })
return
}
- mutEntry(idx, en => { const set = en.sets[i]; if (!set) return; if (w != null) set.w = w; if (r != null) set.r = r })
- if (!now?.done) toggleRef.current(idx, i)
- if (at || hr) mutEntry(idx, en => { const set = en.sets[i]; if (!set?.done) return; if (at) set.at = at; if (hr) set.hr = hr })
+ mutEntry(idx, en => {
+ const set = en.sets[i]
+ if (!set) return
+ if (oneSide) {
+ if (w != null) en.sets[i] = setSideField(en.sets[i], oneSide, 'w', w)
+ if (r != null) en.sets[i] = setSideField(en.sets[i], oneSide, 'r', r)
+ return
+ }
+ if (w != null) set.w = w
+ if (r != null) set.r = r
+ if (sec != null) set.sec = sec // a hold: the seconds it lasted on the watch
+ })
+ if (!wasDone) toggleRef.current(idx, i, oneSide || undefined)
+ if (at || hr) mutEntry(idx, en => { const set = en.sets[i]; if (!(oneSide ? set?.sides?.[oneSide]?.done : set?.done)) return; if (at) set.at = at; if (hr) set.hr = hr })
},
finish: () => { if (!useStore.getState().S.active?.editingWorkoutId) finishWorkoutNow() },
}), [])
diff --git a/frontend/src/views/Workout.watch.test.jsx b/frontend/src/views/Workout.watch.test.jsx
index fa487139f..b5939baed 100644
--- a/frontend/src/views/Workout.watch.test.jsx
+++ b/frontend/src/views/Workout.watch.test.jsx
@@ -77,3 +77,31 @@ describe('the same set on both sides', () => {
expect(useStore.getState().S.active.entries[0].sets[0]).toMatchObject({ w: 70, r: 5, done: true, at: 5000, hr: { avg: 120, max: 130 } })
})
})
+
+// Every kind of set the watch logs: one side of a per-side set at a time, a hold with its seconds.
+describe('sets of every kind from the watch', () => {
+ const sideRow = () => ({ w: 20, r: 16, done: false, sides: { L: { w: 20, r: 8, done: false }, R: { w: 20, r: 8, done: false } } })
+ const load = entries => act(() => { useStore.getState().update(s => { s.active.entries = entries }) })
+
+ it('a per-side set: each side ticked on its own, the row done with both', () => {
+ load([{ id: 'split', target: { sets: 1, reps: 16, weight: 20, side: true }, sets: [sideRow()] }])
+ act(() => { applyEvents([{ id: 'l', type: 'setDone', wid: 'w-watch', exId: 'split', entryIdx: 0, setIdx: 0, side: 'L', w: 22.5, r: 8, at: 10 }], () => useStore.getState()) })
+ let row = useStore.getState().S.active.entries[0].sets[0]
+ expect(row.sides.L).toMatchObject({ w: 22.5, r: 8, done: true })
+ expect(row.sides.R.done).toBe(false)
+ expect(row.done).toBe(false)
+ act(() => { applyEvents([{ id: 'r', type: 'setDone', wid: 'w-watch', exId: 'split', entryIdx: 0, setIdx: 0, side: 'R', w: 20, r: 7, at: 20 }], () => useStore.getState()) })
+ row = useStore.getState().S.active.entries[0].sets[0]
+ expect(row.sides.R).toMatchObject({ w: 20, r: 7, done: true })
+ expect(row).toMatchObject({ done: true, r: 15, w: 22.5 })
+ // the same side again changes nothing
+ act(() => { applyEvents([{ id: 'r2', type: 'setDone', wid: 'w-watch', exId: 'split', entryIdx: 0, setIdx: 0, side: 'R', w: 20, r: 7, at: 20 }], () => useStore.getState()) })
+ expect(useStore.getState().S.active.entries[0].sets[0].sides.R.done).toBe(true)
+ })
+
+ it('a hold: done with the seconds it lasted on the watch', () => {
+ load([{ id: 'plank', target: { sets: 1, sec: 45, mode: 'time' }, sets: [{ sec: 45, done: false }] }])
+ act(() => { applyEvents([{ id: 'h', type: 'setDone', wid: 'w-watch', exId: 'plank', entryIdx: 0, setIdx: 0, sec: 52, at: 30 }], () => useStore.getState()) })
+ expect(useStore.getState().S.active.entries[0].sets[0]).toMatchObject({ sec: 52, done: true })
+ })
+})