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.

Follow-up fixes to the stored-day model, found by manual device testing (#97)

Carterc55940019454
diff --git a/backend/controllers/food.go b/backend/controllers/food.go
index 16a3fd8..f40fd12 100644
--- a/backend/controllers/food.go
+++ b/backend/controllers/food.go
@@ -213,8 +213,7 @@ func (h *Handler) GetFoodHistory(c *gin.Context) {
// The window is counted back from the user's today — the one question a stored
// day still cannot answer on its own.
- since := time.Now().In(h.userLocation(uid)).AddDate(0, 0, -days).Format("2006-01-02")
- points, err := h.s.Food.History(uid, since)
+ points, err := h.s.Food.History(uid, h.daysAgoDay(uid, days))
if utils.DBError(c, err) {
return
}
diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.go
index 3e9e3ab..225625a 100644
--- a/backend/controllers/food_test.go
+++ b/backend/controllers/food_test.go
@@ -1237,15 +1237,6 @@ func TestGetFoodHistory_agreesWithDailyTotals(t *testing.T) {
t.Errorf("history has no bucket for %s, but the daily total is %v", day, dailyCals)
}
-func mustLoad(t *testing.T, name string) *time.Location {
- t.Helper()
- loc, err := ParseLocation(name)
- if err != nil {
- t.Fatalf("load %s: %v", name, err)
- }
- return loc
-}
-
// An unloadable zone must be rejected at write time rather than silently making
// every later query fall back to UTC.
func TestUpdateSettings_rejectsUnknownTimezone(t *testing.T) {
diff --git a/backend/controllers/timezone.go b/backend/controllers/timezone.go
index 0021440..f5358e3 100644
--- a/backend/controllers/timezone.go
+++ b/backend/controllers/timezone.go
@@ -87,6 +87,17 @@ func (h *Handler) resolveQueryDay(uid int64, supplied string) (string, bool) {
return supplied, true
}
+// daysAgoDay is the calendar day `days` before the user's today, for the windows a
+// chart or a rolling stat asks for.
+//
+// Named rather than inlined so every "N days back" bound in the app is the same
+// subtraction against the same today. The history endpoint used to compute this
+// expression by hand, which made it a fourth day-derivation rule living outside this
+// file — the exact drift this file exists to prevent.
+func (h *Handler) daysAgoDay(uid int64, days int) string {
+ return time.Now().In(h.userLocation(uid)).AddDate(0, 0, -days).Format("2006-01-02")
+}
+
// tzOffsetMinutes is the user's UTC offset at a given instant, for stamping onto a
// workout. Resolved through the zone at that instant rather than a fixed number, so
// a summer workout gets the summer offset.
diff --git a/backend/controllers/weight.go b/backend/controllers/weight.go
index 943806a..d86b9fb 100644
--- a/backend/controllers/weight.go
+++ b/backend/controllers/weight.go
@@ -22,29 +22,30 @@ func (h *Handler) ListWeightLogs(c *gin.Context) {
f.Offset = o
}
- // Two kinds of bound, matching the two kinds of question. A bare YYYY-MM-DD asks
- // about the user's calendar and compares against the day stored on the row — no
- // zone, no conversion, nothing that can move later. A full RFC3339 timestamp asks
- // about instants and still compares against logged_at.
+ // `from`/`to` name days in the user's diary, and every row carries the day it was
+ // filed under, so this is a range over stored days: no zone, no conversion, nothing
+ // that can move later. Validated through resolveQueryDay so a range bound and a
+ // single-day lookup cannot disagree about what a day string is.
+ //
+ // Day-only is also what every peer range API takes (Fitbit's food log `date`,
+ // Garmin's `calendarDate`). An instant-bounded RFC3339 variant used to live here
+ // for exact windows; no client ever sent one, and it was a second way to ask the
+ // same question through a different column.
if from := c.Query("from"); from != "" {
- if t, exact, ok := parseDayOrTime(from); ok {
- if exact {
- f.From = &t
- } else {
- day := t.Format("2006-01-02")
- f.FromDay = &day
- }
+ day, ok := h.resolveQueryDay(uid, from)
+ if !ok {
+ utils.BadRequest(c, "from must be YYYY-MM-DD")
+ return
}
+ f.FromDay = &day
}
if to := c.Query("to"); to != "" {
- if t, exact, ok := parseDayOrTime(to); ok {
- if exact {
- f.To = &t
- } else {
- day := t.Format("2006-01-02")
- f.ToDay = &day
- }
+ day, ok := h.resolveQueryDay(uid, to)
+ if !ok {
+ utils.BadRequest(c, "to must be YYYY-MM-DD")
+ return
}
+ f.ToDay = &day
}
logs, err := h.s.Weight.List(uid, f)
@@ -151,7 +152,7 @@ func (h *Handler) DeleteWeightLog(c *gin.Context) {
func (h *Handler) GetWeightStats(c *gin.Context) {
uid := middleware.UserID(c)
- stats, err := h.s.Weight.Stats(uid)
+ stats, err := h.s.Weight.Stats(uid, h.daysAgoDay(uid, 7), h.daysAgoDay(uid, 30))
if utils.DBError(c, err) {
return
}
@@ -176,15 +177,3 @@ func normalizeLoggedAt(t time.Time) time.Time {
}
return t.UTC()
}
-
-// parseDayOrTime accepts a full RFC3339 timestamp or a bare YYYY-MM-DD. Returns
-// the parsed time, whether it was an exact timestamp (don't widen), and success.
-func parseDayOrTime(s string) (t time.Time, exact bool, ok bool) {
- if v, err := time.Parse(time.RFC3339, s); err == nil {
- return v, true, true
- }
- if v, err := time.Parse("2006-01-02", s); err == nil {
- return v, false, true
- }
- return time.Time{}, false, false
-}
diff --git a/backend/controllers/weight_test.go b/backend/controllers/weight_test.go
index fbdfa79..e9863e6 100644
--- a/backend/controllers/weight_test.go
+++ b/backend/controllers/weight_test.go
@@ -141,17 +141,14 @@ func TestListWeightLogs_dateRange(t *testing.T) {
}
}
-// Regression: a YYYY-MM-DD `to` should include entries logged late on that
-// day for users in west-of-UTC timezones. Their `${date}T12:00:00` local
-// stored as UTC ends up several hours after UTC midnight, which a naive
-// "parse as UTC + 24h" would have excluded.
+// A day range matches on the day the entry was filed under, not on where its instant
+// falls in UTC. A UTC-7 user logging noon on the 25th stores 2026-04-25T19:00:00Z;
+// every previous version of this filter had to widen the UTC window to catch it, and
+// each widening was a guess about how far the user might have been from UTC. Matching
+// logged_on needs no guess.
func TestListWeightLogs_dateRangeWestTimezone(t *testing.T) {
setupTestDB(t)
uid := createTestUser(t)
- // Simulate a user in UTC-7 logging "2026-04-25 noon local" — stored as
- // 2026-04-25T19:00:00Z. A naive parser interpreting `to=2026-04-25` as
- // UTC midnight + 24h would treat the cutoff as 2026-04-25T00:00:00Z
- // and miss this entry.
loggedAt := time.Date(2026, 4, 25, 19, 0, 0, 0, time.UTC)
insertWeightLog(t, uid, 175.0, loggedAt)
@@ -168,26 +165,23 @@ func TestListWeightLogs_dateRangeWestTimezone(t *testing.T) {
}
}
-// Regression: an RFC3339 timestamp must be honored exactly without any TZ
-// padding. Callers that pass precise bounds expect exclusive control.
-func TestListWeightLogs_dateRangeExactRFC3339(t *testing.T) {
+// A range bound that isn't a day is rejected rather than silently dropped. Ignoring it
+// would answer a narrow question with the whole history, which reads as data loss in
+// reverse — a chart that quietly shows more than it was asked for.
+func TestListWeightLogs_dateRangeRejectsNonDayBound(t *testing.T) {
setupTestDB(t)
uid := createTestUser(t)
insertWeightLog(t, uid, 175.0, time.Date(2026, 4, 25, 10, 0, 0, 0, time.UTC))
- insertWeightLog(t, uid, 176.0, time.Date(2026, 4, 25, 14, 0, 0, 0, time.UTC))
- c, w := newContext(uid, http.MethodGet,
- "/api/v1/weight?from=2026-04-25T12:00:00Z&to=2026-04-25T15:00:00Z", nil)
- th.ListWeightLogs(c)
-
- resp := decodeResponse(t, w)
- data := resp["data"].([]any)
- if len(data) != 1 {
- t.Fatalf("expected 1 entry within exact window, got %d", len(data))
- }
- first := data[0].(map[string]any)
- if first["weight"].(float64) != 176.0 {
- t.Errorf("expected the 14:00 entry, got %v", first["weight"])
+ for _, q := range []string{
+ "/api/v1/weight?from=2026-04-25T12:00:00Z",
+ "/api/v1/weight?to=not-a-date",
+ } {
+ c, w := newContext(uid, http.MethodGet, q, nil)
+ th.ListWeightLogs(c)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("%s: expected 400, got %d", q, w.Code)
+ }
}
}
@@ -548,7 +542,6 @@ func TestUpdateWeightLog_movingTheDayDoesNotDeleteTheTargetDaysEntry(t *testing.
}
}
-
// The bare-day from/to filter resolves through the user's stored zone now that the
// -12h/+36h widening is gone. TestListWeightLogs_dateRange covers the UTC default;
// this covers a real zone, where a device-derived day and a UTC day disagree.
@@ -621,3 +614,39 @@ func TestLogWeight_oneEntryPerLocalDayOnCreate(t *testing.T) {
t.Errorf("all three instants fall on the user's Aug 7; expected one row, got %d", n)
}
}
+
+// Newest day first, even when the newest day is not the newest instant. Once a row's
+// day comes from logged_on, the two orderings part company: an entry filed for the 10th
+// from UTC+14 happened at an earlier moment than one filed for the 9th from UTC-11, so
+// ordering by the timestamp alone renders the list out of the order it appears to be in.
+func TestListWeightLogs_ordersByStoredDayNotInstant(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ insertWeightLogOn(t, uid, 180.0, "2026-08-10", "2026-08-09T22:00:00Z") // later day, earlier instant
+ insertWeightLogOn(t, uid, 170.0, "2026-08-09", "2026-08-09T23:00:00Z") // earlier day, later instant
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/weight?limit=2", nil)
+ th.ListWeightLogs(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+
+ data := decodeResponse(t, w)["data"].([]any)
+ if len(data) != 2 {
+ t.Fatalf("expected 2 entries, got %d", len(data))
+ }
+ if day := data[0].(map[string]any)["logged_on"]; day != "2026-08-10" {
+ t.Fatalf("newest day not first: got %v, want 2026-08-10", day)
+ }
+}
+
+func insertWeightLogOn(t *testing.T, uid int64, weight float64, day, loggedAt string) {
+ t.Helper()
+ if _, err := db.DB.Exec(
+ `INSERT INTO weight_logs (user_id, weight, notes, logged_at, logged_on) VALUES (?, ?, '', ?, ?)`,
+ uid, weight, loggedAt, day,
+ ); err != nil {
+ t.Fatalf("insert weight log: %v", err)
+ }
+}
diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.go
index 9e3566e..a95b1be 100644
--- a/backend/controllers/workouts.go
+++ b/backend/controllers/workouts.go
@@ -127,6 +127,15 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {
// stays zero: the store then preserves the stored timestamp instead of
// rewriting it to 0001-01-01 (WorkoutStore.Update).
req.StartedAt = req.StartedAt.UTC()
+ // An edit that moves the day also moves the instant, so the offset stored beside it
+ // has to be the one that instant was chosen in — otherwise readers apply the offset
+ // from wherever the workout was first logged and land a day off. Mirrors CreateWorkout:
+ // trust the client's offset, fall back to the account zone for clients too old to send
+ // one. Skipped for a name/notes-only patch (zero StartedAt), which leaves both alone.
+ if !req.StartedAt.IsZero() && req.TZOffsetMinutes == nil {
+ off := h.tzOffsetMinutes(uid, req.StartedAt)
+ req.TZOffsetMinutes = &off
+ }
w, err := h.s.Workout.Update(uid, wid, req)
if err == sql.ErrNoRows {
utils.NotFound(c, "workout not found")
diff --git a/backend/controllers/workouts_test.go b/backend/controllers/workouts_test.go
index 2bef031..3de9777 100644
--- a/backend/controllers/workouts_test.go
+++ b/backend/controllers/workouts_test.go
@@ -298,3 +298,87 @@ func TestListWorkouts_filtersBySearchQuery(t *testing.T) {
t.Errorf("expected 'Morning Push', got %v", name)
}
}
+
+// An edit that moves the day also moves the instant, so the offset stored beside it
+// must be the one that instant was chosen in. Leaving the creation-time offset on a
+// rewritten timestamp makes every reader derive a different day than the edit screen
+// showed: logged from UTC+14, edited from UTC-11, the workout lands a day early.
+func TestUpdateWorkout_carriesTZOffsetWithMovedInstant(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ // Created far east: noon local on the 9th is 22:00Z on the 8th.
+ res, _ := db.DB.Exec(
+ `INSERT INTO workouts (user_id, name, started_at, tz_offset_minutes) VALUES (?, ?, ?, ?)`,
+ uid, "Created east", "2026-08-08T22:00:00Z", 840,
+ )
+ wid, _ := res.LastInsertId()
+
+ // Re-dated from far west: noon local on the 5th is 23:00Z the same day.
+ body := map[string]any{
+ "name": "Edited west",
+ "duration": 1800,
+ "started_at": "2026-08-05T23:00:00Z",
+ "tz_offset_minutes": -660,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "sets": []map[string]any{{"set_number": 1, "reps": 10, "weight": 50.0}},
+ },
+ },
+ }
+ c, w := newContext(uid, http.MethodPut, "/api/v1/workouts/"+fmt.Sprint(wid), body)
+ setParam(c, "id", fmt.Sprint(wid))
+ th.UpdateWorkout(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var off int
+ if err := db.DB.QueryRow(`SELECT tz_offset_minutes FROM workouts WHERE id = ?`, wid).Scan(&off); err != nil {
+ t.Fatalf("read offset: %v", err)
+ }
+ if off != -660 {
+ t.Fatalf("offset not carried with the moved instant: got %d, want -660 (stale 840 means the day drifts)", off)
+ }
+}
+
+// A name/notes-only patch carries no instant, so it must leave the offset alone —
+// the workout still happened where it happened.
+func TestUpdateWorkout_omittedStartedAtKeepsTZOffset(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ res, _ := db.DB.Exec(
+ `INSERT INTO workouts (user_id, name, started_at, tz_offset_minutes) VALUES (?, ?, ?, ?)`,
+ uid, "Original", "2026-08-08T22:00:00Z", 840,
+ )
+ wid, _ := res.LastInsertId()
+
+ body := map[string]any{
+ "name": "Renamed only",
+ "duration": 1800,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "sets": []map[string]any{{"set_number": 1, "reps": 10, "weight": 50.0}},
+ },
+ },
+ }
+ c, w := newContext(uid, http.MethodPut, "/api/v1/workouts/"+fmt.Sprint(wid), body)
+ setParam(c, "id", fmt.Sprint(wid))
+ th.UpdateWorkout(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var off int
+ if err := db.DB.QueryRow(`SELECT tz_offset_minutes FROM workouts WHERE id = ?`, wid).Scan(&off); err != nil {
+ t.Fatalf("read offset: %v", err)
+ }
+ if off != 840 {
+ t.Fatalf("rename rewrote the offset: got %d, want 840", off)
+ }
+}
diff --git a/backend/stores/weight.go b/backend/stores/weight.go
index e9135f5..bd27e61 100644
--- a/backend/stores/weight.go
+++ b/backend/stores/weight.go
@@ -2,7 +2,6 @@ package stores
import (
"database/sql"
- "time"
"github.com/Cawlumm/lyftr-backend/models"
)
@@ -14,13 +13,12 @@ func NewWeightStore(db *sql.DB) *WeightStore { return &WeightStore{db: db} }
// WeightFilter holds resolved query bounds.
//
-// Two kinds, because the API accepts two kinds. A bare YYYY-MM-DD is a question about
-// the user's calendar and filters on the stored day; a full RFC3339 timestamp is a
-// question about instants and filters on logged_at. Neither consults a zone.
+// Days, not instants. "Show me last month" is a question about the user's calendar,
+// answered against the day each row was filed under — so it consults no zone and the
+// answer cannot move later.
type WeightFilter struct {
- Limit, Offset int
- From, To *time.Time // instant bounds, for an exact RFC3339 range
- FromDay, ToDay *string // inclusive day bounds, for a bare YYYY-MM-DD range
+ Limit, Offset int
+ FromDay, ToDay *string // inclusive day bounds, YYYY-MM-DD
}
// WeightStats is the computed summary for GetWeightStats.
@@ -35,14 +33,6 @@ const weightCols = `id, user_id, weight, notes, logged_at, logged_on, created_at
func (s *WeightStore) List(uid int64, f WeightFilter) ([]models.WeightLog, error) {
q := `SELECT ` + weightCols + ` FROM weight_logs WHERE user_id = ?`
args := []any{uid}
- if f.From != nil {
- q += ` AND logged_at >= ?`
- args = append(args, *f.From)
- }
- if f.To != nil {
- q += ` AND logged_at < ?`
- args = append(args, *f.To)
- }
if f.FromDay != nil {
q += ` AND logged_on >= ?`
args = append(args, *f.FromDay)
@@ -52,7 +42,11 @@ func (s *WeightStore) List(uid int64, f WeightFilter) ([]models.WeightLog, error
q += ` AND logged_on <= ?`
args = append(args, *f.ToDay)
}
- q += ` ORDER BY logged_at DESC, id DESC LIMIT ? OFFSET ?`
+ // Newest day first, and only then newest instant within it. Every reader labels a
+ // row with logged_on, so ordering by the instant alone puts the list out of the order
+ // it appears to be in: an entry filed for the 10th from UTC+14 is an earlier *moment*
+ // than one filed for the 9th from UTC-11, and sorted by instant it renders below it.
+ q += ` ORDER BY logged_on DESC, logged_at DESC, id DESC LIMIT ? OFFSET ?`
args = append(args, f.Limit, f.Offset)
rows, err := s.db.Query(q, args...)
@@ -169,13 +163,18 @@ func (s *WeightStore) Delete(uid, id int64) (int64, error) {
return n, nil
}
-func (s *WeightStore) Stats(uid int64) (WeightStats, error) {
+// Stats summarizes a user's weight history. since7d/since30d are the window bounds
+// as calendar days, resolved by the controller through the same helper every other
+// day query uses.
+func (s *WeightStore) Stats(uid int64, since7d, since30d string) (WeightStats, error) {
var latest, oldest, minW, maxW, avgW sql.NullFloat64
var count int
err := s.db.QueryRow(
`SELECT
- (SELECT weight FROM weight_logs WHERE user_id = ? ORDER BY logged_at DESC, id DESC LIMIT 1),
- (SELECT weight FROM weight_logs WHERE user_id = ? ORDER BY logged_at ASC, id ASC LIMIT 1),
+ -- "Latest" means the most recent day weighed, not the most recent instant: those
+ -- part company once a row's day comes from logged_on. Same ordering as List.
+ (SELECT weight FROM weight_logs WHERE user_id = ? ORDER BY logged_on DESC, logged_at DESC, id DESC LIMIT 1),
+ (SELECT weight FROM weight_logs WHERE user_id = ? ORDER BY logged_on ASC, logged_at ASC, id ASC LIMIT 1),
MIN(weight), MAX(weight), AVG(weight), COUNT(*)
FROM weight_logs WHERE user_id = ?`,
uid, uid, uid,
@@ -188,25 +187,28 @@ func (s *WeightStore) Stats(uid int64) (WeightStats, error) {
Min: minW.Float64, Max: maxW.Float64, Avg: avgW.Float64,
TotalEntries: count,
}
- if stats.Change7d, err = s.changeOver(uid, 7); err != nil {
+ if stats.Change7d, err = s.changeOver(uid, since7d); err != nil {
return WeightStats{}, err
}
- if stats.Change30d, err = s.changeOver(uid, 30); err != nil {
+ if stats.Change30d, err = s.changeOver(uid, since30d); err != nil {
return WeightStats{}, err
}
return stats, nil
}
-// changeOver returns latest minus earliest weight within the last `days` days,
-// or 0 with fewer than two entries in the window.
-func (s *WeightStore) changeOver(uid int64, days int) (float64, error) {
- cutoff := time.Now().UTC().AddDate(0, 0, -days)
+// changeOver returns latest minus earliest weight on or after sinceDay, or 0 with
+// fewer than two entries in the window.
+//
+// Bounded by the stored day rather than an instant `now - N*24h`. "The last 7 days"
+// is a question about the user's calendar, and answering it in UTC made it the one
+// window in the app resolved by a different rule than every other day query.
+func (s *WeightStore) changeOver(uid int64, sinceDay string) (float64, error) {
var latest, earliest sql.NullFloat64
if err := s.db.QueryRow(
`SELECT
- (SELECT weight FROM weight_logs WHERE user_id = ? AND logged_at >= ? ORDER BY logged_at DESC, id DESC LIMIT 1),
- (SELECT weight FROM weight_logs WHERE user_id = ? AND logged_at >= ? ORDER BY logged_at ASC, id ASC LIMIT 1)`,
- uid, cutoff, uid, cutoff,
+ (SELECT weight FROM weight_logs WHERE user_id = ? AND logged_on >= ? ORDER BY logged_on DESC, logged_at DESC, id DESC LIMIT 1),
+ (SELECT weight FROM weight_logs WHERE user_id = ? AND logged_on >= ? ORDER BY logged_on ASC, logged_at ASC, id ASC LIMIT 1)`,
+ uid, sinceDay, uid, sinceDay,
).Scan(&latest, &earliest); err != nil {
return 0, err
}
diff --git a/backend/stores/workout.go b/backend/stores/workout.go
index 882b945..2f0d1ce 100644
--- a/backend/stores/workout.go
+++ b/backend/stores/workout.go
@@ -176,8 +176,13 @@ func (s *WorkoutStore) Update(uid, id int64, req models.CreateWorkoutRequest) (m
return err
}
} else if _, err := tx.Exec(
- `UPDATE workouts SET name = ?, notes = ?, duration = ?, started_at = ? WHERE id = ?`,
- req.Name, req.Notes, req.Duration, req.StartedAt, id,
+ // The offset travels with the instant. Rewriting started_at without it leaves
+ // the row describing a moment in one zone and a day in another, so the day the
+ // edit screen showed and the day every reader derives disagree — the entry
+ // silently lands a day off. Only rewritten alongside started_at: the branch
+ // above is a name/notes patch, where the original offset is still the true one.
+ `UPDATE workouts SET name = ?, notes = ?, duration = ?, started_at = ?, tz_offset_minutes = ? WHERE id = ?`,
+ req.Name, req.Notes, req.Duration, req.StartedAt, req.TZOffsetMinutes, id,
); err != nil {
return err
}
diff --git a/mobile/.maestro/assert-day-after-travel.yaml b/mobile/.maestro/assert-day-after-travel.yaml
new file mode 100644
index 0000000..ffa9948
--- /dev/null
+++ b/mobile/.maestro/assert-day-after-travel.yaml
@@ -0,0 +1,33 @@
+# The point of the whole feature, on a real device: an entry keeps the day it was
+# filed under after the phone changes timezone.
+#
+# The runner flips the emulator's zone between log-weight.yaml and this flow, so the
+# app relaunches somewhere else entirely. EXPECTED_DAY is the day the entry was
+# written under, passed in by the runner; UNEXPECTED_DAY is the day it would drift to
+# if a screen went back to deriving the label from the device.
+#
+# Asserting both directions matters. EXPECTED_DAY alone passes on a list that renders
+# *both* days, which is exactly what a partial fix looks like — the history row
+# corrected while the chart or the detail header still reads the instant.
+#
+# This caught a real regression: with the device moved NY -> Tokyo, a row stored as
+# logged_on 2026-08-09 rendered "Aug 10, 2026", because the row formatted logged_at
+# (the instant) instead of the stored day.
+appId: local.lyftr.app
+env:
+ EXPECTED_DAY: ""
+ UNEXPECTED_DAY: ""
+---
+- runFlow: login.yaml
+
+- tapOn:
+ text: "Weight"
+ index: 0
+- assertVisible: "Track your body weight over time"
+
+- scrollUntilVisible:
+ element: "HISTORY"
+ direction: DOWN
+
+- assertVisible: ${EXPECTED_DAY}
+- assertNotVisible: ${UNEXPECTED_DAY}
diff --git a/mobile/.maestro/day-labels.yaml b/mobile/.maestro/day-labels.yaml
new file mode 100644
index 0000000..12c4b0c
--- /dev/null
+++ b/mobile/.maestro/day-labels.yaml
@@ -0,0 +1,34 @@
+# Every screen that names a day must name the day the row was filed under.
+#
+# The dashboard header is the one place the *device* zone is still the right answer
+# ("what is today"). Everything below it reads a stored value: diary rows carry
+# logged_on, workouts carry tz_offset_minutes. If a screen ever goes back to deriving
+# a day from the device, this fails on the screen that regressed.
+appId: local.lyftr.app
+---
+- runFlow: login.yaml
+
+# "What is today" — device zone, formatted like the dashboard header ("SUNDAY, AUGUST 9").
+- evalScript: |
+ ${output.todayHeader = new Date()
+ .toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })
+ .toUpperCase()}
+- assertVisible: ${output.todayHeader}
+
+# Workout rows render their day from the offset recorded when the workout started,
+# never from where the phone is now.
+- tapOn:
+ text: "Workouts"
+ index: 0
+- assertVisible: "Track and review your training sessions"
+- assertVisible: "[A-Z][a-z]{2} \\d{1,2}, \\d{4}"
+
+# Weight rows render logged_on verbatim.
+- tapOn:
+ text: "Weight"
+ index: 0
+- assertVisible: "Track your body weight over time"
+- scrollUntilVisible:
+ element: "History"
+ direction: DOWN
+- assertVisible: "[A-Z][a-z]{2} \\d{1,2}, \\d{4}"
diff --git a/mobile/.maestro/log-weight.yaml b/mobile/.maestro/log-weight.yaml
new file mode 100644
index 0000000..a49fa01
--- /dev/null
+++ b/mobile/.maestro/log-weight.yaml
@@ -0,0 +1,40 @@
+# Logs a weight and asserts it lands on the device's today.
+#
+# The weight value is left at its prefilled default — the day is what is under test,
+# not the number.
+#
+# The screen guards against a second entry on a day that already has one ("Already
+# logged on ... Log again anyway?"). That guard is a feature, but it means a bare
+# tapOn "Log Weight" can succeed as a *tap* while submitting nothing — which is how an
+# earlier version of this flow passed 13/13 without writing a row. Waving the guard
+# through keeps the flow honest on a day that already has an entry.
+appId: local.lyftr.app
+---
+- runFlow: login.yaml
+
+- tapOn:
+ text: "Weight"
+ index: 0
+- assertVisible: "Track your body weight over time"
+
+# "Log Weight" appears twice on this screen — the card heading and the submit button.
+# index 1 is the button; index 0 would tap the heading and silently do nothing.
+- tapOn:
+ text: "Log Weight"
+ index: 1
+
+- runFlow:
+ when:
+ visible: "Log Anyway"
+ commands:
+ - tapOn: "Log Anyway"
+
+- evalScript: |
+ ${output.day = new Date()
+ .toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
+
+# The row the app just wrote must be filed under the device's today.
+- scrollUntilVisible:
+ element: "HISTORY"
+ direction: DOWN
+- assertVisible: ${output.day}
diff --git a/mobile/.maestro/login.yaml b/mobile/.maestro/login.yaml
new file mode 100644
index 0000000..2c173e7
--- /dev/null
+++ b/mobile/.maestro/login.yaml
@@ -0,0 +1,43 @@
+# Reusable sign-in. Points the app at the dev backend and logs in as the demo user.
+#
+# 10.0.2.2 is the Android emulator's alias for the host machine's loopback — the
+# emulator has its own 127.0.0.1, so "localhost:3000" would resolve to the emulator
+# itself and fail. On a physical device over Tailscale, pass SERVER_URL instead:
+# maestro test -e SERVER_URL=http://100.x.y.z:3000 .maestro/login.yaml
+#
+# Selectors are text, because the app has no testIDs — mobile/CONVENTIONS.md puts
+# accessibilityLabel in their place, and Maestro matches those too.
+appId: local.lyftr.app
+env:
+ SERVER_URL: http://10.0.2.2:3000
+ PASSWORD: password123
+---
+- launchApp:
+ clearState: true
+ permissions:
+ all: deny
+
+- assertVisible: "Welcome back"
+
+# The URL field is collapsed behind a summary row until the row is tapped.
+- tapOn: "Server settings"
+- tapOn: "https://your-server.example.com"
+- inputText: ${SERVER_URL}
+- hideKeyboard
+- tapOn: "Test & save"
+# Proves the app reached *our* backend, not just that a field was filled.
+- assertVisible: "Connected to.*"
+
+- tapOn: "[email protected]"
+- inputText: ${EMAIL}
+# The soft keyboard covers the lower half of the form, so "below PASSWORD" resolves
+# to nothing until it is dismissed.
+- hideKeyboard
+- tapOn:
+ below: "PASSWORD"
+- inputText: ${PASSWORD}
+- hideKeyboard
+- tapOn: "Sign in"
+
+- assertVisible: "Good (morning|afternoon|evening), demo"
diff --git a/mobile/.maestro/run-travel-suite.sh b/mobile/.maestro/run-travel-suite.sh
new file mode 100644
index 0000000..2cafd6d
--- /dev/null
+++ b/mobile/.maestro/run-travel-suite.sh
@@ -0,0 +1,45 @@
+#!/usr/bin/env bash
+# Runs the day-attribution suite across a timezone change on a real Android runtime.
+#
+# Maestro cannot change a device's timezone, so this wraps it: log an entry in one
+# zone, move the device, assert the entry did not move with it. The hop is 13 hours
+# (New York -> Tokyo), deliberately past 12 — under 12 the old device-derived label
+# happened to survive for entries written near midday, which is why the bug hid for
+# so long.
+#
+# Usage: mobile/.maestro/run-travel-suite.sh [avd-serial]
+set -euo pipefail
+
+SERIAL="${1:-emulator-5554}"
+ADB="${ANDROID_HOME:-$LOCALAPPDATA/Android/Sdk}/platform-tools/adb"
+FLOWS="$(cd "$(dirname "$0")" && pwd)"
+
+set_tz() {
+ echo "── device timezone -> $1"
+ "$ADB" -s "$SERIAL" shell service call alarm 3 s16 "$1" >/dev/null
+ sleep 2
+}
+
+current_day() {
+ # The device's own idea of today, formatted the way the app renders a row.
+ "$ADB" -s "$SERIAL" shell date +%Y-%m-%d | tr -d '\r'
+}
+
+restore() { set_tz "America/New_York"; }
+trap restore EXIT
+
+set_tz "America/New_York"
+DAY_BEFORE="$(current_day)"
+echo "── device day before travel: $DAY_BEFORE"
+
+maestro test "$FLOWS/day-labels.yaml"
+maestro test "$FLOWS/log-weight.yaml"
+
+# Reformat to the app's display form: "Aug 9, 2026".
+EXPECTED_DAY="$(date -d "$DAY_BEFORE" '+%b %-d, %Y' 2>/dev/null || date -j -f %Y-%m-%d "$DAY_BEFORE" '+%b %-d, %Y')"
+echo "── expecting the entry to stay on: $EXPECTED_DAY"
+
+set_tz "Asia/Tokyo"
+maestro test -e EXPECTED_DAY="$EXPECTED_DAY" "$FLOWS/assert-day-after-travel.yaml"
+
+echo "── entry held its day across a 13-hour move"
diff --git a/mobile/app/(tabs)/index.tsx b/mobile/app/(tabs)/index.tsx
index ebc140a..828bad3 100644
--- a/mobile/app/(tabs)/index.tsx
+++ b/mobile/app/(tabs)/index.tsx
@@ -198,7 +198,11 @@ export default function Dashboard() {
// ── Derived data (unchanged from the 1:1 port) ─────────────────────────────
const weekStart = startOfWeek(now, { weekStartsOn: 1 })
- const weekWorkouts = workouts.filter((w) => new Date(w.started_at) >= weekStart)
+ // Compared as days, not instants: the dot strip below buckets by workoutDay, so a
+ // count taken from the raw timestamp can disagree with the dots it sits above for a
+ // workout logged near the week boundary in another zone.
+ const weekStartDay = format(weekStart, 'yyyy-MM-dd')
+ const weekWorkouts = workouts.filter((w) => workoutDay(w) >= weekStartDay)
const lastWorkout = workouts[0] ?? null
// "Up next": the first (most recently created) program whose due day is a
@@ -221,7 +225,7 @@ export default function Dashboard() {
}
const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map((w) => ({
- date: format(new Date(w.started_at), 'M/d'),
+ date: format(new Date(workoutDay(w) + 'T12:00:00'), 'M/d'),
volume: displayVolume(calcVolume(w), unit),
name: w.name,
}))
@@ -704,8 +708,15 @@ export default function Dashboard() {
lastLog={weightLogs[0] ?? null}
onClose={() => setSheetOpen(false)}
onSuccess={(log) => {
+ // Same order the server returns (logged_on DESC, logged_at DESC), so the
+ // optimistic row sits where the next refetch will put it. Sorting by the
+ // instant alone can place a cross-zone entry above or below its own label.
setWeightLogs((prev) =>
- [log, ...prev].sort((a, b) => new Date(b.logged_at).getTime() - new Date(a.logged_at).getTime())
+ [log, ...prev].sort(
+ (a, b) =>
+ entryDay(b).localeCompare(entryDay(a)) ||
+ new Date(b.logged_at).getTime() - new Date(a.logged_at).getTime()
+ )
)
client.weightAPI.stats().then(setWeightStats).catch(() => {})
}}
diff --git a/mobile/app/(tabs)/nutrition/[id].tsx b/mobile/app/(tabs)/nutrition/[id].tsx
index 051cc0f..28a86e9 100644
--- a/mobile/app/(tabs)/nutrition/[id].tsx
+++ b/mobile/app/(tabs)/nutrition/[id].tsx
@@ -1,9 +1,9 @@
import { useEffect, useState } from 'react'
import { Image, Pressable, ScrollView, Text, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
-import { format, parseISO } from 'date-fns'
+import { format } from 'date-fns'
import { AlertCircle, ArrowLeft, Edit2, Flame, Trash2 } from 'lucide-react-native'
-import type { FoodLog } from '@lyftr/shared'
+import { entryDay, type FoodLog } from '@lyftr/shared'
import {
AppText, Card, ConfirmSheet, Loading, Screen, deleteConfirmProps,
} from '../../../src/components/ui'
@@ -87,7 +87,7 @@ export default function NutritionDetail() {
...(entry.serving_size ? [{ label: 'Serving size', value: entry.serving_size }] : []),
{ label: 'Servings', value: String(entry.servings), tabular: true },
{ label: 'Meal', value: MEAL_LABELS[meal] },
- { label: 'Logged', value: format(parseISO(entry.logged_at), 'EEE, MMM d, yyyy') },
+ { label: 'Logged', value: format(new Date(entryDay(entry) + 'T12:00:00'), 'EEE, MMM d, yyyy') },
]
return (
diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsx
index 04ac0a0..339b0bc 100644
--- a/mobile/app/(tabs)/nutrition/log.tsx
+++ b/mobile/app/(tabs)/nutrition/log.tsx
@@ -6,7 +6,7 @@ import {
AlertCircle, ArrowLeft, Bookmark, BookmarkCheck, ChevronRight, Minus, Plus, Scan, Utensils, Zap,
} from 'lucide-react-native'
import {
- dayToInstant, todayStr,
+ dayToInstant, entryDay, todayStr,
type FoodLog, type FoodSearchResult, type SavedFood,
} from '@lyftr/shared'
import {
@@ -132,7 +132,7 @@ export default function LogFood() {
setSelected(entryToResult(entry))
setServingsStr(String(entry.servings || 1))
setMeal(entry.meal)
- setDate(entry.logged_at.slice(0, 10))
+ setDate(entryDay(entry))
setPhase('detail')
}).catch(() => router.replace('/nutrition'))
}, [editId])
diff --git a/mobile/app/(tabs)/weight/[id].tsx b/mobile/app/(tabs)/weight/[id].tsx
index 3203b2b..73c18b5 100644
--- a/mobile/app/(tabs)/weight/[id].tsx
+++ b/mobile/app/(tabs)/weight/[id].tsx
@@ -1,10 +1,10 @@
import { useEffect, useState } from 'react'
import { Pressable, ScrollView, Text, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
-import { format, parseISO } from 'date-fns'
+import { format } from 'date-fns'
import * as Haptics from 'expo-haptics'
import { AlertCircle, ArrowLeft, Edit2, Scale, Trash2 } from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, displayWeight, instantToDay, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay } from '@lyftr/shared'
+import { apiErrorMessage, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay } from '@lyftr/shared'
import {
AppText, Button, Card, ConfirmSheet, DateInput, Field, Label, Loading, NumberField,
NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, StepperTile, deleteConfirmProps,
@@ -174,7 +174,7 @@ export default function WeightDetail() {
<AppText variant="body" color="muted" className="mb-1.5">{wUnit}</AppText>
</View>
<AppText variant="body" color="muted" className="mt-1">
- {format(parseISO(log.logged_at), 'EEEE, MMMM d, yyyy')}
+ {format(new Date(entryDay(log) + 'T12:00:00'), 'EEEE, MMMM d, yyyy')}
</AppText>
{log.notes ? (
<AppText variant="body" color="secondary" className="mt-2 italic">"{log.notes}"</AppText>
@@ -241,7 +241,7 @@ export default function WeightDetail() {
<ConfirmSheet
{...deleteConfirmProps({
title: 'Delete Entry?',
- subject: `${format(parseISO(log.logged_at), 'MMMM d, yyyy')} · ${displayWeight(log.weight, unit)} ${wUnit}`,
+ subject: `${format(new Date(entryDay(log) + 'T12:00:00'), 'MMMM d, yyyy')} · ${displayWeight(log.weight, unit)} ${wUnit}`,
})}
open={confirming}
busy={deleting}
diff --git a/mobile/app/(tabs)/weight/index.tsx b/mobile/app/(tabs)/weight/index.tsx
index 8066d70..0bae67f 100644
--- a/mobile/app/(tabs)/weight/index.tsx
+++ b/mobile/app/(tabs)/weight/index.tsx
@@ -1,13 +1,13 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ActivityIndicator, FlatList, Pressable, RefreshControl, Text, View } from 'react-native'
import { useFocusEffect } from 'expo-router'
-import { format, parseISO, subDays } from 'date-fns'
+import { format, subDays } from 'date-fns'
import * as Haptics from 'expo-haptics'
import {
Activity, AlertCircle, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,
TrendingDown, TrendingUp, X,
} from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, daysAgoStr, displayToLbs, displayWeight, instantToDay, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay } from '@lyftr/shared'
+import { apiErrorMessage, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay } from '@lyftr/shared'
import {
AppText, Button, Card, DateInput, Field, Label, NumberField, NumericKeyboardAccessory,
NUMERIC_ACCESSORY_ID, PageHeader, Screen, SegmentedControl, StepperTile,
@@ -106,7 +106,7 @@ export default function Weight() {
const chartData: ChartPoint[] = useMemo(
() =>
[...chartLogs].reverse().map((l) => {
- const d = parseISO(l.logged_at)
+ const d = new Date(entryDay(l) + 'T12:00:00')
return { date: format(d, 'M/d'), weight: displayWeight(l.weight, unit), sub: format(d, 'MMM d, yyyy') }
}),
[chartLogs, unit]
@@ -291,7 +291,7 @@ export default function Weight() {
<AlertCircle size={16} color={brand.warningSoft} style={{ marginTop: 2 }} />
<View className="min-w-0 flex-1">
<Text className="font-sans-semibold text-sm text-warning-400">
- Already logged on {format(parseISO(items[0].logged_at), 'MMM d')} ({displayWeight(items[0].weight, unit)} {wUnit}). Log again anyway?
+ Already logged on {format(new Date(entryDay(items[0]) + 'T12:00:00'), 'MMM d')} ({displayWeight(items[0].weight, unit)} {wUnit}). Log again anyway?
</Text>
<View className="mt-2 flex-row gap-2">
<Pressable
diff --git a/mobile/app/(tabs)/workouts/[id]/edit.tsx b/mobile/app/(tabs)/workouts/[id]/edit.tsx
index 53a1167..eaec99b 100644
--- a/mobile/app/(tabs)/workouts/[id]/edit.tsx
+++ b/mobile/app/(tabs)/workouts/[id]/edit.tsx
@@ -5,7 +5,7 @@ import {
AlertCircle, ArrowLeft, CalendarDays, Clock, Dumbbell, FileText, Plus, Zap,
} from 'lucide-react-native'
import type { LucideIcon } from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, instantToDay, displayToLbs, lbsToDisplay, weightShort, type Exercise, workoutDay } from '@lyftr/shared'
+import { apiErrorMessage, dayToInstant, displayToLbs, lbsToDisplay, weightShort, type Exercise, workoutDay } from '@lyftr/shared'
import { AppText, Button, DateInput, EmptyState, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'
import { ExerciseFormCard } from '../../../../src/components/workouts/ExerciseFormCard'
import { DurationField } from '../../../../src/components/workouts/DurationField'
diff --git a/mobile/app/(tabs)/workouts/index.tsx b/mobile/app/(tabs)/workouts/index.tsx
index 1632735..4f5278c 100644
--- a/mobile/app/(tabs)/workouts/index.tsx
+++ b/mobile/app/(tabs)/workouts/index.tsx
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { ActivityIndicator, FlatList, RefreshControl, View } from '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 { format } from 'date-fns'
+import { weightShort, workoutDay, 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'
import { WorkoutsSkeleton } from '../../../src/components/workouts/WorkoutsSkeleton'
@@ -82,7 +83,9 @@ export default function Workouts() {
{ label: 'Total', value: String(workouts.length), unit: 'logged' },
{
label: 'This Month',
- value: String(workouts.filter((w) => new Date(w.started_at).getMonth() === now.getMonth()).length),
+ // The month the workout was logged in, not the month its UTC instant lands in —
+ // a session near a month boundary belongs to the month the lifter trained in.
+ value: String(workouts.filter((w) => workoutDay(w).startsWith(format(now, 'yyyy-MM'))).length),
unit: 'sessions',
},
{
diff --git a/mobile/src/components/dashboard/QuickWeighInSheet.tsx b/mobile/src/components/dashboard/QuickWeighInSheet.tsx
index ad7e271..d3cdec3 100644
--- a/mobile/src/components/dashboard/QuickWeighInSheet.tsx
+++ b/mobile/src/components/dashboard/QuickWeighInSheet.tsx
@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
import { Pressable, Text, View } from 'react-native'
import * as Haptics from 'expo-haptics'
import { AlertCircle, Scale, X } from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, displayToLbs, instantToDay, maxWeight, todayStr, weightError, weightShort, type WeightLog, entryDay } from '@lyftr/shared'
+import { apiErrorMessage, dayToInstant, displayToLbs, maxWeight, todayStr, weightError, weightShort, type WeightLog, entryDay } from '@lyftr/shared'
import {
AppText, Button, DateInput, Field, NumberField, NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID,
Sheet, StepperTile,
diff --git a/mobile/src/components/ui/DateInput.tsx b/mobile/src/components/ui/DateInput.tsx
index 549d93f..9bb1d73 100644
--- a/mobile/src/components/ui/DateInput.tsx
+++ b/mobile/src/components/ui/DateInput.tsx
@@ -41,6 +41,17 @@ export function DateInput({ label, value, onChange, maximumDate }: Props) {
const date = toLocalDate(value)
const isIOS = Platform.OS === 'ios'
+ // A bound must never exclude the value it is currently showing. The native dialog
+ // clamps its initial selection into range, and Android reports that clamped date as
+ // a normal 'set' — so a value past the bound gets rewritten to the bound by merely
+ // opening the picker and confirming, with the user having chosen nothing.
+ //
+ // Callers pass `new Date()` ("no future entries"), and an entry *can* sit past the
+ // device's today without being in the future: log in UTC+14, fly to UTC-11, and
+ // yesterday's entry is dated tomorrow. Silently moving it is the exact day-drift
+ // this codebase stores logged_on to prevent.
+ const effectiveMax = maximumDate && date > maximumDate ? date : maximumDate
+
const handleChange = (event: DateTimePickerEvent, selected?: Date) => {
// Android fires exactly once (set|dismissed) and the dialog is already gone.
// On iOS the inline picker stays up (it's in our Modal) — emit on 'set', keep
@@ -68,7 +79,7 @@ export function DateInput({ label, value, onChange, maximumDate }: Props) {
value={date}
mode="date"
display="default"
- maximumDate={maximumDate}
+ maximumDate={effectiveMax}
onChange={handleChange}
/>
)}
@@ -102,7 +113,7 @@ export function DateInput({ label, value, onChange, maximumDate }: Props) {
value={date}
mode="date"
display="inline"
- maximumDate={maximumDate}
+ maximumDate={effectiveMax}
onChange={handleChange}
themeVariant={isDark ? 'dark' : 'light'}
// Tint the selection to brand so it reads on-theme.
diff --git a/mobile/src/components/weight/WeightEntryRow.tsx b/mobile/src/components/weight/WeightEntryRow.tsx
index 9cb7b45..9293c7f 100644
--- a/mobile/src/components/weight/WeightEntryRow.tsx
+++ b/mobile/src/components/weight/WeightEntryRow.tsx
@@ -1,10 +1,10 @@
import { useState } from 'react'
import { Pressable, Text, View } from 'react-native'
import { router } from 'expo-router'
-import { format, parseISO } from 'date-fns'
+import { format } from 'date-fns'
import * as Haptics from 'expo-haptics'
import { ChevronRight, MoreVertical, Scale, TrendingDown, TrendingUp } from 'lucide-react-native'
-import { displayWeight, weightShort, type WeightLog } from '@lyftr/shared'
+import { displayWeight, entryDay, weightShort, type WeightLog } from '@lyftr/shared'
import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'
import { useTheme } from '../../theme/useTheme'
import { client } from '../../lib/lyftr'
@@ -32,7 +32,7 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {
const deltaLbs = next ? item.weight - next.weight : 0
const displayW = displayWeight(item.weight, unit)
const displayDelta = displayWeight(Math.abs(deltaLbs), unit)
- const dateLabel = format(parseISO(item.logged_at), 'MMM d, yyyy')
+ const dateLabel = format(new Date(entryDay(item) + 'T12:00:00'), 'MMM d, yyyy')
const handleDelete = async () => {
setDeleting(true)
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index 3fe9dec..ed64943 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -45,3 +45,46 @@ describe('foodAPI day windowing', () => {
expect(calls[0].params).toEqual({})
})
})
+
+// The offset must describe the instant being sent. A screen that re-picks the date
+// derives a new instant in this zone and wants this zone's offset; a screen that
+// resends the timestamp it loaded must keep the offset that instant was recorded with,
+// or an edit that never touched the date moves the workout's day.
+describe('workoutAPI tz_offset_minutes', () => {
+ const captureBody = () => {
+ const calls: Array<{ url?: string; body: any }> = []
+ const client = createClient(memStorage())
+ client.api.defaults.adapter = async (config: any) => {
+ calls.push({ url: config.url, body: JSON.parse(config.data ?? '{}') })
+ return { data: { data: {} }, status: 200, statusText: 'OK', headers: {}, config }
+ }
+ return { client, calls }
+ }
+
+ it('update keeps an offset the caller supplied', async () => {
+ const { client, calls } = captureBody()
+ await client.workoutAPI.update(1, {
+ name: 'Rep fix only',
+ started_at: '2026-07-01T23:00:00Z',
+ tz_offset_minutes: -240,
+ })
+ expect(calls[0].body.tz_offset_minutes).toBe(-240)
+ })
+
+ it('update stamps this zone only when the caller sends no offset', async () => {
+ const { client, calls } = captureBody()
+ const startedAt = '2026-07-01T23:00:00Z'
+ await client.workoutAPI.update(1, { name: 'Re-dated', started_at: startedAt })
+ expect(calls[0].body.tz_offset_minutes).toBe(-new Date(startedAt).getTimezoneOffset())
+ })
+
+ it('a zero offset is preserved rather than treated as absent', async () => {
+ const { client, calls } = captureBody()
+ await client.workoutAPI.update(1, {
+ name: 'Logged at UTC',
+ started_at: '2026-07-01T12:00:00Z',
+ tz_offset_minutes: 0,
+ })
+ expect(calls[0].body.tz_offset_minutes).toBe(0)
+ })
+})
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index d0bf243..7b0a087 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -149,7 +149,16 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
...data,
tz_offset_minutes: utcOffsetMinutes(data?.started_at),
}).then(unwrap),
- update: (id: number, data: any) => api.put<{ data: types.Workout }>(`/workouts/${id}`, data).then(unwrap),
+ // The offset must describe the instant being sent, so it is stamped only when the
+ // caller derived that instant here and now. The mobile edit screen re-picks the date
+ // through dayToInstant in this zone and omits the offset, so it gets this device's.
+ // A caller that resends the timestamp it loaded passes the stored offset through,
+ // because stamping there would move the day on an edit that never touched the date.
+ update: (id: number, data: any) =>
+ api.put<{ data: types.Workout }>(`/workouts/${id}`, {
+ ...data,
+ tz_offset_minutes: data?.tz_offset_minutes ?? utcOffsetMinutes(data?.started_at),
+ }).then(unwrap),
delete: (id: number) => api.delete(`/workouts/${id}`),
}
diff --git a/packages/shared/src/utils/dateUtils.ts b/packages/shared/src/utils/dateUtils.ts
index cd377dd..42f250c 100644
--- a/packages/shared/src/utils/dateUtils.ts
+++ b/packages/shared/src/utils/dateUtils.ts
@@ -1,11 +1,22 @@
-// Date helpers for the local-time write / UTC-store pattern used by the weight
-// feature. Ported verbatim from web/src/utils/dateUtils.ts so web and mobile share
-// one implementation.
+// The one place a calendar day is produced or read on the client.
//
-// Storage convention: timestamps are persisted as UTC ISO strings.
-// Display convention: rendered in the device's local timezone.
-// Date-only fields ("the date this entry is *for*"): anchored at local noon so the
-// entry's calendar day is robust across all plausible timezone offsets (±12h).
+// The model, which is the one Fitbit, Garmin, Strava and Health Connect all use: a
+// row stores the instant it happened *plus* enough to name its own day, and that day
+// is never re-derived from wherever the reader happens to be standing.
+//
+// diary entries (food, weight) — instant `logged_at` + stored day `logged_on`
+// workouts — instant `started_at` + offset `tz_offset_minutes`
+//
+// Two shapes because the two questions differ. A diary entry is *about* a day and the
+// user picks it; a workout happened at a moment and its day follows from where that
+// moment was. Fitbit splits them identically — a food log carries `logDate` with no
+// time at all, an activity carries an offset inline on `startTime`.
+//
+// The device zone still answers exactly one question, "what day is it now", for
+// `todayStr` and `daysAgoStr`. Everywhere else read the stored answer: `entryDay` and
+// `workoutDay` exist so no screen has to remember which of the two shapes it holds.
+//
+// Instants are persisted as UTC ISO strings and rendered in the device's zone.
/** Today's calendar date as YYYY-MM-DD in the device's local timezone. */
export const todayStr = (): string => {
@@ -65,11 +76,13 @@ export const dayToInstant = (yyyyMmDd: string, previousIso?: string): string =>
/**
* The local calendar day `n` days before today.
*
- * Exists so range queries build their day the same way everything else does. The
- * weight chart previously used date-fns `format(subDays(new Date(), n), 'yyyy-MM-dd')`,
- * which is a fourth path to a day string and drifts from the server's idea of one:
- * the server resolves a bare day through the *stored* zone, so a device-derived day
- * silently clips the oldest point whenever the two disagree.
+ * One of the only two functions here that consults the device zone, and legitimately:
+ * a window bound is a question about *now*, which no stored row can answer.
+ *
+ * Named so range queries build their day the same way `todayStr` does. The weight
+ * chart previously used date-fns `format(subDays(new Date(), n), 'yyyy-MM-dd')`, a
+ * fourth path to a day string that drifts the moment anything about the other three
+ * changes.
*/
export const daysAgoStr = (n: number): string => {
const d = new Date()
diff --git a/web/package.json b/web/package.json
index db0976a..fcfbd89 100644
--- a/web/package.json
+++ b/web/package.json
@@ -5,7 +5,7 @@
"type": "module",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
+ "build": "tsc -p tsconfig.build.json && vite build",
"preview": "vite preview",
"type-check": "tsc --noEmit",
"test:unit": "cross-env TZ=America/New_York vitest run",
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index 95d4a0a..74a2a58 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -178,7 +178,11 @@ export default function Dashboard() {
// ── Derived data ────────────────────────────────
const weekStart = startOfWeek(TODAY, { weekStartsOn: 1 })
- const weekWorkouts = workouts.filter(w => new Date(w.started_at) >= weekStart)
+ // Compared as days, not instants: the dot strip below buckets by workoutDay, so a
+ // count taken from the raw timestamp can disagree with the dots it sits above for a
+ // workout logged near the week boundary in another zone.
+ const weekStartDay = format(weekStart, 'yyyy-MM-dd')
+ const weekWorkouts = workouts.filter(w => workoutDay(w) >= weekStartDay)
const lastWorkout = workouts[0] ?? null
// "Up next": the first (most recently created) program whose due day is a
@@ -201,7 +205,7 @@ export default function Dashboard() {
// Volume chart: slice by selected period, oldest→newest
const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map(w => ({
- date: format(new Date(w.started_at), 'M/d'),
+ date: format(new Date(workoutDay(w) + 'T12:00:00'), 'M/d'),
volume: displayVolume(calcVolume(w), settings.weight_unit),
name: w.name,
}))
@@ -832,9 +836,14 @@ export default function Dashboard() {
lastLog={weightLogs[0] ?? null}
onClose={() => setSheetOpen(false)}
onSuccess={(log) => {
+ // Same order the server returns (logged_on DESC, logged_at DESC), so the
+ // optimistic row sits where the next refetch will put it. Sorting by the
+ // instant alone can place a cross-zone entry above or below its own label.
setWeightLogs(prev =>
[log, ...prev].sort(
- (a, b) => new Date(b.logged_at).getTime() - new Date(a.logged_at).getTime()
+ (a, b) =>
+ entryDay(b).localeCompare(entryDay(a)) ||
+ new Date(b.logged_at).getTime() - new Date(a.logged_at).getTime()
)
)
weightAPI.stats().then(setWeightStats).catch(() => {})
diff --git a/web/src/pages/EditWorkout.tsx b/web/src/pages/EditWorkout.tsx
index 008aeef..489256e 100644
--- a/web/src/pages/EditWorkout.tsx
+++ b/web/src/pages/EditWorkout.tsx
@@ -26,6 +26,10 @@ export default function EditWorkout() {
const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', duration: 0, exercises: [] })
const [originalStartedAt, setOriginalStartedAt] = useState('')
+ // This form has no date field, so it resends the instant it loaded. The offset has to
+ // travel with it unchanged: stamping the editing device's offset onto an untouched
+ // timestamp would move the workout's day on a rep-count fix made from another zone.
+ const [originalTZOffset, setOriginalTZOffset] = useState<number | undefined>(undefined)
useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])
@@ -38,6 +42,7 @@ export default function EditWorkout() {
;(workout.exercises || []).forEach(ex => { map[ex.exercise_id] = ex.exercise })
setPickerExercises(map)
setOriginalStartedAt(workout.started_at || new Date().toISOString())
+ setOriginalTZOffset(workout.tz_offset_minutes)
setFormData({
name: workout.name,
notes: workout.notes || '',
@@ -96,6 +101,7 @@ export default function EditWorkout() {
...formData,
duration: formData.duration * 60,
started_at: originalStartedAt || new Date().toISOString(),
+ tz_offset_minutes: originalTZOffset,
exercises: formData.exercises.map(ex => ({
...ex,
sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsx
index 654ee61..1c0a0d9 100644
--- a/web/src/pages/LogFood.tsx
+++ b/web/src/pages/LogFood.tsx
@@ -6,7 +6,7 @@ import {
Coffee, Sun, Moon, Cookie, ChevronRight,
} from 'lucide-react'
import { foodAPI, savedFoodsAPI } from '../services/api'
-import { todayStr, dayToInstant } from '../utils/dateUtils'
+import { todayStr, dayToInstant, entryDay } from '../utils/dateUtils'
import { MACRO_COLORS } from '../utils/macroColors'
import BarcodeScanner from '../components/BarcodeScanner'
import IconButton from '../components/ui/IconButton'
@@ -124,7 +124,7 @@ export default function LogFood() {
setSelected(entryToResult(entry))
setServings(entry.servings || 1)
setMeal(entry.meal)
- setDate(entry.logged_at.slice(0, 10))
+ setDate(entryDay(entry))
setPhase('detail')
}).catch(() => navigate('/food', { replace: true }))
}, [editId, navigate])
diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsx
index a5bfe7f..0929016 100644
--- a/web/src/pages/Weight.tsx
+++ b/web/src/pages/Weight.tsx
@@ -258,7 +258,7 @@ export default function Weight() {
.slice()
.reverse()
.map(l => {
- const d = new Date(l.logged_at)
+ const d = new Date(entryDay(l) + 'T12:00:00')
return { ts: d.getTime(), weight: lbsToDisplay(l.weight, settings.weight_unit), date: d }
})
}, [chartLogs, settings.weight_unit])
@@ -424,7 +424,7 @@ export default function Weight() {
<div className="flex items-start gap-3 rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-400" role="alert">
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
<div className="flex-1 min-w-0">
- <p className="font-medium">Already logged on {format(new Date(items[0].logged_at), 'MMM d')} ({displayWeight(items[0].weight, settings.weight_unit)} {wUnit}). Log again anyway?</p>
+ <p className="font-medium">Already logged on {format(new Date(entryDay(items[0]) + 'T12:00:00'), 'MMM d')} ({displayWeight(items[0].weight, settings.weight_unit)} {wUnit}). Log again anyway?</p>
<div className="flex gap-2 mt-2">
<button
type="button"
diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsx
index c7a73dd..78dbf65 100644
--- a/web/src/pages/Workouts.tsx
+++ b/web/src/pages/Workouts.tsx
@@ -248,7 +248,9 @@ export default function Workouts() {
<div className="grid grid-cols-3 gap-3">
{[
{ label: 'Total', value: workouts.length.toString(), unit: 'logged' },
- { label: 'This Month', value: workouts.filter(w => new Date(w.started_at).getMonth() === new Date().getMonth()).length.toString(), unit: 'sessions' },
+ // The month the workout was logged in, not the month its UTC instant lands in —
+ // a session near a month boundary belongs to the month the lifter trained in.
+ { label: 'This Month', value: workouts.filter(w => workoutDay(w).startsWith(format(new Date(), 'yyyy-MM'))).length.toString(), unit: 'sessions' },
{ label: 'Avg Time', value: workouts.length > 0 ? Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60).toString() : '0', unit: 'min' },
].map(s => (
<div key={s.label} className="card p-4">
diff --git a/web/src/services/api.ts b/web/src/services/api.ts
index 0f47bb1..61752a1 100644
--- a/web/src/services/api.ts
+++ b/web/src/services/api.ts
@@ -130,7 +130,16 @@ export const workoutAPI = {
...data,
tz_offset_minutes: utcOffsetMinutes(data?.started_at),
}).then(res => unwrap(res)),
- update: (id: number, data: any) => api.put<{ data: types.Workout }>(`/workouts/${id}`, data).then(res => unwrap(res)),
+ // The offset must describe the instant being sent, so it is stamped only when the
+ // caller derived that instant here and now. A screen that re-picks the date omits it
+ // and gets this device's offset; one that resends the timestamp it loaded passes the
+ // stored offset through, because stamping there would move the day on an edit that
+ // never touched the date.
+ update: (id: number, data: any) =>
+ api.put<{ data: types.Workout }>(`/workouts/${id}`, {
+ ...data,
+ tz_offset_minutes: data?.tz_offset_minutes ?? utcOffsetMinutes(data?.started_at),
+ }).then(res => unwrap(res)),
delete: (id: number) => api.delete(`/workouts/${id}`),
}
diff --git a/web/src/utils/dateUtils.fork.test.ts b/web/src/utils/dateUtils.fork.test.ts
new file mode 100644
index 0000000..d9787f7
--- /dev/null
+++ b/web/src/utils/dateUtils.fork.test.ts
@@ -0,0 +1,30 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+// web/src/utils/dateUtils.ts and packages/shared/src/utils/dateUtils.ts are a
+// deliberate fork: web is not part of the npm workspace (root workspaces are
+// `packages/*` and `mobile`), so it cannot import @lyftr/shared, and mobile cannot
+// import web's copy.
+//
+// A fork kept in step by hand is not a single source of truth — it is one until
+// somebody edits one side. This test makes the two files enforce each other: change
+// the day rules in one place and CI fails until the other matches. It is the closest
+// thing to consolidation available without restructuring the workspace and the Vite
+// and Docker builds that depend on its shape.
+//
+// Comments are compared too. The reasoning is the part most likely to drift and the
+// part most expensive to lose, since it is what stops the next reader reintroducing a
+// device-zone derivation.
+const read = (p: string) => readFileSync(resolve(__dirname, p), 'utf8').replace(/\r\n/g, '\n').trimEnd()
+
+describe('dateUtils forks', () => {
+ it('are byte-identical between web and shared', () => {
+ const web = read('./dateUtils.ts')
+ const shared = read('../../../packages/shared/src/utils/dateUtils.ts')
+
+ // Compared as line arrays so a failure points at the first differing line rather
+ // than dumping two whole files.
+ expect(web.split('\n')).toEqual(shared.split('\n'))
+ })
+})
diff --git a/web/src/utils/dateUtils.ts b/web/src/utils/dateUtils.ts
index 54096d0..42f250c 100644
--- a/web/src/utils/dateUtils.ts
+++ b/web/src/utils/dateUtils.ts
@@ -1,14 +1,24 @@
-/**
- * Date helpers for the local-time write / UTC-store pattern used by the
- * weight feature.
- *
- * Storage convention: timestamps are persisted as UTC ISO strings.
- * Display convention: rendered in the browser's local timezone.
- * Date-only fields ("the date this entry is *for*"): we anchor at local noon
- * so the entry's calendar day is robust across all plausible timezone offsets.
- */
+// The one place a calendar day is produced or read on the client.
+//
+// The model, which is the one Fitbit, Garmin, Strava and Health Connect all use: a
+// row stores the instant it happened *plus* enough to name its own day, and that day
+// is never re-derived from wherever the reader happens to be standing.
+//
+// diary entries (food, weight) — instant `logged_at` + stored day `logged_on`
+// workouts — instant `started_at` + offset `tz_offset_minutes`
+//
+// Two shapes because the two questions differ. A diary entry is *about* a day and the
+// user picks it; a workout happened at a moment and its day follows from where that
+// moment was. Fitbit splits them identically — a food log carries `logDate` with no
+// time at all, an activity carries an offset inline on `startTime`.
+//
+// The device zone still answers exactly one question, "what day is it now", for
+// `todayStr` and `daysAgoStr`. Everywhere else read the stored answer: `entryDay` and
+// `workoutDay` exist so no screen has to remember which of the two shapes it holds.
+//
+// Instants are persisted as UTC ISO strings and rendered in the device's zone.
-/** Today's calendar date as YYYY-MM-DD in the browser's local timezone. */
+/** Today's calendar date as YYYY-MM-DD in the device's local timezone. */
export const todayStr = (): string => {
const d = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
@@ -18,10 +28,12 @@ export const todayStr = (): string => {
/**
- * Extract a YYYY-MM-DD string in the browser's local timezone from any ISO
- * timestamp. Use this to populate `<input type="date">` fields when editing
- * an existing entry so the displayed date matches what the user originally
- * picked.
+ * The calendar day an instant falls on, in the device's local timezone.
+ *
+ * The inverse of `dayToInstant`, and the read half of the same loop: load an entry,
+ * show its day in a date field, save the picked day back as an instant. The pair is
+ * lossy in one direction only — this discards the time, which is why the other one
+ * takes the previous timestamp to put it back.
*/
export const instantToDay = (iso: string): string => {
const d = new Date(iso)
@@ -64,11 +76,13 @@ export const dayToInstant = (yyyyMmDd: string, previousIso?: string): string =>
/**
* The local calendar day `n` days before today.
*
- * Exists so range queries build their day the same way everything else does. The
- * weight chart previously used date-fns `format(subDays(new Date(), n), 'yyyy-MM-dd')`,
- * which is a fourth path to a day string and drifts from the server's idea of one:
- * the server resolves a bare day through the *stored* zone, so a device-derived day
- * silently clips the oldest point whenever the two disagree.
+ * One of the only two functions here that consults the device zone, and legitimately:
+ * a window bound is a question about *now*, which no stored row can answer.
+ *
+ * Named so range queries build their day the same way `todayStr` does. The weight
+ * chart previously used date-fns `format(subDays(new Date(), n), 'yyyy-MM-dd')`, a
+ * fourth path to a day string that drifts the moment anything about the other three
+ * changes.
*/
export const daysAgoStr = (n: number): string => {
const d = new Date()
diff --git a/web/tsconfig.build.json b/web/tsconfig.build.json
new file mode 100644
index 0000000..5df617d
--- /dev/null
+++ b/web/tsconfig.build.json
@@ -0,0 +1,12 @@
+{
+ // Production build only. `npm run type-check` uses tsconfig.json and still covers the
+ // tests; this config exists because the frontend image installs production dependencies
+ // only, so the @types/node that tests rely on (node:fs, __dirname in the dateUtils fork
+ // guard) is absent there. Locally those types resolve from the hoisted root
+ // node_modules, which is why the build passes here and failed in Docker.
+ //
+ // Excluding tests from the *build* costs nothing: nothing shipped imports them, and
+ // type-check keeps checking them.
+ "extends": "./tsconfig.json",
+ "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx", "e2e"]
+}