Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Progressive overload: PR suggestions you approve on the routine (#40) (#61)

Carter274726b9ebe8
diff --git a/backend/controllers/programs.go b/backend/controllers/programs.go
index 134cabf..f070bb5 100644
--- a/backend/controllers/programs.go
+++ b/backend/controllers/programs.go
@@ -115,3 +115,32 @@ func (h *Handler) DeleteProgram(c *gin.Context) {
}
utils.OK(c, gin.H{"deleted": true})
}
+
+// ResolveSuggestions accepts/dismisses staged auto-progression suggestions (#40) and
+// returns the refreshed program. Ownership is enforced in the store.
+func (h *Handler) ResolveSuggestions(c *gin.Context) {
+ uid := middleware.UserID(c)
+ pid, err := strconv.ParseInt(c.Param("id"), 10, 64)
+ if err != nil {
+ utils.BadRequest(c, "invalid program id")
+ return
+ }
+ var req models.ResolveSuggestionsReq
+ if err := c.ShouldBindJSON(&req); err != nil {
+ utils.BadRequest(c, err.Error())
+ return
+ }
+ if err := validate.Struct(req); err != nil {
+ utils.ValidationError(c, err)
+ return
+ }
+ p, err := h.s.Program.ResolveSuggestions(uid, pid, req.Accept, req.Dismiss)
+ if err == sql.ErrNoRows {
+ utils.NotFound(c, "program not found")
+ return
+ }
+ if utils.DBError(c, err) {
+ return
+ }
+ utils.OK(c, p)
+}
diff --git a/backend/controllers/progression_test.go b/backend/controllers/progression_test.go
new file mode 100644
index 0000000..e0567e6
--- /dev/null
+++ b/backend/controllers/progression_test.go
@@ -0,0 +1,426 @@
+package controllers
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/stores"
+)
+
+// ptTarget is a seeded routine set target (issue #40 auto-progression tests).
+type ptTarget struct {
+ Reps int
+ Weight float64
+}
+
+func seedProgram(t *testing.T, uid, exID int64, targets []ptTarget) (int64, []int64) {
+ t.Helper()
+ res, err := db.DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, 'Push A')`, uid)
+ if err != nil {
+ t.Fatalf("seed program: %v", err)
+ }
+ pid, _ := res.LastInsertId()
+ peRes, err := db.DB.Exec(`INSERT INTO program_exercises (program_id, exercise_id, order_index) VALUES (?, ?, 0)`, pid, exID)
+ if err != nil {
+ t.Fatalf("seed program exercise: %v", err)
+ }
+ peid, _ := peRes.LastInsertId()
+ ids := make([]int64, 0, len(targets))
+ for i, tg := range targets {
+ sr, err := db.DB.Exec(
+ `INSERT INTO program_sets (program_exercise_id, set_number, target_reps, target_weight) VALUES (?, ?, ?, ?)`,
+ peid, i+1, tg.Reps, tg.Weight,
+ )
+ if err != nil {
+ t.Fatalf("seed program set: %v", err)
+ }
+ sid, _ := sr.LastInsertId()
+ ids = append(ids, sid)
+ }
+ return pid, ids
+}
+
+func getTarget(t *testing.T, setID int64) (int, float64) {
+ t.Helper()
+ var r int
+ var w float64
+ if err := db.DB.QueryRow(`SELECT target_reps, target_weight FROM program_sets WHERE id = ?`, setID).Scan(&r, &w); err != nil {
+ t.Fatalf("read target %d: %v", setID, err)
+ }
+ return r, w
+}
+
+// getSuggestion returns the staged suggestion for a set: (reps, weight, isPR, present).
+// present is false when no suggestion is staged (suggested_reps IS NULL).
+func getSuggestion(t *testing.T, setID int64) (int, float64, bool, bool) {
+ t.Helper()
+ var nr *int64
+ var nw *float64
+ var npr int
+ if err := db.DB.QueryRow(`SELECT suggested_reps, suggested_weight, suggested_is_pr FROM program_sets WHERE id = ?`, setID).Scan(&nr, &nw, &npr); err != nil {
+ t.Fatalf("read suggestion %d: %v", setID, err)
+ }
+ if nr == nil {
+ return 0, 0, false, false
+ }
+ weight := 0.0
+ if nw != nil {
+ weight = *nw
+ }
+ return int(*nr), weight, npr == 1, true
+}
+
+func insertUser(t *testing.T, email string) int64 {
+ t.Helper()
+ res, err := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, 'h')`, email)
+ if err != nil {
+ t.Fatalf("insert user %s: %v", email, err)
+ }
+ id, _ := res.LastInsertId()
+ return id
+}
+
+// SuggestTargets STAGES suggestions (never mutates target_*): heavier weight suggests
+// weight+reps; same weight + more reps suggests reps; equalled → nothing. The is-PR flag
+// and count/anyPR are surfaced. Targets stay put until approved.
+func TestSuggestTargets_StagesUpwardOnly(t *testing.T) {
+ setupTestDB(t)
+ ps := stores.NewProgramStore(db.DB)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+ pid, ids := seedProgram(t, uid, exID, []ptTarget{{5, 100}, {5, 100}, {5, 100}})
+
+ name, count, anyPR, err := ps.SuggestTargets(uid, pid, []stores.ProgressInput{
+ {ProgramSetID: ids[0], Weight: 105, Reps: 5, IsPR: true}, // heavier → weight+reps, PR
+ {ProgramSetID: ids[1], Weight: 100, Reps: 6, IsPR: false}, // more reps → reps
+ {ProgramSetID: ids[2], Weight: 100, Reps: 5, IsPR: false}, // equalled → nothing
+ })
+ if err != nil {
+ t.Fatalf("SuggestTargets: %v", err)
+ }
+ if name != "Push A" || count != 2 || !anyPR {
+ t.Errorf("got (name=%q count=%d anyPR=%v), want (Push A, 2, true)", name, count, anyPR)
+ }
+ // Targets unchanged (nothing applied yet).
+ for _, id := range ids {
+ if r, w := getTarget(t, id); r != 5 || w != 100 {
+ t.Errorf("target %d changed to %d×%.1f — should stay 5×100 until approved", id, r, w)
+ }
+ }
+ // Suggestions staged on the two beaten sets.
+ if r, w, pr, ok := getSuggestion(t, ids[0]); !ok || r != 5 || w != 105 || !pr {
+ t.Errorf("set0 suggestion = (%d×%.1f pr=%v ok=%v), want 5×105 pr=true", r, w, pr, ok)
+ }
+ if r, _, pr, ok := getSuggestion(t, ids[1]); !ok || r != 6 || pr {
+ t.Errorf("set1 suggestion = (%d reps pr=%v ok=%v), want 6 reps pr=false", r, pr, ok)
+ }
+ if _, _, _, ok := getSuggestion(t, ids[2]); ok {
+ t.Errorf("set2 should have no suggestion (equalled target)")
+ }
+}
+
+// A pending suggestion is never downgraded by a later smaller-but-over-target set;
+// a bigger one overwrites it (compare against best-of target/pending).
+func TestSuggestTargets_KeepsBestPending(t *testing.T) {
+ setupTestDB(t)
+ ps := stores.NewProgramStore(db.DB)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+ pid, ids := seedProgram(t, uid, exID, []ptTarget{{5, 100}})
+
+ // Stage 110, then a lighter 105 (still > target 100) must NOT downgrade it.
+ ps.SuggestTargets(uid, pid, []stores.ProgressInput{{ProgramSetID: ids[0], Weight: 110, Reps: 5}})
+ _, count, _, _ := ps.SuggestTargets(uid, pid, []stores.ProgressInput{{ProgramSetID: ids[0], Weight: 105, Reps: 5}})
+ if count != 0 {
+ t.Errorf("count = %d, want 0 (105 shouldn't overwrite pending 110)", count)
+ }
+ if _, w, _, _ := getSuggestion(t, ids[0]); w != 110 {
+ t.Errorf("pending suggestion = %.1f, want 110 (not downgraded)", w)
+ }
+ // A bigger 115 does overwrite.
+ _, count2, _, _ := ps.SuggestTargets(uid, pid, []stores.ProgressInput{{ProgramSetID: ids[0], Weight: 115, Reps: 5}})
+ if count2 != 1 {
+ t.Errorf("count = %d, want 1 (115 overwrites pending 110)", count2)
+ }
+ if _, w, _, _ := getSuggestion(t, ids[0]); w != 115 {
+ t.Errorf("pending suggestion = %.1f, want 115", w)
+ }
+}
+
+// A lighter set never stages a suggestion, even with more reps (weight-first rule).
+func TestSuggestTargets_NeverLowers(t *testing.T) {
+ setupTestDB(t)
+ ps := stores.NewProgramStore(db.DB)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+ pid, ids := seedProgram(t, uid, exID, []ptTarget{{8, 100}})
+
+ _, count, _, err := ps.SuggestTargets(uid, pid, []stores.ProgressInput{{ProgramSetID: ids[0], Weight: 95, Reps: 12}})
+ if err != nil {
+ t.Fatalf("SuggestTargets: %v", err)
+ }
+ if count != 0 {
+ t.Errorf("count = %d, want 0", count)
+ }
+ if _, _, _, ok := getSuggestion(t, ids[0]); ok {
+ t.Errorf("no suggestion expected for a lighter set")
+ }
+}
+
+// Ownership + program-join guard (IDOR): a user cannot stage onto another user's routine.
+func TestSuggestTargets_OwnershipGuard(t *testing.T) {
+ setupTestDB(t)
+ ps := stores.NewProgramStore(db.DB)
+ owner := createTestUser(t)
+ attacker := insertUser(t, "[email protected]")
+ exID := createTestExercise(t)
+ pid, ids := seedProgram(t, owner, exID, []ptTarget{{5, 100}})
+
+ // attacker uses the owner's program id → ownership gate → no-op.
+ name, count, _, err := ps.SuggestTargets(attacker, pid, []stores.ProgressInput{{ProgramSetID: ids[0], Weight: 999, Reps: 99}})
+ if err != nil || name != "" || count != 0 {
+ t.Errorf("victim-program call = (%q, %d, %v), want (\"\", 0, nil)", name, count, err)
+ }
+ // attacker's own program + owner's set id → join fails → no-op.
+ p2, _ := seedProgram(t, attacker, exID, []ptTarget{{5, 50}})
+ _, count2, _, _ := ps.SuggestTargets(attacker, p2, []stores.ProgressInput{{ProgramSetID: ids[0], Weight: 999, Reps: 99}})
+ if count2 != 0 {
+ t.Errorf("cross-program count = %d, want 0", count2)
+ }
+ if _, _, _, ok := getSuggestion(t, ids[0]); ok {
+ t.Fatalf("owner's set got a suggestion — IDOR!")
+ }
+}
+
+// ResolveSuggestions: accept copies suggestion→target + clears; dismiss clears only.
+func TestResolveSuggestions_AcceptAndDismiss(t *testing.T) {
+ setupTestDB(t)
+ ps := stores.NewProgramStore(db.DB)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+ pid, ids := seedProgram(t, uid, exID, []ptTarget{{5, 100}, {5, 100}})
+
+ if _, count, _, err := ps.SuggestTargets(uid, pid, []stores.ProgressInput{
+ {ProgramSetID: ids[0], Weight: 105, Reps: 5},
+ {ProgramSetID: ids[1], Weight: 110, Reps: 5},
+ }); err != nil || count != 2 {
+ t.Fatalf("stage: count=%d err=%v", count, err)
+ }
+
+ // Accept set0, dismiss set1.
+ prog, err := ps.ResolveSuggestions(uid, pid, []int64{ids[0]}, []int64{ids[1]})
+ if err != nil {
+ t.Fatalf("ResolveSuggestions: %v", err)
+ }
+ if len(prog.Exercises) != 1 {
+ t.Fatalf("expected 1 exercise, got %d", len(prog.Exercises))
+ }
+ // set0: target applied to 105, suggestion cleared.
+ if r, w := getTarget(t, ids[0]); r != 5 || w != 105 {
+ t.Errorf("accepted target = %d×%.1f, want 5×105", r, w)
+ }
+ if _, _, _, ok := getSuggestion(t, ids[0]); ok {
+ t.Errorf("accepted suggestion should be cleared")
+ }
+ // set1: target unchanged, suggestion cleared.
+ if r, w := getTarget(t, ids[1]); r != 5 || w != 100 {
+ t.Errorf("dismissed target = %d×%.1f, want 5×100 (unchanged)", r, w)
+ }
+ if _, _, _, ok := getSuggestion(t, ids[1]); ok {
+ t.Errorf("dismissed suggestion should be cleared")
+ }
+}
+
+// ResolveSuggestions ignores ids that aren't in the caller's program (ownership/IDOR).
+func TestResolveSuggestions_OwnershipGuard(t *testing.T) {
+ setupTestDB(t)
+ ps := stores.NewProgramStore(db.DB)
+ owner := createTestUser(t)
+ attacker := insertUser(t, "[email protected]")
+ exID := createTestExercise(t)
+ pid, ids := seedProgram(t, owner, exID, []ptTarget{{5, 100}})
+ if _, count, _, _ := ps.SuggestTargets(owner, pid, []stores.ProgressInput{{ProgramSetID: ids[0], Weight: 105, Reps: 5}}); count != 1 {
+ t.Fatalf("stage failed")
+ }
+
+ // attacker's own program, tries to accept the owner's staged set id → join fails → no-op.
+ p2, _ := seedProgram(t, attacker, exID, []ptTarget{{5, 50}})
+ if _, err := ps.ResolveSuggestions(attacker, p2, []int64{ids[0]}, nil); err != nil {
+ t.Fatalf("ResolveSuggestions(attacker): %v", err)
+ }
+ if r, w := getTarget(t, ids[0]); r != 5 || w != 100 {
+ t.Fatalf("owner's target mutated to %d×%.1f — IDOR!", r, w)
+ }
+ if _, _, _, ok := getSuggestion(t, ids[0]); !ok {
+ t.Errorf("owner's staged suggestion should be untouched by the attacker")
+ }
+}
+
+// CreateWorkout with a program_id goes through CreateWorkoutWithProgression (the
+// merged-transaction path, issue #40 progression review) end-to-end: a beaten,
+// routine-linked set stages a suggestion and the response's progression summary
+// reflects it.
+func TestCreateWorkout_StagesProgressionSuggestion(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+ pid, ids := seedProgram(t, uid, exID, []ptTarget{{5, 100}})
+
+ body := map[string]any{
+ "name": "Push A",
+ "duration": 1800,
+ "program_id": pid,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "sets": []map[string]any{
+ {"set_number": 1, "reps": 5, "weight": 105.0, "program_set_id": ids[0]},
+ },
+ },
+ },
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ th.CreateWorkout(c)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data := resp["data"].(map[string]any)
+ prog, ok := data["progression"].(map[string]any)
+ if !ok {
+ t.Fatalf("expected progression in response, got %v", data["progression"])
+ }
+ if count, _ := prog["count"].(float64); count != 1 {
+ t.Errorf("progression count = %v, want 1", prog["count"])
+ }
+ if isPR, _ := prog["is_pr"].(bool); !isPR {
+ t.Errorf("progression is_pr = %v, want true", prog["is_pr"])
+ }
+ // The staged suggestion is durably persisted on program_sets, not just echoed
+ // on the response (regression: merging the snapshot/insert/staging transactions
+ // must still leave a fully-committed suggestion, not a partial one).
+ if r, wt, pr, ok := getSuggestion(t, ids[0]); !ok || r != 5 || wt != 105 || !pr {
+ t.Errorf("staged suggestion = (%d×%.1f pr=%v ok=%v), want 5×105 pr=true", r, wt, pr, ok)
+ }
+}
+
+// If suggestion-staging errors mid-transaction, CreateWorkoutWithProgression's
+// SAVEPOINT/ROLLBACK TO SAVEPOINT must undo only staging's own writes and let the
+// already-inserted workout commit (per the "best-effort" doc comment on
+// CreateWorkoutWithProgression) — never let pErr propagate up through inTxDo and
+// roll back the whole transaction, silently discarding the user's workout.
+func TestCreateWorkout_progressionStagingFailureStillSavesWorkout(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+ pid, ids := seedProgram(t, uid, exID, []ptTarget{{5, 100}})
+
+ // Force suggestion-staging to hit a real DB error (not the benign sql.ErrNoRows
+ // the code already tolerates) by pulling program_sets out from under it — the
+ // per-set SELECT in suggestTargetsTx joins that table, so this fails the staging
+ // step without touching workouts/workout_exercises/sets at all.
+ if _, err := db.DB.Exec(`ALTER TABLE program_sets RENAME TO program_sets_gone`); err != nil {
+ t.Fatalf("rename program_sets: %v", err)
+ }
+
+ body := map[string]any{
+ "name": "Push A",
+ "duration": 1800,
+ "program_id": pid,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "sets": []map[string]any{
+ {"set_number": 1, "reps": 5, "weight": 105.0, "program_set_id": ids[0]},
+ },
+ },
+ },
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ th.CreateWorkout(c)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201 even though staging failed, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data := resp["data"].(map[string]any)
+ if data["progression"] != nil {
+ t.Errorf("progression = %v, want nil — staging failed, so nothing was staged", data["progression"])
+ }
+
+ var count int
+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM workouts WHERE user_id = ?`, uid).Scan(&count); err != nil {
+ t.Fatalf("count workouts: %v", err)
+ }
+ if count != 1 {
+ t.Fatalf("workout count = %d, want 1 — a staging failure must not roll back the outer transaction", count)
+ }
+}
+
+// CreateWorkoutRequest.Exercises carries validate:"max=500,dive" specifically so the
+// nested per-exercise Sets cap (also max=500) is enforced too — go-playground/validator
+// only recurses into a struct slice's own element tags when the outer slice is
+// `dive`-tagged. A single exercise with an oversized Sets array must be rejected before
+// it ever reaches CreateWorkoutWithProgression's single-connection transaction.
+func TestCreateWorkout_RejectsOversizedSets(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ sets := make([]map[string]any, 501)
+ for i := range sets {
+ sets[i] = map[string]any{"set_number": i + 1, "reps": 5, "weight": 100.0}
+ }
+ body := map[string]any{
+ "name": "Push A",
+ "duration": 1800,
+ "exercises": []map[string]any{
+ {"exercise_id": exID, "sets": sets},
+ },
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ th.CreateWorkout(c)
+
+ if w.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("expected 422 for a 501-set exercise, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// Exercises and Sets each cap at max=500 independently, which doesn't bound their
+// product: many exercises with a handful of sets each can still add up to more total
+// rows than CreateWorkoutWithProgression's single-connection transaction should ever
+// process for one request. The struct-level total-sets check (models.MaxWorkoutSets)
+// must reject that even though no single list crosses its own max=500.
+func TestCreateWorkout_RejectsOversizedTotalSets(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ // 21 exercises x 25 sets = 525 total sets, over MaxWorkoutSets (500), while every
+ // individual list (21 exercises, 25 sets) stays well under its own max=500.
+ exercises := make([]map[string]any, 21)
+ for i := range exercises {
+ sets := make([]map[string]any, 25)
+ for j := range sets {
+ sets[j] = map[string]any{"set_number": j + 1, "reps": 5, "weight": 100.0}
+ }
+ exercises[i] = map[string]any{"exercise_id": exID, "sets": sets}
+ }
+ body := map[string]any{
+ "name": "Push A",
+ "duration": 1800,
+ "exercises": exercises,
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ th.CreateWorkout(c)
+
+ if w.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("expected 422 for 525 total sets across exercises, got %d: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.go
index 90e60c1..43e7faa 100644
--- a/backend/controllers/testhelper_test.go
+++ b/backend/controllers/testhelper_test.go
@@ -117,7 +117,10 @@ CREATE TABLE IF NOT EXISTS program_sets (
program_exercise_id INTEGER NOT NULL REFERENCES program_exercises(id) ON DELETE CASCADE,
set_number INTEGER NOT NULL DEFAULT 1,
target_reps INTEGER NOT NULL DEFAULT 0,
- target_weight REAL NOT NULL DEFAULT 0
+ target_weight REAL NOT NULL DEFAULT 0,
+ suggested_weight REAL,
+ suggested_reps INTEGER,
+ suggested_is_pr INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS weight_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.go
index 09316f6..43ca530 100644
--- a/backend/controllers/workouts.go
+++ b/backend/controllers/workouts.go
@@ -10,8 +10,28 @@ import (
"github.com/Cawlumm/lyftr-backend/stores"
"github.com/Cawlumm/lyftr-backend/utils"
"github.com/gin-gonic/gin"
+ "github.com/go-playground/validator/v10"
)
+// Exercises/Sets in CreateWorkoutRequest each cap at max=500 independently (models.go),
+// which doesn't bound their product — a request with 500 exercises x 500 sets (250,000
+// rows) still passes those tags. This struct-level check enforces the total-sets bound
+// (models.MaxWorkoutSets) that CreateWorkoutWithProgression's single-transaction
+// processing actually needs, since db.DB.SetMaxOpenConns(1) means that transaction
+// holds the process's only SQLite connection for the whole request.
+func init() {
+ validate.RegisterStructValidation(func(sl validator.StructLevel) {
+ req := sl.Current().Interface().(models.CreateWorkoutRequest)
+ total := 0
+ for _, ex := range req.Exercises {
+ total += len(ex.Sets)
+ }
+ if total > models.MaxWorkoutSets {
+ sl.ReportError(req.Exercises, "Exercises", "Exercises", "maxtotalsets", "")
+ }
+ }, models.CreateWorkoutRequest{})
+}
+
func (h *Handler) ListWorkouts(c *gin.Context) {
uid := middleware.UserID(c)
f := stores.WorkoutFilter{Limit: 20, Query: c.Query("q")}
@@ -60,7 +80,11 @@ func (h *Handler) CreateWorkout(c *gin.Context) {
if req.StartedAt.IsZero() {
req.StartedAt = time.Now()
}
- w, err := h.s.Workout.Create(uid, req)
+ // Snapshot, insert, and stage routine target suggestions in one transaction (issue
+ // #40) — closes a TOCTOU race where two concurrent submissions could both read the
+ // same stale prior best. Staging is still best-effort internally: a failure there
+ // never fails the already-saved workout.
+ w, progression, err := h.s.CreateWorkoutWithProgression(uid, req)
if utils.IsForeignKeyViolation(err) {
utils.BadRequest(c, "one or more exercises do not exist")
return
@@ -68,6 +92,7 @@ func (h *Handler) CreateWorkout(c *gin.Context) {
if utils.DBError(c, err) {
return
}
+ w.Progression = progression
utils.Created(c, w)
}
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index 07e514a..d778070 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -48,6 +48,13 @@ func alterMigrations() {
// Per-exercise rest timer (#33). Existing rows seed to 90s (on); 0 = off.
ensureColumn("program_exercises", "rest_seconds", `ALTER TABLE program_exercises ADD COLUMN rest_seconds INTEGER NOT NULL DEFAULT 90`)
ensureColumn("workout_exercises", "rest_seconds", `ALTER TABLE workout_exercises ADD COLUMN rest_seconds INTEGER NOT NULL DEFAULT 90`)
+
+ // Progressive-overload suggestions (#40). Nullable = "no pending suggestion";
+ // a suggestion exists when suggested_reps IS NOT NULL (weight+reps staged together).
+ // The user reviews + approves these on the routine; approving copies them into target_*.
+ ensureColumn("program_sets", "suggested_weight", `ALTER TABLE program_sets ADD COLUMN suggested_weight REAL`)
+ ensureColumn("program_sets", "suggested_reps", `ALTER TABLE program_sets ADD COLUMN suggested_reps INTEGER`)
+ ensureColumn("program_sets", "suggested_is_pr", `ALTER TABLE program_sets ADD COLUMN suggested_is_pr INTEGER NOT NULL DEFAULT 0`)
}
// ensureColumn adds a column to a table if it's missing — idempotent on every boot.
diff --git a/backend/models/models.go b/backend/models/models.go
index 93d2a02..b13326b 100644
--- a/backend/models/models.go
+++ b/backend/models/models.go
@@ -54,6 +54,29 @@ type Workout struct {
StartedAt time.Time `json:"started_at" db:"started_at"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
Exercises []WorkoutExercise `json:"exercises,omitempty"`
+ // Progression is set in-memory on the create response when finishing this
+ // workout auto-progressed routine targets (issue #40). Never persisted.
+ Progression *ProgressionResult `json:"progression,omitempty"`
+}
+
+// ProgressionResult summarizes staged auto-progression for the finish toast: which
+// routine, how many per-set targets got a pending suggestion, and whether any was an
+// all-time PR (drives the 🏆 toast). Transient (issue #40).
+type ProgressionResult struct {
+ ProgramID int64 `json:"program_id"`
+ ProgramName string `json:"program_name"`
+ Count int `json:"count"`
+ IsPR bool `json:"is_pr"`
+}
+
+// ResolveSuggestionsReq accepts or dismisses staged routine suggestions (#40) by
+// program_set id. Accepted ids copy suggested_* → target_*; both clear the suggestion.
+// max=500 bounds each list well above any plausible routine's set count — the store
+// loops one UPDATE per id inside a single transaction, so an unbounded list could hold
+// SQLite's writer lock for an extended period.
+type ResolveSuggestionsReq struct {
+ Accept []int64 `json:"accept" validate:"max=500"`
+ Dismiss []int64 `json:"dismiss" validate:"max=500"`
}
type WorkoutExercise struct {
@@ -164,12 +187,31 @@ type RefreshRequest struct {
RefreshToken string `json:"refresh_token" validate:"required"`
}
+// MaxWorkoutSets bounds the TOTAL number of sets across every exercise in a
+// CreateWorkoutRequest (sum of len(Exercises[i].Sets), not each list's own max=500
+// below independently) — enforced by the struct-level validation registered in
+// controllers/workouts.go's init(). Exercises/Sets each also carry their own
+// max=500 as a belt-and-suspenders per-list cap, but that alone doesn't bound their
+// product (500 exercises x 500 sets = 250,000 rows), which is what actually matters
+// since issue #40's CreateWorkoutWithProgression processes the whole request inside
+// one transaction holding the process's single SQLite connection
+// (db.DB.SetMaxOpenConns(1)) — see the total-sets check for why this constant, not
+// the per-list tags, is the real bound on that transaction's worst-case duration.
+const MaxWorkoutSets = 500
+
type CreateWorkoutRequest struct {
Name string `json:"name" validate:"required"`
Notes string `json:"notes"`
Duration int `json:"duration"`
StartedAt time.Time `json:"started_at"`
- Exercises []CreateWorkoutExerciseReq `json:"exercises"`
+ // ProgramID is set when the workout was started from a routine — it enables
+ // per-set auto-progression of that routine's targets (issue #40). nil for
+ // freestyle/quick workouts, which never progress a routine.
+ ProgramID *int64 `json:"program_id"`
+ // Exercises/Sets each cap at max=500 as an outer sanity bound, but that bounds
+ // each dimension independently, not their product — see MaxWorkoutSets above for
+ // the cap that actually matters.
+ Exercises []CreateWorkoutExerciseReq `json:"exercises" validate:"max=500,dive"`
}
type CreateWorkoutExerciseReq struct {
@@ -177,7 +219,7 @@ type CreateWorkoutExerciseReq struct {
OrderIndex int `json:"order_index"`
Notes string `json:"notes"`
RestSeconds int `json:"rest_seconds"`
- Sets []CreateSetReq `json:"sets"`
+ Sets []CreateSetReq `json:"sets" validate:"max=500"`
}
type CreateSetReq struct {
@@ -188,6 +230,10 @@ type CreateSetReq struct {
Distance float64 `json:"distance"`
RPE float64 `json:"rpe"`
IsWarmup bool `json:"is_warmup"`
+ // ProgramSetID links this logged set back to the routine set it came from, so
+ // auto-progression (issue #40) can bump exactly that target. nil for sets not
+ // sourced from a routine (freestyle, or ad-hoc sets added mid-workout).
+ ProgramSetID *int64 `json:"program_set_id"`
}
type LogWeightRequest struct {
@@ -260,6 +306,12 @@ type ProgramSet struct {
SetNumber int `json:"set_number"`
TargetReps int `json:"target_reps"`
TargetWeight float64 `json:"target_weight"`
+ // Pending auto-progression suggestion (#40) — nil when none. The user approves
+ // it on the routine, which copies suggested_* into target_*. SuggestedIsPR marks
+ // the set as also an all-time best (drives the 🏆 flair).
+ SuggestedWeight *float64 `json:"suggested_weight,omitempty"`
+ SuggestedReps *int `json:"suggested_reps,omitempty"`
+ SuggestedIsPR bool `json:"suggested_is_pr,omitempty"`
}
type CreateProgramRequest struct {
diff --git a/backend/routes/routes.go b/backend/routes/routes.go
index 2113465..453d349 100644
--- a/backend/routes/routes.go
+++ b/backend/routes/routes.go
@@ -87,6 +87,7 @@ func Setup(r *gin.Engine, h *controllers.Handler) {
protected.GET("programs/:id", h.GetProgram)
protected.PUT("programs/:id", h.UpdateProgram)
protected.DELETE("programs/:id", h.DeleteProgram)
+ protected.POST("programs/:id/suggestions/resolve", h.ResolveSuggestions)
// Admin
protected.POST("admin/sync-exercises", h.SyncExercises)
diff --git a/backend/stores/program.go b/backend/stores/program.go
index 86b9f0b..0de521b 100644
--- a/backend/stores/program.go
+++ b/backend/stores/program.go
@@ -137,6 +137,158 @@ func (s *ProgramStore) Update(uid, id int64, req models.CreateProgramRequest) (m
return s.get(id)
}
+// ProgressInput is one logged working set to consider for auto-progression:
+// the routine set it came from, what the user logged, and whether that logged set
+// was also an all-time best (computed by the controller from a pre-save PR snapshot).
+type ProgressInput struct {
+ ProgramSetID int64
+ Weight float64
+ Reps int
+ IsPR bool
+}
+
+// SuggestTargets stages (does NOT apply) a per-set target suggestion for each set the
+// user beat this workout (issue #40). The user later approves them on the routine via
+// ResolveSuggestions. Upward only, per progressedTarget. Returns the routine name, how
+// many suggestions were staged, and whether any was an all-time PR (drives the 🏆
+// toast). If the program isn't the caller's, nothing is touched (name "", count 0, no
+// error): the ownership check + the pe.program_id join stop a client from staging onto
+// another user's routine by guessing set ids.
+func (s *ProgramStore) SuggestTargets(uid, programID int64, sets []ProgressInput) (string, int, bool, error) {
+ var name string
+ var count int
+ var anyPR bool
+ err := inTxDo(s.db, func(tx *sql.Tx) error {
+ var err error
+ name, count, anyPR, err = suggestTargetsTx(tx, uid, programID, sets)
+ return err
+ })
+ if err != nil {
+ return "", 0, false, err
+ }
+ return name, count, anyPR, nil
+}
+
+// suggestTargetsTx is SuggestTargets' body, scoped to an existing transaction so a
+// caller can serialize it with an earlier PR-snapshot read and workout insert (see
+// WorkoutStore.CreateWithProgression) — closes a TOCTOU race where two concurrent
+// workout submissions could both compute suggested_is_pr against the same stale prior
+// best (issue #40 progression review).
+func suggestTargetsTx(tx *sql.Tx, uid, programID int64, sets []ProgressInput) (string, int, bool, error) {
+ var name string
+ count, anyPR := 0, false
+ if err := tx.QueryRow(`SELECT name FROM programs WHERE id = ? AND user_id = ?`, programID, uid).Scan(&name); err != nil {
+ if err == sql.ErrNoRows {
+ return "", 0, false, nil // not the caller's program — no-op, not an error
+ }
+ return "", 0, false, err
+ }
+ for _, in := range sets {
+ var curReps int
+ var curWeight float64
+ var sugReps sql.NullInt64
+ var sugWeight sql.NullFloat64
+ // Re-assert the set belongs to THIS (already-owned) program before touching it.
+ err := tx.QueryRow(
+ `SELECT ps.target_reps, ps.target_weight, ps.suggested_reps, ps.suggested_weight
+ FROM program_sets ps
+ JOIN program_exercises pe ON pe.id = ps.program_exercise_id
+ WHERE ps.id = ? AND pe.program_id = ?`,
+ in.ProgramSetID, programID,
+ ).Scan(&curReps, &curWeight, &sugReps, &sugWeight)
+ if err == sql.ErrNoRows {
+ continue // set isn't in this routine anymore (edited/deleted) — skip
+ }
+ if err != nil {
+ return "", 0, false, err
+ }
+ // Compare against the best of (current target, any pending suggestion) so a
+ // smaller-but-still-over-target set can't downgrade an un-approved PR (#40 edge).
+ baseReps, baseWeight := curReps, curWeight
+ if sugReps.Valid {
+ baseReps = int(sugReps.Int64)
+ }
+ if sugWeight.Valid {
+ baseWeight = sugWeight.Float64
+ }
+ newWeight, newReps, improved := progressedTarget(baseWeight, baseReps, in.Weight, in.Reps)
+ if !improved {
+ continue
+ }
+ if _, err := tx.Exec(
+ `UPDATE program_sets SET suggested_weight = ?, suggested_reps = ?, suggested_is_pr = ? WHERE id = ?`,
+ newWeight, newReps, in.IsPR, in.ProgramSetID,
+ ); err != nil {
+ return "", 0, false, err
+ }
+ count++
+ if in.IsPR {
+ anyPR = true
+ }
+ }
+ return name, count, anyPR, nil
+}
+
+// ResolveSuggestions applies (accept) or clears (dismiss) staged routine suggestions by
+// program_set id, then returns the refreshed program. Accepting copies suggested_* into
+// target_*; both paths clear the suggestion. Ownership-gated, and every id is re-scoped
+// to this program via the pe.program_id sub-select — the same IDOR guard as SuggestTargets,
+// so a client can't touch another user's routine by guessing ids.
+func (s *ProgramStore) ResolveSuggestions(uid, programID int64, accept, dismiss []int64) (models.Program, error) {
+ err := inTxDo(s.db, func(tx *sql.Tx) error {
+ var ownedID int64
+ if err := tx.QueryRow(`SELECT id FROM programs WHERE id = ? AND user_id = ?`, programID, uid).Scan(&ownedID); err != nil {
+ return err
+ }
+ owned := `AND program_exercise_id IN (SELECT id FROM program_exercises WHERE program_id = ?)`
+ for _, id := range accept {
+ if _, err := tx.Exec(
+ `UPDATE program_sets
+ SET target_weight = COALESCE(suggested_weight, target_weight),
+ target_reps = COALESCE(suggested_reps, target_reps),
+ suggested_weight = NULL, suggested_reps = NULL, suggested_is_pr = 0
+ WHERE id = ? `+owned,
+ id, programID,
+ ); err != nil {
+ return err
+ }
+ }
+ for _, id := range dismiss {
+ if _, err := tx.Exec(
+ `UPDATE program_sets
+ SET suggested_weight = NULL, suggested_reps = NULL, suggested_is_pr = 0
+ WHERE id = ? `+owned,
+ id, programID,
+ ); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return models.Program{}, err
+ }
+ return s.get(programID)
+}
+
+// progressedTarget applies the upward-only progression rule for a single set and
+// reports whether the target changed: a heavier logged weight raises the weight
+// and adopts the reps done at it; the same weight with more reps raises the reps;
+// equal-or-lighter leaves the target untouched (a deload never lowers a routine).
+// eps absorbs float drift from unit conversion so an unchanged weight still counts
+// as "same" for the reps branch.
+func progressedTarget(curWeight float64, curReps int, logWeight float64, logReps int) (float64, int, bool) {
+ const eps = 1e-6
+ switch {
+ case logWeight > curWeight+eps:
+ return logWeight, logReps, true
+ case logWeight >= curWeight-eps && logReps > curReps:
+ return curWeight, logReps, true
+ default:
+ return curWeight, curReps, false
+ }
+}
+
func (s *ProgramStore) Delete(uid, id int64) (int64, error) {
res, err := s.db.Exec(`DELETE FROM programs WHERE id = ? AND user_id = ?`, id, uid)
if err != nil {
@@ -221,7 +373,8 @@ func (s *ProgramStore) loadExercises(programID int64) ([]models.ProgramExercise,
func (s *ProgramStore) loadSets(programExerciseID int64) ([]models.ProgramSet, error) {
rows, err := s.db.Query(
- `SELECT id, program_exercise_id, set_number, target_reps, target_weight
+ `SELECT id, program_exercise_id, set_number, target_reps, target_weight,
+ suggested_weight, suggested_reps, suggested_is_pr
FROM program_sets WHERE program_exercise_id = ? ORDER BY set_number`,
programExerciseID,
)
@@ -232,9 +385,19 @@ func (s *ProgramStore) loadSets(programExerciseID int64) ([]models.ProgramSet, e
var sets []models.ProgramSet
for rows.Next() {
var st models.ProgramSet
- if err := rows.Scan(&st.ID, &st.ProgramExerciseID, &st.SetNumber, &st.TargetReps, &st.TargetWeight); err != nil {
+ var sw sql.NullFloat64
+ var sr sql.NullInt64
+ if err := rows.Scan(&st.ID, &st.ProgramExerciseID, &st.SetNumber, &st.TargetReps, &st.TargetWeight,
+ &sw, &sr, &st.SuggestedIsPR); err != nil {
return nil, err
}
+ if sw.Valid {
+ st.SuggestedWeight = &sw.Float64
+ }
+ if sr.Valid {
+ r := int(sr.Int64)
+ st.SuggestedReps = &r
+ }
sets = append(sets, st)
}
return sets, rows.Err()
diff --git a/backend/stores/stores.go b/backend/stores/stores.go
index 13456ab..f6bb3b3 100644
--- a/backend/stores/stores.go
+++ b/backend/stores/stores.go
@@ -16,6 +16,7 @@ type Stores struct {
Exercise *ExerciseStore
Workout *WorkoutStore
Program *ProgramStore
+ db *sql.DB // for operations that must span two stores in one transaction
}
func New(db *sql.DB) *Stores {
@@ -27,6 +28,7 @@ func New(db *sql.DB) *Stores {
Exercise: NewExerciseStore(db),
Workout: NewWorkoutStore(db),
Program: NewProgramStore(db),
+ db: db,
}
}
diff --git a/backend/stores/workout.go b/backend/stores/workout.go
index 9aa4c80..6eafd4f 100644
--- a/backend/stores/workout.go
+++ b/backend/stores/workout.go
@@ -99,21 +99,7 @@ func (s *WorkoutStore) get(id int64) (models.Workout, error) {
func (s *WorkoutStore) Create(uid int64, req models.CreateWorkoutRequest) (models.Workout, error) {
wid, err := inTx(s.db, func(tx *sql.Tx) (int64, error) {
- res, err := tx.Exec(
- `INSERT INTO workouts (user_id, name, notes, duration, started_at) VALUES (?, ?, ?, ?, ?)`,
- uid, req.Name, req.Notes, req.Duration, req.StartedAt,
- )
- if err != nil {
- return 0, err
- }
- wid, err := res.LastInsertId()
- if err != nil {
- return 0, err
- }
- if err := insertWorkoutExercises(tx, wid, req.Exercises); err != nil {
- return 0, err
- }
- return wid, nil
+ return createWorkoutTx(tx, uid, req)
})
if err != nil {
return models.Workout{}, err
@@ -121,6 +107,29 @@ func (s *WorkoutStore) Create(uid int64, req models.CreateWorkoutRequest) (model
return s.get(wid)
}
+// createWorkoutTx inserts the workout + its exercises/sets within an existing
+// transaction, returning the new workout id. Factored out of Create so the
+// PR-snapshot read, the insert, and the suggestion-staging write can share one
+// transaction (see CreateWithProgression) — SQLite then serializes concurrent
+// submissions instead of letting them read the same stale prior-best (#40).
+func createWorkoutTx(tx *sql.Tx, uid int64, req models.CreateWorkoutRequest) (int64, error) {
+ res, err := tx.Exec(
+ `INSERT INTO workouts (user_id, name, notes, duration, started_at) VALUES (?, ?, ?, ?, ?)`,
+ uid, req.Name, req.Notes, req.Duration, req.StartedAt,
+ )
+ if err != nil {
+ return 0, err
+ }
+ wid, err := res.LastInsertId()
+ if err != nil {
+ return 0, err
+ }
+ if err := insertWorkoutExercises(tx, wid, req.Exercises); err != nil {
+ return 0, err
+ }
+ return wid, nil
+}
+
// Update replaces a user-owned workout and its children in one tx. sql.ErrNoRows
// if the workout isn't theirs (nothing is mutated).
func (s *WorkoutStore) Update(uid, id int64, req models.CreateWorkoutRequest) (models.Workout, error) {
@@ -280,8 +289,17 @@ type ExerciseHistoryPoint struct {
// they have no qualifying (non-warmup, weighted) set. Reads workout tables — this
// is workout-derived analytics keyed by exercise, so it lives on WorkoutStore.
func (s *WorkoutStore) PRForExercise(uid, exerciseID int64) (ExercisePR, error) {
+ return prForExerciseTx(s.db, uid, exerciseID)
+}
+
+// prForExerciseTx runs the PRForExercise query against anything that can QueryRow —
+// s.db for the standalone read, or an existing *sql.Tx when the read must be
+// serialized with a later write in the same transaction (see CreateWithProgression).
+func prForExerciseTx(q interface {
+ QueryRow(query string, args ...any) *sql.Row
+}, uid, exerciseID int64) (ExercisePR, error) {
var pr ExercisePR
- err := s.db.QueryRow(`
+ err := q.QueryRow(`
SELECT s.weight, s.reps, w.started_at, w.id
FROM sets s
JOIN workout_exercises we ON we.id = s.workout_exercise_id
diff --git a/backend/stores/workout_progression.go b/backend/stores/workout_progression.go
new file mode 100644
index 0000000..b533c9f
--- /dev/null
+++ b/backend/stores/workout_progression.go
@@ -0,0 +1,152 @@
+package stores
+
+import (
+ "database/sql"
+ "log"
+
+ "github.com/Cawlumm/lyftr-backend/models"
+)
+
+// CreateWorkoutWithProgression creates a workout and, if it came from a routine,
+// stages auto-progression suggestions (issue #40) for the sets the user beat — all in
+// ONE transaction.
+//
+// The PR-snapshot read (what's the current best for each exercise), the workout
+// insert, and the suggestion-staging write used to run as separate transactions
+// (snapshot read → Workout.Create → progressRoutine/SuggestTargets). Two concurrent
+// workout submissions for the same exercise could both read the identical "prior
+// best" before either committed, so both could get flagged suggested_is_pr = true
+// even though only the one that actually committed last was the genuine all-time
+// best. Reading the prior best and staging the suggestion inside the same
+// transaction as the insert lets SQLite's writer-serialization close that race: a
+// concurrent commit landing between this transaction's snapshot read and its own
+// commit now fails this transaction outright (surfaced as a DB error) rather than
+// silently persisting a wrong PR flag.
+//
+// Suggestion-staging stays best-effort: if it errors, the error is logged and
+// dropped so the already-inserted workout still commits — never fail a save the
+// user is waiting on because routine bookkeeping hiccuped. Its (possibly partial)
+// writes are rolled back via a SAVEPOINT rather than left committed, so "dropped"
+// stays true even now that staging shares a transaction with the insert.
+//
+// This does widen the critical section: with db.DB.SetMaxOpenConns(1), the whole
+// PR-snapshot + insert + suggestion-staging sequence now holds the process's one
+// connection for its full duration instead of releasing it between the three
+// steps. That's an accepted tradeoff for closing the TOCTOU race above — the race
+// specifically requires the snapshot read and the dependent write to be
+// serialized — not an oversight. Exercises and Sets each independently capping at
+// max=500 (models.go) does NOT bound that widened section, since it bounds each
+// dimension separately, not their product — the actual bound is the total-sets
+// struct-level validation (models.MaxWorkoutSets, enforced in
+// controllers/workouts.go's init()), which caps sum(len(Exercises[i].Sets)) across
+// the whole request.
+func (s *Stores) CreateWorkoutWithProgression(uid int64, req models.CreateWorkoutRequest) (models.Workout, *models.ProgressionResult, error) {
+ var wid int64
+ var progression *models.ProgressionResult
+ err := inTxDo(s.db, func(tx *sql.Tx) error {
+ priors := snapshotPRsTx(tx, uid, req)
+
+ id, err := createWorkoutTx(tx, uid, req)
+ if err != nil {
+ return err
+ }
+ wid = id
+
+ // Run suggestion-staging under its own SAVEPOINT: a mid-loop error must only
+ // undo staging's own (possibly partial) UPDATEs, never the workout insert above.
+ if _, spErr := tx.Exec("SAVEPOINT suggest_targets"); spErr != nil {
+ log.Printf("[workouts/progress] uid=%d: savepoint: %v", uid, spErr)
+ return nil
+ }
+ p, pErr := progressRoutineTx(tx, uid, req, priors)
+ if pErr != nil {
+ log.Printf("[workouts/progress] uid=%d: %v", uid, pErr)
+ if _, rbErr := tx.Exec("ROLLBACK TO SAVEPOINT suggest_targets"); rbErr != nil {
+ // The savepoint rollback itself failed, so staging's partial writes
+ // can no longer be undone in isolation — fail the whole transaction
+ // (the outer inTxDo rolls everything back) rather than let it commit
+ // with partially-applied suggestion writes the caller was told about
+ // as "dropped".
+ log.Printf("[workouts/progress] uid=%d: rollback savepoint: %v", uid, rbErr)
+ return rbErr
+ }
+ return nil
+ }
+ progression = p
+ if _, relErr := tx.Exec("RELEASE SAVEPOINT suggest_targets"); relErr != nil {
+ log.Printf("[workouts/progress] uid=%d: release savepoint: %v", uid, relErr)
+ }
+ return nil
+ })
+ if err != nil {
+ return models.Workout{}, nil, err
+ }
+ w, err := s.Workout.get(wid)
+ if err != nil {
+ return models.Workout{}, nil, err
+ }
+ return w, progression, nil
+}
+
+// snapshotPRsTx records each routine exercise's current best (weight desc, then
+// reps) before the workout is saved, so is-PR can be judged against the prior best.
+// Empty for freestyle workouts. A missing PR (no rows) is recorded as absent.
+func snapshotPRsTx(tx *sql.Tx, uid int64, req models.CreateWorkoutRequest) map[int64]*ExercisePR {
+ if req.ProgramID == nil {
+ return nil
+ }
+ priors := make(map[int64]*ExercisePR)
+ for _, ex := range req.Exercises {
+ if _, seen := priors[ex.ExerciseID]; seen {
+ continue
+ }
+ pr, err := prForExerciseTx(tx, uid, ex.ExerciseID)
+ if err != nil {
+ priors[ex.ExerciseID] = nil // no prior best (first time) or lookup failed
+ continue
+ }
+ p := pr
+ priors[ex.ExerciseID] = &p
+ }
+ return priors
+}
+
+// progressRoutineTx stages a target suggestion for each set the user beat, flagging
+// all-time PRs, and returns a summary for the finish toast (nil if nothing staged or
+// the workout wasn't from a routine). Only sets carrying a program_set_id count; the
+// store enforces ownership.
+func progressRoutineTx(tx *sql.Tx, uid int64, req models.CreateWorkoutRequest, priors map[int64]*ExercisePR) (*models.ProgressionResult, error) {
+ if req.ProgramID == nil {
+ return nil, nil
+ }
+ const eps = 1e-6
+ var inputs []ProgressInput
+ for _, ex := range req.Exercises {
+ for _, st := range ex.Sets {
+ if st.ProgramSetID == nil || st.IsWarmup {
+ continue
+ }
+ prior := priors[ex.ExerciseID]
+ isPR := prior == nil ||
+ st.Weight > prior.Weight+eps ||
+ (st.Weight >= prior.Weight-eps && st.Reps > prior.Reps)
+ inputs = append(inputs, ProgressInput{
+ ProgramSetID: *st.ProgramSetID,
+ Weight: st.Weight,
+ Reps: st.Reps,
+ IsPR: isPR,
+ })
+ }
+ }
+ if len(inputs) == 0 {
+ return nil, nil
+ }
+ name, count, anyPR, err := suggestTargetsTx(tx, uid, *req.ProgramID, inputs)
+ if err != nil {
+ return nil, err
+ }
+ if count == 0 {
+ return nil, nil
+ }
+ return &models.ProgressionResult{ProgramID: *req.ProgramID, ProgramName: name, Count: count, IsPR: anyPR}, nil
+}
diff --git a/mobile/.maestro/progressive_overload.yaml b/mobile/.maestro/progressive_overload.yaml
new file mode 100644
index 0000000..43baa4d
--- /dev/null
+++ b/mobile/.maestro/progressive_overload.yaml
@@ -0,0 +1,58 @@
+appId: host.exp.exponent
+---
+# End-to-end check for the progressive-overload feature (#40): finish a routine
+# workout that beats a set target, confirm the finish toast, then confirm the
+# routine's review banner and approve the suggestion.
+#
+# Requires: Metro + backend running locally, an emulator/device with Expo Go
+# already logged into an account that owns "Tuesday - Pull (Back Width)" (the
+# demo seed data). Run with:
+# maestro test mobile/.maestro/progressive_overload.yaml
+
+- pressKey: Back
+- pressKey: Home
+- openLink: "exp://127.0.0.1:8081"
+
+# openLink only resets to Home on a cold start; if Expo Go was already running it
+# just resumes wherever the app was left. Land on a known tab either way.
+- tapOn: "Workouts"
+- runFlow:
+ when:
+ visible: "Cancel Workout"
+ commands:
+ - tapOn: "Cancel Workout"
+ - tapOn:
+ text: "Cancel Workout"
+ index: 1
+
+- tapOn: "Programs"
+- tapOn: "Tuesday - Pull (Back Width)"
+- tapOn: "Start"
+
+# Beat set 1's target weight on the first exercise.
+- tapOn:
+ text: "Weight, set 1, Full Range-Of-Motion Lat Pulldown"
+- eraseText: 8
+- inputText: "500"
+- hideKeyboard
+- tapOn:
+ text: "Complete set 1, Full Range-Of-Motion Lat Pulldown"
+- tapOn: "Finish"
+- tapOn: "Finish"
+
+# Finish toast — PR or plain "new targets", either is fine. Best-effort: it's a
+# transient 4s auto-dismiss overlay racing the save+navigate round-trip, so a miss
+# here isn't a regression — the banner check below is the reliable assertion.
+- extendedWaitUntil:
+ visible: "New (PR|targets) in Tuesday - Pull \\(Back Width\\)"
+ timeout: 8000
+ optional: true
+- takeScreenshot: finish_toast
+
+# Review banner on the routine screen.
+- tapOn: "Programs"
+- tapOn: "Tuesday - Pull (Back Width)"
+- assertVisible: "New targets from your last workout"
+- takeScreenshot: review_banner
+- tapOn: "Apply all (1)"
+- assertNotVisible: "New targets from your last workout"
diff --git a/mobile/app/(tabs)/programs/[id].tsx b/mobile/app/(tabs)/programs/[id].tsx
index 501a05e..297e51f 100644
--- a/mobile/app/(tabs)/programs/[id].tsx
+++ b/mobile/app/(tabs)/programs/[id].tsx
@@ -1,9 +1,10 @@
-import { useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import { Pressable, ScrollView, View } from 'react-native'
-import { router, useLocalSearchParams, type Href } from 'expo-router'
+import { router, useFocusEffect, useLocalSearchParams, type Href } from 'expo-router'
import { format } from 'date-fns'
import {
- AlertCircle, ArrowLeft, BookOpen, ChevronRight, Dumbbell, Edit2, Layers, Pause, Play, TimerOff, Trash2,
+ AlertCircle, ArrowLeft, Award, BookOpen, Check, ChevronDown, ChevronRight, ChevronUp, Dumbbell, Edit2,
+ Layers, Pause, Play, TimerOff, TrendingUp, Trash2, X,
} from 'lucide-react-native'
import {
apiErrorMessage, displayWeight, weightShort,
@@ -24,14 +25,18 @@ const activeHref = '/workouts/active' as unknown as Href
const restLabel = (s: number) => (s % 60 === 0 && s >= 60 ? `${s / 60}m` : `${s}s`)
-function SetChip({ set, isBest, unit }: { set: ProgramSet; isBest: boolean; unit: string }) {
+// Rows shown before the review banner collapses behind a "Show all" toggle (#40).
+const SUGGESTION_CAP = 3
+
+function SetChip({ set, isBest, hasSuggestion, unit }: { set: ProgramSet; isBest: boolean; hasSuggestion: boolean; unit: string }) {
return (
<View
- className={`px-2.5 py-1.5 rounded-lg ${
- isBest ? 'bg-brand-500/15 border border-brand-500/25' : 'bg-surface-raised border border-transparent'
+ className={`px-2.5 py-1.5 rounded-lg border ${
+ hasSuggestion ? 'bg-warning-500/10 border-warning-500/40'
+ : isBest ? 'bg-brand-500/15 border-brand-500/25' : 'bg-surface-raised border-transparent'
}`}
>
- <AppText variant="caption" color={isBest ? 'brand' : 'secondary'} style={{ fontVariant: ['tabular-nums'] }}>
+ <AppText variant="caption" color={hasSuggestion ? 'secondary' : isBest ? 'brand' : 'secondary'} style={{ fontVariant: ['tabular-nums'] }}>
{set.target_reps > 0 ? set.target_reps : '—'} ×{' '}
{set.target_weight > 0 ? `${displayWeight(set.target_weight, unit)} ${unit}` : 'BW'}
</AppText>
@@ -39,6 +44,16 @@ function SetChip({ set, isBest, unit }: { set: ProgramSet; isBest: boolean; unit
)
}
+// One pending auto-progression suggestion (#40), flattened for the review banner.
+interface Suggestion {
+ setId: number
+ exName: string
+ setNumber: number
+ isPR: boolean
+ oldLabel: string
+ newLabel: string
+}
+
function MuscleBadge({ muscle }: { muscle: string }) {
const { colors } = useTheme()
const tint = muscleColor(muscle)
@@ -63,26 +78,70 @@ export default function ProgramDetail() {
const [error, setError] = useState<string | null>(null)
const [deleting, setDeleting] = useState(false)
const [confirming, setConfirming] = useState(false)
+ const [resolving, setResolving] = useState(false)
+ const [showAllSuggestions, setShowAllSuggestions] = useState(false)
useEffect(() => {
fetchSettings()
}, [fetchSettings])
- useEffect(() => {
- let cancelled = false
- const load = async () => {
- try {
- const data = await client.programAPI.get(Number(id))
- if (!cancelled) setProgram(data)
- } catch (err) {
- if (!cancelled) setError(apiErrorMessage(err, 'Failed to load program'))
- } finally {
- if (!cancelled) setLoading(false)
- }
+ // Bumped by both the focus refetch and resolveSuggestions. "Last dispatched wins"
+ // isn't enough on its own — the GET and the PATCH are independent HTTP requests, so
+ // a focus refetch dispatched AFTER an Accept/Dismiss tap can still have its response
+ // computed from a server-side read that lands before the PATCH commits, and land
+ // either before or after the PATCH's own response. So resolveSuggestions applies its
+ // result unconditionally (only one can ever be in flight — the `resolving` guard
+ // below blocks a second tap) and bumps the seq again AFTER doing so, invalidating
+ // any refetch that was dispatched at any point up to that moment, however its
+ // response happens to be ordered.
+ const requestSeq = useRef(0)
+
+ // Accept (apply → target) or dismiss staged auto-progression suggestions (#40),
+ // then refresh from the returned program.
+ const resolveSuggestions = async (accept: number[], dismiss: number[]) => {
+ if (!program || resolving) return
+ setResolving(true)
+ ++requestSeq.current
+ try {
+ const updated = await client.programAPI.resolveSuggestions(program.id, { accept, dismiss })
+ setProgram(updated)
+ // Invalidate any focus refetch still in flight from before this point — its
+ // response can't be trusted to reflect this write, whichever order it lands in.
+ ++requestSeq.current
+ } catch {
+ // leave the banner in place so the user can retry
+ } finally {
+ setResolving(false)
}
- load()
- return () => { cancelled = true }
- }, [id])
+ }
+
+ // Refetch on every focus (not just mount) — otherwise a routine reopened from the tab
+ // bar shows whatever it looked like when the screen was first pushed, missing targets
+ // approved elsewhere or auto-progression suggestions staged by a workout finished since
+ // (#40). `loading` only gates the very first render — later refetches update silently
+ // so revisiting the screen doesn't flash the full-screen spinner over existing content.
+ // A refetch failure only surfaces the full-screen error when nothing has loaded yet —
+ // once a program is showing, a transient refocus failure leaves it in place instead of
+ // wiping the screen (matches the dashboard's focus-refetch, which doesn't setError at all).
+ const loadedRef = useRef(false)
+ useFocusEffect(
+ useCallback(() => {
+ let cancelled = false
+ const load = async () => {
+ const seq = ++requestSeq.current
+ try {
+ const data = await client.programAPI.get(Number(id))
+ if (!cancelled && requestSeq.current === seq) { setProgram(data); setError(null); loadedRef.current = true }
+ } catch (err) {
+ if (!cancelled && !loadedRef.current) setError(apiErrorMessage(err, 'Failed to load program'))
+ } finally {
+ if (!cancelled) setLoading(false)
+ }
+ }
+ load()
+ return () => { cancelled = true }
+ }, [id])
+ )
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/programs'))
@@ -143,6 +202,43 @@ export default function ProgramDetail() {
const exs = program.exercises ?? []
const totalSets = exs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)
+ // Pending auto-progression suggestions (#40). A suggestion exists when suggested_reps
+ // is set. Show the FULL reps×weight on both sides when both changed (a heavier set can
+ // also drop the rep target — the user must see that before approving), else the single
+ // changed dimension.
+ const suggestions: Suggestion[] = exs.flatMap((ex) =>
+ (ex.sets ?? [])
+ .filter((s) => s.id != null && s.suggested_reps != null)
+ .map((s) => {
+ const sw = s.suggested_weight as number
+ const sr = s.suggested_reps as number
+ const weightChanged = s.suggested_weight != null && Math.abs(sw - s.target_weight) > 1e-6
+ const repsChanged = sr !== s.target_reps
+ const wLabel = (v: number) => (v > 0 ? `${displayWeight(v, wUnit)} ${wUnit}` : 'BW')
+ let oldLabel: string, newLabel: string
+ if (weightChanged && repsChanged) {
+ oldLabel = `${s.target_reps} × ${wLabel(s.target_weight)}`
+ newLabel = `${sr} × ${wLabel(sw)}`
+ } else if (weightChanged) {
+ oldLabel = wLabel(s.target_weight)
+ newLabel = wLabel(sw)
+ } else {
+ oldLabel = `${s.target_reps}`
+ newLabel = `${sr} reps`
+ }
+ return {
+ setId: s.id as number,
+ exName: ex.exercise?.name ?? 'Exercise',
+ setNumber: s.set_number,
+ isPR: !!s.suggested_is_pr,
+ oldLabel,
+ newLabel,
+ }
+ })
+ )
+ const suggestedSetIds = suggestions.map((s) => s.setId)
+ const warningColor = isDark ? brand.warningSoft : brand.warning
+
return (
<Screen>
<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: 32 }}>
@@ -197,6 +293,81 @@ export default function ProgramDetail() {
onCancel={() => setConfirming(false)}
/>
+ {/* Auto-progression review banner (#40) — approve the targets you beat last workout */}
+ {suggestions.length > 0 && (
+ <View className="bg-surface-raised border border-warning-500/30 rounded-2xl overflow-hidden">
+ <View className="flex-row items-center gap-2 px-4 py-3">
+ {suggestions.some((s) => s.isPR)
+ ? <Award size={16} color={warningColor} />
+ : <TrendingUp size={16} color={warningColor} />}
+ <AppText variant="bodySemibold" className="flex-1">New targets from your last workout</AppText>
+ <View className="bg-warning-500/15 rounded-full px-2 py-0.5">
+ <AppText variant="caption" style={{ color: warningColor, fontWeight: 'bold' }}>{suggestions.length}</AppText>
+ </View>
+ </View>
+ {(showAllSuggestions ? suggestions : suggestions.slice(0, SUGGESTION_CAP)).map((sg) => (
+ <View key={sg.setId} className="flex-row items-center gap-3 px-4 py-2.5 border-t border-surface-border/60">
+ <View className="flex-1 flex-row items-center gap-1.5 min-w-0">
+ {sg.isPR ? <Award size={14} color={warningColor} /> : null}
+ <AppText variant="caption" color="secondary" numberOfLines={1} className="flex-1">
+ <AppText variant="caption" color="primary" style={{ fontWeight: '600' }}>{sg.exName}</AppText> · Set {sg.setNumber}
+ </AppText>
+ </View>
+ <View className="flex-row items-center flex-shrink-0">
+ <AppText variant="caption" color="muted" style={{ fontVariant: ['tabular-nums'], textDecorationLine: 'line-through' }}>{sg.oldLabel}</AppText>
+ <AppText variant="caption" style={{ color: warningColor, marginHorizontal: 6 }}>→</AppText>
+ <AppText variant="bodySemibold" style={{ fontVariant: ['tabular-nums'] }}>{sg.newLabel}</AppText>
+ </View>
+ <View className="flex-row gap-1.5 flex-shrink-0">
+ <Pressable
+ onPress={() => resolveSuggestions([sg.setId], [])}
+ disabled={resolving}
+ accessibilityLabel={`Accept ${sg.exName} set ${sg.setNumber}`}
+ className={`w-7 h-7 rounded-lg bg-success-500/15 items-center justify-center active:scale-95 ${resolving ? 'opacity-50' : ''}`}
+ >
+ <Check size={14} color={isDark ? brand.successSoft : brand.success} strokeWidth={3} />
+ </Pressable>
+ <Pressable
+ onPress={() => resolveSuggestions([], [sg.setId])}
+ disabled={resolving}
+ accessibilityLabel={`Dismiss ${sg.exName} set ${sg.setNumber}`}
+ className={`w-7 h-7 rounded-lg bg-surface-muted items-center justify-center active:scale-95 ${resolving ? 'opacity-50' : ''}`}
+ >
+ <X size={14} color={colors.txMuted} strokeWidth={3} />
+ </Pressable>
+ </View>
+ </View>
+ ))}
+ {suggestions.length > SUGGESTION_CAP && (
+ <Pressable
+ onPress={() => setShowAllSuggestions((v) => !v)}
+ className="flex-row items-center justify-center gap-1.5 py-2 border-t border-surface-border/60 active:opacity-60"
+ >
+ <AppText variant="caption" style={{ color: warningColor, fontWeight: '600' }}>
+ {showAllSuggestions ? 'Show less' : `Show all ${suggestions.length}`}
+ </AppText>
+ {showAllSuggestions ? <ChevronUp size={14} color={warningColor} /> : <ChevronDown size={14} color={warningColor} />}
+ </Pressable>
+ )}
+ <View className="flex-row gap-2 px-4 py-3 border-t border-surface-border/60">
+ <Pressable
+ onPress={() => resolveSuggestions([], suggestedSetIds)}
+ disabled={resolving}
+ className={`flex-1 py-2 rounded-lg bg-surface-muted border border-surface-border items-center active:scale-95 ${resolving ? 'opacity-50' : ''}`}
+ >
+ <AppText variant="bodySemibold" color="secondary">Dismiss all</AppText>
+ </Pressable>
+ <Pressable
+ onPress={() => resolveSuggestions(suggestedSetIds, [])}
+ disabled={resolving}
+ className={`flex-1 py-2 rounded-lg bg-warning-500 items-center active:scale-95 ${resolving ? 'opacity-50' : ''}`}
+ >
+ <AppText variant="bodySemibold" style={{ color: brand.warningText }}>Apply all ({suggestions.length})</AppText>
+ </Pressable>
+ </View>
+ </View>
+ )}
+
{/* Header card */}
<View className="bg-surface-raised border border-surface-border rounded-2xl p-4">
<View className="flex-row items-start gap-3">
@@ -272,7 +443,7 @@ export default function ProgramDetail() {
<View className="flex-row items-center gap-2 px-4 pb-4 pt-3 border-t border-surface-border/50">
<View className="flex-1 flex-row flex-wrap gap-1.5">
{sets.map((set, i) => (
- <SetChip key={i} set={set} isBest={set.target_weight === maxTargetLbs && maxTargetLbs > 0} unit={wUnit} />
+ <SetChip key={i} set={set} isBest={set.target_weight === maxTargetLbs && maxTargetLbs > 0} hasSuggestion={set.suggested_reps != null} unit={wUnit} />
))}
</View>
{restOn && (
diff --git a/mobile/app/(tabs)/workouts/active.tsx b/mobile/app/(tabs)/workouts/active.tsx
index 118db7f..0ee813b 100644
--- a/mobile/app/(tabs)/workouts/active.tsx
+++ b/mobile/app/(tabs)/workouts/active.tsx
@@ -84,7 +84,7 @@ export default function ActiveWorkout() {
setSaveError('')
try {
const created = await client.workoutAPI.create(buildPayload())
- setOutcome({ kind: 'saved', workoutId: created.id })
+ setOutcome({ kind: 'saved', workoutId: created.id, progression: created.progression })
cancelSession()
router.replace('/workouts')
} catch (err: any) {
@@ -271,6 +271,7 @@ export default function ActiveWorkout() {
placeholder="+ Add note…"
placeholderTextColor={colors.txMuted}
className="font-sans text-xs text-tx-secondary"
+ accessibilityLabel={`Notes, ${ex.exercise.name}`}
/>
</View>
@@ -304,6 +305,7 @@ export default function ActiveWorkout() {
placeholderTextColor={colors.txMuted}
className={`${CELL} ${set.completed ? 'opacity-40' : ''}`}
style={{ fontVariant: ['tabular-nums'] }}
+ accessibilityLabel={`Reps, set ${set.set_number}, ${ex.exercise.name}`}
/>
</View>
<View className="flex-1">
@@ -322,9 +324,15 @@ export default function ActiveWorkout() {
placeholderTextColor={colors.txMuted}
className={`${CELL} ${set.completed ? 'opacity-40' : ''}`}
style={{ fontVariant: ['tabular-nums'] }}
+ accessibilityLabel={`Weight, set ${set.set_number}, ${ex.exercise.name}`}
/>
</View>
- <Pressable onPress={() => handleCompleteSet(exIdx, setIdx)} className={`h-11 w-12 items-center justify-center ${set.completed ? 'bg-brand-500' : isNextSet ? 'bg-brand-500/20' : ''}`}>
+ <Pressable
+ onPress={() => handleCompleteSet(exIdx, setIdx)}
+ className={`h-11 w-12 items-center justify-center ${set.completed ? 'bg-brand-500' : isNextSet ? 'bg-brand-500/20' : ''}`}
+ accessibilityRole="button"
+ accessibilityLabel={`${set.completed ? 'Completed' : 'Complete'} set ${set.set_number}, ${ex.exercise.name}`}
+ >
<CheckCircle2 size={24} color={set.completed ? '#ffffff' : isNextSet ? accent : colors.txMuted} />
</Pressable>
<Pressable onPress={() => removeSet(exIdx, setIdx)} hitSlop={6} accessibilityLabel="Remove set" className="w-7 items-center justify-center">
diff --git a/mobile/app/(tabs)/workouts/index.tsx b/mobile/app/(tabs)/workouts/index.tsx
index 00152a3..1632735 100644
--- a/mobile/app/(tabs)/workouts/index.tsx
+++ b/mobile/app/(tabs)/workouts/index.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { ActivityIndicator, FlatList, RefreshControl, View } from 'react-native'
-import { router, useFocusEffect } from 'expo-router'
-import { CheckCircle2, Dumbbell, Plus, RotateCcw } from 'lucide-react-native'
+import { router, useFocusEffect, type Href } from 'expo-router'
+import { Award, CheckCircle2, Dumbbell, Plus, RotateCcw, TrendingUp } from 'lucide-react-native'
import { weightShort, type Workout } from '@lyftr/shared'
import { AppText, Card, EmptyState, IconButton, Label, PageHeader, Screen, SearchField, Toast } from '../../../src/components/ui'
import { WorkoutCard } from '../../../src/components/workouts/WorkoutCard'
@@ -11,6 +11,10 @@ import { client, useSettingsStore, useWorkoutSession } from '../../../src/lib/ly
import { useWorkoutOutcome } from '../../../src/lib/workoutOutcome'
import { useTheme } from '../../../src/theme/useTheme'
+// Cross-tab jump (workouts → programs), same rule as programs/[id]'s handleStart:
+// router.navigate, not push, or it corrupts the native tab/back stack.
+const programHref = (id: number) => `/programs/${id}` as unknown as Href
+
export default function Workouts() {
const settings = useSettingsStore((s) => s.settings)
const fetchSettings = useSettingsStore((s) => s.fetch)
@@ -190,17 +194,32 @@ export default function Workouts() {
(restores the exact session snapshot and drops you back into it). */}
{outcome ? (
outcome.kind === 'saved' ? (
- <Toast
- variant="success"
- icon={CheckCircle2}
- title="Workout saved"
- description="Tap to view"
- onPress={() => {
- clearOutcome()
- router.push(`/workouts/${outcome.workoutId}`)
- }}
- onDismiss={clearOutcome}
- />
+ outcome.progression ? (
+ <Toast
+ variant={outcome.progression.is_pr ? 'warning' : 'success'}
+ icon={outcome.progression.is_pr ? Award : TrendingUp}
+ title={outcome.progression.is_pr ? `New PR in ${outcome.progression.program_name}` : `New targets in ${outcome.progression.program_name}`}
+ description={`Tap to review ${outcome.progression.count} ${outcome.progression.count === 1 ? 'update' : 'updates'}`}
+ onPress={() => {
+ const programId = outcome.progression!.program_id
+ clearOutcome()
+ router.navigate(programHref(programId))
+ }}
+ onDismiss={clearOutcome}
+ />
+ ) : (
+ <Toast
+ variant="success"
+ icon={CheckCircle2}
+ title="Workout saved"
+ description="Tap to view"
+ onPress={() => {
+ clearOutcome()
+ router.push(`/workouts/${outcome.workoutId}`)
+ }}
+ onDismiss={clearOutcome}
+ />
+ )
) : (
<Toast
variant="default"
diff --git a/mobile/src/components/workouts/GymModeWorkout.tsx b/mobile/src/components/workouts/GymModeWorkout.tsx
index ecf9e03..2020a80 100644
--- a/mobile/src/components/workouts/GymModeWorkout.tsx
+++ b/mobile/src/components/workouts/GymModeWorkout.tsx
@@ -123,7 +123,7 @@ export function GymModeWorkout() {
setSaving(true)
try {
const created = await client.workoutAPI.create(buildPayload())
- setOutcome({ kind: 'saved', workoutId: created.id })
+ setOutcome({ kind: 'saved', workoutId: created.id, progression: created.progression })
cancelSession()
minimizeGym()
router.replace('/workouts')
diff --git a/mobile/src/lib/workoutOutcome.ts b/mobile/src/lib/workoutOutcome.ts
index 226ec56..ee8a60d 100644
--- a/mobile/src/lib/workoutOutcome.ts
+++ b/mobile/src/lib/workoutOutcome.ts
@@ -1,12 +1,14 @@
import { create } from 'zustand'
-import type { ActiveSession } from '@lyftr/shared'
+import type { ActiveSession, ProgressionResult } from '@lyftr/shared'
// A one-shot signal handed from the session teardown (gym overlay / active list) to the
// Workouts list, which shows a confirmation toast on arrival. The overlay unmounts and we
// navigate, so a tiny store is the courier. 'discarded' carries the session snapshot so the
-// toast's "Tap to undo" can restore it verbatim. Mobile-only (UI feedback, never persisted).
+// toast's "Tap to undo" can restore it verbatim. 'saved' carries an optional `progression`
+// (#40) when finishing beat a routine target — the list shows the PR/targets toast instead
+// of the generic save confirmation. Mobile-only (UI feedback, never persisted).
export type WorkoutOutcome =
- | { kind: 'saved'; workoutId: number }
+ | { kind: 'saved'; workoutId: number; progression?: ProgressionResult }
| { kind: 'discarded'; session: ActiveSession }
| null
diff --git a/mobile/src/theme/theme.ts b/mobile/src/theme/theme.ts
index aaa69f5..9597d92 100644
--- a/mobile/src/theme/theme.ts
+++ b/mobile/src/theme/theme.ts
@@ -51,4 +51,9 @@ export const brand = {
errorSoft: '#f87171',
warning: '#eab308',
warningSoft: '#facc15',
+ // Near-black text for content sitting directly on a solid warning-500 fill (e.g.
+ // "Apply all") — mirrors web's ProgramDetail.tsx `text-[#1a1400]` as a named token
+ // instead of a repeated literal, and matches this screen's other warningColor
+ // usages routing through brand/useTheme() rather than a hardcoded hex.
+ warningText: '#1a1400',
}
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index f692239..65d0a0a 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -162,6 +162,9 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
create: (data: any) => api.post<{ data: types.Program }>('/programs', data).then(unwrap),
update: (id: number, data: any) => api.put<{ data: types.Program }>(`/programs/${id}`, data).then(unwrap),
delete: (id: number) => api.delete(`/programs/${id}`),
+ // Accept/dismiss staged auto-progression suggestions (#40); returns the updated program.
+ resolveSuggestions: (id: number, data: { accept: number[]; dismiss: number[] }) =>
+ api.post<{ data: types.Program }>(`/programs/${id}/suggestions/resolve`, data).then(unwrap),
}
const weightAPI = {
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 2b3cdf8..bb81f7e 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -62,6 +62,16 @@ export interface Workout {
started_at: string
created_at: string
exercises: WorkoutExercise[]
+ // Present on the create response when finishing auto-progressed routine targets (#40).
+ progression?: ProgressionResult
+}
+
+// Summary of staged routine suggestions, used for the finish toast (#40).
+export interface ProgressionResult {
+ program_id: number
+ program_name: string
+ count: number
+ is_pr?: boolean
}
export interface WeightLog {
@@ -151,6 +161,11 @@ export interface ProgramSet {
set_number: number
target_reps: number
target_weight: number
+ // Pending auto-progression suggestion (#40) — present when the last workout beat
+ // this set's target. The user approves it on the routine (copies into target_*).
+ suggested_reps?: number
+ suggested_weight?: number
+ suggested_is_pr?: boolean
}
export interface ProgramExercise {
diff --git a/web/e2e/workouts.spec.ts b/web/e2e/workouts.spec.ts
index a2a4078..248c3aa 100644
--- a/web/e2e/workouts.spec.ts
+++ b/web/e2e/workouts.spec.ts
@@ -4,6 +4,7 @@ import { cleanupSeed } from './seedHelpers'
const E2E_WORKOUT_NAME = 'Test Workout E2E'
const SEED_WORKOUT_NAME = 'Seeded Test Workout'
const SEED_SEARCH_WORKOUT_NAME = 'ZZZ E2E SearchTarget Workout'
+const PROG_PROGRESSION_NAME = 'E2E AutoProgression Routine'
const LAYOUT_KEY = 'lyftr_workout_layout'
const SESSION_KEY = 'lyftr_active_session'
@@ -177,6 +178,68 @@ test.describe('Workouts', () => {
await page.goto('/settings')
await page.getByRole('button', { name: 'lbs' }).click()
})
+
+ // Issue #40: finishing a workout that beat a routine's per-set target STAGES a
+ // suggestion (target unchanged) + toasts it; approving on the routine applies it.
+ test('finishing a workout that beats a routine target stages a suggestion to approve', async ({ page, request }) => {
+ const headers = { Authorization: `Bearer ${authToken}` }
+ const exId = (await (await request.get(`${API}/exercises?limit=1`, { headers })).json()).data[0].id
+
+ // Routine with one working set targeting 5 × 100.
+ const created = await request.post(`${API}/programs`, {
+ headers,
+ data: { name: PROG_PROGRESSION_NAME, notes: '', exercises: [{ exercise_id: exId, notes: '', rest_seconds: 90, sets: [{ set_number: 1, target_reps: 5, target_weight: 100 }] }] },
+ })
+ const progId = (await created.json()).data.id
+ const psid = (await (await request.get(`${API}/programs/${progId}`, { headers })).json()).data.exercises[0].sets[0].id
+
+ // Seed a list-mode session where the logged set beat the target (105 > 100).
+ const session = {
+ program_id: progId,
+ name: PROG_PROGRESSION_NAME,
+ started_at: new Date(Date.now() - 600000).toISOString(),
+ exercises: [{
+ exercise_id: exId,
+ exercise: { id: exId, name: 'Bench Press', muscle_group: 'Chest', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
+ notes: '', rest_seconds: 90,
+ sets: [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 105, completed: true, program_set_id: psid }],
+ }],
+ }
+ await page.addInitScript(({ sk, lk, s }: { sk: string; lk: string; s: any }) => {
+ localStorage.setItem(sk, JSON.stringify(s))
+ localStorage.setItem(lk, 'list')
+ }, { sk: SESSION_KEY, lk: LAYOUT_KEY, s: session })
+
+ await page.goto('/workout/active')
+ await page.getByRole('button', { name: 'Finish' }).first().click()
+ await page.getByRole('button', { name: 'Finish' }).last().click()
+
+ await page.waitForURL('**/workouts')
+ // Toast invites a review (PR wording when it's also an all-time best; either is fine).
+ await expect(page.getByText(/Tap to review 1 update/)).toBeVisible({ timeout: 5000 })
+
+ // Staged, NOT applied — the routine target is still 100 until approved.
+ const staged = await (await request.get(`${API}/programs/${progId}`, { headers })).json()
+ expect(staged.data.exercises[0].sets[0].target_weight).toBe(100)
+ expect(staged.data.exercises[0].sets[0].suggested_weight).toBe(105)
+
+ // Approve on the routine → target becomes 105, suggestion cleared.
+ await page.goto(`/programs/${progId}`)
+ await expect(page.getByText('New targets from your last workout')).toBeVisible({ timeout: 5000 })
+ await page.getByRole('button', { name: /Apply all/ }).click()
+ await expect(page.getByText('New targets from your last workout')).toHaveCount(0, { timeout: 5000 })
+
+ const after = await (await request.get(`${API}/programs/${progId}`, { headers })).json()
+ expect(after.data.exercises[0].sets[0].target_weight).toBe(105)
+ expect(after.data.exercises[0].sets[0].suggested_weight ?? null).toBeNull()
+
+ // Cleanup: the workout we just logged + the routine.
+ const wl = await (await request.get(`${API}/workouts?limit=20`, { headers })).json()
+ for (const w of (wl.data ?? []).filter((x: any) => x.name === PROG_PROGRESSION_NAME)) {
+ await request.delete(`${API}/workouts/${w.id}`, { headers })
+ }
+ await request.delete(`${API}/programs/${progId}`, { headers })
+ })
})
// ── Gym Mode (active workout route, alternative layout) ───────────────────────
diff --git a/web/src/components/StartWorkoutModal.tsx b/web/src/components/StartWorkoutModal.tsx
index ca6c33b..49f410e 100644
--- a/web/src/components/StartWorkoutModal.tsx
+++ b/web/src/components/StartWorkoutModal.tsx
@@ -55,6 +55,7 @@ export default function StartWorkoutModal({ isOpen, onClose }: Props) {
actual_reps: s.target_reps,
actual_weight: s.target_weight,
completed: false,
+ program_set_id: s.id, // link for routine target auto-progression (#40)
})),
}))
startSession(program.name, exercises, program.id)
diff --git a/web/src/components/ui/Toast.tsx b/web/src/components/ui/Toast.tsx
new file mode 100644
index 0000000..3899f12
--- /dev/null
+++ b/web/src/components/ui/Toast.tsx
@@ -0,0 +1,83 @@
+import { useEffect } from 'react'
+import { createPortal } from 'react-dom'
+import { X, ChevronRight } from 'lucide-react'
+import type { LucideIcon } from 'lucide-react'
+
+export type ToastVariant = 'default' | 'success' | 'brand' | 'warning' | 'error'
+
+interface Props {
+ title: string
+ description?: string
+ icon?: LucideIcon
+ variant?: ToastVariant
+ /** When set, the body is tappable (a chevron affordance is shown). */
+ onClick?: () => void
+ onDismiss: () => void
+ /** Auto-dismiss delay; pass 0 to keep it until dismissed. Default 4s. */
+ autoDismissMs?: number
+}
+
+// Semantic colour applied only to the icon chip + border, keeping the text in the
+// normal tx-* hierarchy — a fully tinted toast reads as obnoxious over content.
+const VARIANTS: Record<ToastVariant, { border: string; chip: string; icon: string }> = {
+ default: { border: 'border-surface-border', chip: 'bg-surface-muted border-surface-border', icon: 'text-tx-secondary' },
+ success: { border: 'border-success-500/20', chip: 'bg-success-500/10 border-success-500/20', icon: 'text-success-400' },
+ brand: { border: 'border-brand-500/20', chip: 'bg-brand-500/10 border-brand-500/20', icon: 'text-brand-400' },
+ warning: { border: 'border-warning-500/20', chip: 'bg-warning-500/10 border-warning-500/20', icon: 'text-warning-400' },
+ error: { border: 'border-error-500/20', chip: 'bg-error-500/10 border-error-500/20', icon: 'text-error-400' },
+}
+
+// A dismissible floating toast — the app's shared transient notification. Docks in
+// the same bottom slot as the floating RestTimerBanner (bottom-24 clears the nav);
+// callers that fire it after a session ends don't collide with session-gated UI.
+export default function Toast({ title, description, icon: Icon, variant = 'default', onClick, onDismiss, autoDismissMs = 4000 }: Props) {
+ // Armed once on mount — parent re-renders must not extend the window (0 disables).
+ useEffect(() => {
+ if (!autoDismissMs) return
+ const id = setTimeout(onDismiss, autoDismissMs)
+ return () => clearTimeout(id)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ const v = VARIANTS[variant]
+ const body = (
+ <>
+ {Icon && (
+ <div className={`w-8 h-8 rounded-full border flex items-center justify-center flex-shrink-0 ${v.chip}`}>
+ <Icon className={`w-4 h-4 ${v.icon}`} />
+ </div>
+ )}
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-semibold text-tx-primary leading-tight">{title}</p>
+ {description && <p className="text-xs text-tx-muted leading-tight truncate">{description}</p>}
+ </div>
+ {onClick && <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />}
+ </>
+ )
+
+ // Portal to <body>: a page root with a lingering transform (animate-slide-up)
+ // would otherwise become the containing block for this position:fixed toast and
+ // shove it off-screen. The portal gives us a true viewport anchor.
+ return createPortal(
+ <div role="status" className="fixed bottom-24 inset-x-3 z-[70] mx-auto max-w-md animate-slide-up">
+ <div className={`flex items-center gap-3 rounded-2xl px-4 py-3 bg-surface-raised border shadow-lg ${v.border}`}>
+ {onClick ? (
+ <button type="button" onClick={onClick} className="flex items-center gap-3 min-w-0 flex-1 text-left">
+ {body}
+ </button>
+ ) : (
+ <div className="flex items-center gap-3 min-w-0 flex-1">{body}</div>
+ )}
+ <button
+ type="button"
+ onClick={onDismiss}
+ aria-label="Dismiss"
+ className="p-1.5 -m-1.5 text-tx-muted hover:text-tx-primary flex-shrink-0"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/web/src/components/ui/index.ts b/web/src/components/ui/index.ts
index 5da1b59..fb941c6 100644
--- a/web/src/components/ui/index.ts
+++ b/web/src/components/ui/index.ts
@@ -6,3 +6,5 @@ export { default as SectionHeader } from './SectionHeader'
export { default as PageHeader } from './PageHeader'
export { default as NumberField } from './NumberField'
export { default as StepperTile } from './StepperTile'
+export { default as Toast } from './Toast'
+export type { ToastVariant } from './Toast'
diff --git a/web/src/pages/ActiveWorkout.tsx b/web/src/pages/ActiveWorkout.tsx
index 5fd28de..7830d63 100644
--- a/web/src/pages/ActiveWorkout.tsx
+++ b/web/src/pages/ActiveWorkout.tsx
@@ -104,9 +104,10 @@ export default function ActiveWorkout() {
setSaveError('')
try {
const payload = buildPayload()
- await workoutAPI.create(payload)
+ const saved = await workoutAPI.create(payload)
cancelSession()
- navigate('/workouts')
+ // Surface the routine auto-progression as a toast on the workouts list (#40).
+ navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)
} catch (err: any) {
setSaveError(err.response?.data?.error || 'Failed to save workout')
setSaving(false)
diff --git a/web/src/pages/GymModeWorkout.tsx b/web/src/pages/GymModeWorkout.tsx
index 862efa9..908d08d 100644
--- a/web/src/pages/GymModeWorkout.tsx
+++ b/web/src/pages/GymModeWorkout.tsx
@@ -93,10 +93,11 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
setSaveError('')
try {
const payload = buildPayload()
- await workoutAPI.create(payload)
+ const saved = await workoutAPI.create(payload)
cancelSession()
minimizeGym()
- navigate('/workouts')
+ // Surface the routine auto-progression as a toast on the workouts list (#40).
+ navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)
} catch (err: any) {
setSaveError(err.response?.data?.error || 'Failed to save workout')
setSaving(false)
diff --git a/web/src/pages/ProgramDetail.tsx b/web/src/pages/ProgramDetail.tsx
index 749e8e5..19ae13f 100644
--- a/web/src/pages/ProgramDetail.tsx
+++ b/web/src/pages/ProgramDetail.tsx
@@ -4,6 +4,7 @@ import { useParams, useNavigate, Link } from 'react-router-dom'
import { format } from 'date-fns'
import {
ArrowLeft, BookOpen, Dumbbell, Edit2, Trash2, Play, AlertCircle, Loader, ChevronRight, Pause, TimerOff,
+ Award, TrendingUp, Check, X, ChevronDown, ChevronUp,
} from 'lucide-react'
import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
@@ -11,6 +12,9 @@ import { useSettingsStore, weightShort, displayWeight } from '../stores/settings
import * as types from '../types'
import { muscleColor } from '../utils/exerciseUtils'
+// Rows shown before the review banner collapses behind a "Show all" toggle (#40).
+const SUGGESTION_CAP = 3
+
export default function ProgramDetail() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
@@ -24,6 +28,23 @@ export default function ProgramDetail() {
const [error, setError] = useState<string | null>(null)
const [confirming, setConfirming] = useState(false)
const [deleting, setDeleting] = useState(false)
+ const [resolving, setResolving] = useState(false)
+ const [showAllSuggestions, setShowAllSuggestions] = useState(false)
+
+ // Accept (apply → target) or dismiss staged auto-progression suggestions (#40),
+ // then refresh from the returned program.
+ const resolveSuggestions = async (accept: number[], dismiss: number[]) => {
+ if (!program || resolving) return
+ setResolving(true)
+ try {
+ const updated = await programAPI.resolveSuggestions(program.id, { accept, dismiss })
+ setProgram(updated)
+ } catch {
+ /* leave the banner in place so the user can retry */
+ } finally {
+ setResolving(false)
+ }
+ }
useEffect(() => {
const load = async () => {
@@ -54,6 +75,7 @@ export default function ProgramDetail() {
actual_reps: s.target_reps,
actual_weight: s.target_weight,
completed: false,
+ program_set_id: s.id, // link for routine target auto-progression (#40)
})),
}))
startSession(program.name, exercises, program.id)
@@ -97,6 +119,42 @@ export default function ProgramDetail() {
const exs = program.exercises ?? []
const totalSets = exs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)
+ // Pending auto-progression suggestions (#40), flattened for the review banner. A
+ // suggestion exists when suggested_reps is set. Show the FULL reps×weight on both
+ // sides when both changed (a heavier set can also drop the rep target — the user
+ // must see that before approving), else the single changed dimension.
+ const suggestions = exs.flatMap(ex =>
+ (ex.sets ?? [])
+ .filter(s => s.id != null && s.suggested_reps != null)
+ .map(s => {
+ const sw = s.suggested_weight as number
+ const sr = s.suggested_reps as number
+ const weightChanged = s.suggested_weight != null && Math.abs(sw - s.target_weight) > 1e-6
+ const repsChanged = sr !== s.target_reps
+ const wLabel = (v: number) => (v > 0 ? `${displayWeight(v, wUnit)} ${wUnit}` : 'BW')
+ let oldLabel: string, newLabel: string
+ if (weightChanged && repsChanged) {
+ oldLabel = `${s.target_reps} × ${wLabel(s.target_weight)}`
+ newLabel = `${sr} × ${wLabel(sw)}`
+ } else if (weightChanged) {
+ oldLabel = wLabel(s.target_weight)
+ newLabel = wLabel(sw)
+ } else {
+ oldLabel = `${s.target_reps}`
+ newLabel = `${sr} reps`
+ }
+ return {
+ setId: s.id as number,
+ exName: ex.exercise?.name ?? 'Exercise',
+ setNumber: s.set_number,
+ isPR: !!s.suggested_is_pr,
+ oldLabel,
+ newLabel,
+ }
+ })
+ )
+ const suggestedSetIds = suggestions.map(s => s.setId)
+
return (
<div className="space-y-5 animate-slide-up max-w-2xl">
{/* Back nav */}
@@ -147,6 +205,76 @@ export default function ProgramDetail() {
document.body
)}
+ {/* Auto-progression review banner (#40) — approve the targets you beat last workout */}
+ {suggestions.length > 0 && (
+ <div className="bg-surface-raised border border-warning-500/30 rounded-xl overflow-hidden animate-slide-up">
+ <div className="flex items-center gap-2 px-4 py-3">
+ {suggestions.some(s => s.isPR)
+ ? <Award className="w-4 h-4 text-warning-400 flex-shrink-0" />
+ : <TrendingUp className="w-4 h-4 text-warning-400 flex-shrink-0" />}
+ <span className="text-sm font-semibold text-tx-primary flex-1">New targets from your last workout</span>
+ <span className="text-xs font-bold text-warning-400 bg-warning-500/15 px-2 py-0.5 rounded-full tabular-nums">{suggestions.length}</span>
+ </div>
+ {(showAllSuggestions ? suggestions : suggestions.slice(0, SUGGESTION_CAP)).map(sg => (
+ <div key={sg.setId} className="flex items-center gap-3 px-4 py-2.5 border-t border-surface-border/60">
+ <span className="text-sm text-tx-secondary min-w-0 flex-1 truncate flex items-center gap-1.5">
+ {sg.isPR && <Award className="w-3.5 h-3.5 text-warning-400 flex-shrink-0" />}
+ <span className="truncate"><span className="font-semibold text-tx-primary">{sg.exName}</span> · Set {sg.setNumber}</span>
+ </span>
+ <span className="text-sm tabular-nums whitespace-nowrap flex-shrink-0">
+ <span className="text-tx-muted line-through">{sg.oldLabel}</span>
+ <span className="text-warning-400 mx-1.5">→</span>
+ <span className="text-tx-primary font-bold">{sg.newLabel}</span>
+ </span>
+ <span className="flex gap-1.5 flex-shrink-0">
+ <button
+ onClick={() => resolveSuggestions([sg.setId], [])}
+ disabled={resolving}
+ aria-label={`Accept ${sg.exName} set ${sg.setNumber}`}
+ className="w-7 h-7 rounded-lg bg-success-500/15 text-success-400 hover:bg-success-500/25 disabled:opacity-50 flex items-center justify-center transition-colors"
+ >
+ <Check className="w-4 h-4" strokeWidth={3} />
+ </button>
+ <button
+ onClick={() => resolveSuggestions([], [sg.setId])}
+ disabled={resolving}
+ aria-label={`Dismiss ${sg.exName} set ${sg.setNumber}`}
+ className="w-7 h-7 rounded-lg bg-surface-muted text-tx-muted hover:text-tx-primary disabled:opacity-50 flex items-center justify-center transition-colors"
+ >
+ <X className="w-4 h-4" strokeWidth={3} />
+ </button>
+ </span>
+ </div>
+ ))}
+ {suggestions.length > SUGGESTION_CAP && (
+ <button
+ onClick={() => setShowAllSuggestions(v => !v)}
+ className="w-full flex items-center justify-center gap-1.5 py-2 border-t border-surface-border/60 text-warning-400 hover:text-warning-300 text-xs font-semibold transition-colors"
+ >
+ {showAllSuggestions
+ ? <>Show less <ChevronUp className="w-3.5 h-3.5" /></>
+ : <>Show all {suggestions.length} <ChevronDown className="w-3.5 h-3.5" /></>}
+ </button>
+ )}
+ <div className="flex gap-2 px-4 py-3 border-t border-surface-border/60">
+ <button
+ onClick={() => resolveSuggestions([], suggestedSetIds)}
+ disabled={resolving}
+ className="flex-1 py-2 rounded-lg bg-surface-muted border border-surface-border text-tx-secondary hover:text-tx-primary disabled:opacity-50 text-sm font-medium transition-colors"
+ >
+ Dismiss all
+ </button>
+ <button
+ onClick={() => resolveSuggestions(suggestedSetIds, [])}
+ disabled={resolving}
+ className="flex-1 py-2 rounded-lg bg-warning-500 hover:bg-warning-400 disabled:opacity-50 text-[#1a1400] text-sm font-semibold transition-colors"
+ >
+ Apply all ({suggestions.length})
+ </button>
+ </div>
+ </div>
+ )}
+
{/* Header */}
<div className="card p-4">
<div className="flex items-start gap-3">
@@ -242,9 +370,11 @@ export default function ProgramDetail() {
<div className="flex flex-wrap gap-1.5 flex-1 min-w-0">
{sets.map((set, i) => {
const isBest = set.target_weight === maxTargetLbs && maxTargetLbs > 0
+ const hasSuggestion = set.suggested_reps != null
return (
<div key={i} className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${
- isBest ? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25' : 'bg-surface-raised text-tx-secondary'
+ hasSuggestion ? 'bg-warning-500/10 text-tx-secondary ring-1 ring-warning-500/40'
+ : isBest ? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25' : 'bg-surface-raised text-tx-secondary'
}`}>
{set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${displayWeight(set.target_weight, wUnit)} ${wUnit}` : 'BW'}
</div>
diff --git a/web/src/pages/Programs.tsx b/web/src/pages/Programs.tsx
index c68279f..14c0b3a 100644
--- a/web/src/pages/Programs.tsx
+++ b/web/src/pages/Programs.tsx
@@ -52,6 +52,7 @@ function ProgramCard({
actual_reps: s.target_reps,
actual_weight: s.target_weight,
completed: false,
+ program_set_id: s.id, // link for routine target auto-progression (#40)
})),
}))
startSession(program.name, exercises, program.id)
diff --git a/web/src/pages/StartWorkout.tsx b/web/src/pages/StartWorkout.tsx
index 265209f..3f105fb 100644
--- a/web/src/pages/StartWorkout.tsx
+++ b/web/src/pages/StartWorkout.tsx
@@ -39,6 +39,7 @@ export default function StartWorkout() {
actual_reps: s.target_reps,
actual_weight: s.target_weight,
completed: false,
+ program_set_id: s.id, // link for routine target auto-progression (#40)
})),
}))
startSession(program.name, exercises, program.id)
diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsx
index 774e67b..9a82d9f 100644
--- a/web/src/pages/Workouts.tsx
+++ b/web/src/pages/Workouts.tsx
@@ -1,11 +1,12 @@
import { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { format } from 'date-fns'
-import { Dumbbell, Plus, Clock, Search, AlertCircle, Edit2, Trash2, TrendingUp, ChevronRight, MoreVertical } from 'lucide-react'
-import { useNavigate } from 'react-router-dom'
+import { Dumbbell, Plus, Clock, Search, AlertCircle, Edit2, Trash2, TrendingUp, Award, ChevronRight, MoreVertical } from 'lucide-react'
+import { useNavigate, useLocation } from 'react-router-dom'
import Loading from '../components/Loading'
import EmptyState from '../components/ui/EmptyState'
import PageHeader from '../components/ui/PageHeader'
+import { Toast } from '../components/ui'
import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, displayVolume } from '../stores/settings'
@@ -201,10 +202,24 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on
export default function Workouts() {
const navigate = useNavigate()
+ const location = useLocation()
const [search, setSearch] = useState('')
const [debouncedSearch, setDebouncedSearch] = useState('')
const [error, setError] = useState<string | null>(null)
+ // Auto-progression toast (#40): the finish flow navigates here with the summary
+ // in router state. Capture it once, then wipe history state so it can't replay on
+ // back/refresh.
+ const [progression, setProgression] = useState<types.ProgressionResult | null>(
+ (location.state as { progression?: types.ProgressionResult } | null)?.progression ?? null
+ )
+ useEffect(() => {
+ if ((location.state as { progression?: types.ProgressionResult } | null)?.progression) {
+ window.history.replaceState({}, '')
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
// Debounce search so we don't fire a request on every keystroke
useEffect(() => {
const t = setTimeout(() => setDebouncedSearch(search), 300)
@@ -291,6 +306,16 @@ export default function Workouts() {
)}
</div>
+ {progression && (
+ <Toast
+ variant={progression.is_pr ? 'warning' : 'success'}
+ icon={progression.is_pr ? Award : TrendingUp}
+ title={progression.is_pr ? `New PR in ${progression.program_name}` : `New targets in ${progression.program_name}`}
+ description={`Tap to review ${progression.count} ${progression.count === 1 ? 'update' : 'updates'}`}
+ onClick={() => { setProgression(null); navigate(`/programs/${progression.program_id}`) }}
+ onDismiss={() => setProgression(null)}
+ />
+ )}
</div>
)
}
diff --git a/web/src/services/api.ts b/web/src/services/api.ts
index bcfaf52..222c01f 100644
--- a/web/src/services/api.ts
+++ b/web/src/services/api.ts
@@ -160,6 +160,9 @@ export const programAPI = {
create: (data: any) => api.post<{ data: types.Program }>('/programs', data).then(res => unwrap(res)),
update: (id: number, data: any) => api.put<{ data: types.Program }>(`/programs/${id}`, data).then(res => unwrap(res)),
delete: (id: number) => api.delete(`/programs/${id}`),
+ // Accept/dismiss staged auto-progression suggestions (#40); returns the updated program.
+ resolveSuggestions: (id: number, data: { accept: number[]; dismiss: number[] }) =>
+ api.post<{ data: types.Program }>(`/programs/${id}/suggestions/resolve`, data).then(res => unwrap(res)),
}
export const weightAPI = {
diff --git a/web/src/stores/workoutSession.test.ts b/web/src/stores/workoutSession.test.ts
index f3dece8..437dff0 100644
--- a/web/src/stores/workoutSession.test.ts
+++ b/web/src/stores/workoutSession.test.ts
@@ -112,3 +112,49 @@ describe('workoutSession rest timer (ephemeral)', () => {
expect(raw).not.toContain('restDurationSec')
})
})
+
+describe('workoutSession buildPayload — auto-progression (#40)', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ store().cancelSession()
+ })
+
+ it('carries program_id and per-set program_set_id for a routine-sourced session', () => {
+ store().startSession('Push A', [
+ {
+ exercise_id: 1, exercise: { id: 1, name: 'Bench' }, notes: '',
+ sets: [
+ { set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 105, completed: true, program_set_id: 11 },
+ { set_number: 2, target_reps: 5, target_weight: 100, actual_reps: 6, actual_weight: 100, completed: true, program_set_id: 12 },
+ ],
+ },
+ ] as any, 7)
+ const payload = store().buildPayload()
+ expect(payload.program_id).toBe(7)
+ expect(payload.exercises[0].sets[0].program_set_id).toBe(11)
+ expect(payload.exercises[0].sets[1].program_set_id).toBe(12)
+ // logged actuals are what the backend compares against the target
+ expect(payload.exercises[0].sets[0].weight).toBe(105)
+ expect(payload.exercises[0].sets[1].reps).toBe(6)
+ })
+
+ it('freestyle session sends null program_id and null program_set_id (no progression)', () => {
+ store().startSession('Freestyle', [
+ { exercise_id: 1, exercise: { id: 1, name: 'Bench' }, notes: '',
+ sets: [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 0, actual_weight: 0, completed: true }] },
+ ] as any)
+ const payload = store().buildPayload()
+ expect(payload.program_id).toBeNull()
+ expect(payload.exercises[0].sets[0].program_set_id).toBeNull()
+ })
+
+ it('blank actuals fall back to target so logged == target → no false progression', () => {
+ store().startSession('Push A', [
+ { exercise_id: 1, exercise: { id: 1, name: 'Bench' }, notes: '',
+ sets: [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 0, actual_weight: 0, completed: true, program_set_id: 11 }] },
+ ] as any, 7)
+ const payload = store().buildPayload()
+ expect(payload.exercises[0].sets[0].reps).toBe(5)
+ expect(payload.exercises[0].sets[0].weight).toBe(100)
+ })
+})
diff --git a/web/src/stores/workoutSession.ts b/web/src/stores/workoutSession.ts
index 12a9c38..6be7e6e 100644
--- a/web/src/stores/workoutSession.ts
+++ b/web/src/stores/workoutSession.ts
@@ -254,6 +254,7 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
notes: '',
duration: durationSec,
started_at: session.started_at,
+ program_id: session.program_id ?? null, // lets the backend auto-progress the routine (#40)
exercises: session.exercises.map(ex => ({
exercise_id: ex.exercise_id,
notes: ex.notes,
@@ -262,6 +263,7 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
set_number: i + 1,
reps: s.actual_reps || s.target_reps,
weight: s.actual_weight || s.target_weight,
+ program_set_id: s.program_set_id ?? null, // which routine target this set can progress (#40)
})),
})),
}
diff --git a/web/src/types.ts b/web/src/types.ts
index abb36ec..422930f 100644
--- a/web/src/types.ts
+++ b/web/src/types.ts
@@ -61,6 +61,16 @@ export interface Workout {
started_at: string
created_at: string
exercises: WorkoutExercise[]
+ // Present on the create response when finishing auto-progressed routine targets (#40).
+ progression?: ProgressionResult
+}
+
+// Summary of staged routine suggestions, used for the finish toast (#40).
+export interface ProgressionResult {
+ program_id: number
+ program_name: string
+ count: number
+ is_pr?: boolean
}
export interface WeightLog {
@@ -150,6 +160,11 @@ export interface ProgramSet {
set_number: number
target_reps: number
target_weight: number
+ // Pending auto-progression suggestion (#40) — present when the last workout beat
+ // this set's target. The user approves it on the routine (copies into target_*).
+ suggested_reps?: number
+ suggested_weight?: number
+ suggested_is_pr?: boolean
}
export interface ProgramExercise {
@@ -177,6 +192,9 @@ export interface ActiveSessionSet {
actual_reps: number
actual_weight: number
completed: boolean
+ // Links back to the routine's ProgramSet so finishing can auto-progress that
+ // target (issue #40). Absent for freestyle sessions and ad-hoc added sets.
+ program_set_id?: number
}
export interface ActiveSessionExercise {