Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Show the catalog sync status in Settings (#213)
Carter612927b04ada
diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.goindex 2e63fe7..b912be3 100644--- a/backend/controllers/exercises.go+++ b/backend/controllers/exercises.go@@ -125,11 +125,12 @@ func (h *Handler) RefreshExerciseCache(c *gin.Context) {utils.OK(c, gin.H{"refreshed": n})}-// ExerciseCacheStatus reports how many catalog rows this instance holds.+// ExerciseCacheStatus reports how many catalog rows this instance holds and how catalog+// passes are going.func (h *Handler) ExerciseCacheStatus(c *gin.Context) {- count, err := h.s.Exercise.CachedCount()+ st, err := h.s.Exercise.CacheStatus()if utils.DBError(c, err) {return}- utils.OK(c, gin.H{"count": count})+ utils.OK(c, st)}diff --git a/backend/controllers/exercises_test.go b/backend/controllers/exercises_test.goindex a21e5da..4ac26c7 100644--- a/backend/controllers/exercises_test.go+++ b/backend/controllers/exercises_test.go@@ -3,7 +3,10 @@ package controllersimport ("fmt""net/http"+ "net/http/httptest"+ "strings""testing"+ "time""github.com/Cawlumm/lyftr-backend/db")@@ -275,3 +278,68 @@ func TestLocaleQueryParam(t *testing.T) {t.Errorf("GetExercise?locale=xx!! = %d %s, want 200 English", w.Code, w.Body.String())}}++func TestExerciseCacheStatus_shapeBeforeAnyPass(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ c, w := newContext(uid, http.MethodGet, "/api/v1/admin/seed-status", nil)+ th.ExerciseCacheStatus(c)++ data, _ := decodeResponse(t, w)["data"].(map[string]any)+ want := []string{"count", "syncing", "last_synced_at", "last_attempt_at", "next_attempt_at", "last_failed", "last_failure"}+ if len(data) != len(want) {+ t.Errorf("data = %v, want exactly %v", data, want)+ }+ for _, k := range want {+ if _, ok := data[k]; !ok {+ t.Errorf("key %q missing from %v", k, data)+ }+ }+ for _, k := range []string{"last_synced_at", "last_attempt_at", "next_attempt_at", "last_failure"} {+ if v, ok := data[k]; !ok || v != nil {+ t.Errorf("%s = %v, want null", k, v)+ }+ }+ if data["count"] != float64(0) || data["syncing"] != false || data["last_failed"] != false {+ t.Errorf("data = %v", data)+ }+}++func seedStatusAfter(t *testing.T, w *httptest.ResponseRecorder) map[string]any {+ t.Helper()+ if w.Code != http.StatusOK && w.Code != http.StatusServiceUnavailable {+ t.Fatalf("refresh = %d", w.Code)+ }+ c, w2 := newContext(1, http.MethodGet, "/api/v1/admin/seed-status", nil)+ th.ExerciseCacheStatus(c)+ data, _ := decodeResponse(t, w2)["data"].(map[string]any)+ return data+}++func TestExerciseCacheStatus_afterFailedRefresh(t *testing.T) {+ w := refreshWithCatalog(t, "http://127.0.0.1:1")+ data := seedStatusAfter(t, w)+ if data["last_failed"] != true || data["last_failure"] != "unreachable" || data["last_synced_at"] != nil {+ t.Fatalf("data = %v, want failed unreachable with no success", data)+ }+ at, _ := data["last_attempt_at"].(string)+ if _, err := time.Parse(time.RFC3339, at); err != nil || !strings.HasSuffix(at, "Z") {+ t.Errorf("last_attempt_at = %q, want RFC3339 UTC", at)+ }+}++func TestExerciseCacheStatus_afterSuccessfulRefresh(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"exercises":[{"id":"uuid-1","slug":"held","muscle_group":"chest","translation":{"name":"Held Renamed","instructions":[]}},{"id":"uuid-2","slug":"new","muscle_group":"back","translation":{"name":"New One","instructions":[]}}],"total":2}`))+ }))+ defer srv.Close()+ w := refreshWithCatalog(t, srv.URL)+ data := seedStatusAfter(t, w)+ if data["count"] != float64(2) || data["last_failed"] != false || data["last_failure"] != nil || data["syncing"] != false {+ t.Fatalf("data = %v", data)+ }+ at, _ := data["last_synced_at"].(string)+ if _, err := time.Parse(time.RFC3339, at); err != nil || !strings.HasSuffix(at, "Z") {+ t.Errorf("last_synced_at = %q, want RFC3339 UTC", at)+ }+}diff --git a/backend/models/models.go b/backend/models/models.goindex eaf9b36..4f5fe4d 100644--- a/backend/models/models.go+++ b/backend/models/models.go@@ -531,3 +531,15 @@ type DailyStats struct {type ActiveSessionRequest struct {Data string `json:"data" binding:"required"`}++// ExerciseCacheStatus is what GET /admin/seed-status reports. The sync fields are this+// process's memory, so they read null after a restart until the boot pass ends.+type ExerciseCacheStatus struct {+ Count int `json:"count"`+ Syncing bool `json:"syncing"`+ LastSyncedAt *time.Time `json:"last_synced_at"`+ LastAttemptAt *time.Time `json:"last_attempt_at"`+ NextAttemptAt *time.Time `json:"next_attempt_at"`+ LastFailed bool `json:"last_failed"`+ LastFailure *string `json:"last_failure"`+}diff --git a/backend/stores/exercise.go b/backend/stores/exercise.goindex debd7d0..81bb865 100644--- a/backend/stores/exercise.go+++ b/backend/stores/exercise.go@@ -9,6 +9,7 @@ import ("log""sort""strings"+ "sync""sync/atomic""time"@@ -26,6 +27,9 @@ type ExerciseStore struct {// syncing is held for the length of a catalog pass, so the daily timer and the// admin endpoint can never run two imports against the one SQLite connection.syncing atomic.Bool+ // status is how recent passes went. syncing above stays the one running flag.+ statusMu sync.Mutex+ status models.ExerciseCacheStatus}func NewExerciseStore(db *sql.DB) *ExerciseStore { return &ExerciseStore{db: db} }@@ -578,12 +582,28 @@ var ErrCatalogUnreachable = errors.New("exercise catalog unreachable")// ErrSyncRunning is returned when a catalog pass is already in progress.var ErrSyncRunning = errors.New("exercise sync already running")-// CachedCount reports how many catalog rows this instance currently holds.+// CacheStatus reports how many catalog rows this instance currently holds and how the+// sync passes are going.//// After the first scheduled pass the table holds the whole catalog plus any legacy// rows; before it, only what reads have had reason to record. A fresh install reports// zero and is fully functional.-func (s *ExerciseStore) CachedCount() (int, error) { return s.Count() }+func (s *ExerciseStore) CacheStatus() (models.ExerciseCacheStatus, error) {+ n, err := s.Count()+ if err != nil {+ return models.ExerciseCacheStatus{}, err+ }+ // Flag first: recordPass runs before it is released, so a reader that sees it down+ // is guaranteed to read the finished pass's outcome below.+ syncing := s.syncing.Load()+ s.statusMu.Lock()+ st := s.status+ s.statusMu.Unlock()+ st.Count = n+ st.Syncing = syncing+ st.LastFailed = st.LastFailure != nil+ return st, nil+}// RefreshCached is the scheduled catalog pass run on demand: it imports every upstream// exercise in English and re-reads every held one in each other language. The int isdiff --git a/backend/stores/exercise_locale_sync.go b/backend/stores/exercise_locale_sync.goindex e62146b..80ed068 100644--- a/backend/stores/exercise_locale_sync.go+++ b/backend/stores/exercise_locale_sync.go@@ -18,6 +18,11 @@ const CatalogSyncInterval = 24 * time.Hour// a pass comes back clean; CatalogSyncInterval still caps every wait.var catalogRetryBackoff = []time.Duration{time.Minute, 5 * time.Minute, 30 * time.Minute}+const (+ syncFailureUnreachable = "unreachable"+ syncFailureOther = "other"+)+// localeSyncTimeout bounds locale discovery and each language, so a hung upstream cannot// stall the loop. A var so a test can shrink it.var localeSyncTimeout = 2 * time.Minute@@ -32,6 +37,7 @@ func (s *ExerciseStore) RunCatalogSync(ctx context.Context, every time.Duration)}failures := 0for {+ s.setNextAttempt(nil)wait := everyif _, err := s.syncCatalog(ctx); err != nil {wait = retryDelay(failures, every)@@ -40,6 +46,8 @@ func (s *ExerciseStore) RunCatalogSync(ctx context.Context, every time.Duration)} else {failures = 0}+ next := time.Now().Add(wait).UTC()+ s.setNextAttempt(&next)select {case <-ctx.Done():return@@ -48,6 +56,32 @@ func (s *ExerciseStore) RunCatalogSync(ctx context.Context, every time.Duration)}}+func (s *ExerciseStore) setNextAttempt(t *time.Time) {+ s.statusMu.Lock()+ defer s.statusMu.Unlock()+ s.status.NextAttemptAt = t+}++// recordPass is the one place a finished pass is written to the status. A failed pass+// leaves LastSyncedAt at the last clean one.+func (s *ExerciseStore) recordPass(started time.Time, err error) {+ s.statusMu.Lock()+ defer s.statusMu.Unlock()+ at := started.UTC()+ s.status.LastAttemptAt = &at+ if err == nil {+ now := time.Now().UTC()+ s.status.LastSyncedAt = &now+ s.status.LastFailure = nil+ return+ }+ reason := syncFailureOther+ if errors.Is(err, ErrCatalogUnreachable) {+ reason = syncFailureUnreachable+ }+ s.status.LastFailure = &reason+}+// retryDelay is the wait after the failures-th consecutive failed pass, never longer than// the regular interval.func retryDelay(failures int, every time.Duration) time.Duration {@@ -58,7 +92,7 @@ func retryDelay(failures int, every time.Duration) time.Duration {// syncCatalog is the one catalog pass. English goes first, because it creates the rows// every translation attaches to; the other languages follow. The int is how many// exercises the English pass recorded. A language that fails does not stop the rest.-func (s *ExerciseStore) syncCatalog(ctx context.Context) (int, error) {+func (s *ExerciseStore) syncCatalog(ctx context.Context) (_ int, err error) {if s.catalog == nil {return 0, ErrNoCatalog}@@ -66,6 +100,10 @@ func (s *ExerciseStore) syncCatalog(ctx context.Context) (int, error) {return 0, ErrSyncRunning}defer s.syncing.Store(false)+ started := time.Now()+ // Deferred after the flag's release, so it runs first: a reader never sees the pass+ // finished with the old outcome.+ defer func() { s.recordPass(started, err) }()dctx, cancel := context.WithTimeout(ctx, localeSyncTimeout)codes, err := s.catalog.Revalidating().Locales(dctx)cancel()diff --git a/backend/stores/exercise_locale_sync_test.go b/backend/stores/exercise_locale_sync_test.goindex eafcc97..c14aa52 100644--- a/backend/stores/exercise_locale_sync_test.go+++ b/backend/stores/exercise_locale_sync_test.go@@ -693,3 +693,183 @@ func TestSyncCatalog_RefusesASecondPassWhileOneRuns(t *testing.T) {t.Error("the flag was left held after a pass")}}++func TestCacheStatus_NothingKnownBeforeAPass(t *testing.T) {+ s := NewExerciseStore(testDB(t))+ st, err := s.CacheStatus()+ if err != nil {+ t.Fatal(err)+ }+ if st.LastSyncedAt != nil || st.LastAttemptAt != nil || st.NextAttemptAt != nil || st.LastFailure != nil {+ t.Errorf("status = %+v, want every time and the reason unknown", st)+ }+ if st.LastFailed || st.Syncing || st.Count != 0 {+ t.Errorf("status = %+v, want not failed, not syncing, count 0", st)+ }+}++func TestSyncCatalog_CleanPassRecordsSuccess(t *testing.T) {+ s, _ := syncStore(t, 2, "en")+ before := time.Now()+ if _, err := s.syncCatalog(t.Context()); err != nil {+ t.Fatal(err)+ }+ after := time.Now()+ st, _ := s.CacheStatus()+ if st.LastAttemptAt == nil || st.LastSyncedAt == nil {+ t.Fatalf("status = %+v, want both times set", st)+ }+ for _, ts := range []*time.Time{st.LastAttemptAt, st.LastSyncedAt} {+ if ts.Before(before) || ts.After(after) {+ t.Errorf("time %s outside [%s, %s]", ts, before, after)+ }+ if ts.Location() != time.UTC {+ t.Errorf("time %s is not UTC", ts)+ }+ }+ if st.LastAttemptAt.After(*st.LastSyncedAt) {+ t.Errorf("attempt %s after success %s", st.LastAttemptAt, st.LastSyncedAt)+ }+ if st.LastFailed || st.LastFailure != nil || st.Syncing {+ t.Errorf("status = %+v, want clean and idle", st)+ }+}++func TestSyncCatalog_UnreachableFailureKeepsLastSuccess(t *testing.T) {+ s, cat := syncStore(t, 2, "en")+ if _, err := s.syncCatalog(t.Context()); err != nil {+ t.Fatal(err)+ }+ first, _ := s.CacheStatus()++ cat.setFail("/api/v1/meta/locales", "")+ time.Sleep(2 * time.Millisecond)+ if _, err := s.syncCatalog(t.Context()); !errors.Is(err, ErrCatalogUnreachable) {+ t.Fatalf("err = %v, want unreachable", err)+ }+ st, _ := s.CacheStatus()+ if !st.LastFailed || st.LastFailure == nil || *st.LastFailure != "unreachable" {+ t.Fatalf("status = %+v, want failed unreachable", st)+ }+ if !st.LastSyncedAt.Equal(*first.LastSyncedAt) {+ t.Errorf("LastSyncedAt moved to %s on a failed pass, want %s", st.LastSyncedAt, first.LastSyncedAt)+ }+ if !st.LastAttemptAt.After(*first.LastAttemptAt) {+ t.Errorf("LastAttemptAt = %s, want after %s", st.LastAttemptAt, first.LastAttemptAt)+ }++ cat.mu.Lock()+ delete(cat.failPath, "/api/v1/meta/locales")+ cat.mu.Unlock()+ if _, err := s.syncCatalog(t.Context()); err != nil {+ t.Fatal(err)+ }+ st, _ = s.CacheStatus()+ if st.LastFailed || st.LastFailure != nil {+ t.Errorf("status = %+v, want the failure cleared by a clean pass", st)+ }+}++func TestSyncCatalog_DatabaseFailureIsOther(t *testing.T) {+ s, _ := catalogStore(t, 250, "en")+ if _, err := s.db.Exec("CREATE TRIGGER t BEFORE INSERT ON exercises WHEN NEW.oedb_id = 'uuid-150' BEGIN SELECT RAISE(ABORT, 'boom'); END"); err != nil {+ t.Fatal(err)+ }+ if _, err := s.syncCatalog(t.Context()); err == nil {+ t.Fatal("want an error")+ }+ st, _ := s.CacheStatus()+ if !st.LastFailed || st.LastFailure == nil || *st.LastFailure != "other" {+ t.Errorf("status = %+v, want failed other", st)+ }+}++func TestSyncCatalog_RefusedPassRecordsNothing(t *testing.T) {+ s, _ := syncStore(t, 1, "en")+ s.syncing.Store(true)+ if _, err := s.syncCatalog(t.Context()); !errors.Is(err, ErrSyncRunning) {+ t.Fatalf("err = %v, want ErrSyncRunning", err)+ }+ st, _ := s.CacheStatus()+ if st.LastAttemptAt != nil || st.LastFailed {+ t.Errorf("status = %+v, want a refused pass to record nothing", st)+ }+ if !st.Syncing {+ t.Error("Syncing = false, want it read from the running flag")+ }+}++func TestCacheStatus_ReportsRunningDuringAPassAndReleasesAfter(t *testing.T) {+ release := make(chan struct{})+ started := make(chan struct{}, 1)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if strings.Contains(r.URL.Path, "locales") {+ select {+ case started <- struct{}{}:+ default:+ }+ <-release+ _, _ = w.Write([]byte(`{"locales":[],"total":0}`))+ return+ }+ _, _ = w.Write([]byte(`{"exercises":[],"total":0}`))+ }))+ defer srv.Close()+ s := NewExerciseStore(testDB(t))+ s.UseCatalog(oedb.New(srv.URL, "test"))++ done := make(chan struct{})+ go func() {+ defer close(done)+ _, _ = s.syncCatalog(t.Context())+ }()+ <-started+ st, _ := s.CacheStatus()+ if !st.Syncing || st.LastAttemptAt != nil {+ t.Errorf("mid-pass status = %+v, want syncing with no attempt recorded yet", st)+ }+ close(release)+ <-done+ st, _ = s.CacheStatus()+ if st.Syncing || st.LastSyncedAt == nil {+ t.Errorf("after status = %+v, want idle and synced", st)+ }+}++func TestRunCatalogSync_SchedulesNextAttempt(t *testing.T) {+ t.Run("clean pass waits the full interval", func(t *testing.T) {+ s, _ := syncStore(t, 2, "en")+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ go s.RunCatalogSync(ctx, time.Hour)+ waitFor(t, func() bool {+ st, _ := s.CacheStatus()+ return st.LastSyncedAt != nil && st.NextAttemptAt != nil+ })+ st, _ := s.CacheStatus()+ if st.NextAttemptAt.Before(st.LastSyncedAt.Add(time.Hour-time.Second)) || st.NextAttemptAt.After(time.Now().Add(time.Hour)) {+ t.Errorf("next = %s, want about an hour after %s", st.NextAttemptAt, st.LastSyncedAt)+ }+ })+ t.Run("failed pass waits the retry delay", func(t *testing.T) {+ old := catalogRetryBackoff+ catalogRetryBackoff = []time.Duration{30 * time.Minute}+ t.Cleanup(func() { catalogRetryBackoff = old })+ s, cat := syncStore(t, 2, "en")+ cat.setFail("/api/v1/meta/locales", "")+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ go s.RunCatalogSync(ctx, time.Hour)+ waitFor(t, func() bool {+ st, _ := s.CacheStatus()+ return st.NextAttemptAt != nil+ })+ st, _ := s.CacheStatus()+ if d := time.Until(*st.NextAttemptAt); d < 29*time.Minute || d > 30*time.Minute {+ t.Errorf("next in %s, want about 30m, not the full hour", d)+ }+ if st.LastFailure == nil || *st.LastFailure != "unreachable" {+ t.Errorf("status = %+v, want unreachable", st)+ }+ })+}diff --git a/docs/API_CHANGES.md b/docs/API_CHANGES.mdindex 54bfe44..b91170d 100644--- a/docs/API_CHANGES.md+++ b/docs/API_CHANGES.md@@ -14,6 +14,17 @@ catches what the author knew and forgot; it cannot catch what the author never nIf your PR changes a status code, narrows an accepted value, or renames a response field,add the entry in that PR.+## `GET /api/v1/admin/seed-status` — gains sync status (additive)++`count` is unchanged. The response now also carries `syncing` (a catalog pass is running),+`last_synced_at` (when the last clean pass ended), `last_attempt_at` (when the last pass+started), `next_attempt_at` (when the scheduled pass runs next, null while one runs),+`last_failed`, and `last_failure` (`"unreachable"` for an open-exercise-db outage,+`"other"` for anything else, null when the last pass was clean). Times are RFC3339 UTC and+may carry fractional seconds; unknown ones are null. The values live in memory, so they are+null after a restart until the boot pass finishes. Callers that read only `count` see no+change.+## `POST /api/v1/admin/reset-exercises` removed; `POST /api/v1/admin/sync-exercises` imports the whole catalog`reset-exercises` no longer exists and answers 404, so a caller using it to drop unreferenceddiff --git a/packages/shared/src/client.ts b/packages/shared/src/client.tsindex 6f4fbfb..bbfbe8c 100644--- a/packages/shared/src/client.ts+++ b/packages/shared/src/client.ts@@ -451,7 +451,7 @@ export function createClient(getHistory: (id: number, limit = 20) => api.get<{ data: types.ExerciseHistoryPoint[] }>(`/exercises/${id}/history`, { params: { limit } }).then(unwrap),// The server imports the whole open-exercise-db catalog in a daily background pass;// these two report its size and run that pass now.- cacheStatus: () => api.get<{ data: { count: number } }>('/admin/seed-status').then(unwrap),+ cacheStatus: () => api.get<{ data: types.ExerciseCacheStatus }>('/admin/seed-status').then(unwrap),// Runs the full catalog pass now: imports every upstream exercise and refreshes every// language. On a cold server that runs past the// global 20s — the button is an explicit admin action the user waits on, so it getsdiff --git a/packages/shared/src/hooks/useServerList.ts b/packages/shared/src/hooks/useServerList.tsindex 6c8c492..048e5af 100644--- a/packages/shared/src/hooks/useServerList.ts+++ b/packages/shared/src/hooks/useServerList.ts@@ -25,7 +25,10 @@ import { useTranslation } from '../i18n'interface Options<T> {fetcher: (offset: number, limit: number) => Promise<T[]>pageSize?: number- // Changing any dep resets the list and re-fetches from offset 0 (e.g. search query)+ // Changing any dep resets the list and re-fetches from offset 0 (e.g. search query).+ // Compared with Object.is, so pass primitives or stable references: a fresh object or+ // array each render reads as a change every render, which keeps hasMore true and+ // refetches page 0 every render.deps?: readonly unknown[]// Shown when the server gives us nothing better to say. Pass it translated, at render.errorFallback?: stringdiff --git a/packages/shared/src/i18n/locales/en.json b/packages/shared/src/i18n/locales/en.jsonindex 7d690ad..21f14c2 100644--- a/packages/shared/src/i18n/locales/en.json+++ b/packages/shared/src/i18n/locales/en.json@@ -181,7 +181,12 @@"refreshed_other": "Refreshed {{amount}} exercises","refresh": "Refresh cached","refreshing": "Refreshing…",- "refreshFailed": "Couldn't refresh the cache."+ "refreshFailed": "Couldn't refresh the cache.",+ "lastSynced": "Last synced at {{when}}",+ "syncing": "Syncing…",+ "syncUnreachable": "Last sync couldn't reach the exercise catalog.",+ "syncFailed": "Last sync didn't finish.",+ "syncRetry": "Trying again at {{when}}."},"danger": {"title": "Danger Zone",@@ -220,7 +225,9 @@"weekdayMonthDay": "EEE, MMM d","weekdayMonthDayYear": "EEE, MMM d, yyyy","year": "yyyy",- "monthYearLong": "MMMM yyyy"+ "monthYearLong": "MMMM yyyy",+ "time": "h:mm a",+ "monthDayTime": "MMM d, h:mm a"},"day": {"today": "Today",diff --git a/packages/shared/src/i18n/locales/es.json b/packages/shared/src/i18n/locales/es.jsonindex 879a376..afb8876 100644--- a/packages/shared/src/i18n/locales/es.json+++ b/packages/shared/src/i18n/locales/es.json@@ -183,7 +183,12 @@"refreshed_other": "Se actualizaron {{amount}} ejercicios","refresh": "Actualizar caché","refreshing": "Actualizando…",- "refreshFailed": "No se pudo actualizar la caché."+ "refreshFailed": "No se pudo actualizar la caché.",+ "lastSynced": "Última sincronización: {{when}}",+ "syncing": "Sincronizando…",+ "syncUnreachable": "La última sincronización no pudo conectar con el catálogo de ejercicios.",+ "syncFailed": "La última sincronización no terminó.",+ "syncRetry": "Nuevo intento: {{when}}."},"danger": {"title": "Zona de peligro",@@ -222,7 +227,9 @@"weekdayMonthDay": "EEE, d MMM","weekdayMonthDayYear": "EEE, d MMM yyyy","year": "yyyy",- "monthYearLong": "MMMM 'de' yyyy"+ "monthYearLong": "MMMM 'de' yyyy",+ "time": "H:mm",+ "monthDayTime": "d MMM, H:mm"},"day": {"today": "Hoy",diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex cfc1561..95d7cc6 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -319,3 +319,14 @@ export interface ChangePasswordRequest {current_password: stringnew_password: string}++// The sync fields are absent from servers older than the one that added them.+export interface ExerciseCacheStatus {+ count: number+ syncing?: boolean+ last_synced_at?: string | null+ last_attempt_at?: string | null+ next_attempt_at?: string | null+ last_failed?: boolean+ last_failure?: 'unreachable' | 'other' | null+}diff --git a/packages/shared/src/utils/dateUtils.test.ts b/packages/shared/src/utils/dateUtils.test.tsindex 4d4bde6..0c7c37f 100644--- a/packages/shared/src/utils/dateUtils.test.ts+++ b/packages/shared/src/utils/dateUtils.test.ts@@ -1,4 +1,4 @@-import { todayStr, daysAgoStr, dayToInstant, dayToLocalDate, instantToDay, entryDay, workoutDay, memberSince, withLoggedOn, formatDay, formatDate, relativeDayLabel, defaultWorkoutName, UNKNOWN_DAY, type DateFormatName } from './dateUtils'+import { todayStr, daysAgoStr, dayToInstant, dayToLocalDate, instantToDay, entryDay, workoutDay, memberSince, withLoggedOn, formatDay, formatDate, formatInstant, relativeDayLabel, defaultWorkoutName, UNKNOWN_DAY, type DateFormatName } from './dateUtils'import { i18n } from '../i18n'@@ -284,6 +284,8 @@ describe('display format names', () => {weekdayMonthDayYear: 'Sat, Oct 10, 2026',year: '2026',monthYearLong: 'October 2026',+ time: '12:00 PM',+ monthDayTime: 'Oct 10, 12:00 PM',}it.each(Object.entries(en))('en %s', (name, expected) => {@@ -301,6 +303,8 @@ describe('display format names', () => {expect(formatDay('2026-08-01', 'numericMonthDay')).toBe('1/8')expect(formatDay(day, 'weekdayDate')).toBe('sábado, 10 de octubre de 2026')expect(formatDay(day, 'monthYearLong')).toBe('octubre de 2026')+ expect(formatDay(day, 'time')).toBe('12:00')+ expect(formatDay(day, 'monthDayTime')).toBe('10 oct, 12:00')})it('keeps an unknown day unknown', () => {@@ -342,3 +346,29 @@ describe('defaultWorkoutName', () => {}})})++describe('formatInstant', () => {+ const today = () => { const n = new Date(); n.setHours(15, 42, 0, 0); return n }++ it('shows the time alone for today', () => {+ expect(formatInstant(today().toISOString())).toBe('3:42 PM')+ })++ it('adds the date for another day', () => {+ expect(formatInstant(new Date(2020, 9, 10, 15, 42).toISOString())).toBe('Oct 10, 3:42 PM')+ })++ it('reads an unreadable instant as unknown', () => {+ expect(formatInstant('garbage')).toBe(UNKNOWN_DAY)+ })++ describe('in es', () => {+ beforeEach(async () => { await i18n.changeLanguage('es') })+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('draws 24-hour times and day-month order', () => {+ expect(formatInstant(today().toISOString())).toBe('15:42')+ expect(formatInstant(new Date(2020, 9, 10, 15, 42).toISOString())).toBe('10 oct, 15:42')+ })+ })+})diff --git a/packages/shared/src/utils/dateUtils.ts b/packages/shared/src/utils/dateUtils.tsindex 11f28e4..fb7ed2a 100644--- a/packages/shared/src/utils/dateUtils.ts+++ b/packages/shared/src/utils/dateUtils.ts@@ -194,6 +194,17 @@ const DATE_LOCALES: Record<string, Locale> = { es }export const formatDate = (d: Date, name: DateFormatName): string =>format(d, i18n.t(`common.dateFormat.${name}`), { locale: DATE_LOCALES[i18n.language] })+/**+ * An instant, drawn: the time alone when it falls on the reader's today, else the date+ * and time. Device zone on purpose: this answers "when, relative to me now", not which+ * day a row belongs to. An unreadable instant reads as unknown.+ */+export const formatInstant = (iso: string): string => {+ const d = new Date(iso)+ if (Number.isNaN(d.getTime())) return UNKNOWN_DAY+ return formatDate(d, instantToDay(iso) === todayStr() ? 'time' : 'monthDayTime')+}+/*** A calendar day, drawn. The single point of truth for turning a `YYYY-MM-DD` into text* a person reads — the day equivalent of `formatNumber`, and the only place the idiomdiff --git a/packages/shared/src/utils/exerciseUtils.test.ts b/packages/shared/src/utils/exerciseUtils.test.tsindex d6221e3..9046d47 100644--- a/packages/shared/src/utils/exerciseUtils.test.ts+++ b/packages/shared/src/utils/exerciseUtils.test.ts@@ -1,5 +1,5 @@import { i18n } from '../i18n'-import { categoryLabel, equipmentLabel, exerciseCatalogEmpty, muscleLabel, resolveMuscleSlugs } from './exerciseUtils'+import { catalogSyncLines, categoryLabel, equipmentLabel, exerciseCatalogEmpty, muscleLabel, resolveMuscleSlugs } from './exerciseUtils'// A stand-in for the per-platform tables — the rule under test is the lookup, not any// particular library's slug vocabulary.@@ -137,3 +137,56 @@ describe('exerciseCatalogEmpty (locale-independent)', () => {expect(exerciseCatalogEmpty('', { ...settled, items: [{ id: 1 }] })).toBe(false)})})++describe('catalogSyncLines', () => {+ // The clock is 2026-10-10 15:00 local, so "today" times draw as a time alone. English+ // unless a case says otherwise.+ beforeEach(() => { jest.useFakeTimers({ now: new Date(2026, 9, 10, 15, 0) }) })+ afterEach(async () => {+ jest.useRealTimers()+ await i18n.changeLanguage('en')+ })++ const at = (h: number, m = 0) => new Date(2026, 9, 10, h, m).toISOString()++ it('says nothing without a status or from a server too old to send sync fields', () => {+ expect(catalogSyncLines(null)).toEqual([])+ expect(catalogSyncLines({ count: 5 })).toEqual([])+ })++ it('reports the last clean pass', () => {+ expect(catalogSyncLines({ count: 5, last_synced_at: at(14) })).toEqual([{ text: 'Last synced at 2:00 PM', warning: false }])+ })++ it('says Syncing while a pass runs and hides the failure', () => {+ const lines = catalogSyncLines({ count: 5, syncing: true, last_failed: true, last_failure: 'other', last_synced_at: at(14) })+ expect(lines).toEqual([+ { text: 'Last synced at 2:00 PM', warning: false },+ { text: 'Syncing…', warning: false },+ ])+ })++ it('names an unreachable catalog and the retry time', () => {+ expect(catalogSyncLines({ count: 5, last_failed: true, last_failure: 'unreachable', next_attempt_at: at(15, 30) })).toEqual([+ { text: "Last sync couldn't reach the exercise catalog. Trying again at 3:30 PM.", warning: true },+ ])+ })++ it('uses the generic sentence for any other reason, known or not', () => {+ const generic = "Last sync didn't finish. Trying again at 3:30 PM."+ expect(catalogSyncLines({ count: 5, last_failed: true, last_failure: 'other', next_attempt_at: at(15, 30) })[0].text).toBe(generic)+ expect(catalogSyncLines({ count: 5, last_failed: true, last_failure: 'newer' as 'other', next_attempt_at: at(15, 30) })[0].text).toBe(generic)+ })++ it('drops the retry clause when the time is past or unknown', () => {+ const base = { count: 5, last_failed: true, last_failure: 'other' as const }+ expect(catalogSyncLines({ ...base, next_attempt_at: at(14, 59) })[0].text).toBe("Last sync didn't finish.")+ expect(catalogSyncLines({ ...base, next_attempt_at: null })[0].text).toBe("Last sync didn't finish.")+ })++ it('draws in Spanish', async () => {+ await i18n.changeLanguage('es')+ const text = catalogSyncLines({ count: 5, last_failed: true, last_failure: 'other', next_attempt_at: at(15, 30) })[0].text+ expect(text).toContain('Nuevo intento: 15:30.')+ })+})diff --git a/packages/shared/src/utils/exerciseUtils.ts b/packages/shared/src/utils/exerciseUtils.tsindex 2096a61..25126c8 100644--- a/packages/shared/src/utils/exerciseUtils.ts+++ b/packages/shared/src/utils/exerciseUtils.ts@@ -15,6 +15,8 @@// The *lookup rule* over those tables is identical on both sides, so it lives here.import { i18n } from '../i18n'+import type { ExerciseCacheStatus } from '../types'+import { formatInstant } from './dateUtils'// Equipment and muscle names are read off exercises the server serves. Both vocabularies are// open-exercise-db's slugs, so a label is looked up by slug and anything outside the list@@ -74,6 +76,30 @@ export function exerciseCatalogEmpty(return !query && !list.error && !list.hasMore && list.items.length === 0}+export interface CatalogSyncLine { text: string; warning: boolean }++// What the library section says about the catalog sync, for web and mobile alike. Looked up+// at call time, so render under useTranslation() like relativeDayLabel. A server too old+// to send sync fields, or no answer yet, gives no lines.+export function catalogSyncLines(s: ExerciseCacheStatus | null | undefined): CatalogSyncLine[] {+ if (!s) return []+ const lines: CatalogSyncLine[] = []+ if (s.last_synced_at) {+ lines.push({ text: i18n.t('settings.library.lastSynced', { when: formatInstant(s.last_synced_at) }), warning: false })+ }+ if (s.syncing) {+ lines.push({ text: i18n.t('settings.library.syncing'), warning: false })+ } else if (s.last_failed) {+ let text = i18n.t(s.last_failure === 'unreachable' ? 'settings.library.syncUnreachable' : 'settings.library.syncFailed')+ // A retry time already past (stale page, skewed clock) is dropped rather than named.+ if (s.next_attempt_at && Date.parse(s.next_attempt_at) > Date.now()) {+ text += ' ' + i18n.t('settings.library.syncRetry', { when: formatInstant(s.next_attempt_at) })+ }+ lines.push({ text, warning: true })+ }+ return lines+}+export function muscleLabel(raw: string | undefined | null): string {const slug = raw ?? ''return isOneOf(MUSCLE_SLUGS, slug) ? i18n.t(`exercises.muscle.${slug}`) : slugdiff --git a/web/src/pages/Settings.test.tsx b/web/src/pages/Settings.test.tsxindex 8e81476..5ca1217 100644--- a/web/src/pages/Settings.test.tsx+++ b/web/src/pages/Settings.test.tsx@@ -3,6 +3,7 @@ import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'import { MemoryRouter } from 'react-router-dom'import Settings from './Settings'import { i18n } from '@lyftr/shared'+import { exerciseAPI } from '../services/api'import { useLanguageStore } from '../lib/lyftr'// What these pin is the shape of the WRITES this page makes, which is where #170 went@@ -196,3 +197,38 @@ describe('language', () => {await waitFor(() => expect(screen.getByRole('heading', { name: 'Settings' })).toBeTruthy())})})++describe('the catalog sync lines', () => {+ const cacheStatus = vi.mocked(exerciseAPI.cacheStatus)+ const base = { count: 5, syncing: false, last_synced_at: null, last_attempt_at: null, next_attempt_at: null, last_failed: false, last_failure: null }++ it('says Syncing while a pass runs', async () => {+ cacheStatus.mockResolvedValueOnce({ ...base, syncing: true })+ renderPage()+ expect(await screen.findByText('Syncing…')).toBeTruthy()+ })++ it('names an unreachable catalog and when it tries again', async () => {+ cacheStatus.mockResolvedValueOnce({+ ...base, last_failed: true, last_failure: 'unreachable',+ next_attempt_at: new Date(Date.now() + 30 * 60e3).toISOString(),+ })+ renderPage()+ expect(await screen.findByText(/Last sync couldn't reach the exercise catalog\. Trying again at /)).toBeTruthy()+ })++ it('shows no sync line for a server that sends only the count', async () => {+ cacheStatus.mockResolvedValueOnce({ count: 0 })+ renderPage()+ await waitFor(() => expect(cacheStatus).toHaveBeenCalled())+ expect(screen.queryByText(/Last synced/)).toBeNull()+ })++ it('reloads the status after a refresh that failed', async () => {+ vi.mocked(exerciseAPI.refreshCache).mockRejectedValueOnce(new Error('503'))+ renderPage()+ await waitFor(() => expect(cacheStatus).toHaveBeenCalledTimes(1))+ fireEvent.click(screen.getByRole('button', { name: 'Refresh cached' }))+ await waitFor(() => expect(cacheStatus).toHaveBeenCalledTimes(2))+ })+})diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsxindex 2b0d0c2..ad917e7 100644--- a/web/src/pages/Settings.tsx+++ b/web/src/pages/Settings.tsx@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react'import {uiMessage, useAsyncAction, memberSince, displayName, MAX_DISPLAY_NAME_LEN,useTranslation, LANGUAGE_ORDER, LANGUAGE_NAMES, languageChoiceLabel,- type LanguagePreference, type UiMessage,+ catalogSyncLines, type ExerciseCacheStatus, type LanguagePreference, type UiMessage,} from '@lyftr/shared'import { useLanguageStore } from '../lib/lyftr'import { useAuthStore } from '../stores/auth'@@ -97,7 +97,7 @@ export default function Settings() {// "say it where the tap was" failure this whole branch exists to stop.const [unitError, setUnitError] = useState<UiMessage | null>(null)- const [cacheStatus, setCacheStatus] = useState<{ count: number } | null>(null)+ const [cacheStatus, setCacheStatus] = useState<ExerciseCacheStatus | null>(null)const [seedAction, setSeedAction] = useState<'refresh' | null>(null)// Carries whether it FAILED, not just what it said. Both outcomes used to land in// one muted grey line, so "Refreshed 812 exercises" and "Can't reach the server@@ -163,14 +163,18 @@ export default function Settings() {try {const res = await exerciseAPI.refreshCache()setSeedMsg({ message: { key: 'settings.library.refreshed', params: { count: res.refreshed, amount: res.refreshed.toLocaleString() } }, failed: false })- loadCacheStatus()} catch (err: any) {setSeedMsg({ message: { key: 'settings.library.refreshFailed', cause: err }, failed: true })} finally {+ // Also after a failed or refused refresh: the failure line and Syncing state are+ // exactly what changed.+ loadCacheStatus()setSeedAction(null)}}+ const syncLines = catalogSyncLines(cacheStatus)+// The store rolls its own optimistic patch back when the write fails, so the app no// longer shows a unit the server never accepted. Saying so is still this page's job —@@ -580,6 +584,14 @@ export default function Settings() {</span></SettingRow>+ {syncLines.length > 0 && (+ <div className="py-2 px-1 space-y-1">+ {syncLines.map(l => (+ <p key={l.text} className={`text-xs break-words ${l.warning ? 'text-warning-400' : 'text-tx-muted'}`}>{l.text}</p>+ ))}+ </div>+ )}+{seedMsg && (<div className="py-2 px-1"><p className={`text-xs ${seedMsg.failed ? 'text-[color:var(--alert-error)]' : 'text-tx-muted'}`}>