diff --git a/README.md b/README.md index f82e7d4..d523a89 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ grit/ | `/onboarding/reveal` | Personalised TDEE + macro plan reveal | | `/onboarding/signup` | Account creation (email + password, or Google / Apple) | | `/(auth)/login` | Returning user login (email, Google or Apple) | -| `/(tabs)/` | Home — daily calorie budget, macro progress, today's workout | +| `/(tabs)/` | Home — daily calorie budget, macro progress, the plan's next session (or the workout in progress) | | `/(tabs)/food` | Food log — any day, meal sections, edit entries, barcode scanner, ✨ Smart log (describe or photograph a meal) | | `/(tabs)/habits` | Habit tracker — check-ins, undo, 30-day history and back-fill | | `/(tabs)/activity` | Stats — adaptive calorie target, 7D/30D/3M trends for calories, protein, activity and weight, then any week's workouts | @@ -51,11 +51,14 @@ grit/ | `/settings/privacy` | Private account, AI features, data-use permissions, the wellbeing answer, blocked people | | `/welcome-check` | Age and the wellbeing question, for users who skipped onboarding (Google or Apple sign-in); GRIT is 18+ | | `/exercises` | Exercise library: search, filter by equipment, pictures and instructions | -| `/settings/health` | Apple Health / Health Connect: connect, sync now, what was imported | +| `/settings/health` | Apple Health / Health Connect: connect, sync now, why each kind of data is read, cycle data (its own consent), writing meals back, recovery metrics | +| `/workout` | The workout in progress: sets filled with today's targets, last time one tap away, rest timers, supersets, plate and warm-up calculators, swaps, PRs, Say it; works offline | +| `/workouts/[id]` | A saved workout's sets and PRs; delete it | +| `/exercise-history/[id]` | One exercise's estimated 1RM or top weight over time, records and sessions | | `/settings/foods` | Foods GRIT knows: portions learned from Smart log | | `/settings/coach-memory` | What your coach knows: notes from chats, add or delete | | `/auth-callback` | Finishes Google or Apple sign-in | -| `/plan` | Weekly workout plan built by the coach from the exercise library | +| `/plan` | Weekly workout plan built by the coach from the exercise library; sessions run in order ("Next up · Session 2") | | `/friends` | Search people, follow requests, followers and following | | `/profile/[id]` | Someone's profile: follow state, this week's stats and recent activity (if allowed) | | `/connections` | A user's followers or following | @@ -117,11 +120,12 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS). | `users` | `GET/PUT/DELETE /users/me` (delete removes the account and its Supabase sign-in), `POST/DELETE /users/me/ai-consent`; safety rules (18+, calorie floors, no weight-loss goals after a "yes", no pro-eating-disorder names) | | `food` | `GET/POST /food-logs` (with the day's calorie budget and macro targets), `GET /food-logs/week?date=`, `PATCH/DELETE /food-logs/:id`, Open Food Facts search + barcode proxy, `GET /food/recent`, `GET/POST /food/favorites`, `DELETE /food/favorites/:id`, `POST /food/search-events`; caffeine and alcohol per log | | `meal-parse` | `POST /food/parse` (text and/or photo → items), `POST /food/parse/log`, `GET /food/memories`, `DELETE /food/memories/:id` | -| `health` | `POST /health/import` (workouts, daily steps and sleep, weigh-ins from Apple Health / Health Connect), `GET /health/recent` | +| `health` | `POST /health/import` (workouts with heart rate and distance, daily steps and sleep, weigh-ins, and recovery and cycle metrics from Apple Health / Health Connect; workout calories from heart rate when the device gives none), `GET /health/recent` (with recovery metrics against their 30-day average), `GET /health/cycle` | +| `workouts` | `POST /workouts` (a finished workout, saved once per `clientId`), `GET /workouts`, `GET/PUT/DELETE /workouts/:id`, `POST /workouts/prepare` (last time, records and the progression rules' targets), `POST /workouts/parse` (Say it), `GET /workouts/exercises/:id/history` | | `activity` | `GET/POST /activity-logs`, `GET /activity-logs/week?date=`, `PATCH/DELETE /activity-logs/:id`, `POST /activity-logs/:id/kudos` | | `habits` | `GET/POST/PUT/DELETE /habits`, `POST/DELETE /habits/:id/log?date=`, `GET /habits/streaks`, `GET /habits/:id/streak` | | `workout-plan` | `GET /workout-plan`, `POST /workout-plan/generate` (exercises chosen from the library, avoiding injuries in coach notes), `PUT /workout-plan/days/:day` | -| `exercises` | `GET /exercises?q=&muscle=&equipment=`, `GET /exercises/:id`; 876 exercises from free-exercise-db (public domain, bundled in `packages/backend/data/`), loaded on first start | +| `exercises` | `GET /exercises?q=&muscle=&equipment=&pattern=`, `GET /exercises/:id`; 876 exercises from free-exercise-db (public domain, bundled in `packages/backend/data/`), loaded on first start | | `challenges` | `GET/POST /challenges` (steps, active minutes or workouts; progress from logged workouts), `GET/DELETE /challenges/:id`, `POST /challenges/join/:code`, `DELETE /challenges/:id/participants/me` | | `social` | `GET /feed`, `GET /leaderboard/weekly`, `GET /search/users?q=`, `POST/DELETE /follow/:userId`, `GET /follow-requests`, `POST /follow-requests/:userId/accept`, `DELETE /follow-requests/:userId`, `DELETE /followers/:userId`, `GET /users/:id/{profile,followers,following}`, `GET/POST/DELETE /blocks` | | `progress` | `GET/POST /weight`, `DELETE /weight/:id`, `GET /stats/trends?days=7\|30\|90`, `GET /targets/adaptive`, `POST /targets/adaptive/apply`, `POST /targets/adaptive/snooze` | @@ -130,7 +134,7 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS). | `app` | `GET /health`, `POST /client-errors` (crash reports from the app, no sign-in, throttled) | | `alerts` | Hourly job: challenge results, 1pm coach check-ins, 8pm streak-at-risk and Sunday 6pm weekly check-in (with any target suggestion), in each user's local time | -**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · CoachMemory · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood · FoodMemory · HealthDay · SearchEvent · Exercise +**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · CoachMemory · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood · FoodMemory · HealthDay · HealthMetric · SearchEvent · Exercise · WorkoutSession · WorkoutSet See [`docs/ROADMAP.md`](./docs/ROADMAP.md) for what's done and what's next. diff --git a/apps/mobile/__tests__/healthTransform.test.ts b/apps/mobile/__tests__/healthTransform.test.ts index 2ee57cd..763b7f2 100644 --- a/apps/mobile/__tests__/healthTransform.test.ts +++ b/apps/mobile/__tests__/healthTransform.test.ts @@ -1,4 +1,4 @@ -import { androidExerciseType, appleWorkoutType, latestWeightPerDay, sleepByNight, toImportPayload } from '@/lib/health/transform'; +import { androidExerciseType, appleWorkoutType, dailyMetrics, latestWeightPerDay, sleepByNight, temperatureDeviations, toImportPayload, toMetres } from '@/lib/health/transform'; const at = (iso: string) => new Date(iso); @@ -47,6 +47,7 @@ describe('health transform', () => { steps: [{ date: '2026-11-04', steps: 6400.4 }, { date: '2026-11-05', steps: 10 }], sleep: [{ start: at('2026-11-03T23:30:00'), end: at('2026-11-04T06:30:00'), asleep: true }], weights: [{ at: at('2026-11-04T07:00:00'), kg: 80.21 }], + metrics: [], }, now); expect(body.workouts).toEqual([ { externalId: 'hk:1', activityType: 'running', startedAt: at('2026-11-04T07:00:00').toISOString(), durationMin: 33, caloriesBurned: 311 }, @@ -54,4 +55,44 @@ describe('health transform', () => { expect(body.days).toEqual([{ date: '2026-11-04', steps: 6400, sleepMinutes: 420 }]); expect(body.weights).toEqual([{ date: '2026-11-04', weightKg: 80.21 }]); }); + + it('turns readings into one value per metric per day', () => { + const rows = dailyMetrics([ + // Apple takes several HRV readings overnight: averaged + { metric: 'hrv', type: 'sdnn', at: at('2026-11-04T02:00:00'), value: 40 }, + { metric: 'hrv', type: 'sdnn', at: at('2026-11-04T05:00:00'), value: 50, device: 'Apple Watch' }, + // Resting heart rate: the day's latest + { metric: 'resting_hr', at: at('2026-11-04T08:00:00'), value: 58 }, + { metric: 'resting_hr', at: at('2026-11-04T20:00:00'), value: 55 }, + // Flow: the heaviest of the day + { metric: 'menstrual_flow', at: at('2026-11-04T08:00:00'), value: 1 }, + { metric: 'menstrual_flow', at: at('2026-11-04T18:00:00'), value: 3 }, + { metric: 'vo2max', at: at('2026-11-03T09:00:00'), value: 47.25 }, + ]); + expect(rows).toEqual([ + { date: '2026-11-03', metric: 'vo2max', value: 47.25 }, + { date: '2026-11-04', metric: 'hrv', type: 'sdnn', value: 45, device: 'Apple Watch' }, + { date: '2026-11-04', metric: 'menstrual_flow', value: 3 }, + { date: '2026-11-04', metric: 'resting_hr', value: 55 }, + ]); + }); + + it("works out Apple's temperature as a deviation from earlier nights", () => { + const nights = [36.1, 36.2, 36.0, 36.1, 36.1, 36.6].map((celsius, i) => ({ at: at(`2026-11-0${i + 1}T06:00:00`), celsius })); + const dev = temperatureDeviations(nights); + // Only the sixth night has five before it + expect(dev).toHaveLength(1); + expect(dev[0].value).toBe(0.5); + expect(toMetres({ quantity: 5.2, unit: 'km' })).toBe(5200); + expect(toMetres({ quantity: 1, unit: 'furlong' })).toBeUndefined(); + }); + + it('sends heart rate and distance with workouts', () => { + const body = toImportPayload('health_connect', { + workouts: [{ id: 'hc:1', activityType: 'running', start: at('2026-11-04T07:00:00'), end: at('2026-11-04T07:45:00'), avgHeartRate: 151.4, distanceM: 8012.6 }], + steps: [], sleep: [], weights: [], metrics: [{ metric: 'resting_hr', at: at('2026-11-04T08:00:00'), value: 52 }], + }, at('2026-11-04T12:00:00')); + expect(body.workouts[0]).toMatchObject({ avgHeartRate: 151, distanceM: 8013 }); + expect(body.metrics).toEqual([{ date: '2026-11-04', metric: 'resting_hr', value: 52 }]); + }); }); diff --git a/apps/mobile/__tests__/strength.test.ts b/apps/mobile/__tests__/strength.test.ts new file mode 100644 index 0000000..6d8baba --- /dev/null +++ b/apps/mobile/__tests__/strength.test.ts @@ -0,0 +1,45 @@ +import { epley, parseDetail, platesFor, prOf, restSeconds, warmupsFor, withSet } from '../lib/strength'; + +describe('strength helpers', () => { + it('works out plates per side', () => { + expect(platesFor(100)).toEqual({ perSide: [25, 15], rest: 0 }); + expect(platesFor(62.5)).toEqual({ perSide: [20, 1.25], rest: 0 }); + expect(platesFor(61)).toEqual({ perSide: [20], rest: 1 }); + expect(platesFor(20)).toEqual({ perSide: [], rest: 0 }); + }); + + it('builds warm-ups that climb to the working weight', () => { + expect(warmupsFor(100)).toEqual([ + { weightKg: 20, reps: 10 }, + { weightKg: 40, reps: 5 }, + { weightKg: 60, reps: 3 }, + { weightKg: 80, reps: 2 }, + ]); + // Light weights skip steps that would be at or below the bar + expect(warmupsFor(40).map((s) => s.weightKg)).toEqual([20, 25, 32.5]); + expect(warmupsFor(20)).toEqual([]); + }); + + it('marks PRs only against earlier history, updating as sets are done', () => { + const none = { e1rm: null, weightKg: null, reps: null }; + expect(prOf({ reps: 5, weightKg: 100 }, none)).toBeNull(); + const before = { e1rm: 110, weightKg: 95, reps: null }; + expect(prOf({ reps: 5, weightKg: 100 }, before)).toBe('weight'); + expect(prOf({ reps: 8, weightKg: 90 }, before)).toBe('e1rm'); + expect(prOf({ reps: 5, weightKg: 100, warmup: true }, before)).toBeNull(); + const after = withSet(before, { reps: 5, weightKg: 100 }); + expect(after.weightKg).toBe(100); + expect(prOf({ reps: 5, weightKg: 100 }, after)).toBeNull(); + expect(prOf({ reps: 13 }, { ...none, reps: 12 })).toBe('reps'); + }); + + it('rests by set type and reads plan details', () => { + expect(restSeconds('warmup', true)).toBe(45); + expect(restSeconds('superset', true)).toBe(0); + expect(restSeconds('working', true)).toBeGreaterThan(restSeconds('working', false)); + expect(epley(100, 5)).toBe(116.7); + expect(parseDetail('3 × 8–12')).toEqual({ kind: 'reps', sets: 3, repsLow: 8, repsHigh: 12 }); + expect(parseDetail('3 × 30 s')).toEqual({ kind: 'timed', sets: 3, seconds: 30 }); + expect(parseDetail('20 min easy')).toBeNull(); + }); +}); diff --git a/apps/mobile/app.json b/apps/mobile/app.json index e541b2f..db4c4da 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -61,7 +61,17 @@ "android.permission.health.READ_EXERCISE", "android.permission.health.READ_STEPS", "android.permission.health.READ_WEIGHT", - "android.permission.health.READ_SLEEP" + "android.permission.health.READ_SLEEP", + "android.permission.health.READ_HEART_RATE", + "android.permission.health.READ_HEART_RATE_VARIABILITY", + "android.permission.health.READ_RESTING_HEART_RATE", + "android.permission.health.READ_RESPIRATORY_RATE", + "android.permission.health.READ_SKIN_TEMPERATURE", + "android.permission.health.READ_VO2_MAX", + "android.permission.health.READ_DISTANCE", + "android.permission.health.READ_MENSTRUATION", + "android.permission.health.WRITE_NUTRITION", + "android.permission.health.READ_HEALTH_DATA_HISTORY" ], "blockedPermissions": [ "android.permission.RECORD_AUDIO" @@ -104,8 +114,8 @@ [ "@kingstinct/react-native-healthkit", { - "NSHealthShareUsageDescription": "GRIT reads your workouts, steps, sleep and weight so they count toward your goals and challenges, and so your coach can see how you're recovering.", - "NSHealthUpdateUsageDescription": false, + "NSHealthShareUsageDescription": "GRIT reads your workouts, heart rate, steps, sleep, weight and recovery data (and cycle data, if you turn it on) so they count toward your goals and challenges, and so your coach can see how you're recovering.", + "NSHealthUpdateUsageDescription": "If you turn it on, GRIT writes the meals you log (calories, protein, carbs, fat and caffeine) to Apple Health.", "background": false } ], diff --git a/apps/mobile/app/(tabs)/activity.tsx b/apps/mobile/app/(tabs)/activity.tsx index 1c2fac8..67533cf 100644 --- a/apps/mobile/app/(tabs)/activity.tsx +++ b/apps/mobile/app/(tabs)/activity.tsx @@ -1,10 +1,15 @@ import React, { useState } from 'react'; import { View, Text, ScrollView, Pressable, RefreshControl } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; -import { useFocusEffect } from 'expo-router'; +import { router, useFocusEffect } from 'expo-router'; import * as Haptics from 'expo-haptics'; import Svg, { Path, Circle, Line, Defs, LinearGradient, Stop, G } from 'react-native-svg'; import { useWeeklySummary, type ActivityLog } from '@/hooks/useActivityLog'; +import { useStartWorkout } from '@/hooks/useStartWorkout'; +import { useOnlineManager } from '@/hooks/useOnline'; +import { useWorkoutStore } from '@/stores/workoutStore'; +import { useAuthStore } from '@/stores/authStore'; +import { retryWorkout } from '@/lib/workoutSync'; import { useFoodWeek } from '@/hooks/useFoodLog'; import { useHabits, useHabitSummary } from '@/hooks/useHabits'; import { useMe } from '@/hooks/useMe'; @@ -81,7 +86,34 @@ function LineChart({ ); } +/** Finished workouts not on the server yet: waiting for a connection, or failed. */ +function PendingWorkouts() { + const userId = useAuthStore((st) => st.session?.user.id); + // Select the list itself: a filtered copy would be new on every render + const all = useWorkoutStore((st) => st.pending); + const pending = all.filter((p) => p.ownerId === userId); + const online = useOnlineManager(); + if (!pending.length) return null; + return ( + + {pending.map((p) => ( + + + {p.body.title || 'Workout'}: {p.error ? `not saved (${p.error})` : online ? 'saving…' : "waiting for a connection. It's safe on your phone."} + + {!!p.error && ( + retryWorkout(p.body.clientId)} accessibilityRole="button"> + Retry + + )} + + ))} + + ); +} + export default function ActivityScreen() { + const startWorkout = useStartWorkout(); const today = localDateStr(); const thisWeek = weekStartStr(today); const [week, setWeek] = useState(thisWeek); @@ -278,8 +310,17 @@ export default function ActivityScreen() { > + Log workout + startWorkout()} + style={({ pressed }) => ({ marginTop: 8, borderRadius: 999, paddingVertical: 11, alignItems: 'center', borderWidth: 1.5, borderColor: Colors.orange, opacity: pressed ? 0.7 : 1 })} + > + Start a strength workout + + + {/* Workouts logged this week: tap to edit or delete */} Workouts @@ -291,18 +332,20 @@ export default function ActivityScreen() { [...(weekly?.logs ?? [])].reverse().map((log) => ( setEditingWorkout(log)} + onPress={() => (log.workoutSession ? router.push(`/workouts/${log.workoutSession.id}`) : setEditingWorkout(log))} accessibilityRole="button" - accessibilityLabel={`${ACTIVITY_LABELS[log.activityType] ?? log.activityType}, ${log.durationMin} minutes`} - accessibilityHint="Tap to edit" + accessibilityLabel={`${log.workoutSession?.title || ACTIVITY_LABELS[log.activityType] || log.activityType}, ${log.durationMin} minutes`} + accessibilityHint={log.workoutSession ? 'Tap to see the sets' : 'Tap to edit'} style={({ pressed }) => ({ flexDirection: 'row', alignItems: 'center', gap: 12, opacity: pressed ? 0.6 : 1 })} > - {ACTIVITY_LABELS[log.activityType] ?? log.activityType} + {log.workoutSession?.title || ACTIVITY_LABELS[log.activityType] || log.activityType} {dayLabel(localDateStr(new Date(log.loggedAt)), today)} · {log.durationMin} min + {log.workoutSession?.setCount ? ` · ${log.workoutSession.setCount} sets` : ''} + {log.workoutSession?.prCount ? ` · 🏆 ${log.workoutSession.prCount}` : ''} diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/index.tsx index 381d475..9af8aad 100644 --- a/apps/mobile/app/(tabs)/index.tsx +++ b/apps/mobile/app/(tabs)/index.tsx @@ -19,7 +19,10 @@ import { useMe } from '@/hooks/useMe'; import { ErrorNotice, useQueriesStatus } from '@/components/ui/QueryStatus'; import { ScreenSkeleton } from '@/components/ui/Skeleton'; import { calcMacros } from '@/lib/tdee'; -import { todayWeekday, useWorkoutPlan } from '@/hooks/useWorkoutPlan'; +import { isLiftingDay, nextUp, useWorkoutPlan } from '@/hooks/useWorkoutPlan'; +import { useStartWorkout } from '@/hooks/useStartWorkout'; +import { useWorkoutStore } from '@/stores/workoutStore'; +import { useAuthStore } from '@/stores/authStore'; import { usePullToRefresh } from '@/hooks/usePullToRefresh'; @@ -132,44 +135,57 @@ function MacroBar({ value, goal, color }: { value: number; goal: number; color: ); } -/** Today's day of the coach's plan, or an invitation to get one. */ +/** The plan's next session (or the workout in progress), or an invitation to get a plan. */ function TodayWorkoutCard() { const { data: plan, isLoading } = useWorkoutPlan(); - if (isLoading) return null; - const today = plan?.days.find((d) => d.day === todayWeekday()); + const userId = useAuthStore((s) => s.session?.user.id); + const active = useWorkoutStore((s) => (s.active?.ownerId === userId ? s.active : null)); + const startWorkout = useStartWorkout(); + if (isLoading && !active) return null; + const next = nextUp(plan); + const lifting = !!next && isLiftingDay(next.day); return ( router.push('/plan')} + onPress={() => router.push(active ? '/workout' : '/plan')} accessibilityRole="button" - accessibilityLabel={plan ? "Today's workout" : 'Get a workout plan'} + accessibilityLabel={active ? 'Workout in progress' : next ? 'Next workout' : 'Get a workout plan'} style={({ pressed }) => ({ backgroundColor: Colors.surface, borderRadius: 20, borderWidth: 1, - borderColor: Colors.border, + borderColor: active ? Colors.teal : Colors.border, padding: 18, - flexDirection: 'row', - alignItems: 'center', - gap: 14, + gap: 12, opacity: pressed ? 0.85 : 1, })} > - {!plan ? '🗓️' : today?.rest ? '😌' : '🏋️'} - - - {plan ? "Today's workout" : 'Workout plan'} - - - {!plan ? 'Get a weekly plan from your coach' : today?.rest ? 'Rest day — recover well' : today?.title} - - {!!plan && today && !today.rest && ( - - {today.durationMin} min · {today.exercises.length} exercises + + {active ? '⏱️' : !plan ? '🗓️' : '🏋️'} + + + {active ? 'Workout in progress' : next ? `Next up · Session ${next.number} of ${next.total}` : 'Workout plan'} - )} + + {active ? active.title || 'Workout' : !plan ? 'Get a weekly plan from your coach' : next ? next.day.title : 'All rest days this week'} + + {!active && !!next && ( + + {next.day.durationMin} min · {next.day.exercises.length} exercises + + )} + + › - › + {(active || lifting) && ( + (active ? router.push('/workout') : next && startWorkout({ session: next.number, day: next.day }))} + accessibilityRole="button" + style={({ pressed }) => ({ backgroundColor: active ? Colors.teal : Colors.orange, borderRadius: 999, paddingVertical: 11, alignItems: 'center', opacity: pressed ? 0.85 : 1 })} + > + {active ? 'Resume workout' : 'Start workout'} + + )} ); } diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index 1054289..f98aa9c 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -2,7 +2,8 @@ import '../global.css'; import React, { useEffect, useRef } from 'react'; import { useColorScheme } from 'react-native'; import { Stack, SplashScreen, router, useSegments, usePathname } from 'expo-router'; -import { QueryClientProvider } from '@tanstack/react-query'; +import { onlineManager } from '@tanstack/react-query'; +import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { StatusBar } from 'expo-status-bar'; import { @@ -17,6 +18,7 @@ import { import { supabase } from '@/lib/supabase'; import { queryClient } from '@/lib/queryClient'; +import { flushPendingWorkouts, persistOptions, queryPersister } from '@/lib/workoutSync'; import { useAuthStore } from '@/stores/authStore'; import { usePushNotifications } from '@/hooks/usePushNotifications'; import { useHealthSync } from '@/hooks/useHealthSync'; @@ -101,15 +103,27 @@ export default function RootLayout() { const { data: { subscription }, } = supabase.auth.onAuthStateChange((event, session) => { - // Drop the previous user's cached data on sign-out (including after a 401) - if (event === 'SIGNED_OUT') queryClient.clear(); + // Drop the previous user's cached data on sign-out (including after a + // 401). Finished workouts waiting to sync stay, marked with whose they + // are, and are only sent when that user signs back in. + if (event === 'SIGNED_OUT') { + queryClient.clear(); + queryPersister.removeClient(); + } + if (event === 'SIGNED_IN') flushPendingWorkouts(); if (mounted) setSession(session); }); + // Back online: send any finished workouts that were waiting + const offOnline = onlineManager.subscribe((online) => { + if (online) flushPendingWorkouts(); + }); + return () => { mounted = false; clearTimeout(fallback); subscription.unsubscribe(); + offOnline(); }; }, [setSession, loadOnboardingState]); @@ -142,7 +156,8 @@ export default function RootLayout() { } return ( - + // Keeps workouts waiting for a connection (and the plan) across restarts + @@ -166,6 +181,9 @@ export default function RootLayout() { + + + @@ -173,6 +191,6 @@ export default function RootLayout() { {session && } - + ); } diff --git a/apps/mobile/app/exercise-history/[id].tsx b/apps/mobile/app/exercise-history/[id].tsx new file mode 100644 index 0000000..5c6ac53 --- /dev/null +++ b/apps/mobile/app/exercise-history/[id].tsx @@ -0,0 +1,141 @@ +import React, { useState } from 'react'; +import { View, Text, ScrollView, ActivityIndicator, Pressable } from 'react-native'; +import { useLocalSearchParams } from 'expo-router'; +import { SafeAreaView } from 'react-native-safe-area-context'; +import Svg, { Circle, Line, Polyline, Text as SvgText } from 'react-native-svg'; +import { Colors } from '@/constants/colors'; +import { useExerciseHistory } from '@/hooks/useWorkouts'; +import { useMe } from '@/hooks/useMe'; +import { kgToUnit } from '@/lib/units'; +import { ScreenHeader, Section } from '@/components/settings/SettingsUI'; +import { ExerciseSheet } from '@/components/exercises/ExerciseSheet'; + +const W = 320; +const H = 160; +const PAD = 28; + +/** A line over time, oldest on the left. */ +function Chart({ points, color, unit }: { points: { date: string; value: number }[]; color: string; unit: string }) { + if (points.length < 2) { + return Log this exercise twice to see a chart.; + } + const values = points.map((p) => p.value); + const min = Math.min(...values); + const max = Math.max(...values); + const span = max - min || 1; + const x = (i: number) => PAD + (i / (points.length - 1)) * (W - PAD * 2); + const y = (v: number) => H - PAD - ((v - min) / span) * (H - PAD * 2); + return ( + + + `${x(i)},${y(p.value)}`).join(' ')} fill="none" stroke={color} strokeWidth={2.5} /> + {points.map((p, i) => ( + + ))} + {`${max} ${unit}`} + {`${min} ${unit}`} + {points[points.length - 1].date.slice(5)} + + ); +} + +/** One exercise's history: top weight and estimated one-rep max over time, records, sessions. */ +export default function ExerciseHistoryScreen() { + const { id } = useLocalSearchParams<{ id: string }>(); + const { data, isLoading, isError, refetch } = useExerciseHistory(id ?? null); + const { data: me } = useMe(); + const unit = me?.weightUnit ?? 'kg'; + const [chosen, setChosen] = useState<'e1rm' | 'top' | null>(null); + // Estimated 1RM needs sets of 10 reps or fewer; until there are two such + // sessions, show top weight instead + const e1rmSessions = (data?.sessions ?? []).filter((s) => s.bestE1rm != null).length; + const metric = chosen ?? (e1rmSessions >= 2 ? 'e1rm' : 'top'); + const setMetric = setChosen; + const [info, setInfo] = useState(null); + + const oldestFirst = [...(data?.sessions ?? [])].reverse(); + const points = oldestFirst + .map((s) => ({ date: s.date, value: metric === 'e1rm' ? s.bestE1rm : s.topWeightKg })) + .filter((p): p is { date: string; value: number } => p.value != null) + .map((p) => ({ ...p, value: kgToUnit(p.value, unit) })); + const bodyweight = !!data && data.sessions.every((s) => s.topWeightKg == null); + + return ( + + setInfo(data.exercise.id)} accessibilityRole="button" hitSlop={8}> + How to + + ) : undefined + } + /> + + {isLoading ? ( + + ) : isError || !data ? ( + refetch()} accessibilityRole="button"> + Couldn't load the history. Try again + + ) : !data.sessions.length ? ( + You haven't logged this exercise yet. + ) : ( + <> + + {data.records.weightKg != null && } + {data.records.e1rm != null && } + {data.records.reps != null && } + + + {!bodyweight && ( +
+ + {(['e1rm', 'top'] as const).map((m) => ( + setMetric(m)} + accessibilityRole="button" + accessibilityState={{ selected: metric === m }} + style={{ paddingHorizontal: 12, paddingVertical: 6, borderRadius: 999, backgroundColor: metric === m ? Colors.orange : Colors.surface2 }} + > + {m === 'e1rm' ? 'Estimated 1RM' : 'Top weight'} + + ))} + + + + Estimated one-rep max uses the Epley formula, from sets of 10 reps or fewer. + +
+ )} + +
+ {data.sessions.map((s) => ( + + {s.date} + + {s.sets + .map((x) => `${x.warmup ? 'W ' : ''}${x.durationSec ? `${x.durationSec}s` : x.weightKg ? `${kgToUnit(x.weightKg, unit)}×${x.reps}` : x.reps}${x.pr ? ' 🏆' : ''}`) + .join(' ')} + + + ))} +
+ + )} +
+ setInfo(null)} /> + + ); +} + +function Record({ label, value }: { label: string; value: string }) { + return ( + + {label} + {value} + + ); +} diff --git a/apps/mobile/app/plan.tsx b/apps/mobile/app/plan.tsx index 5cafdf5..461c0d9 100644 --- a/apps/mobile/app/plan.tsx +++ b/apps/mobile/app/plan.tsx @@ -5,11 +5,13 @@ import { useFocusEffect } from 'expo-router'; import { SafeAreaView } from 'react-native-safe-area-context'; import * as Haptics from 'expo-haptics'; import { Colors } from '@/constants/colors'; +import * as Crypto from 'expo-crypto'; import { - todayWeekday, useGeneratePlan, useWorkoutPlan, WEEKDAY_NAMES, + isLiftingDay, nextUp, planSessions, todayWeekday, useGeneratePlan, useWorkoutPlan, WEEKDAY_NAMES, type PlanDay, type WorkoutPlan, } from '@/hooks/useWorkoutPlan'; -import { useLogActivity } from '@/hooks/useActivityLog'; +import { useLogPlanSession } from '@/hooks/useWorkouts'; +import { useStartWorkout } from '@/hooks/useStartWorkout'; import { usePullToRefresh } from '@/hooks/usePullToRefresh'; import { ACTIVITY_LABELS } from '@/components/activity/LogActivitySheet'; import { EditPlanDaySheet } from '@/components/plan/EditPlanDaySheet'; @@ -27,7 +29,7 @@ function errorMessage(err: any) { return err?.response?.data?.message?.toString() ?? 'Check your connection and try again.'; } -/** The coach-built weekly plan: view it, log a session, edit a day or rebuild it. */ +/** The coach-built weekly plan: start the next session, edit a day or rebuild it. */ export default function PlanScreen() { const { data: plan, isLoading, isError, refetch } = useWorkoutPlan(); const { refreshing, onRefresh } = usePullToRefresh([['workout-plan']]); @@ -70,14 +72,23 @@ export default function PlanScreen() { function PlanWeek({ plan, onEdit, onOpenExercise }: { plan: WorkoutPlan; onEdit: (day: PlanDay) => void; onOpenExercise: (id: string) => void }) { const today = todayWeekday(); - const { mutateAsync: logActivity } = useLogActivity(); - const [logged, setLogged] = useState(null); + const next = nextUp(plan); + const sessions = new Map(planSessions(plan).map((x) => [x.day.day, x.number])); + const startWorkout = useStartWorkout(); + const { mutateAsync: logSession, isPending } = useLogPlanSession(); - async function logSession(day: PlanDay) { + async function logAsDone(day: PlanDay, session: number) { + const end = new Date(); try { - await logActivity({ activityType: day.activityType, durationMin: day.durationMin }); + await logSession({ + clientId: Crypto.randomUUID(), + planSession: session, + title: day.title, + activityType: day.activityType, + startedAt: new Date(end.getTime() - day.durationMin * 60_000).toISOString(), + endedAt: end.toISOString(), + }); Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); - setLogged(day.day); } catch (err) { notify("Couldn't log the workout", errorMessage(err)); } @@ -88,8 +99,15 @@ function PlanWeek({ plan, onEdit, onOpenExercise }: { plan: WorkoutPlan; onEdit: {!!plan.summary && ( {plan.summary} )} + {next && ( + + Sessions run in order, so a missed day doesn't skip one: do session {next.number} whenever you next train. + + )} {plan.days.map((day) => { const isToday = day.day === today; + const session = sessions.get(day.day); + const isNext = !!next && next.day.day === day.day; return ( - - {WEEKDAY_NAMES[day.day]}{isToday ? ' · Today' : ''} + + {session ? `Session ${session} · ` : ''}{WEEKDAY_NAMES[day.day]}{isToday ? ' (today)' : ''}{isNext ? ' · Next up' : ''} {day.title} {!day.rest && ( @@ -134,24 +152,29 @@ function PlanWeek({ plan, onEdit, onOpenExercise }: { plan: WorkoutPlan; onEdit: ))} - {!day.rest && isToday && ( - logSession(day)} - disabled={logged === day.day} - accessibilityRole="button" - style={({ pressed }) => ({ - marginTop: 4, - borderRadius: 999, - paddingVertical: 12, - alignItems: 'center', - backgroundColor: logged === day.day ? `${Colors.teal}22` : Colors.orange, - opacity: pressed ? 0.85 : 1, - })} - > - - {logged === day.day ? '✓ Logged' : 'Log this workout'} - - + {!day.rest && session != null && ( + isNext ? ( + (isLiftingDay(day) ? startWorkout({ session, day }) : logAsDone(day, session))} + disabled={isPending} + accessibilityRole="button" + style={({ pressed }) => ({ marginTop: 4, borderRadius: 999, paddingVertical: 12, alignItems: 'center', backgroundColor: Colors.orange, opacity: pressed || isPending ? 0.85 : 1 })} + > + + {isLiftingDay(day) ? 'Start workout' : 'Log as done'} + + + ) : ( + (isLiftingDay(day) ? startWorkout({ session, day }) : logAsDone(day, session))} + disabled={isPending} + accessibilityRole="button" + accessibilityLabel={`Do session ${session} instead`} + hitSlop={6} + > + Do this one instead + + ) )} ); diff --git a/apps/mobile/app/settings/health.tsx b/apps/mobile/app/settings/health.tsx index f702ce4..9437df3 100644 --- a/apps/mobile/app/settings/health.tsx +++ b/apps/mobile/app/settings/health.tsx @@ -4,12 +4,25 @@ import { SafeAreaView } from 'react-native-safe-area-context'; import { Colors } from '@/constants/colors'; import { ScreenHeader, Section, ToggleRow, NavRow, PrimaryButton } from '@/components/settings/SettingsUI'; import { healthSource } from '@/lib/health/source'; -import { connectHealth, disconnectHealth, isHealthSyncOn, lastHealthSync, syncHealth } from '@/lib/health/sync'; -import { useHealthRecent } from '@/hooks/useHealthRecent'; +import { connectHealth, disconnectHealth, isFoodWriteOn, isHealthSyncOn, lastHealthSync, requestCycleAccess, setFoodWrite, syncHealth } from '@/lib/health/sync'; +import { useCycleSummary, useHealthRecent } from '@/hooks/useHealthRecent'; +import { useMe, useUpdateMe } from '@/hooks/useMe'; +import { useQueryClient } from '@tanstack/react-query'; +import { CYCLE_REASON, HEALTH_REASONS } from '@/lib/health/reasons'; + import { dayLabel } from '@/lib/date'; import { confirmAction, notify } from '@/lib/confirm'; import { showToast } from '@/stores/toastStore'; +const METRIC_LABELS: Record = { + resting_hr: 'Resting heart rate', + hrv: 'Heart rate variability', + respiratory_rate: 'Breathing rate asleep', + sleep_temp_deviation: 'Sleeping temperature vs usual', + vo2max: 'VO2max', +}; +const UNITS: Record = { ms: 'ms', bpm: 'bpm', breaths_min: '/min', degC: '°C', ml_kg_min: 'mL/kg/min' }; + function timeAgo(d: Date | null) { if (!d) return 'Never'; const mins = Math.round((Date.now() - d.getTime()) / 60000); @@ -25,13 +38,50 @@ export default function HealthSettingsScreen() { const [on, setOn] = useState(false); const [last, setLast] = useState(null); const [syncing, setSyncing] = useState(false); + const [writeFood, setWriteFood] = useState(false); const recent = useHealthRecent(); + const cycle = useCycleSummary(); + const { data: me } = useMe(); + const updateMe = useUpdateMe(); + const qc = useQueryClient(); const refresh = useCallback(async () => { setAvailable(await healthSource.isAvailable()); setOn(await isHealthSyncOn()); setLast(await lastHealthSync()); + setWriteFood(await isFoodWriteOn()); }, []); + + async function toggleCycle(value: boolean) { + if (value) { + const ok = await confirmAction({ + title: 'Turn on cycle data?', + message: `GRIT will read period days and flow from ${healthSource.name}. They're kept for you alone, never shared in your feed, challenges or coach chats, and turning this off deletes them.`, + confirmLabel: 'Turn on', + }); + if (!ok) return; + } + try { + await updateMe.mutateAsync({ consentCycleData: value }); + qc.invalidateQueries({ queryKey: ['health-cycle'] }); + if (value && on) { + await requestCycleAccess(); + await runSync(); + } + if (!value) showToast('Cycle data turned off and deleted', 'info'); + } catch { + showToast("Couldn't save that. Check your connection."); + } + } + + async function toggleWriteFood(value: boolean) { + const ok = await setFoodWrite(value); + if (!ok) { + notify(`Couldn't get permission`, `Allow GRIT to write nutrition in ${healthSource.name}, then try again.`); + return; + } + setWriteFood(value); + } useEffect(() => { refresh(); }, [refresh]); async function runSync() { @@ -95,13 +145,50 @@ export default function HealthSettingsScreen() { ) : ( <> -
+
+ {on && ( + + )}
{on && } )} +
+ {HEALTH_REASONS.map((r) => ( + + {r.label} + {r.reason} + + ))} +
+ +
+ +
+ + {!!recent.data?.recovery?.length && ( +
+ {recent.data.recovery.map((m) => ( + + + {METRIC_LABELS[m.metric] ?? m.metric}{m.type ? ` (${m.type.toUpperCase()})` : ''} + + + {m.metric === 'sleep_temp_deviation' && m.latest > 0 ? '+' : ''}{m.latest} {UNITS[m.unit] ?? m.unit}{m.days >= 7 ? ` · avg ${m.average}` : ''} + + + ))} +
+ )} +
{recent.isLoading ? ( diff --git a/apps/mobile/app/workout.tsx b/apps/mobile/app/workout.tsx new file mode 100644 index 0000000..efb8143 --- /dev/null +++ b/apps/mobile/app/workout.tsx @@ -0,0 +1,391 @@ +import React, { useEffect, useMemo, useState } from 'react'; +import { View, Text, ScrollView, Pressable, TextInput, ActivityIndicator, KeyboardAvoidingView, Platform } from 'react-native'; +import { router } from 'expo-router'; +import { SafeAreaView } from 'react-native-safe-area-context'; +import * as Haptics from 'expo-haptics'; +import { useOnlineManager } from '@/hooks/useOnline'; +import { Colors } from '@/constants/colors'; +import { useAuthStore } from '@/stores/authStore'; +import { useWorkoutStore, type DraftExercise, type DraftSet, type SaveWorkoutBody } from '@/stores/workoutStore'; +import { usePrepareWorkout, useParseSets, type PastSet, type PreparedExercise, type SpokenSet } from '@/hooks/useWorkouts'; +import { useMe } from '@/hooks/useMe'; +import { useEnsureAiConsent } from '@/hooks/useAiConsent'; +import { isCompound } from '@/hooks/useStartWorkout'; +import { ExerciseCard } from '@/components/workout/ExerciseCard'; +import { RestBar } from '@/components/workout/RestBar'; +import { MenuSheet, type MenuItem } from '@/components/workout/MenuSheet'; +import { ExercisePicker } from '@/components/workout/ExercisePicker'; +import { PlatesSheet } from '@/components/workout/PlatesSheet'; +import { ExerciseSheet } from '@/components/exercises/ExerciseSheet'; +import { formatClock, parseDetail, prOf, PR_LABELS, restSeconds, withSet, type PrKind } from '@/lib/strength'; +import { kgToUnit } from '@/lib/units'; +import { sendWorkout, retryWorkout } from '@/lib/workoutSync'; +import { confirmAction } from '@/lib/confirm'; +import { showToast } from '@/stores/toastStore'; + +const haptic = (kind: 'light' | 'success') => { + if (Platform.OS === 'web') return; + if (kind === 'success') Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); + else Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); +}; + +/** The sets to start with: today's target, or last time's, or the plan's. */ +function startingSets(p: PreparedExercise | undefined, e: DraftExercise): Partial[] { + if (p?.timed) return Array.from({ length: p.timed.sets }, () => ({ durationSec: p.timed!.seconds, reps: 0 })); + const plan = e.detail ? parseDetail(e.detail) : null; + if (plan?.kind === 'timed') return Array.from({ length: plan.sets }, () => ({ durationSec: plan.seconds, reps: 0 })); + const s = p?.suggestion; + const n = s?.sets ?? (plan?.kind === 'reps' ? plan.sets : p?.last?.sets.length || 3); + return Array.from({ length: n }, (_, i) => ({ + weightKg: s?.weightKg ?? (s?.action === 'start' ? null : p?.last?.sets[i]?.weightKg ?? null), + reps: s?.reps ?? (plan?.kind === 'reps' ? plan.repsLow : p?.last?.sets[i]?.reps ?? null), + })); +} + +/** Logs a workout set by set: last time's numbers one tap away, rest timers, PRs as they happen. */ +export default function WorkoutScreen() { + const userId = useAuthStore((s) => s.session?.user.id); + const stored = useWorkoutStore((s) => s.active); + const active = stored && stored.ownerId === userId ? stored : null; + const store = useWorkoutStore.getState; + const { data: me } = useMe(); + const unit = me?.weightUnit ?? 'kg'; + const [summary, setSummary] = useState<{ body: SaveWorkoutBody; prs: string[]; volume: number } | null>(null); + + const prepare = usePrepareWorkout(active?.exercises.map((e) => ({ exerciseId: e.exerciseId, detail: e.detail })) ?? []); + const prepared = useMemo(() => new Map((prepare.data?.exercises ?? []).map((p) => [p.exerciseId, p])), [prepare.data]); + + // Fill in each exercise's sets once its targets are in (or straight away + // if they can't be fetched, e.g. offline with nothing cached) + useEffect(() => { + if (!active) return; + for (const e of active.exercises) { + if (e.prefilled) continue; + const p = prepared.get(e.exerciseId); + if (p || prepare.isError) store().prefill(e.key, startingSets(p, e)); + } + }, [active, prepared, prepare.isError, store]); + + const [menuFor, setMenuFor] = useState(null); + const [picker, setPicker] = useState<{ mode: 'add' | 'swap'; key?: string; pattern?: string | null } | null>(null); + const [plates, setPlates] = useState<{ key: string; weightKg: number | null } | undefined>(undefined); + const [infoId, setInfoId] = useState(null); + const [workoutMenu, setWorkoutMenu] = useState(false); + + if (summary) return ; + + if (!active) { + return ( + + No workout in progress + userId && store().start({ ownerId: userId, exercises: [] })} + accessibilityRole="button" + style={{ backgroundColor: Colors.orange, borderRadius: 999, paddingVertical: 14, alignItems: 'center' }} + > + Start an empty workout + + (router.canGoBack() ? router.back() : router.replace('/(tabs)/'))} accessibilityRole="button" style={{ alignItems: 'center', padding: 10 }}> + Back + + + ); + } + + const exercises = active.exercises; + + /** Ticks a set (or unticks it), marking a PR and starting the rest timer. */ + function complete(e: DraftExercise, set: DraftSet, values?: Partial) { + const s = { ...set, ...values }; + if (set.done && !values) { + store().updateSet(e.key, set.id, { done: false, pr: null }); + return; + } + const p = prepared.get(e.exerciseId); + const timed = !!p?.timed || !!s.durationSec; + if (!timed && !(s.reps && s.reps > 0)) { + showToast('Add the reps first'); + return; + } + let pr: PrKind | null = null; + const base = p?.records; + if (base && (base.e1rm != null || base.weightKg != null || base.reps != null)) { + const current = useWorkoutStore.getState().active?.exercises.find((x) => x.key === e.key); + const records = (current?.sets ?? []).filter((x) => x.done && x.id !== set.id).reduce((r, x) => withSet(r, { reps: x.reps ?? 0, weightKg: x.weightKg, warmup: x.warmup }), base); + pr = prOf({ reps: s.reps ?? 0, weightKg: s.weightKg, warmup: s.warmup, durationSec: s.durationSec }, records); + } + store().updateSet(e.key, set.id, { ...values, done: true, pr }); + haptic(pr ? 'success' : 'light'); + if (pr) showToast(`🏆 New PR on ${e.name}: ${PR_LABELS[pr]}`, 'info'); + + const group = e.supersetId ? exercises.filter((x) => x.supersetId === e.supersetId) : null; + const kind = set.warmup ? 'warmup' : group && group[group.length - 1].key !== e.key ? 'superset' : 'working'; + const sec = restSeconds(kind, isCompound(p?.pattern)); + if (sec) store().startRest(sec, kind === 'warmup' ? 'Warm-up rest' : group ? 'Rest after the round' : 'Rest'); + else store().clearRest(); + } + + /** Puts spoken sets into the first sets not done yet, adding sets as needed. */ + function logSpoken(sets: SpokenSet[]) { + for (const spoken of sets) { + let ex = useWorkoutStore.getState().active?.exercises.find((x) => x.exerciseId === spoken.exerciseId); + if (!ex) { + store().addExercise({ exerciseId: spoken.exerciseId, name: spoken.exerciseName }); + ex = useWorkoutStore.getState().active?.exercises.find((x) => x.exerciseId === spoken.exerciseId); + if (ex) store().prefill(ex.key, []); + } + if (!ex) continue; + let target = ex.sets.find((x) => !x.done && !x.warmup); + if (!target) { + store().insertSets(ex.key, [{}], 'end'); + target = useWorkoutStore.getState().active?.exercises.find((x) => x.key === ex!.key)?.sets.at(-1); + } + if (target) complete(ex, target, { reps: spoken.reps, weightKg: spoken.weightKg, durationSec: spoken.durationSec }); + } + } + + async function finish() { + const all = exercises.flatMap((e) => e.sets); + const done = all.filter((s) => s.done); + if (!done.length) { + const discard = await confirmAction({ title: 'No sets ticked', message: 'Tick the sets you did, or discard this workout.', confirmLabel: 'Discard workout', destructive: true }); + if (discard) { + store().discard(); + if (router.canGoBack()) router.back(); + else router.replace('/(tabs)/'); + } + return; + } + if (done.length < all.length) { + const ok = await confirmAction({ title: 'Finish workout?', message: `${all.length - done.length} sets aren't ticked and won't be saved.`, confirmLabel: 'Finish' }); + if (!ok) return; + } + const prs = exercises.flatMap((e) => e.sets.filter((s) => s.done && s.pr).map((s) => `${e.name}: ${s.weightKg ? `${kgToUnit(s.weightKg, unit)} ${unit} × ${s.reps}` : `${s.reps} reps`}`)); + const volume = done.filter((s) => !s.warmup).reduce((t, s) => t + (s.weightKg ?? 0) * (s.reps ?? 0), 0); + const body = store().finish(); + if (!body) return; + sendWorkout(body); + haptic('success'); + setSummary({ body, prs, volume }); + } + + function menuItems(e: DraftExercise): MenuItem[] { + const i = exercises.findIndex((x) => x.key === e.key); + const p = prepared.get(e.exerciseId); + const firstWorking = e.sets.find((s) => !s.warmup); + return [ + { label: 'Swap for a similar exercise', onPress: () => setPicker({ mode: 'swap', key: e.key, pattern: p?.pattern ?? null }) }, + { label: 'Plates and warm-ups', onPress: () => setPlates({ key: e.key, weightKg: firstWorking?.weightKg ?? p?.suggestion?.weightKg ?? null }), disabled: !!p?.timed }, + { label: e.supersetId ? 'Remove from superset' : 'Superset with the next exercise', onPress: () => store().toggleSuperset(e.key), disabled: !e.supersetId && i === exercises.length - 1 }, + { label: 'Move up', onPress: () => store().moveExercise(e.key, -1), disabled: i === 0 }, + { label: 'Move down', onPress: () => store().moveExercise(e.key, 1), disabled: i === exercises.length - 1 }, + { label: 'History', onPress: () => router.push(`/exercise-history/${encodeURIComponent(e.exerciseId)}`) }, + { label: 'How to do it', onPress: () => setInfoId(e.exerciseId) }, + { label: 'Remove exercise', onPress: () => store().removeExercise(e.key), destructive: true }, + ]; + } + + const supersetLabel = (e: DraftExercise) => { + if (!e.supersetId) return null; + const group = exercises.filter((x) => x.supersetId === e.supersetId); + const letter = String.fromCharCode(65 + [...new Set(exercises.filter((x) => x.supersetId).map((x) => x.supersetId))].indexOf(e.supersetId)); + return `Superset ${letter}${group.indexOf(e) + 1}`; + }; + + return ( + + + + setWorkoutMenu(true)} hitSlop={10} accessibilityRole="button" accessibilityLabel="Workout options"> + ⋯ + + + {active.title || 'Workout'} + + + + Finish + + + + + e.exerciseId)} onSets={logSpoken} /> + {prepare.isLoading && !prepare.data && } + {exercises.map((e) => ( + router.push(`/exercise-history/${encodeURIComponent(e.exerciseId)}`)} + onMenu={() => setMenuFor(e)} + onComplete={(set) => complete(e, set)} + onCopyPrevious={(set, prev: PastSet) => complete(e, set, { weightKg: prev.weightKg, reps: prev.reps, durationSec: prev.durationSec })} + onUpdate={(setId, patch) => store().updateSet(e.key, setId, patch)} + onAddSet={(warmup) => store().addSet(e.key, warmup)} + /> + ))} + setPicker({ mode: 'add' })} + accessibilityRole="button" + style={{ borderRadius: 16, borderWidth: 1.5, borderStyle: 'dashed', borderColor: Colors.border, paddingVertical: 16, alignItems: 'center' }} + > + + Add exercise + + + + + + setMenuFor(null)} /> + setWorkoutMenu(false)} + items={[ + { label: 'Leave it running in the background', onPress: () => (router.canGoBack() ? router.back() : router.replace('/(tabs)/')) }, + { + label: 'Discard workout', + destructive: true, + onPress: async () => { + if (await confirmAction({ title: 'Discard workout?', message: "Sets you've ticked won't be saved.", confirmLabel: 'Discard', destructive: true })) { + store().discard(); + if (router.canGoBack()) router.back(); + else router.replace('/(tabs)/'); + } + }, + }, + ]} + /> + setPicker(null)} + onPick={(x) => { + const next = { exerciseId: x.id, name: x.name, compound: x.mechanics !== 'isolation' }; + if (picker?.mode === 'swap' && picker.key) store().swapExercise(picker.key, next); + else store().addExercise(next); + setPicker(null); + }} + /> + setPlates(undefined)} + onAddWarmups={(sets) => plates && store().insertSets(plates.key, sets.map((s) => ({ ...s, warmup: true })), 'start')} + /> + setInfoId(null)} /> + + ); +} + +function Elapsed({ since }: { since: string }) { + const [now, setNow] = useState(Date.now()); + useEffect(() => { + const t = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(t); + }, []); + return ( + + {formatClock((now - new Date(since).getTime()) / 1000)} + + ); +} + +/** "bench 80 for 8, 8, 7": typed, or spoken with the keyboard's microphone. */ +function SayIt({ exerciseIds, onSets }: { exerciseIds: string[]; onSets: (sets: SpokenSet[]) => void }) { + const [text, setText] = useState(''); + const parse = useParseSets(); + const ensureAiConsent = useEnsureAiConsent(); + + async function submit() { + const t = text.trim(); + if (!t) return; + const run = () => parse.mutateAsync({ text: t, exerciseIds }); + try { + let res; + try { + res = await run(); + } catch (err: any) { + // Phrasings the app can't read itself go to the AI, which needs consent + if (err?.response?.data?.code !== 'ai_consent_required' || !(await ensureAiConsent())) throw err; + res = await run(); + } + if (!res.sets.length) { + showToast('No sets in that. Try "bench 80 for 8, 8, 7".'); + return; + } + onSets(res.sets); + setText(''); + } catch (err: any) { + showToast(err?.response?.data?.message?.toString() ?? "Couldn't read that. Try \"bench 80 for 8, 8, 7\"."); + } + } + + return ( + + + + {parse.isPending ? : Log} + + + ); +} + +/** After finishing: what was done, and whether it's saved yet. */ +function Summary({ body, prs, volume, unit }: { body: SaveWorkoutBody; prs: string[]; volume: number; unit: 'kg' | 'lb' }) { + const pending = useWorkoutStore((s) => s.pending.find((p) => p.body.clientId === body.clientId)); + const online = useOnlineManager(); + const minutes = Math.max(1, Math.round((new Date(body.endedAt).getTime() - new Date(body.startedAt).getTime()) / 60_000)); + const working = body.sets.filter((s) => !s.warmup).length; + const status = !pending ? '✓ Saved' : pending.error ? `Not saved: ${pending.error}` : online ? 'Saving…' : "Saved on your phone. It'll sync when you're back online."; + + return ( + + + 💪 + Workout done + + + + + + {prs.length > 0 && ( + + 🏆 {prs.length === 1 ? 'New personal record' : `${prs.length} personal records`} + {prs.map((p, i) => ( + {p} + ))} + + )} + {status} + {pending?.error && ( + retryWorkout(body.clientId)} accessibilityRole="button" style={{ alignSelf: 'center' }}> + Try again + + )} + + router.replace('/(tabs)/activity')} accessibilityRole="button" style={{ backgroundColor: Colors.orange, borderRadius: 999, paddingVertical: 15, alignItems: 'center' }}> + Done + + + ); +} + +function Stat({ label, value }: { label: string; value: string }) { + return ( + + {value} + {label} + + ); +} diff --git a/apps/mobile/app/workouts/[id].tsx b/apps/mobile/app/workouts/[id].tsx new file mode 100644 index 0000000..fc5b80a --- /dev/null +++ b/apps/mobile/app/workouts/[id].tsx @@ -0,0 +1,75 @@ +import React from 'react'; +import { View, Text, ScrollView, ActivityIndicator, Pressable } from 'react-native'; +import { router, useLocalSearchParams } from 'expo-router'; +import { SafeAreaView } from 'react-native-safe-area-context'; +import { Colors } from '@/constants/colors'; +import { useDeleteWorkout, useWorkout, type SavedSet } from '@/hooks/useWorkouts'; +import { useMe } from '@/hooks/useMe'; +import { kgToUnit } from '@/lib/units'; +import { confirmAction } from '@/lib/confirm'; +import { PR_LABELS } from '@/lib/strength'; +import { ScreenHeader, Section } from '@/components/settings/SettingsUI'; + +/** A saved workout: its sets by exercise, with PRs. */ +export default function WorkoutDetailScreen() { + const { id } = useLocalSearchParams<{ id: string }>(); + const { data: w, isLoading, isError } = useWorkout(id ?? null); + const { data: me } = useMe(); + const unit = me?.weightUnit ?? 'kg'; + const del = useDeleteWorkout(); + + const groups: { exerciseId: string; name: string; sets: SavedSet[] }[] = []; + for (const s of w?.sets ?? []) { + const last = groups[groups.length - 1]; + if (last?.exerciseId === s.exerciseId) last.sets.push(s); + else groups.push({ exerciseId: s.exerciseId, name: s.exerciseName, sets: [s] }); + } + + async function remove() { + if (!w) return; + const ok = await confirmAction({ title: 'Delete workout?', message: 'Its sets, PRs and the activity log go too.', confirmLabel: 'Delete', destructive: true }); + if (!ok) return; + await del.mutateAsync(w.id); + if (router.canGoBack()) router.back(); + else router.replace('/(tabs)/activity'); + } + + return ( + + + + {isLoading ? ( + + ) : isError || !w ? ( + Couldn't load this workout. + ) : ( + <> + + {new Date(w.startedAt).toLocaleString()} · {w.activityLog.durationMin} min · {w.setCount} sets · {Math.round(kgToUnit(w.volumeKg, unit))} {unit} moved + {w.prCount ? ` · 🏆 ${w.prCount} PR${w.prCount > 1 ? 's' : ''}` : ''} + + {groups.map((g, i) => ( +
+ router.push(`/exercise-history/${encodeURIComponent(g.exerciseId)}`)} accessibilityRole="button"> + {g.name} + + {g.sets.map((s) => ( + + {s.warmup ? 'W' : '•'} + + {s.durationSec ? `${s.durationSec} s` : s.weightKg ? `${kgToUnit(s.weightKg, unit)} ${unit} × ${s.reps}` : `${s.reps} reps`} + + {!!s.pr && 🏆 {PR_LABELS[s.pr]}} + + ))} +
+ ))} + + Delete workout + + + )} +
+
+ ); +} diff --git a/apps/mobile/components/social/ActivityFeedItem.tsx b/apps/mobile/components/social/ActivityFeedItem.tsx index c2466f4..c46d7ac 100644 --- a/apps/mobile/components/social/ActivityFeedItem.tsx +++ b/apps/mobile/components/social/ActivityFeedItem.tsx @@ -39,17 +39,25 @@ function FeedContent({ item }: { item: FeedItem }) { } if (item.type === 'activity_log') { const label = ACTIVITY_LABELS[d.activityType as string] ?? `✨ ${d.activityType}`; + // Logged set by set: counts only, never the weights + const workout = d.workout as { title: string | null; setCount: number; prCount: number } | null | undefined; return ( {item.user.displayName} - {' '}completed {label} + {' '}completed {workout?.title ? `${label}: ${workout.title}` : label} {d.durationMin as number} min + {workout?.setCount ? ` · ${workout.setCount} sets` : ''} {d.caloriesBurned ? ` · ${Math.round(d.caloriesBurned as number)} kcal` : ''} {d.steps ? ` · ${(d.steps as number).toLocaleString()} steps` : ''} + {!!workout?.prCount && ( + + 🏆 {workout.prCount === 1 ? 'New personal record' : `${workout.prCount} personal records`} + + )} ); } diff --git a/apps/mobile/components/workout/ExerciseCard.tsx b/apps/mobile/components/workout/ExerciseCard.tsx new file mode 100644 index 0000000..d03870a --- /dev/null +++ b/apps/mobile/components/workout/ExerciseCard.tsx @@ -0,0 +1,180 @@ +import React from 'react'; +import { View, Text, Pressable, TextInput } from 'react-native'; +import { Colors } from '@/constants/colors'; +import { kgToUnit, unitToKg, type WeightUnit } from '@/lib/units'; +import type { DraftExercise, DraftSet } from '@/stores/workoutStore'; +import type { PastSet, PreparedExercise } from '@/hooks/useWorkouts'; +import { PR_LABELS } from '@/lib/strength'; + +const ACTION_ICON: Record = { increase: '↑', reps: '+1', hold: '=', deload: '↓', start: '•' }; + +function fmtSet(s: PastSet, unit: WeightUnit) { + if (s.durationSec) return `${s.durationSec}s`; + return s.weightKg ? `${kgToUnit(s.weightKg, unit)}×${s.reps}` : `${s.reps}`; +} + +/** One exercise in the workout: last time, today's target, and its sets. */ +export function ExerciseCard({ + exercise, prepared, unit, supersetLabel, onOpen, onMenu, onComplete, onCopyPrevious, onUpdate, onAddSet, +}: { + exercise: DraftExercise; + prepared: PreparedExercise | undefined; + unit: WeightUnit; + supersetLabel: string | null; + onOpen: () => void; + onMenu: () => void; + onComplete: (set: DraftSet) => void; + onCopyPrevious: (set: DraftSet, previous: PastSet) => void; + onUpdate: (setId: string, patch: Partial) => void; + onAddSet: (warmup: boolean) => void; +}) { + const s = prepared?.suggestion; + const timed = !!prepared?.timed; + const previous = prepared?.last?.sets ?? []; + let working = -1; + + return ( + + + + {!!supersetLabel && ( + {supersetLabel} + )} + {exercise.name} + {!!exercise.detail && {exercise.detail}} + + + ⋯ + + + + {!!s && ( + + + {ACTION_ICON[s.action]} {s.weightKg ? `${kgToUnit(s.weightKg, unit)} ${unit} × ${s.reps}` : s.action === 'start' ? `Start with ${s.reps} reps` : `${s.reps} reps`} + + {s.reasons.map((r, i) => ( + {r} + ))} + {!!prepared?.historyFrom && ( + Based on your {prepared.historyFrom.name}. + )} + + )} + + + SET + LAST + {!timed && {unit.toUpperCase()}} + {timed ? 'SEC' : 'REPS'} + + + + {exercise.sets.map((set) => { + if (!set.warmup) working++; + const prev = set.warmup ? undefined : previous[working]; + const label = set.warmup ? 'W' : String(working + 1); + return ( + + {label} + prev && onCopyPrevious(set, prev)} + accessibilityRole="button" + accessibilityLabel={prev ? `Repeat last time: ${fmtSet(prev, unit)}` : undefined} + > + + {prev ? fmtSet(prev, unit) : '—'} + + + {!timed && ( + onUpdate(set.id, { weightKg: v == null ? null : unitToKg(v, unit) })} + decimal + label={`Set ${label} weight in ${unit}`} + placeholder="—" + /> + )} + onUpdate(set.id, timed ? { durationSec: v } : { reps: v })} + label={`Set ${label} ${timed ? 'seconds' : 'reps'}`} + placeholder="0" + /> + onComplete(set)} + accessibilityRole="checkbox" + accessibilityState={{ checked: set.done }} + aria-checked={set.done} + accessibilityLabel={`Set ${label} done`} + style={{ width: 38, height: 34, borderRadius: 10, alignItems: 'center', justifyContent: 'center', backgroundColor: set.done ? Colors.teal : Colors.surface2, marginLeft: 6 }} + > + ✓ + + {!!set.pr && ( + 🏆 PR + )} + + ); + })} + + + onAddSet(false)} accessibilityRole="button"> + + Add set + + {!timed && ( + onAddSet(true)} accessibilityRole="button"> + + Warm-up + + )} + + + ); +} + +const headStyle = (width: number) => ({ + ...(width ? { width } : {}), + color: Colors.muted, + fontFamily: 'DMSans-Bold' as const, + fontSize: 10, + letterSpacing: 0.6, +}); + +function NumberBox({ value, onChange, width, decimal, label, placeholder }: { + value: number | null; + onChange: (v: number | null) => void; + width: number; + decimal?: boolean; + label: string; + placeholder: string; +}) { + const [text, setText] = React.useState(value != null ? String(value) : ''); + // Follow changes made elsewhere (prefill, Say it), but not while typing "8." + React.useEffect(() => { + const parsed = text === '' ? null : Number(text.replace(',', '.')); + if (parsed !== value) setText(value != null ? String(value) : ''); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [value]); + return ( + { + const clean = t.replace(',', '.').replace(decimal ? /[^0-9.]/g : /[^0-9]/g, ''); + setText(clean); + const n = clean === '' ? null : Number(clean); + if (n == null || Number.isFinite(n)) onChange(n); + }} + keyboardType={decimal ? 'decimal-pad' : 'number-pad'} + selectTextOnFocus + placeholder={placeholder} + placeholderTextColor={`${Colors.muted}88`} + accessibilityLabel={label} + maxLength={6} + style={{ width, height: 34, borderRadius: 10, backgroundColor: Colors.surface2, color: Colors.text, textAlign: 'center', fontFamily: 'JetBrainsMono-Regular', fontSize: 14, paddingVertical: 0 }} + /> + ); +} diff --git a/apps/mobile/components/workout/ExercisePicker.tsx b/apps/mobile/components/workout/ExercisePicker.tsx new file mode 100644 index 0000000..ed76aa2 --- /dev/null +++ b/apps/mobile/components/workout/ExercisePicker.tsx @@ -0,0 +1,74 @@ +import React, { useState } from 'react'; +import { Modal, View, Text, Pressable, TextInput, FlatList, ActivityIndicator } from 'react-native'; +import { Colors } from '@/constants/colors'; +import { useExerciseSearch, type Exercise } from '@/hooks/useExercises'; +import { useAlternatives } from '@/hooks/useWorkouts'; + +/** + * Picks an exercise from the library: to add one, or to swap one for + * another on the same movement (which keeps its progression history). + */ +export function ExercisePicker({ mode, pattern, onPick, onClose }: { + mode: 'add' | 'swap' | null; + pattern?: string | null; + onPick: (e: Exercise) => void; + onClose: () => void; +}) { + const [q, setQ] = useState(''); + const swapping = mode === 'swap' && !!pattern; + const search = useExerciseSearch(swapping ? '' : q); + const alternatives = useAlternatives(swapping ? pattern! : null, q); + const { data, isLoading } = swapping ? alternatives : search; + + return ( + + + + + {swapping ? 'Swap for' : 'Add an exercise'} + + + Cancel + + + {swapping && ( + + Same movement, so your progress carries over. + + )} + + {isLoading ? ( + + ) : ( + e.id} + keyboardShouldPersistTaps="handled" + contentContainerStyle={{ paddingHorizontal: 20, paddingBottom: 40 }} + renderItem={({ item }) => ( + onPick(item)} + accessibilityRole="button" + style={({ pressed }) => ({ paddingVertical: 12, borderBottomWidth: 1, borderColor: Colors.border, opacity: pressed ? 0.6 : 1 })} + > + {item.name} + + {[...item.equipment, ...item.primary].join(' · ')} + + + )} + ListEmptyComponent={Nothing found.} + /> + )} + + + ); +} diff --git a/apps/mobile/components/workout/MenuSheet.tsx b/apps/mobile/components/workout/MenuSheet.tsx new file mode 100644 index 0000000..b84e8ef --- /dev/null +++ b/apps/mobile/components/workout/MenuSheet.tsx @@ -0,0 +1,35 @@ +import React from 'react'; +import { Modal, View, Text, Pressable } from 'react-native'; +import { Colors } from '@/constants/colors'; + +export interface MenuItem { + label: string; + onPress: () => void; + destructive?: boolean; + disabled?: boolean; +} + +/** A list of actions sliding up from the bottom. */ +export function MenuSheet({ title, items, onClose }: { title: string | null; items: MenuItem[]; onClose: () => void }) { + return ( + + + + {title} + {items.filter((i) => !i.disabled).map((i) => ( + { + onClose(); + i.onPress(); + }} + accessibilityRole="button" + style={({ pressed }) => ({ paddingVertical: 13, opacity: pressed ? 0.6 : 1 })} + > + {i.label} + + ))} + + + ); +} diff --git a/apps/mobile/components/workout/PlatesSheet.tsx b/apps/mobile/components/workout/PlatesSheet.tsx new file mode 100644 index 0000000..a3bed5a --- /dev/null +++ b/apps/mobile/components/workout/PlatesSheet.tsx @@ -0,0 +1,67 @@ +import React, { useState } from 'react'; +import { Modal, View, Text, Pressable, TextInput } from 'react-native'; +import { Colors } from '@/constants/colors'; +import { platesFor, warmupsFor } from '@/lib/strength'; +import { kgToUnit, unitToKg, type WeightUnit } from '@/lib/units'; + +const LB_PLATES = [45, 35, 25, 10, 5, 2.5]; + +/** Plates per side for a weight, and warm-up sets that lead up to it. */ +export function PlatesSheet({ weightKg, unit, onClose, onAddWarmups }: { + weightKg: number | null | undefined; + unit: WeightUnit; + onClose: () => void; + onAddWarmups: (sets: { weightKg: number; reps: number }[]) => void; +}) { + const visible = weightKg !== undefined; + const [text, setText] = useState(weightKg ? String(kgToUnit(weightKg, unit)) : ''); + React.useEffect(() => setText(weightKg ? String(kgToUnit(weightKg, unit)) : ''), [weightKg, unit]); + const shown = Number(text.replace(',', '.')) || 0; + const bar = unit === 'lb' ? 45 : 20; + const plates = platesFor(shown, bar, unit === 'lb' ? LB_PLATES : undefined); + const warmups = warmupsFor(unitToKg(shown, unit)); + + return ( + + + + Plates and warm-ups + + setText(t.replace(/[^0-9.,]/g, ''))} + keyboardType="decimal-pad" + accessibilityLabel={`Weight in ${unit}`} + style={{ width: 110, height: 44, borderRadius: 12, backgroundColor: Colors.surface2, color: Colors.text, textAlign: 'center', fontFamily: 'JetBrainsMono-Regular', fontSize: 18 }} + /> + {unit} on a {bar} {unit} bar + + + Each side: {plates.perSide.length ? plates.perSide.join(' + ') : 'just the bar'} + {plates.rest > 0 ? ` (${plates.rest} ${unit} short: needs smaller plates)` : ''} + + {warmups.length > 0 && ( + + WARM-UP + + {warmups.map((w) => `${kgToUnit(w.weightKg, unit)}×${w.reps}`).join(' ')} + + { + onAddWarmups(warmups); + onClose(); + }} + accessibilityRole="button" + style={{ alignSelf: 'flex-start', marginTop: 4, paddingHorizontal: 16, paddingVertical: 10, borderRadius: 999, backgroundColor: Colors.orange }} + > + Add warm-up sets + + + )} + + Close + + + + ); +} diff --git a/apps/mobile/components/workout/RestBar.tsx b/apps/mobile/components/workout/RestBar.tsx new file mode 100644 index 0000000..f916b12 --- /dev/null +++ b/apps/mobile/components/workout/RestBar.tsx @@ -0,0 +1,48 @@ +import React, { useEffect, useState } from 'react'; +import { View, Text, Pressable, Platform } from 'react-native'; +import * as Haptics from 'expo-haptics'; +import { Colors } from '@/constants/colors'; +import { formatClock } from '@/lib/strength'; +import { useWorkoutStore } from '@/stores/workoutStore'; + +/** The rest timer between sets, pinned to the bottom of the workout. */ +export function RestBar() { + const rest = useWorkoutStore((s) => s.rest); + const extend = useWorkoutStore((s) => s.extendRest); + const clear = useWorkoutStore((s) => s.clearRest); + const [now, setNow] = useState(Date.now()); + + useEffect(() => { + if (!rest) return; + const t = setInterval(() => setNow(Date.now()), 500); + return () => clearInterval(t); + }, [rest]); + + const left = rest ? Math.ceil((rest.endsAt - now) / 1000) : 0; + useEffect(() => { + if (rest && left <= 0) { + if (Platform.OS !== 'web') Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); + clear(); + } + }, [rest, left, clear]); + + if (!rest || left <= 0) return null; + const pct = Math.max(0, Math.min(1, left / rest.totalSec)); + return ( + + + + + + {rest.label} + {formatClock(left)} + extend(30)} accessibilityRole="button" accessibilityLabel="Add 30 seconds" style={{ paddingHorizontal: 10, paddingVertical: 6, borderRadius: 999, backgroundColor: Colors.surface2 }}> + +30s + + + Skip + + + + ); +} diff --git a/apps/mobile/hooks/useActivityLog.ts b/apps/mobile/hooks/useActivityLog.ts index 7f281aa..6aa8451 100644 --- a/apps/mobile/hooks/useActivityLog.ts +++ b/apps/mobile/hooks/useActivityLog.ts @@ -12,6 +12,8 @@ export interface ActivityLog { kudosCount: number; /** light | moderate | vigorous; picks the calorie estimate */ intensity: Intensity | null; + /** Set when it was logged set by set in a workout */ + workoutSession?: { id: string; title: string | null; setCount: number; prCount: number } | null; } export type Intensity = 'light' | 'moderate' | 'vigorous'; diff --git a/apps/mobile/hooks/useFoodLog.ts b/apps/mobile/hooks/useFoodLog.ts index f01501a..04aa8bb 100644 --- a/apps/mobile/hooks/useFoodLog.ts +++ b/apps/mobile/hooks/useFoodLog.ts @@ -1,5 +1,6 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { api } from '@/lib/api'; +import { deleteFoodFromHealth, updateFoodInHealth, writeFoodsToHealth } from '@/lib/health/sync'; export interface FoodLog { id: string; @@ -119,7 +120,9 @@ export function useLogFood() { /** For back-filling an earlier day; omitted for now */ loggedAt?: string; }) => api.post('/food-logs', data).then((r) => r.data), - onSuccess: () => { + onSuccess: (log) => { + // To Apple Health / Health Connect, if the user turned that on + writeFoodsToHealth([log]); qc.invalidateQueries({ queryKey: ['food-recent'] }); qc.invalidateQueries({ queryKey: ['food-logs'] }); qc.invalidateQueries({ queryKey: ['food-week'] }); @@ -159,6 +162,9 @@ export function useDeleteFoodLog() { onError: (_err, _id, context) => { for (const [key, day] of context?.previous ?? []) qc.setQueryData(key, day); }, + onSuccess: (_res, id) => { + deleteFoodFromHealth(id); + }, onSettled: () => { qc.invalidateQueries({ queryKey: ['food-logs'] }); qc.invalidateQueries({ queryKey: ['food-recent'] }); @@ -176,7 +182,8 @@ export function useUpdateFoodLog() { return useMutation({ mutationFn: ({ id, ...data }: FoodLogUpdate & { id: string }) => api.patch(`/food-logs/${id}`, data).then((r) => r.data), - onSuccess: () => { + onSuccess: (log) => { + updateFoodInHealth(log); qc.invalidateQueries({ queryKey: ['food-logs'] }); qc.invalidateQueries({ queryKey: ['food-recent'] }); qc.invalidateQueries({ queryKey: ['food-week'] }); diff --git a/apps/mobile/hooks/useHealthRecent.ts b/apps/mobile/hooks/useHealthRecent.ts index bba6553..bba9c63 100644 --- a/apps/mobile/hooks/useHealthRecent.ts +++ b/apps/mobile/hooks/useHealthRecent.ts @@ -5,6 +5,16 @@ export interface HealthRecent { days: { date: string; steps: number | null; sleepMinutes: number | null; source: string }[]; importedWorkouts: number; lastSyncedAt: string | null; + /** Each recovery metric's latest value and 30-day average; never cycle data */ + recovery?: { metric: string; type: string | null; unit: string; latest: number; latestDate: string; average: number; days: number }[]; +} + +/** Whether cycle data is on, and how many days of it are stored. */ +export function useCycleSummary() { + return useQuery<{ consent: boolean; days: number }>({ + queryKey: ['health-cycle'], + queryFn: () => api.get('/health/cycle').then((r) => r.data), + }); } /** The last week of synced steps and sleep. */ diff --git a/apps/mobile/hooks/useMe.ts b/apps/mobile/hooks/useMe.ts index 70ec6e3..beb5216 100644 --- a/apps/mobile/hooks/useMe.ts +++ b/apps/mobile/hooks/useMe.ts @@ -42,6 +42,8 @@ export interface Me { consentHealthTraining: boolean; consentWorkoutTraining: boolean; consentOffSharing: boolean; + /** Reading menstrual data from the health app: its own consent */ + consentCycleData: boolean; } /** Fields the signed-in user can change with PUT /users/me. */ diff --git a/apps/mobile/hooks/useOnline.ts b/apps/mobile/hooks/useOnline.ts new file mode 100644 index 0000000..c7a8ec1 --- /dev/null +++ b/apps/mobile/hooks/useOnline.ts @@ -0,0 +1,10 @@ +import { useSyncExternalStore } from 'react'; +import { onlineManager } from '@tanstack/react-query'; + +const subscribe = (cb: () => void) => onlineManager.subscribe(cb); +const isOnline = () => onlineManager.isOnline(); + +/** Whether the phone is online, as React Query sees it. */ +export function useOnlineManager() { + return useSyncExternalStore(subscribe, isOnline, isOnline); +} diff --git a/apps/mobile/hooks/useSmartLog.ts b/apps/mobile/hooks/useSmartLog.ts index 45d2079..6518de7 100644 --- a/apps/mobile/hooks/useSmartLog.ts +++ b/apps/mobile/hooks/useSmartLog.ts @@ -1,5 +1,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { api } from '@/lib/api'; +import { writeFoodsToHealth } from '@/lib/health/sync'; +import type { FoodLog } from '@/hooks/useFoodLog'; export type ItemSource = 'memory' | 'database' | 'estimate'; @@ -75,8 +77,9 @@ export function useLogParsedMeal() { alcoholPer100g?: number; remember?: boolean; }[]; - }) => api.post<{ logged: number }>('/food/parse/log', body).then((r) => r.data), - onSuccess: () => { + }) => api.post<{ logged: number; logs: FoodLog[] }>('/food/parse/log', body).then((r) => r.data), + onSuccess: (res) => { + writeFoodsToHealth(res.logs ?? []); for (const key of ['food-logs', 'food-recent', 'food-week', 'trends', 'adaptive', 'food-memories']) { qc.invalidateQueries({ queryKey: [key] }); } diff --git a/apps/mobile/hooks/useStartWorkout.ts b/apps/mobile/hooks/useStartWorkout.ts new file mode 100644 index 0000000..a7f39f8 --- /dev/null +++ b/apps/mobile/hooks/useStartWorkout.ts @@ -0,0 +1,53 @@ +import { useCallback } from 'react'; +import { router } from 'expo-router'; +import { useAuthStore } from '@/stores/authStore'; +import { useWorkoutStore, type NewExercise } from '@/stores/workoutStore'; +import { confirmAction } from '@/lib/confirm'; +import type { PlanDay } from '@/hooks/useWorkoutPlan'; + +const COMPOUND = new Set(['squat', 'hip_hinge', 'lunge', 'horizontal_press', 'vertical_press', 'horizontal_pull', 'vertical_pull', 'carry']); +export const isCompound = (pattern: string | null | undefined) => !!pattern && COMPOUND.has(pattern); + +/** + * Opens the workout screen with a plan session (or an empty workout). If a + * workout is already in progress, offers to carry on with it instead. + */ +export function useStartWorkout() { + const userId = useAuthStore((s) => s.session?.user.id); + return useCallback( + async (from?: { session: number; day: PlanDay }) => { + if (!userId) return; + const { active, start, discard } = useWorkoutStore.getState(); + if (active && active.ownerId === userId) { + const carryOn = await confirmAction({ + title: 'Workout in progress', + message: 'You have a workout going. Carry on with it, or start this one instead?', + confirmLabel: 'Carry on', + }); + if (carryOn) { + router.push('/workout'); + return; + } + const replace = await confirmAction({ + title: 'Start a new workout?', + message: "The one in progress will be discarded. Sets you've ticked won't be saved.", + confirmLabel: 'Discard and start', + destructive: true, + }); + if (!replace) return; + discard(); + } + const exercises: NewExercise[] = (from?.day.exercises ?? []) + .filter((e) => e.exerciseId) + .map((e) => ({ exerciseId: e.exerciseId!, name: e.name, detail: e.detail || null })); + start({ + ownerId: userId, + planSession: from?.session ?? null, + title: from?.day.title ?? null, + exercises, + }); + router.push('/workout'); + }, + [userId], + ); +} diff --git a/apps/mobile/hooks/useWorkoutPlan.ts b/apps/mobile/hooks/useWorkoutPlan.ts index d43f0f4..5eb95f0 100644 --- a/apps/mobile/hooks/useWorkoutPlan.ts +++ b/apps/mobile/hooks/useWorkoutPlan.ts @@ -30,9 +30,30 @@ export interface WorkoutPlan { daysPerWeek: number; location: 'home' | 'gym'; days: PlanDay[]; + /** The training session (1, 2, 3…) that comes next; plans run in order */ + nextSession: number; updatedAt: string; } +/** The plan's training days in order, as sessions 1, 2, 3… */ +export function planSessions(plan: WorkoutPlan) { + return plan.days.filter((d) => !d.rest).map((day, i) => ({ number: i + 1, day })); +} + +/** The session that's next, whatever day it is. */ +export function nextUp(plan: WorkoutPlan | null | undefined) { + if (!plan) return null; + const sessions = planSessions(plan); + if (!sessions.length) return null; + const n = Math.min(Math.max(plan.nextSession ?? 1, 1), sessions.length); + return { ...sessions[n - 1], total: sessions.length }; +} + +/** Whether the session is set by set (it has library exercises) rather than a run or class. */ +export function isLiftingDay(day: PlanDay) { + return day.exercises.some((e) => e.exerciseId) && !['running', 'cycling', 'walking', 'swimming', 'hiking', 'rowing', 'elliptical'].includes(day.activityType); +} + /** Today's weekday key on the device's clock. */ export function todayWeekday(d: Date = new Date()): Weekday { return WEEKDAYS[(d.getDay() + 6) % 7]; diff --git a/apps/mobile/hooks/useWorkouts.ts b/apps/mobile/hooks/useWorkouts.ts new file mode 100644 index 0000000..16cc6a7 --- /dev/null +++ b/apps/mobile/hooks/useWorkouts.ts @@ -0,0 +1,161 @@ +import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { api } from '@/lib/api'; +import type { PrKind, Records } from '@/lib/strength'; +import type { Exercise } from '@/hooks/useExercises'; + +export interface Suggestion { + action: 'start' | 'increase' | 'reps' | 'hold' | 'deload'; + weightKg: number | null; + sets: number; + reps: number; + repsLow: number; + repsHigh: number; + holds: ('deficit' | 'protein' | 'sleep')[]; + reasons: string[]; +} + +export interface PastSet { + reps: number; + weightKg: number | null; + durationSec: number | null; +} + +export interface PreparedExercise { + exerciseId: string; + name: string; + equipment: string[]; + pattern: string | null; + imageUrl: string | null; + detail: string | null; + timed: { sets: number; seconds: number } | null; + last: { date: string; sets: PastSet[] } | null; + /** Set when the history is borrowed from a similar exercise after a swap */ + historyFrom: { id: string; name: string } | null; + records: Records; + suggestion: Suggestion | null; +} + +export interface SavedSet { + id: string; + exerciseId: string; + exerciseName: string; + reps: number; + weightKg: number | null; + durationSec: number | null; + rpe: number | null; + warmup: boolean; + supersetId: string | null; + pr: PrKind | null; +} + +export interface SavedWorkout { + id: string; + clientId: string; + title: string | null; + planSession: number | null; + startedAt: string; + endedAt: string; + setCount: number; + volumeKg: number; + prCount: number; + activityLog: { id: string; caloriesBurned: number | null; durationMin: number }; + sets: SavedSet[]; +} + +/** Last time, records and today's targets for the exercises about to be done. */ +export function usePrepareWorkout(exercises: { exerciseId: string; detail?: string | null }[]) { + const body = { exercises: exercises.map((e) => ({ exerciseId: e.exerciseId, ...(e.detail ? { detail: e.detail } : {}) })) }; + return useQuery<{ today: string; exercises: PreparedExercise[] }>({ + queryKey: ['workout-prepare', body], + queryFn: () => api.post('/workouts/prepare', body).then((r) => r.data), + enabled: exercises.length > 0, + staleTime: 10 * 60_000, + // Offline, use what was fetched before rather than waiting + networkMode: 'offlineFirst', + // Keep showing the targets while an added exercise loads + placeholderData: keepPreviousData, + }); +} + +export function useWorkout(id: string | null) { + return useQuery({ + queryKey: ['workouts', 'detail', id], + queryFn: () => api.get(`/workouts/${id}`).then((r) => r.data), + enabled: !!id, + }); +} + +export function useDeleteWorkout() { + const qc = useQueryClient(); + return useMutation({ + mutationFn: (id: string) => api.delete(`/workouts/${id}`).then((r) => r.data), + onSuccess: () => { + for (const key of ['workouts', 'activity-logs', 'activity-week', 'workout-history', 'feed', 'challenges']) { + qc.invalidateQueries({ queryKey: [key] }); + } + }, + meta: { errorMessage: "Couldn't delete the workout" }, + }); +} + +export interface ExerciseHistory { + exercise: Pick; + records: Records; + sessions: { + sessionId: string; + date: string; + sets: (PastSet & { warmup: boolean; pr: PrKind | null })[]; + bestE1rm: number | null; + topWeightKg: number | null; + bestReps: number | null; + }[]; +} + +export function useExerciseHistory(exerciseId: string | null) { + return useQuery({ + queryKey: ['workout-history', exerciseId], + queryFn: () => api.get(`/workouts/exercises/${encodeURIComponent(exerciseId!)}/history`).then((r) => r.data), + enabled: !!exerciseId, + }); +} + +export interface SpokenSet { + exerciseId: string; + exerciseName: string; + reps: number; + weightKg: number | null; + durationSec: number | null; +} + +/** "bench 80 for 8, 8, 7" → sets */ +export function useParseSets() { + return useMutation({ + mutationFn: (body: { text: string; exerciseIds: string[] }) => + api.post<{ sets: SpokenSet[]; source: 'rules' | 'ai' }>('/workouts/parse', body, { timeout: 45_000 }).then((r) => r.data), + }); +} + +/** Exercises on the same movement, for swapping. */ +export function useAlternatives(pattern: string | null, q = '') { + const params = new URLSearchParams(); + if (pattern) params.set('pattern', pattern); + if (q.trim()) params.set('q', q.trim()); + return useQuery({ + queryKey: ['exercises', 'pattern', pattern, q.trim()], + queryFn: () => api.get(`/exercises?${params.toString()}`).then((r) => r.data), + enabled: !!pattern || q.trim().length > 1, + staleTime: 60 * 60_000, + }); +} + +/** Logs a plan day done without sets (a run, a class), moving the plan on. */ +export function useLogPlanSession() { + const qc = useQueryClient(); + return useMutation({ + mutationFn: (body: { clientId: string; planSession: number; title: string; activityType: string; startedAt: string; endedAt: string }) => + api.post('/workouts', { ...body, sets: [] }).then((r) => r.data), + onSuccess: () => { + for (const key of ['workout-plan', 'activity-logs', 'activity-week', 'feed', 'challenges']) qc.invalidateQueries({ queryKey: [key] }); + }, + }); +} diff --git a/apps/mobile/lib/health/reasons.ts b/apps/mobile/lib/health/reasons.ts new file mode 100644 index 0000000..f284f44 --- /dev/null +++ b/apps/mobile/lib/health/reasons.ts @@ -0,0 +1,16 @@ +/** + * What GRIT reads from the health app, and why. Health Connect asks apps to + * explain every permission; Apple asks for the same in review. Shown on the + * health settings screen before the system prompt. + */ +export const HEALTH_REASONS: { label: string; reason: string }[] = [ + { label: 'Workouts, steps and distance', reason: 'So they count toward your goals and challenges.' }, + { label: 'Heart rate during workouts', reason: "To work out calories from your heart rate, which beats a general estimate." }, + { label: 'Sleep, heart rate variability, resting heart rate, breathing rate and sleeping temperature', reason: "So your coach and the progression rules know how you're recovering." }, + { label: 'VO2max', reason: 'To show your fitness trend.' }, + { label: 'Weight', reason: 'For your weight trend and calorie targets.' }, + { label: 'Past data', reason: 'To import the last two months when you first connect.' }, +]; + +export const CYCLE_REASON = + "Period days and flow, only if you turn this on. They're kept for you alone: never in your feed, challenges or coach chats, and turning it off deletes them."; diff --git a/apps/mobile/lib/health/source.android.ts b/apps/mobile/lib/health/source.android.ts index 86a3181..c43ce5f 100644 --- a/apps/mobile/lib/health/source.android.ts +++ b/apps/mobile/lib/health/source.android.ts @@ -1,24 +1,38 @@ import { aggregateGroupByPeriod, + aggregateRecord, + deleteRecordsByUuids, getSdkStatus, initialize, + insertRecords, readRecords, requestPermission, SdkAvailabilityStatus, } from 'react-native-health-connect'; import { localDateStr } from '@/lib/date'; import { androidExerciseType } from './transform'; -import type { HealthSource, SleepInterval } from './types'; +import type { AccessOptions, HealthSource, HealthWorkout, MetricSample, SleepInterval } from './types'; // Sleep stage types that are awake time inside a session const AWAKE_STAGES = new Set([1, 3]); -const PERMISSIONS = [ - { accessType: 'read', recordType: 'ExerciseSession' }, - { accessType: 'read', recordType: 'Steps' }, - { accessType: 'read', recordType: 'Weight' }, - { accessType: 'read', recordType: 'SleepSession' }, +// Health Connect MealType: 1 breakfast, 2 lunch, 3 dinner, 4 snack +const MEAL_TYPES: Record = { breakfast: 1, lunch: 2, dinner: 3, snack: 4 }; + +const READ = [ + 'ExerciseSession', + 'Steps', + 'Weight', + 'SleepSession', + 'HeartRate', + 'HeartRateVariabilityRmssd', + 'RestingHeartRate', + 'RespiratoryRate', + 'SkinTemperature', + 'Vo2Max', + 'Distance', ] as const; +const CYCLE = ['MenstruationFlow', 'MenstruationPeriod'] as const; let initialized = false; async function ready() { @@ -26,6 +40,18 @@ async function ready() { return initialized; } +async function records(type: string, timeRangeFilter: object): Promise { + try { + return ((await readRecords(type as never, { timeRangeFilter } as never)) as unknown as { records: T[] }).records; + } catch { + // Not allowed: carry on without it + return []; + } +} + +type WithOrigin = { metadata?: { dataOrigin?: string; device?: { model?: string; manufacturer?: string } } }; +const deviceOf = (r: WithOrigin) => r.metadata?.device?.model ?? r.metadata?.dataOrigin; + /** Health Connect, through react-native-health-connect. */ export const healthSource: HealthSource = { id: 'health_connect', @@ -37,22 +63,42 @@ export const healthSource: HealthSource = { return false; } }, - requestAccess: async () => { + requestAccess: async (opts?: AccessOptions) => { if (!(await ready())) return false; - const granted = await requestPermission([...PERMISSIONS] as never); + const permissions = [ + ...READ.map((recordType) => ({ accessType: 'read', recordType })), + ...(opts?.cycle ? CYCLE.map((recordType) => ({ accessType: 'read', recordType })) : []), + ...(opts?.writeFood ? [{ accessType: 'write', recordType: 'Nutrition' }] : []), + // Data from before GRIT was connected (Health Connect otherwise allows 30 days) + { accessType: 'read', recordType: 'ReadHealthDataHistory' }, + ]; + const granted = await requestPermission(permissions as never); return granted.length > 0; }, - read: async (since, until) => { + read: async (since, until, opts) => { await ready(); const timeRangeFilter = { operator: 'between' as const, startTime: since.toISOString(), endTime: until.toISOString() }; - const sessions = await readRecords('ExerciseSession', { timeRangeFilter }); - const workouts = sessions.records.map((r) => ({ - id: `hc:${r.metadata?.id ?? `${r.startTime}-${r.exerciseType}`}`, - activityType: androidExerciseType(r.exerciseType), - start: new Date(r.startTime), - end: new Date(r.endTime), - })); + const sessions = await records<{ startTime: string; endTime: string; exerciseType: number; metadata?: { id?: string } }>('ExerciseSession', timeRangeFilter); + const workouts: HealthWorkout[] = []; + for (const r of sessions) { + const range = { operator: 'between' as const, startTime: r.startTime, endTime: r.endTime }; + const beats = (await records<{ samples: { beatsPerMinute: number }[] }>('HeartRate', range)).flatMap((h) => h.samples); + let distanceM: number | undefined; + try { + distanceM = ((await aggregateRecord({ recordType: 'Distance', timeRangeFilter: range } as never)) as unknown as { DISTANCE?: { inMeters: number } }).DISTANCE?.inMeters; + } catch { + distanceM = undefined; + } + workouts.push({ + id: `hc:${r.metadata?.id ?? `${r.startTime}-${r.exerciseType}`}`, + activityType: androidExerciseType(r.exerciseType), + start: new Date(r.startTime), + end: new Date(r.endTime), + avgHeartRate: beats.length ? beats.reduce((t, b) => t + b.beatsPerMinute, 0) / beats.length : undefined, + distanceM: distanceM && distanceM > 0 ? distanceM : undefined, + }); + } const midnight = new Date(since); midnight.setHours(0, 0, 0, 0); @@ -66,12 +112,10 @@ export const healthSource: HealthSource = { steps: g.result.COUNT_TOTAL ?? 0, })); - const weightRecords = await readRecords('Weight', { timeRangeFilter }); - const weights = weightRecords.records.map((w) => ({ at: new Date(w.time), kg: w.weight.inKilograms })); + const weights = (await records<{ time: string; weight: { inKilograms: number } }>('Weight', timeRangeFilter)).map((w) => ({ at: new Date(w.time), kg: w.weight.inKilograms })); - const sleepRecords = await readRecords('SleepSession', { timeRangeFilter }); const sleep: SleepInterval[] = []; - for (const s of sleepRecords.records) { + for (const s of await records<{ startTime: string; endTime: string; stages?: { stage: number; startTime: string; endTime: string }[] }>('SleepSession', timeRangeFilter)) { sleep.push({ start: new Date(s.startTime), end: new Date(s.endTime), asleep: true }); for (const stage of s.stages ?? []) { if (AWAKE_STAGES.has(stage.stage)) { @@ -80,6 +124,64 @@ export const healthSource: HealthSource = { } } - return { workouts, steps, sleep, weights }; + const metrics: MetricSample[] = []; + for (const r of await records<{ time: string; heartRateVariabilityMillis: number } & WithOrigin>('HeartRateVariabilityRmssd', timeRangeFilter)) { + metrics.push({ metric: 'hrv', type: 'rmssd', at: new Date(r.time), value: r.heartRateVariabilityMillis, device: deviceOf(r) }); + } + for (const r of await records<{ time: string; beatsPerMinute: number } & WithOrigin>('RestingHeartRate', timeRangeFilter)) { + metrics.push({ metric: 'resting_hr', at: new Date(r.time), value: r.beatsPerMinute, device: deviceOf(r) }); + } + for (const r of await records<{ time: string; rate: number } & WithOrigin>('RespiratoryRate', timeRangeFilter)) { + metrics.push({ metric: 'respiratory_rate', at: new Date(r.time), value: r.rate, device: deviceOf(r) }); + } + for (const r of await records<{ time: string; vo2MillilitersPerMinuteKilogram: number } & WithOrigin>('Vo2Max', timeRangeFilter)) { + metrics.push({ metric: 'vo2max', at: new Date(r.time), value: r.vo2MillilitersPerMinuteKilogram, device: deviceOf(r) }); + } + // Skin temperature comes as deviations from the device's baseline: the night's average + for (const r of await records<{ endTime: string; deltas: { delta: { inCelsius: number } }[] } & WithOrigin>('SkinTemperature', timeRangeFilter)) { + if (!r.deltas?.length) continue; + const avg = r.deltas.reduce((t, d) => t + d.delta.inCelsius, 0) / r.deltas.length; + metrics.push({ metric: 'sleep_temp_deviation', at: new Date(r.endTime), value: avg, device: deviceOf(r) }); + } + + if (opts?.cycle) { + // Flow: 0 unknown, 1 light, 2 medium, 3 heavy, matching GRIT's levels + for (const r of await records<{ time: string; flow?: number }>('MenstruationFlow', timeRangeFilter)) { + metrics.push({ metric: 'menstrual_flow', at: new Date(r.time), value: r.flow ?? 0 }); + } + // Period days without a flow record count as flow with no level + for (const r of await records<{ startTime?: string; endTime?: string; time?: string }>('MenstruationPeriod', timeRangeFilter)) { + const start = new Date(r.startTime ?? r.time!); + const end = new Date(r.endTime ?? r.time!); + for (let d = new Date(start); d <= end; d = new Date(d.getTime() + 86_400_000)) { + metrics.push({ metric: 'menstrual_flow', at: d, value: 0 }); + } + } + } + + return { workouts, steps, sleep, weights, metrics }; + }, + writeFood: async (food) => { + const at = new Date(food.loggedAt).toISOString(); + const g = (value: number) => ({ unit: 'grams', value: Math.max(0, value) }); + await insertRecords([ + { + recordType: 'Nutrition', + startTime: at, + endTime: at, + name: food.name.slice(0, 100), + mealType: MEAL_TYPES[food.mealType ?? ''] ?? 0, + energy: { unit: 'kilocalories', value: Math.max(0, food.calories) }, + protein: g(food.proteinG), + totalCarbohydrate: g(food.carbsG), + totalFat: g(food.fatG), + ...(food.caffeineMg ? { caffeine: { unit: 'milligrams', value: food.caffeineMg } } : {}), + // Keyed on GRIT's log, so writing it again replaces it + metadata: { clientRecordId: food.id, clientRecordVersion: Date.now() }, + }, + ] as never); + }, + deleteFood: async (id) => { + await deleteRecordsByUuids('Nutrition', [], [id]).catch(() => undefined); }, }; diff --git a/apps/mobile/lib/health/source.ios.ts b/apps/mobile/lib/health/source.ios.ts index 5e6b9dd..e567652 100644 --- a/apps/mobile/lib/health/source.ios.ts +++ b/apps/mobile/lib/health/source.ios.ts @@ -1,26 +1,75 @@ import { + ComparisonPredicateOperator, + deleteObjects, isHealthDataAvailable, + isObjectTypeAvailable, queryCategorySamples, queryQuantitySamples, queryStatisticsCollectionForQuantity, queryWorkoutSamples, requestAuthorization, + saveQuantitySample, } from '@kingstinct/react-native-healthkit'; import { localDateStr } from '@/lib/date'; -import { appleWorkoutType } from './transform'; -import type { HealthSource, HealthWorkout, SleepInterval } from './types'; +import { appleWorkoutType, temperatureDeviations, toMetres } from './transform'; +import type { AccessOptions, FoodEntry, HealthSource, HealthWorkout, MetricSample, SleepInterval } from './types'; // Sleep analysis values that mean asleep (unspecified, core, deep, REM); 0 is // in bed and 2 is awake const ASLEEP = new Set([1, 3, 4, 5]); +// Menstrual flow: 1 unspecified, 2 light, 3 medium, 4 heavy, 5 none → +// GRIT's 0 (flow, no level), 1, 2, 3; "none" isn't kept +const FLOW: Record = { 1: 0, 2: 1, 3: 2, 4: 3 }; + +const RMSSD = 'HKQuantityTypeIdentifierHeartRateVariabilityRMSSD'; + const READ = [ 'HKWorkoutTypeIdentifier', 'HKQuantityTypeIdentifierStepCount', 'HKQuantityTypeIdentifierBodyMass', 'HKCategoryTypeIdentifierSleepAnalysis', 'HKQuantityTypeIdentifierActiveEnergyBurned', + 'HKQuantityTypeIdentifierHeartRate', + 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN', + 'HKQuantityTypeIdentifierRestingHeartRate', + 'HKQuantityTypeIdentifierRespiratoryRate', + 'HKQuantityTypeIdentifierAppleSleepingWristTemperature', + 'HKQuantityTypeIdentifierVO2Max', + 'HKQuantityTypeIdentifierDistanceWalkingRunning', ] as const; +const CYCLE = 'HKCategoryTypeIdentifierMenstrualFlow'; + +// What GRIT writes for a logged meal, and the unit for each +const FOOD_TYPES = [ + ['HKQuantityTypeIdentifierDietaryEnergyConsumed', 'kcal', (f: FoodEntry) => f.calories], + ['HKQuantityTypeIdentifierDietaryProtein', 'g', (f: FoodEntry) => f.proteinG], + ['HKQuantityTypeIdentifierDietaryCarbohydrates', 'g', (f: FoodEntry) => f.carbsG], + ['HKQuantityTypeIdentifierDietaryFatTotal', 'g', (f: FoodEntry) => f.fatG], + ['HKQuantityTypeIdentifierDietaryCaffeine', 'mg', (f: FoodEntry) => f.caffeineMg ?? 0], +] as const; +const FOOD_KEY = 'GRITFoodLogId'; + +/** RMSSD arrives in newer iOS versions; ask for it only where it exists. */ +function hasRmssd() { + try { + return isObjectTypeAvailable(RMSSD as never); + } catch { + return false; + } +} + +type Sample = { quantity: number; startDate: Date; sourceRevision?: { source?: { name?: string } }; device?: { name?: string } }; +const deviceOf = (s: Sample) => s.device?.name ?? s.sourceRevision?.source?.name; + +async function quantities(id: string, unit: string, filter: object): Promise { + try { + return (await queryQuantitySamples(id as never, { limit: 0, unit, filter } as never)) as unknown as Sample[]; + } catch { + // Not allowed, or not on this iOS: carry on without it + return []; + } +} /** Apple Health, through @kingstinct/react-native-healthkit. */ export const healthSource: HealthSource = { @@ -33,12 +82,14 @@ export const healthSource: HealthSource = { return false; } }, - requestAccess: async () => { + requestAccess: async (opts?: AccessOptions) => { + const toRead = [...READ, ...(hasRmssd() ? [RMSSD] : []), ...(opts?.cycle ? [CYCLE] : [])]; + const toShare = opts?.writeFood ? FOOD_TYPES.map(([id]) => id) : []; // iOS never says what was granted, only that it asked - await requestAuthorization({ toRead: READ as never }); + await requestAuthorization({ toRead: toRead as never, toShare: toShare as never }); return true; }, - read: async (since, until) => { + read: async (since, until, opts) => { const filter = { date: { startDate: since, endDate: until } }; const rawWorkouts = (await queryWorkoutSamples({ limit: 0, filter } as never)) as unknown as { @@ -47,14 +98,27 @@ export const healthSource: HealthSource = { startDate: Date; endDate: Date; totalEnergyBurned?: { quantity: number; unit: string }; + totalDistance?: { quantity: number; unit: string }; + getStatistic?: (id: string, unit?: string) => Promise<{ averageQuantity?: { quantity: number } } | undefined>; }[]; - const workouts: HealthWorkout[] = rawWorkouts.map((w) => ({ - id: `hk:${w.uuid}`, - activityType: appleWorkoutType(w.workoutActivityType), - start: new Date(w.startDate), - end: new Date(w.endDate), - kcal: w.totalEnergyBurned?.unit === 'kcal' ? w.totalEnergyBurned.quantity : undefined, - })); + const workouts: HealthWorkout[] = []; + for (const w of rawWorkouts) { + let avgHeartRate: number | undefined; + try { + avgHeartRate = (await w.getStatistic?.('HKQuantityTypeIdentifierHeartRate', 'count/min'))?.averageQuantity?.quantity; + } catch { + avgHeartRate = undefined; + } + workouts.push({ + id: `hk:${w.uuid}`, + activityType: appleWorkoutType(w.workoutActivityType), + start: new Date(w.startDate), + end: new Date(w.endDate), + kcal: w.totalEnergyBurned?.unit === 'kcal' ? w.totalEnergyBurned.quantity : undefined, + avgHeartRate, + distanceM: toMetres(w.totalDistance), + }); + } // Daily step totals, de-duplicated across iPhone and Watch by HealthKit const midnight = new Date(since); @@ -70,12 +134,7 @@ export const healthSource: HealthSource = { .filter((d) => d.startDate && d.sumQuantity) .map((d) => ({ date: localDateStr(new Date(d.startDate!)), steps: d.sumQuantity!.quantity })); - const weightSamples = (await queryQuantitySamples('HKQuantityTypeIdentifierBodyMass', { - limit: 0, - unit: 'kg', - filter, - } as never)) as unknown as { quantity: number; startDate: Date }[]; - const weights = weightSamples.map((w) => ({ at: new Date(w.startDate), kg: w.quantity })); + const weights = (await quantities('HKQuantityTypeIdentifierBodyMass', 'kg', filter)).map((w) => ({ at: new Date(w.startDate), kg: w.quantity })); const sleepSamples = (await queryCategorySamples('HKCategoryTypeIdentifierSleepAnalysis', { limit: 0, @@ -85,6 +144,48 @@ export const healthSource: HealthSource = { .filter((s) => s.value !== 0) // "in bed" isn't sleep .map((s) => ({ start: new Date(s.startDate), end: new Date(s.endDate), asleep: ASLEEP.has(s.value) })); - return { workouts, steps, sleep, weights }; + const metrics: MetricSample[] = []; + const add = async (id: string, unit: string, metric: MetricSample['metric'], type?: 'sdnn' | 'rmssd') => { + for (const s of await quantities(id, unit, filter)) { + metrics.push({ metric, type, at: new Date(s.startDate), value: s.quantity, device: deviceOf(s) }); + } + }; + await add('HKQuantityTypeIdentifierHeartRateVariabilitySDNN', 'ms', 'hrv', 'sdnn'); + if (hasRmssd()) await add(RMSSD, 'ms', 'hrv', 'rmssd'); + await add('HKQuantityTypeIdentifierRestingHeartRate', 'count/min', 'resting_hr'); + await add('HKQuantityTypeIdentifierRespiratoryRate', 'count/min', 'respiratory_rate'); + await add('HKQuantityTypeIdentifierVO2Max', 'ml/(kg*min)', 'vo2max'); + // Temperature needs earlier nights for its baseline, so read five weeks of it + const tempFrom = new Date(Math.min(since.getTime(), until.getTime() - 35 * 86_400_000)); + const temps = await quantities('HKQuantityTypeIdentifierAppleSleepingWristTemperature', 'degC', { date: { startDate: tempFrom, endDate: until } }); + metrics.push( + ...temperatureDeviations(temps.map((t) => ({ at: new Date(t.startDate), celsius: t.quantity, device: deviceOf(t) }))).filter((m) => m.at >= since), + ); + + if (opts?.cycle) { + try { + const flow = (await queryCategorySamples(CYCLE as never, { limit: 0, filter } as never)) as unknown as { value: number; startDate: Date }[]; + for (const f of flow) { + if (f.value in FLOW) metrics.push({ metric: 'menstrual_flow', at: new Date(f.startDate), value: FLOW[f.value] }); + } + } catch { + // Not allowed: nothing to import + } + } + + return { workouts, steps, sleep, weights, metrics }; + }, + writeFood: async (food) => { + const at = new Date(food.loggedAt); + for (const [id, unit, pick] of FOOD_TYPES) { + const value = pick(food); + if (!(value > 0)) continue; + await saveQuantitySample(id as never, unit as never, value, at, at, { [FOOD_KEY]: food.id, HKFoodType: food.name.slice(0, 100) } as never); + } + }, + deleteFood: async (foodId) => { + for (const [id] of FOOD_TYPES) { + await deleteObjects(id as never, { metadata: { withMetadataKey: FOOD_KEY, operatorType: ComparisonPredicateOperator.equalTo, value: foodId } } as never).catch(() => 0); + } }, }; diff --git a/apps/mobile/lib/health/source.ts b/apps/mobile/lib/health/source.ts index 12b476e..65c3259 100644 --- a/apps/mobile/lib/health/source.ts +++ b/apps/mobile/lib/health/source.ts @@ -6,5 +6,7 @@ export const healthSource: HealthSource = { name: 'Health data', isAvailable: async () => false, requestAccess: async () => false, - read: async () => ({ workouts: [], steps: [], sleep: [], weights: [] }), + read: async () => ({ workouts: [], steps: [], sleep: [], weights: [], metrics: [] }), + writeFood: async () => {}, + deleteFood: async () => {}, }; diff --git a/apps/mobile/lib/health/sync.ts b/apps/mobile/lib/health/sync.ts index 17743c4..16a7201 100644 --- a/apps/mobile/lib/health/sync.ts +++ b/apps/mobile/lib/health/sync.ts @@ -3,11 +3,18 @@ import { storage } from '@/lib/storage'; import { queryClient } from '@/lib/queryClient'; import { healthSource } from './source'; import { toImportPayload } from './transform'; +import type { FoodEntry } from './types'; const ENABLED_KEY = 'grit_health_enabled'; const LAST_KEY = 'grit_health_last_sync'; +const WRITE_FOOD_KEY = 'grit_health_write_food'; +// Bumped when GRIT reads new kinds of data, so people who connected before +// are asked once for the new ones (Phase 6: heart rate, HRV, recovery) +const PERMISSIONS_KEY = 'grit_health_permissions'; +const PERMISSIONS_VERSION = '2'; const MIN_GAP_MS = 15 * 60_000; -const FIRST_SYNC_DAYS = 14; +// The backend takes up to about two months +const FIRST_SYNC_DAYS = 60; // Re-read a little before the last sync: the watch may upload late const OVERLAP_MS = 2 * 86_400_000; @@ -20,11 +27,45 @@ export async function lastHealthSync(): Promise { return raw ? new Date(raw) : null; } +/** Whether menstrual data may be read: the user's separate consent in GRIT. */ +function cycleAllowed() { + return !!queryClient.getQueryData<{ consentCycleData?: boolean }>(['me'])?.consentCycleData; +} + +export async function isFoodWriteOn() { + return (await storage.getItem(WRITE_FOOD_KEY).catch(() => null)) === '1'; +} + +async function access(extra: { cycle?: boolean; writeFood?: boolean } = {}) { + return healthSource.requestAccess({ + cycle: extra.cycle ?? cycleAllowed(), + writeFood: extra.writeFood ?? (await isFoodWriteOn()), + }); +} + /** Asks the health app for access and turns syncing on. False if refused or unavailable. */ export async function connectHealth(): Promise { if (!(await healthSource.isAvailable())) return false; - if (!(await healthSource.requestAccess())) return false; + if (!(await access())) return false; await storage.setItem(ENABLED_KEY, '1'); + await storage.setItem(PERMISSIONS_KEY, PERMISSIONS_VERSION); + return true; +} + +/** Asks again with menstrual data included, after the user turns on cycle consent. */ +export async function requestCycleAccess() { + if (!(await isHealthSyncOn())) return false; + return access({ cycle: true }); +} + +/** Turns writing logged meals to the health app on (asking for permission) or off. */ +export async function setFoodWrite(on: boolean): Promise { + if (!on) { + await storage.removeItem(WRITE_FOOD_KEY); + return true; + } + if (!(await access({ writeFood: true }))) return false; + await storage.setItem(WRITE_FOOD_KEY, '1'); return true; } @@ -32,12 +73,41 @@ export async function connectHealth(): Promise { export async function disconnectHealth() { await storage.removeItem(ENABLED_KEY); await storage.removeItem(LAST_KEY); + await storage.removeItem(WRITE_FOOD_KEY); +} + +type LoggedFood = { id: string; name: string; loggedAt: string; calories: number; proteinG: number; carbsG: number; fatG: number; caffeineMg?: number | null; mealType?: string | null }; + +const toEntry = (f: LoggedFood): FoodEntry => ({ ...f, loggedAt: new Date(f.loggedAt) }); + +async function writingFood() { + return !!healthSource.id && (await isHealthSyncOn()) && (await isFoodWriteOn()); +} + +/** Writes newly logged meals to the health app, if that's on. Never throws. */ +export async function writeFoodsToHealth(foods: LoggedFood[]) { + if (!foods.length || !(await writingFood())) return; + for (const f of foods) await healthSource.writeFood(toEntry(f)).catch(() => undefined); +} + +/** Replaces a meal GRIT wrote after it's edited. Never throws. */ +export async function updateFoodInHealth(food: LoggedFood) { + if (!(await writingFood())) return; + await healthSource.deleteFood(food.id).catch(() => undefined); + await healthSource.writeFood(toEntry(food)).catch(() => undefined); +} + +/** Removes a meal GRIT wrote after it's deleted. Never throws. */ +export async function deleteFoodFromHealth(id: string) { + if (!(await writingFood())) return; + await healthSource.deleteFood(id).catch(() => undefined); } export interface SyncResult { workouts: { created: number; updated: number }; days: number; weights: number; + metrics: { stored: number; skipped: number }; } let running: Promise | null = null; @@ -55,10 +125,15 @@ export async function syncHealth({ force = false } = {}): Promise { + if ((await storage.getItem(PERMISSIONS_KEY).catch(() => null)) !== PERMISSIONS_VERSION) { + // Only shows the kinds of data not asked about before + await access().catch(() => false); + await storage.setItem(PERMISSIONS_KEY, PERMISSIONS_VERSION); + } const since = last ? new Date(last.getTime() - OVERLAP_MS) : new Date(now.getTime() - FIRST_SYNC_DAYS * 86_400_000); - const data = await healthSource.read(since, now); + const data = await healthSource.read(since, now, { cycle: cycleAllowed() }); const payload = toImportPayload(healthSource.id!, data, now); const { data: result } = await api.post('/health/import', payload); await storage.setItem(LAST_KEY, now.toISOString()); diff --git a/apps/mobile/lib/health/transform.ts b/apps/mobile/lib/health/transform.ts index 9a924cf..a86aa82 100644 --- a/apps/mobile/lib/health/transform.ts +++ b/apps/mobile/lib/health/transform.ts @@ -1,5 +1,5 @@ import { localDateStr } from '@/lib/date'; -import type { HealthData, SleepInterval, WeightSample } from './types'; +import type { HealthData, MetricSample, SleepInterval, WeightSample } from './types'; // Apple Health workout activity types (HKWorkoutActivityType) → GRIT's const APPLE_TYPES: Record = { @@ -71,6 +71,78 @@ export function latestWeightPerDay(samples: WeightSample[]): { date: string; wei .sort((a, b) => a.date.localeCompare(b.date)); } +// How a day's readings become one value: HRV and breathing rate are +// averaged over the day's readings (Apple takes several overnight); for the +// rest the day's latest counts, and for flow the heaviest +const COMBINE: Record = { + hrv: 'mean', + respiratory_rate: 'mean', + resting_hr: 'latest', + sleep_temp_deviation: 'latest', + vo2max: 'latest', + menstrual_flow: 'max', +}; + +export interface DailyMetric { + date: string; + metric: MetricSample['metric']; + type?: 'sdnn' | 'rmssd'; + value: number; + device?: string; +} + +/** One value per metric (and HRV type) per local day. */ +export function dailyMetrics(samples: MetricSample[]): DailyMetric[] { + const groups = new Map(); + for (const s of samples) { + if (!Number.isFinite(s.value)) continue; + const k = `${localDateStr(s.at)}|${s.metric}|${s.type ?? ''}`; + groups.set(k, [...(groups.get(k) ?? []), s]); + } + const out: DailyMetric[] = []; + for (const [k, list] of groups) { + const [date, metric] = k.split('|') as [string, MetricSample['metric']]; + const sorted = [...list].sort((a, b) => a.at.getTime() - b.at.getTime()); + const latest = sorted[sorted.length - 1]; + const how = COMBINE[metric]; + const value = + how === 'mean' ? sorted.reduce((t, s) => t + s.value, 0) / sorted.length : how === 'max' ? Math.max(...sorted.map((s) => s.value)) : latest.value; + out.push({ + date, + metric, + ...(latest.type ? { type: latest.type } : {}), + value: Math.round(value * 100) / 100, + ...(latest.device ? { device: latest.device.slice(0, 80) } : {}), + }); + } + return out.sort((a, b) => a.date.localeCompare(b.date) || a.metric.localeCompare(b.metric)); +} + +/** + * Apple records sleeping wrist temperature as a reading, not a deviation: + * each night against the average of the nights before it (at least 5, up to + * 30), as the Health app shows it. Nights before there's a baseline are left out. + */ +export function temperatureDeviations(nights: { at: Date; celsius: number; device?: string }[]): MetricSample[] { + const sorted = [...nights].filter((n) => n.celsius > 25 && n.celsius < 45).sort((a, b) => a.at.getTime() - b.at.getTime()); + const out: MetricSample[] = []; + sorted.forEach((n, i) => { + const before = sorted.slice(Math.max(0, i - 30), i); + if (before.length < 5) return; + const baseline = before.reduce((t, b) => t + b.celsius, 0) / before.length; + out.push({ metric: 'sleep_temp_deviation', at: n.at, value: Math.round((n.celsius - baseline) * 100) / 100, device: n.device }); + }); + return out; +} + +/** Metres from a HealthKit quantity in any length unit. */ +export function toMetres(q: { quantity: number; unit: string } | undefined) { + if (!q || !Number.isFinite(q.quantity)) return undefined; + const per: Record = { m: 1, km: 1000, mi: 1609.344, ft: 0.3048, yd: 0.9144, cm: 0.01 }; + const f = per[q.unit]; + return f ? Math.round(q.quantity * f) : undefined; +} + /** The backend's import body for what was read. */ export function toImportPayload(source: 'healthkit' | 'health_connect', data: HealthData, now = new Date()) { const workouts = data.workouts @@ -81,6 +153,8 @@ export function toImportPayload(source: 'healthkit' | 'health_connect', data: He startedAt: w.start.toISOString(), durationMin: Math.min(1440, Math.max(1, Math.round((w.end.getTime() - w.start.getTime()) / 60_000))), ...(w.kcal && w.kcal > 0 ? { caloriesBurned: Math.min(20000, Math.round(w.kcal)) } : {}), + ...(w.avgHeartRate && w.avgHeartRate >= 30 && w.avgHeartRate <= 230 ? { avgHeartRate: Math.round(w.avgHeartRate) } : {}), + ...(w.distanceM && w.distanceM > 0 ? { distanceM: Math.min(1_000_000, Math.round(w.distanceM)) } : {}), })) .slice(-300); @@ -97,5 +171,6 @@ export function toImportPayload(source: 'healthkit' | 'health_connect', data: He workouts, days: [...days.values()].filter((d) => d.date <= today).sort((a, b) => a.date.localeCompare(b.date)).slice(-62), weights: latestWeightPerDay(data.weights).filter((w) => w.date <= today).slice(-62), + metrics: dailyMetrics(data.metrics ?? []).filter((m) => m.date <= today).slice(-600), }; } diff --git a/apps/mobile/lib/health/types.ts b/apps/mobile/lib/health/types.ts index 20877e9..fae26c8 100644 --- a/apps/mobile/lib/health/types.ts +++ b/apps/mobile/lib/health/types.ts @@ -8,6 +8,42 @@ export interface HealthWorkout { start: Date; end: Date; kcal?: number; + /** Average over the workout, from the watch */ + avgHeartRate?: number; + distanceM?: number; +} + +export type MetricName = 'hrv' | 'resting_hr' | 'respiratory_rate' | 'sleep_temp_deviation' | 'vo2max' | 'menstrual_flow'; + +/** One reading of a recovery or cycle metric. */ +export interface MetricSample { + metric: MetricName; + /** HRV only: Apple gives SDNN, Health Connect RMSSD; they can't be compared */ + type?: 'sdnn' | 'rmssd'; + at: Date; + value: number; + /** The app or device that recorded it */ + device?: string; +} + +/** A logged meal, written back to the health app when that's turned on. */ +export interface FoodEntry { + id: string; + name: string; + loggedAt: Date; + calories: number; + proteinG: number; + carbsG: number; + fatG: number; + caffeineMg?: number | null; + mealType?: string | null; +} + +export interface AccessOptions { + /** Menstrual data: its own consent in GRIT */ + cycle: boolean; + /** Write logged meals back */ + writeFood: boolean; } /** A stretch of sleep (or awake time inside a sleep session). */ @@ -33,6 +69,7 @@ export interface HealthData { steps: DailySteps[]; sleep: SleepInterval[]; weights: WeightSample[]; + metrics: MetricSample[]; } /** One phone's health store. */ @@ -42,7 +79,11 @@ export interface HealthSource { /** "Apple Health" or "Health Connect" */ name: string; isAvailable(): Promise; - /** Asks for read access; true if granted (iOS never says, so true once asked) */ - requestAccess(): Promise; - read(since: Date, until: Date): Promise; + /** Asks for access; true if granted (iOS never says, so true once asked) */ + requestAccess(opts?: AccessOptions): Promise; + read(since: Date, until: Date, opts?: { cycle: boolean }): Promise; + /** Writes a logged meal's energy, macros and caffeine */ + writeFood(food: FoodEntry): Promise; + /** Removes a meal GRIT wrote, when it's deleted in GRIT */ + deleteFood(id: string): Promise; } diff --git a/apps/mobile/lib/strength.ts b/apps/mobile/lib/strength.ts new file mode 100644 index 0000000..5756d11 --- /dev/null +++ b/apps/mobile/lib/strength.ts @@ -0,0 +1,118 @@ +/** + * Strength helpers for the workout screen: plate and warm-up calculators, + * PR checks as sets are ticked, and rest timers. The backend marks PRs + * again when the workout is saved; these just show them as they happen. + */ + +export interface Records { + e1rm: number | null; + weightKg: number | null; + reps: number | null; +} + +export const round1 = (n: number) => Math.round(n * 10) / 10; + +/** Epley's estimated one-rep max, up to 10 reps. */ +export function epley(weightKg: number | null | undefined, reps: number) { + if (!weightKg || weightKg <= 0 || reps < 1 || reps > 10) return null; + return reps === 1 ? weightKg : round1(weightKg * (1 + reps / 30)); +} + +export type PrKind = 'e1rm' | 'weight' | 'reps'; + +/** The record a set beats, if any. Nothing counts until there's history to beat. */ +export function prOf(set: { reps: number; weightKg?: number | null; warmup?: boolean; durationSec?: number | null }, before: Records): PrKind | null { + if (set.warmup || set.reps <= 0) return null; + if (set.weightKg && set.weightKg > 0) { + if (before.weightKg == null) return null; + if (set.weightKg > before.weightKg) return 'weight'; + const e = epley(set.weightKg, set.reps); + return e != null && before.e1rm != null && e > before.e1rm ? 'e1rm' : null; + } + if (set.durationSec) return null; + return before.reps != null && set.reps > before.reps ? 'reps' : null; +} + +/** Records after a set is done. */ +export function withSet(r: Records, set: { reps: number; weightKg?: number | null; warmup?: boolean }): Records { + if (set.warmup || set.reps <= 0) return r; + const max = (a: number | null, b: number | null) => (a == null ? b : b == null ? a : Math.max(a, b)); + if (set.weightKg && set.weightKg > 0) { + return { ...r, weightKg: max(r.weightKg, set.weightKg), e1rm: max(r.e1rm, epley(set.weightKg, set.reps)) }; + } + return { ...r, reps: max(r.reps, set.reps) }; +} + +export const PR_LABELS: Record = { + weight: 'Heaviest yet', + e1rm: 'Best estimated 1RM', + reps: 'Most reps yet', +}; + +// Standard plates, per side, in kg +export const PLATES_KG = [25, 20, 15, 10, 5, 2.5, 1.25] as const; + +/** + * Plates per side for a barbell weight. `rest` is what can't be made with + * the plates (e.g. 0.5 kg), so the screen can say so. + */ +export function platesFor(totalKg: number, barKg = 20, plates: readonly number[] = PLATES_KG) { + let side = (totalKg - barKg) / 2; + if (side <= 0) return { perSide: [] as number[], rest: Math.max(0, round1(totalKg - barKg)) }; + const perSide: number[] = []; + for (const p of plates) { + while (side + 1e-9 >= p) { + perSide.push(p); + side -= p; + } + } + return { perSide, rest: round1(side * 2) }; +} + +/** + * Warm-up sets before a working weight: the empty bar, then about 40%, 60% + * and 80%, rounded to 2.5 kg, with fewer reps as the weight climbs. Lighter + * working weights get fewer warm-ups. + */ +export function warmupsFor(workingKg: number, barKg = 20) { + if (workingKg <= barKg) return []; + const steps: [number, number][] = [ + [0.4, 5], + [0.6, 3], + [0.8, 2], + ]; + const out: { weightKg: number; reps: number }[] = [{ weightKg: barKg, reps: 10 }]; + for (const [pct, reps] of steps) { + const w = Math.round((workingKg * pct) / 2.5) * 2.5; + if (w > out[out.length - 1].weightKg && w < workingKg) out.push({ weightKg: w, reps }); + } + return out; +} + +export type SetKind = 'warmup' | 'working' | 'superset'; + +// Rest after a set, by kind: short after warm-ups, none between the +// exercises of a superset, longer after heavy compound work +export function restSeconds(kind: SetKind, compound: boolean) { + if (kind === 'warmup') return 45; + if (kind === 'superset') return 0; + return compound ? 150 : 90; +} + +export function formatClock(totalSec: number) { + const s = Math.max(0, Math.round(totalSec)); + const m = Math.floor(s / 60); + return `${m}:${String(s % 60).padStart(2, '0')}`; +} + +/** "3 × 8–12" → sets and reps, as the backend reads it. */ +export function parseDetail(detail: string) { + const d = detail.toLowerCase().replace(/\s+/g, ' ').trim(); + const timed = /^(\d{1,2}) ?[x×] ?(\d{1,3}) ?(s|sec|secs|seconds)\b/.exec(d); + if (timed) return { kind: 'timed' as const, sets: +timed[1], seconds: +timed[2] }; + const m = /^(\d{1,2}) ?[x×] ?(\d{1,3})(?: ?(?:-|–|—|to) ?(\d{1,3}))?(?!\d)(?! ?(?:s|sec|secs|seconds|min|mins|m)\b)/.exec(d); + if (!m) return null; + const a = +m[2]; + const b = m[3] ? +m[3] : a; + return { kind: 'reps' as const, sets: +m[1], repsLow: Math.min(a, b), repsHigh: Math.max(a, b) }; +} diff --git a/apps/mobile/lib/workoutSync.ts b/apps/mobile/lib/workoutSync.ts new file mode 100644 index 0000000..4ef5e9c --- /dev/null +++ b/apps/mobile/lib/workoutSync.ts @@ -0,0 +1,100 @@ +import AsyncStorage from '@react-native-async-storage/async-storage'; +import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'; +import type { Query } from '@tanstack/react-query'; +import { api } from '@/lib/api'; +import { queryClient } from '@/lib/queryClient'; +import { supabase } from '@/lib/supabase'; +import { useWorkoutStore, type SaveWorkoutBody } from '@/stores/workoutStore'; + +/** + * Saving finished workouts, online or not. Each finished workout waits in + * the workout store's `pending` list until the backend has it. Sending is a + * React Query mutation that pauses while offline; paused mutations are + * persisted with the query cache, so they carry on after the app restarts. + * The backend keys workouts on clientId, so sending one twice is harmless. + */ + +export const SAVE_WORKOUT = ['save-workout'] as const; + +// Queries kept on the phone, so a workout can start offline from a cold start +const PERSISTED_QUERIES = new Set(['workout-plan', 'workout-prepare', 'exercise']); + +const isRetryable = (err: any) => !err?.response || err.response.status >= 500 || err.response.status === 429; + +queryClient.setMutationDefaults(SAVE_WORKOUT, { + mutationFn: (body: SaveWorkoutBody) => api.post('/workouts', body).then((r) => r.data), + // Pause while offline instead of failing straight away + networkMode: 'online', + retry: (count, err) => count < 4 && isRetryable(err), + retryDelay: (n) => Math.min(30_000, 2000 * 2 ** n), + onSuccess: (_saved, body: SaveWorkoutBody) => { + useWorkoutStore.getState().markSaved(body.clientId); + for (const key of ['activity-logs', 'activity-week', 'workouts', 'workout-plan', 'workout-history', 'workout-prepare', 'feed', 'challenges', 'trends']) { + queryClient.invalidateQueries({ queryKey: [key] }); + } + }, + onError: (err: any, body: SaveWorkoutBody) => { + if (!isRetryable(err)) { + useWorkoutStore.getState().markFailed(body.clientId, err?.response?.data?.message?.toString() ?? "Couldn't save this workout"); + } + }, +}); + +/** Sends a finished workout; resolves when saved (which may be after reconnecting). */ +export function sendWorkout(body: SaveWorkoutBody) { + const inFlight = queryClient + .getMutationCache() + .findAll({ mutationKey: SAVE_WORKOUT }) + .find((m) => (m.state.variables as SaveWorkoutBody | undefined)?.clientId === body.clientId && m.state.status !== 'error' && m.state.status !== 'success'); + if (inFlight) return; + return queryClient + .getMutationCache() + .build(queryClient, { mutationKey: SAVE_WORKOUT }) + .execute(body) + .catch(() => undefined); +} + +/** Resolves once the workout store has loaded from the phone. */ +function storeLoaded() { + if (useWorkoutStore.persist.hasHydrated()) return Promise.resolve(); + return new Promise((resolve) => { + const off = useWorkoutStore.persist.onFinishHydration(() => { + off(); + resolve(); + }); + }); +} + +/** Re-sends this user's waiting workouts that nothing is sending yet. */ +export async function flushPendingWorkouts() { + await storeLoaded(); + const { data } = await supabase.auth.getSession(); + const me = data.session?.user.id; + if (!me) return; + await queryClient.resumePausedMutations().catch(() => undefined); + for (const p of useWorkoutStore.getState().pending) { + if (p.ownerId === me && !p.error) sendWorkout(p.body); + } +} + +/** Tries a workout that failed again. */ +export function retryWorkout(clientId: string) { + const store = useWorkoutStore.getState(); + const p = store.pending.find((x) => x.body.clientId === clientId); + if (!p) return; + useWorkoutStore.setState({ pending: store.pending.map((x) => (x.body.clientId === clientId ? { ...x, error: undefined } : x)) }); + sendWorkout(p.body); +} + +export const queryPersister = createAsyncStoragePersister({ storage: AsyncStorage, key: 'grit-query-cache' }); + +export const persistOptions = { + persister: queryPersister, + maxAge: 7 * 86_400_000, + buster: 'workouts-1', + dehydrateOptions: { + shouldDehydrateQuery: (q: Query) => q.state.status === 'success' && PERSISTED_QUERIES.has(String(q.queryKey[0])), + // The default: paused mutations, i.e. workouts waiting for a connection + shouldDehydrateMutation: (m: { state: { isPaused: boolean } }) => m.state.isPaused, + }, +}; diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 2bd4c75..3bc847d 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -17,9 +17,12 @@ "@expo/vector-icons": "^15.0.3", "@gorhom/bottom-sheet": "^5.2.8", "@kingstinct/react-native-healthkit": "^16.2.0", + "@react-native-async-storage/async-storage": "2.2.0", "@react-native-community/netinfo": "11.4.1", "@supabase/supabase-js": "^2.100.0", - "@tanstack/react-query": "^5.95.2", + "@tanstack/query-async-storage-persister": "^5.106.1", + "@tanstack/react-query": "^5.106.1", + "@tanstack/react-query-persist-client": "^5.106.1", "axios": "^1.13.6", "cross-env": "^10.1.0", "expo": "~54.0.0", diff --git a/apps/mobile/stores/workoutStore.ts b/apps/mobile/stores/workoutStore.ts new file mode 100644 index 0000000..8dce94d --- /dev/null +++ b/apps/mobile/stores/workoutStore.ts @@ -0,0 +1,271 @@ +import { create } from 'zustand'; +import { createJSONStorage, persist } from 'zustand/middleware'; +import AsyncStorage from '@react-native-async-storage/async-storage'; +import * as Crypto from 'expo-crypto'; +import type { PrKind } from '@/lib/strength'; + +/** + * The workout in progress, kept on the phone so it survives the app closing + * and works offline. Finishing moves it to `pending` until the backend has + * it; a workout is only ever edited on one phone, so nothing needs merging. + */ + +export interface DraftSet { + id: string; + reps: number | null; + weightKg: number | null; + durationSec: number | null; + warmup: boolean; + done: boolean; + pr: PrKind | null; +} + +export interface DraftExercise { + key: string; + exerciseId: string; + name: string; + /** The plan's "3 × 8–12", if it came from the plan */ + detail: string | null; + compound: boolean; + /** Exercises sharing one are a superset or circuit */ + supersetId: string | null; + /** Set once the targets are in, so they're only filled in once */ + prefilled: boolean; + sets: DraftSet[]; +} + +export interface ActiveWorkout { + clientId: string; + /** The Supabase user it belongs to */ + ownerId: string; + startedAt: string; + planSession: number | null; + title: string | null; + activityType: string; + exercises: DraftExercise[]; +} + +export interface SaveWorkoutBody { + clientId: string; + planSession?: number; + title?: string; + activityType?: string; + startedAt: string; + endedAt: string; + sets: { + exerciseId: string; + reps: number; + weightKg?: number | null; + durationSec?: number | null; + warmup?: boolean; + supersetId?: string | null; + }[]; +} + +export interface PendingWorkout { + ownerId: string; + body: SaveWorkoutBody; + /** Shown if saving keeps failing for a reason other than the connection */ + error?: string; +} + +export interface Rest { + endsAt: number; + totalSec: number; + label: string; +} + +const newId = () => Crypto.randomUUID(); + +const blankSet = (prev?: Partial): DraftSet => ({ + id: newId(), + reps: prev?.reps ?? null, + weightKg: prev?.weightKg ?? null, + durationSec: prev?.durationSec ?? null, + warmup: prev?.warmup ?? false, + done: false, + pr: null, +}); + +export interface NewExercise { + exerciseId: string; + name: string; + detail?: string | null; + compound?: boolean; +} + +const toDraft = (e: NewExercise): DraftExercise => ({ + key: newId(), + exerciseId: e.exerciseId, + name: e.name, + detail: e.detail ?? null, + compound: e.compound ?? true, + supersetId: null, + prefilled: false, + sets: [], +}); + +interface WorkoutState { + active: ActiveWorkout | null; + rest: Rest | null; + pending: PendingWorkout[]; + start(w: { ownerId: string; planSession?: number | null; title?: string | null; activityType?: string; exercises: NewExercise[] }): void; + discard(): void; + setTitle(title: string): void; + addExercise(e: NewExercise): void; + removeExercise(key: string): void; + swapExercise(key: string, e: NewExercise): void; + moveExercise(key: string, by: -1 | 1): void; + /** Links an exercise with the next one as a superset, or unlinks it */ + toggleSuperset(key: string): void; + /** Fills in the planned sets once, from the targets or last time */ + prefill(key: string, sets: Partial[]): void; + addSet(key: string, warmup?: boolean): void; + insertSets(key: string, sets: Partial[], where: 'start' | 'end'): void; + updateSet(key: string, setId: string, patch: Partial): void; + removeSet(key: string, setId: string): void; + startRest(totalSec: number, label: string): void; + extendRest(sec: number): void; + clearRest(): void; + /** Ends the workout and queues it for saving; returns what will be sent */ + finish(endedAt?: Date): SaveWorkoutBody | null; + markSaved(clientId: string): void; + markFailed(clientId: string, error: string): void; +} + +const mapExercise = (s: WorkoutState, key: string, fn: (e: DraftExercise) => DraftExercise) => + s.active ? { active: { ...s.active, exercises: s.active.exercises.map((e) => (e.key === key ? fn(e) : e)) } } : {}; + +export const useWorkoutStore = create()( + persist( + (set, get) => ({ + active: null, + rest: null, + pending: [], + + start: ({ ownerId, planSession, title, activityType, exercises }) => + set({ + active: { + clientId: newId(), + ownerId, + startedAt: new Date().toISOString(), + planSession: planSession ?? null, + title: title ?? null, + activityType: activityType ?? 'strength_training', + exercises: exercises.map(toDraft), + }, + rest: null, + }), + discard: () => set({ active: null, rest: null }), + setTitle: (title) => set((s) => (s.active ? { active: { ...s.active, title } } : {})), + + addExercise: (e) => + set((s) => (s.active ? { active: { ...s.active, exercises: [...s.active.exercises, toDraft(e)] } } : {})), + removeExercise: (key) => + set((s) => (s.active ? { active: { ...s.active, exercises: s.active.exercises.filter((e) => e.key !== key) } } : {})), + swapExercise: (key, e) => + set((s) => + mapExercise(s, key, (old) => ({ + ...toDraft({ ...e, detail: e.detail ?? old.detail }), + key: old.key, + supersetId: old.supersetId, + // Done sets stay with the exercise they were done on + sets: old.sets.filter((x) => !x.done).map((x) => ({ ...x, weightKg: null, pr: null })), + })), + ), + moveExercise: (key, by) => + set((s) => { + if (!s.active) return {}; + const list = [...s.active.exercises]; + const i = list.findIndex((e) => e.key === key); + const j = i + by; + if (i < 0 || j < 0 || j >= list.length) return {}; + [list[i], list[j]] = [list[j], list[i]]; + return { active: { ...s.active, exercises: list } }; + }), + toggleSuperset: (key) => + set((s) => { + if (!s.active) return {}; + const list = [...s.active.exercises]; + const i = list.findIndex((e) => e.key === key); + const next = list[i + 1]; + if (i < 0) return {}; + if (list[i].supersetId) { + const id = list[i].supersetId; + const left = list.filter((e) => e.supersetId === id); + // Unlink this one; a superset of one isn't a superset + list[i] = { ...list[i], supersetId: null }; + if (left.length <= 2) for (let k = 0; k < list.length; k++) if (list[k].supersetId === id) list[k] = { ...list[k], supersetId: null }; + } else if (next) { + const id = next.supersetId ?? newId().slice(0, 8); + list[i] = { ...list[i], supersetId: id }; + list[i + 1] = { ...next, supersetId: id }; + } + return { active: { ...s.active, exercises: list } }; + }), + + prefill: (key, sets) => + set((s) => mapExercise(s, key, (e) => (e.prefilled ? e : { ...e, prefilled: true, sets: e.sets.length ? e.sets : sets.map((x) => blankSet(x)) }))), + addSet: (key, warmup = false) => + set((s) => + mapExercise(s, key, (e) => { + const last = [...e.sets].reverse().find((x) => x.warmup === warmup) ?? e.sets[e.sets.length - 1]; + const added = blankSet({ ...last, warmup }); + return { ...e, sets: warmup ? [...e.sets.filter((x) => x.warmup), added, ...e.sets.filter((x) => !x.warmup)] : [...e.sets, added] }; + }), + ), + insertSets: (key, sets, where) => + set((s) => + mapExercise(s, key, (e) => { + const added = sets.map((x) => ({ ...blankSet(x), done: x.done ?? false })); + return { ...e, prefilled: true, sets: where === 'start' ? [...added, ...e.sets] : [...e.sets, ...added] }; + }), + ), + updateSet: (key, setId, patch) => + set((s) => mapExercise(s, key, (e) => ({ ...e, sets: e.sets.map((x) => (x.id === setId ? { ...x, ...patch } : x)) }))), + removeSet: (key, setId) => set((s) => mapExercise(s, key, (e) => ({ ...e, sets: e.sets.filter((x) => x.id !== setId) }))), + + startRest: (totalSec, label) => set({ rest: totalSec > 0 ? { endsAt: Date.now() + totalSec * 1000, totalSec, label } : null }), + extendRest: (sec) => set((s) => (s.rest ? { rest: { ...s.rest, endsAt: s.rest.endsAt + sec * 1000, totalSec: s.rest.totalSec + sec } } : {})), + clearRest: () => set({ rest: null }), + + finish: (endedAt = new Date()) => { + const a = get().active; + if (!a) return null; + const sets = a.exercises.flatMap((e) => + e.sets + .filter((x) => x.done && ((x.reps ?? 0) > 0 || (x.durationSec ?? 0) > 0)) + .map((x) => ({ + exerciseId: e.exerciseId, + reps: x.durationSec ? 0 : x.reps ?? 0, + weightKg: x.weightKg && x.weightKg > 0 ? x.weightKg : null, + durationSec: x.durationSec ?? null, + warmup: x.warmup, + supersetId: e.supersetId, + })), + ); + const body: SaveWorkoutBody = { + clientId: a.clientId, + ...(a.planSession ? { planSession: a.planSession } : {}), + ...(a.title?.trim() ? { title: a.title.trim().slice(0, 60) } : {}), + activityType: a.activityType, + startedAt: a.startedAt, + // Never in the future, even if the phone's clock moved + endedAt: new Date(Math.max(new Date(a.startedAt).getTime(), Math.min(endedAt.getTime(), Date.now()))).toISOString(), + sets, + }; + set((s) => ({ active: null, rest: null, pending: [...s.pending.filter((p) => p.body.clientId !== a.clientId), { ownerId: a.ownerId, body }] })); + return body; + }, + markSaved: (clientId) => set((s) => ({ pending: s.pending.filter((p) => p.body.clientId !== clientId) })), + markFailed: (clientId, error) => + set((s) => ({ pending: s.pending.map((p) => (p.body.clientId === clientId ? { ...p, error } : p)) })), + }), + { + name: 'grit-workout', + version: 1, + storage: createJSONStorage(() => AsyncStorage), + partialize: (s) => ({ active: s.active, rest: s.rest, pending: s.pending }), + }, + ), +); diff --git a/docs/PLAN_PHASES_5_TO_9.md b/docs/PLAN_PHASES_5_TO_9.md index 076f323..9f040ff 100644 --- a/docs/PLAN_PHASES_5_TO_9.md +++ b/docs/PLAN_PHASES_5_TO_9.md @@ -7,7 +7,7 @@ each one sets up the data or infrastructure the next needs. | Phase | Name | Kind of work | Weeks (one developer) | |---|---|---|---| | **5** ✅ | Quick wins and safety | App and backend changes on what GRIT already has; no new infrastructure | about 3 | -| **6** | Strength logging and health data | Large app features and native health permissions; product work, no research | about 5 | +| **6** ✅ | Strength logging and health data | Large app features and native health permissions; product work, no research | about 5 | | **7** | GRIT's own food database | Data pipelines, bulk imports, search performance, a Supabase upgrade | about 4 | | **8** | Data quality and regional foods | Contributions, moderation, merging duplicates, curating regional data | about 3 | | **9** | ML and research | Test sets, models and statistics; research-heavy and needs real usage data | about 5 | @@ -234,7 +234,32 @@ model Exercise { --- -# Phase 6 — Strength logging and health data (about 5 weeks) +# Phase 6 — Strength logging and health data (about 5 weeks) ✅ done + +**As built** (details in [ROADMAP.md](./ROADMAP.md)): everything below, +with these differences: +- **Offline:** the workout in progress lives in a store saved on the phone, + and the finished workout is sent whole. The upload is a persisted React + Query mutation, so it waits for a connection and survives a restart; the + backend saves it once per `clientId`, so a resend never duplicates. +- **Schema:** `WorkoutSession` also stores `clientId`, a title and summary + counts (sets, volume, PRs) for the feed; `WorkoutSet` adds `userId` (for + per-exercise history), `durationSec` (timed sets) and the PR it set; + `WorkoutPlan.nextSession` holds the session order; `ActivityLog` adds + `calorieMethod` (device, heart_rate, met or manual), which measures + "burn estimates with heart rate"; `User.consentCycleData` is cycle data's + own consent. +- **Swaps** keep history by borrowing from the same movement on the same + equipment (weights on different equipment aren't comparable). +- **Deloads** last one session, then double progression climbs back, so no + increase is ever more than 5%. +- **Heart-rate calories** apply when the device gives no calories of its + own, and only from 90 to 200 bpm, the equation's range. +- **Health Connect background read** isn't requested: GRIT syncs while + open, and Play rejects unused permissions. The history permission is + requested, and the first sync reads two months. +- **Water** isn't written back: GRIT doesn't record water amounts yet. + **Difficulty: medium.** Large app features and native health permissions, but no research. Needs a development build on real phones for the health diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 0136058..d46a5b9 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -153,21 +153,75 @@ first time they use an AI feature. The Azure steps in `TRUST_AND_SAFETY.md` section 2, and the store declarations in section 4, are for the account owner. -## Phases 6–9 (planned) +## Phase 6 — Strength logging and health data ✅ + +- **Strength logging** (the workout screen, from Home, the plan or the + Activity tab): + - each set starts filled with today's target; one tap ticks it, and one + tap on last time's numbers repeats them; + - rest timers by set type (45 s after a warm-up, none inside a superset, + 90–150 s after working sets), with +30 s and skip; + - supersets and circuits, plate and warm-up calculators, adding, swapping + and reordering exercises; + - a swap to a similar exercise (same movement, same equipment) borrows its + history, so progression carries on; + - PRs (heaviest, best estimated 1RM, most reps) marked as they happen; + - "Say it": "bench 80 for 8, 8, 7" logs three sets. Common phrasings are + read without the AI; others use it, sharing Smart log's 30 a day; + - offline: the workout lives on the phone, and a finished one waits there + until it's saved. React Query's persisted mutations carry it across + restarts, and the backend saves it once however often it's sent; + - finishing creates the activity log, so the feed (set and PR counts, no + weights), challenges, calories and streaks work as before; + - history per exercise: a chart of estimated 1RM (Epley, 10 reps or fewer) + or top weight, records and past sessions; + - plans run by session order: "Next up · Session 2 of 3", so a missed day + doesn't skip a session. +- **Progression rules** (rules, not AI, with every change explained in the + app and to the coach): + - double progression: add one equipment step (2.5 kg, 5 kg for the lower + body), never more than 5%; light dumbbells and kettlebells add a rep + instead; + - a 10% deload after two sessions without progress, or two missed weeks; + - hold the weight in a deficit of more than 500 kcal a day ("preserve"), + on protein under 1.6 g/kg on most logged days, or after under 6 h sleep. +- **Health data:** + - HRV (SDNN or RMSSD, stored apart), resting heart rate, breathing rate, + sleeping temperature (Apple's as a deviation from earlier nights), + VO2max, and each workout's average heart rate and distance; + - workout calories from heart rate (Keytel et al., 2005) when the device + gives none, with the method recorded; + - a second sync with the same data changes nothing; + - cycle data with its own consent, deleted when turned off, and never in + the feed, challenges, the coach's context or coach memory; + - logged meals written back to Apple Health or Health Connect, if turned + on; + - the settings screen says why each kind of data is read; the first sync + reads two months (Health Connect's history permission). + +**After deploying Phase 6:** the migration is applied to Supabase. The +app needs a new development or store build: +it adds AsyncStorage and new health permissions, so Expo Go and older +builds can't be used for the health parts. Check on real phones that a +first sync's values match the phone's own health app, that a second sync +reports nothing new, and that meals appear in the health app when +writing is on. + +**Not done in Phase 6:** +- Health Connect's background-read permission isn't requested: GRIT syncs + when the app is open, and Play rejects permissions an app doesn't use. + Ask for it when background sync is built. +- Apple's RMSSD is read where iOS offers it; older iOS has SDNN only. +- Weights are stored in kg; for lb users, suggested weights convert from + kg steps rather than 5 lb plates. + +## Phases 7–9 (planned) See [`PLAN_PHASES_5_TO_9.md`](./PLAN_PHASES_5_TO_9.md), shaped by the research in [`reports/GRIT health fitness nutrition moat.md`](../reports/GRIT%20health%20fitness%20nutrition%20moat.md). Ordered from easiest to hardest, each phase is released on its own: -- **Phase 6 — Strength logging and health data (about 5 weeks):** - - set-by-set logging with PRs, supersets, calculators, voice and offline - logging, and plans that run by session order; - - progression rules that switch to "preserve" in a big deficit or when - protein is low; - - a wider health import (HRV, resting heart rate, VO2max, cycle data) with - heart-rate calories; - - nutrition written back to the phone's health app. - **Phase 7 — GRIT's own food database (about 4 weeks):** imports from USDA, Open Food Facts and the UK, Canada, France and Finland tables; local search and barcodes; micronutrient tracking from measured values. diff --git a/docs/TRUST_AND_SAFETY.md b/docs/TRUST_AND_SAFETY.md index e65e2df..d1848f0 100644 --- a/docs/TRUST_AND_SAFETY.md +++ b/docs/TRUST_AND_SAFETY.md @@ -24,7 +24,8 @@ that carry no health data. | Expo push service (`expo-notifications`) | Push tokens and the text of each push | **Watch:** push text includes streak counts, the weekly summary (workouts, active minutes, days with food logged) and coach check-ins ("No meals logged for 3 days"). Expo is a service provider, but see recommendation below | | Azure OpenAI (backend `openai` client) | Meal text and photos, coach chats with a summary of the user's logs | Only after the AI consent in the app; see section 2 | | Open Food Facts (backend) | Search terms and barcodes, from the server, with no user identity | Fine | -| Apple HealthKit / Health Connect (`@kingstinct/react-native-healthkit`, `react-native-health-connect`) | Read on the phone, sent only to GRIT's backend | Fine; no HealthKit data in iCloud or used for ads | +| Apple HealthKit / Health Connect (`@kingstinct/react-native-healthkit`, `react-native-health-connect`) | Read on the phone, sent only to GRIT's backend. If the user turns it on, GRIT writes logged meals (calories, macros, caffeine) back to the phone's health app | Fine; no HealthKit data in iCloud or used for ads | +| AsyncStorage and React Query persistence (`@react-native-async-storage/async-storage`, `@tanstack/*-persist*`), Phase 6 | The workout in progress, finished workouts waiting for a connection, and the cached plan, on the phone only | Fine; nothing leaves the phone. Cleared from the cache on sign-out; a waiting workout is only sent for the account it belongs to | | Expo modules (camera, image picker, haptics, fonts, secure store, …) | Nothing leaves the phone | Fine | | `@react-native-community/netinfo` | Checks connectivity; no user data | Fine | | Google / Apple sign-in | Sign-in only | Fine | @@ -95,6 +96,8 @@ Facebook SDK, PostHog and so on). | **Loss-rate cap:** planned loss of at most 1% of body weight a week, in onboarding targets, adaptive suggestions and the time-to-goal estimate | Same files, plus `lib/tdee.ts` | | **Eating-disorder question:** asked in onboarding (and at the "Before you start" check). A "yes" means no weight-loss goal (hidden in the app, refused by the server), adaptive suggestions for maintenance only, and coach instructions to avoid weight-loss talk | `wellbeing.tsx`, `users.service.ts`, `adaptive.service.ts`, `ai.service.ts` | | **Pro-eating-disorder names:** display names and challenge names containing terms like "thinspo" or "proana" are refused, also when split up ("thin-spo") | `common/safety.ts`, `users.service.ts`, `challenges.service.ts` | +| **Cycle data (Phase 6):** menstrual flow and period days are read only with their own consent (Settings → Health data), off by default. Turning it off deletes what was imported. Cycle data never appears in the feed or challenges, never reaches the coach's context, and notes about it are never kept in coach memory (the model is told not to, and a word filter drops any it proposes). No third-party code runs on its screen | `health.service.ts`, `users.service.ts`, `ai.service.ts`, `coach-memory.ts`, `settings/health.tsx` | +| **Health data in other users' view:** a workout logged set by set shows in the feed as counts only (sets and PRs), never weights | `social.service.ts` | | **Separate data permissions**, all off by default: improving food data, training on health data, training on workout data, and sharing products with Open Food Facts. GRIT does none of these today; the settings record the user's choice for when it does | Settings → Privacy | **To review with a dietitian:** the floors and the loss-rate cap are the @@ -114,12 +117,29 @@ are added, they need the same check plus reporting. weight, sleep and steps from Health Connect, an AI coach, and challenges; - for each Health Connect permission GRIT requests, describe the feature - that uses it. + that uses it (the same reasons are on the app's Health data screen): + - exercise, steps, distance: workouts and steps count toward goals and + challenges; + - heart rate: workout calories from heart rate; + - sleep, heart rate variability, resting heart rate, respiratory rate, + skin temperature: recovery, for the coach and the progression rules; + - VO2max: the fitness trend; + - weight: the weight trend and calorie targets; + - menstruation (only after the in-app cycle consent): the user's own + cycle record, not shared; + - write nutrition (only if the user turns it on): logged meals in + Health Connect; + - read health data history: the first sync imports two months. + - GRIT doesn't request background read; add it to the declaration if + background sync is built. - **The privacy policy shown in Health Connect must be the same one as on the Play listing.** - **Apple App Store privacy labels:** - Health & Fitness, collected and linked to the user; - not used for tracking. +- **Apple HealthKit:** the app now asks to write nutrition (with + `NSHealthUpdateUsageDescription`), only when the user turns on writing + meals; App Review checks that the text matches. --- @@ -133,8 +153,13 @@ alongside the main privacy policy.* - **What you enter:** food and drinks, workouts, habits, weight, height, date of birth, sex, goals, your answer to the eating-disorder question, chats with the AI coach, and the coach's notes about you. -- **From your phone's health app, if you connect it:** workouts, steps, - sleep and weight. +- **From your phone's health app, if you connect it:** workouts (with heart + rate and distance), steps, sleep, weight, heart rate variability, resting + heart rate, breathing rate, sleeping temperature and VO2max; and, only if + you turn on cycle data separately, period days and flow. +- **Cycle data** is used only to show you your own record. It's never + shared with other users or sent to the AI coach, and turning it off + deletes it. - **Inferred:** calorie and macro targets, estimates of how much you burn, and the patterns behind coach check-ins. diff --git a/packages/backend/prisma/migrations/20261108120000_phase6_strength_health/migration.sql b/packages/backend/prisma/migrations/20261108120000_phase6_strength_health/migration.sql new file mode 100644 index 0000000..51fae4f --- /dev/null +++ b/packages/backend/prisma/migrations/20261108120000_phase6_strength_health/migration.sql @@ -0,0 +1,101 @@ +-- AlterTable +ALTER TABLE "activity_logs" ADD COLUMN "avgHeartRate" INTEGER, +ADD COLUMN "calorieMethod" TEXT, +ADD COLUMN "distanceM" DOUBLE PRECISION; + +-- AlterTable +ALTER TABLE "users" ADD COLUMN "consentCycleData" BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable +ALTER TABLE "workout_plans" ADD COLUMN "nextSession" INTEGER NOT NULL DEFAULT 1; + +-- CreateTable +CREATE TABLE "workout_sessions" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "clientId" TEXT NOT NULL, + "activityLogId" TEXT NOT NULL, + "planSession" INTEGER, + "title" TEXT, + "startedAt" TIMESTAMP(3) NOT NULL, + "endedAt" TIMESTAMP(3) NOT NULL, + "setCount" INTEGER NOT NULL DEFAULT 0, + "volumeKg" DOUBLE PRECISION NOT NULL DEFAULT 0, + "prCount" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "workout_sessions_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "workout_sets" ( + "id" TEXT NOT NULL, + "sessionId" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "exerciseId" TEXT NOT NULL, + "order" INTEGER NOT NULL, + "reps" INTEGER NOT NULL DEFAULT 0, + "weightKg" DOUBLE PRECISION, + "durationSec" INTEGER, + "rpe" DOUBLE PRECISION, + "warmup" BOOLEAN NOT NULL DEFAULT false, + "supersetId" TEXT, + "pr" TEXT, + + CONSTRAINT "workout_sets_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "health_metrics" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "day" TIMESTAMP(3) NOT NULL, + "metric" TEXT NOT NULL, + "type" TEXT NOT NULL DEFAULT '', + "value" DOUBLE PRECISION NOT NULL, + "unit" TEXT NOT NULL, + "source" TEXT NOT NULL, + "device" TEXT, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "health_metrics_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "workout_sessions_activityLogId_key" ON "workout_sessions"("activityLogId"); + +-- CreateIndex +CREATE INDEX "workout_sessions_userId_startedAt_idx" ON "workout_sessions"("userId", "startedAt"); + +-- CreateIndex +CREATE UNIQUE INDEX "workout_sessions_userId_clientId_key" ON "workout_sessions"("userId", "clientId"); + +-- CreateIndex +CREATE INDEX "workout_sets_sessionId_idx" ON "workout_sets"("sessionId"); + +-- CreateIndex +CREATE INDEX "workout_sets_userId_exerciseId_idx" ON "workout_sets"("userId", "exerciseId"); + +-- CreateIndex +CREATE INDEX "health_metrics_userId_metric_day_idx" ON "health_metrics"("userId", "metric", "day"); + +-- CreateIndex +CREATE UNIQUE INDEX "health_metrics_userId_day_metric_type_key" ON "health_metrics"("userId", "day", "metric", "type"); + +-- AddForeignKey +ALTER TABLE "workout_sessions" ADD CONSTRAINT "workout_sessions_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "workout_sessions" ADD CONSTRAINT "workout_sessions_activityLogId_fkey" FOREIGN KEY ("activityLogId") REFERENCES "activity_logs"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "workout_sets" ADD CONSTRAINT "workout_sets_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "workout_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "health_metrics" ADD CONSTRAINT "health_metrics_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + + +-- Same as every other table: only the API (as table owner) may read or write it +ALTER TABLE "workout_sessions" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "workout_sets" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "health_metrics" ENABLE ROW LEVEL SECURITY; diff --git a/packages/backend/prisma/schema.prisma b/packages/backend/prisma/schema.prisma index 8737a8b..ba15c5c 100644 --- a/packages/backend/prisma/schema.prisma +++ b/packages/backend/prisma/schema.prisma @@ -60,6 +60,9 @@ model User { consentHealthTraining Boolean @default(false) consentWorkoutTraining Boolean @default(false) consentOffSharing Boolean @default(false) + // Its own consent (Phase 6): reading menstrual data from the health app. + // Turning it off deletes what was imported. + consentCycleData Boolean @default(false) // Meal descriptions/photos read by the AI today (a daily cap) aiParseDay String? @@ -94,6 +97,8 @@ model User { weightLogs WeightLog[] favoriteFoods FavoriteFood[] healthDays HealthDay[] + healthMetrics HealthMetric[] + workoutSessions WorkoutSession[] foodMemories FoodMemory[] notifications Notification[] @relation("recipient") notificationsSent Notification[] @relation("actor") @@ -172,9 +177,16 @@ model ActivityLog { kudosCount Int @default(0) // The health app's ID for an imported workout, so importing again updates it externalId String? + // From the health app: the workout's average heart rate and distance + avgHeartRate Int? + distanceM Float? + // How caloriesBurned was worked out: manual | device | heart_rate | met + calorieMethod String? - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - kudos Kudos[] + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + kudos Kudos[] + // Set by set, for a strength session logged in GRIT + workoutSession WorkoutSession? @@unique([userId, externalId]) @@index([userId, loggedAt]) @@ -316,6 +328,10 @@ model WorkoutPlan { generationDay String // local YYYY-MM-DD of the latest generation generationsToday Int @default(1) + // The training session (1, 2, 3…) that comes next. Plans run in order, so + // a missed day moves the week along instead of skipping a session. + nextSession Int @default(1) + createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -488,3 +504,84 @@ model Exercise { @@index([name]) @@map("exercises") } + +// One training session logged set by set (Phase 6). Finishing it creates the +// ActivityLog, so the feed, challenges, calories and streaks work unchanged; +// deleting that log deletes the session. +model WorkoutSession { + id String @id @default(cuid()) + userId String + // Made on the phone, so an upload retried after being offline is saved once + clientId String + activityLogId String @unique + // Which training session of the plan this was (1, 2, 3…), if any + planSession Int? + title String? + startedAt DateTime + endedAt DateTime + // Summary for the feed and history + setCount Int @default(0) + volumeKg Float @default(0) + prCount Int @default(0) + createdAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + activityLog ActivityLog @relation(fields: [activityLogId], references: [id], onDelete: Cascade) + sets WorkoutSet[] + + @@unique([userId, clientId]) + @@index([userId, startedAt]) + @@map("workout_sessions") +} + +model WorkoutSet { + id String @id @default(cuid()) + sessionId String + // Copied from the session, for per-exercise history + userId String + exerciseId String + order Int + reps Int @default(0) + weightKg Float? // null for bodyweight + durationSec Int? // for timed sets: planks, intervals + rpe Float? // optional effort, 6–10 + warmup Boolean @default(false) + // Sets sharing one are a superset or circuit + supersetId String? + // The record this set set when it was logged: e1rm | weight | reps + pr String? + + session WorkoutSession @relation(fields: [sessionId], references: [id], onDelete: Cascade) + + @@index([sessionId]) + @@index([userId, exerciseId]) + @@map("workout_sets") +} + +// Daily recovery and cycle values from Apple Health / Health Connect +// (Phase 6). Cycle data needs consentCycleData, and is never shown in the +// feed or challenges or written into coach memory. +model HealthMetric { + id String @id @default(cuid()) + userId String + // The local day, stored as midnight UTC of that date + day DateTime + // hrv | resting_hr | respiratory_rate | sleep_temp_deviation | vo2max | menstrual_flow + metric String + // For HRV: sdnn (Apple) or rmssd (Health Connect), which can't be + // compared; '' for everything else + type String @default("") + value Float + // ms | bpm | breaths_min | degC | ml_kg_min | level + unit String + source String // healthkit | health_connect + // The app or device that recorded it, if the health app says + device String? + updatedAt DateTime @updatedAt + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([userId, day, metric, type]) + @@index([userId, metric, day]) + @@map("health_metrics") +} diff --git a/packages/backend/src/activity/activity.service.ts b/packages/backend/src/activity/activity.service.ts index 3606e27..49295b5 100644 --- a/packages/backend/src/activity/activity.service.ts +++ b/packages/backend/src/activity/activity.service.ts @@ -135,6 +135,12 @@ export class ActivityService { return this.prisma.activityLog.findMany({ where: { userId, loggedAt: { gte: start, lt: end } }, orderBy: { loggedAt: 'asc' }, + // Logged set by set: the app opens the workout instead of the quick editor + include: { + workoutSession: { + select: { id: true, title: true, setCount: true, prCount: true }, + }, + }, }); } @@ -154,6 +160,11 @@ export class ActivityService { }, }, orderBy: { loggedAt: 'asc' }, + include: { + workoutSession: { + select: { id: true, title: true, setCount: true, prCount: true }, + }, + }, }); const byDay = days.map((date) => { diff --git a/packages/backend/src/ai/ai.module.ts b/packages/backend/src/ai/ai.module.ts index a0be9f8..46ab891 100644 --- a/packages/backend/src/ai/ai.module.ts +++ b/packages/backend/src/ai/ai.module.ts @@ -3,9 +3,10 @@ import { AIController } from './ai.controller'; import { AIService } from './ai.service'; import { azureOpenAIProviders } from './azure-openai'; import { ProgressModule } from '../progress/progress.module'; +import { WorkoutsModule } from '../workouts/workouts.module'; @Module({ - imports: [ProgressModule], + imports: [ProgressModule, WorkoutsModule], controllers: [AIController], providers: [...azureOpenAIProviders, AIService], }) diff --git a/packages/backend/src/ai/ai.service.ts b/packages/backend/src/ai/ai.service.ts index eb9dcc3..c20f215 100644 --- a/packages/backend/src/ai/ai.service.ts +++ b/packages/backend/src/ai/ai.service.ts @@ -25,6 +25,9 @@ import { import { macroTargets } from '../common/nutrition'; import { assertAiConsent } from '../common/ai-consent'; import { AdaptiveService } from '../progress/adaptive.service'; +import { WorkoutsService } from '../workouts/workouts.service'; +import { recoveryLines, summarizeMetrics } from '../health/health.service'; +import { CYCLE_METRICS } from '../health/heart-rate'; import { MAX_MEMORIES, MEMORY_SCHEMA, @@ -50,6 +53,7 @@ export class AIService { private openai: OpenAI, @Inject(AI_MODEL) private model: string, private adaptive: AdaptiveService, + private workouts: WorkoutsService, ) {} private async resolveUser(supabaseId: string) { @@ -72,6 +76,7 @@ export class AIService { healthDays, weekFood, memories, + metrics, ] = await Promise.all([ this.prisma.user.findUnique({ where: { id: userId } }), this.prisma.foodLog.findMany({ @@ -106,6 +111,15 @@ export class AIService { orderBy: { createdAt: 'asc' }, select: { text: true }, }), + // Recovery metrics from the health app; cycle data never reaches the coach + this.prisma.healthMetric.findMany({ + where: { + userId, + day: { gte: dateMarker(addDays(todayDate, -30)) }, + metric: { notIn: [...CYCLE_METRICS] }, + }, + orderBy: { day: 'asc' }, + }), ]); const todayCalories = todayFood.reduce((s, f) => s + f.calories, 0); @@ -170,6 +184,7 @@ export class AIService { todayHealth?.sleepMinutes != null ? `- Sleep last night: ${Math.floor(todayHealth.sleepMinutes / 60)}h ${todayHealth.sleepMinutes % 60}m` : null, + ...recoveryLines(summarizeMetrics(metrics), todayDate), ].filter(Boolean); // Averages over the days they logged, so unlogged days don't drag them down @@ -205,6 +220,11 @@ export class AIService { ); } + // What the progression rules say about the next session, and recent PRs + const strengthLines = user + ? await this.workouts.coachLines(user, offset).catch(() => []) + : []; + const memoryBlock = memories.length ? `\nWhat you know about them from earlier chats (use it naturally; don't list it back to them):\n${memories.map((m) => `- ${m.text}`).join('\n')}\n` : ''; @@ -224,7 +244,11 @@ Habits today: ${habitLines} Activity (last 7 days): -${activityLines}`; +${activityLines}${ + strengthLines.length + ? `\n\nStrength training (the app's progression rules, not your guesses; explain them in these words when asked why a weight changed or held):\n${strengthLines.join('\n')}` + : '' + }`; } private getSystemPrompt(context: string): string { diff --git a/packages/backend/src/ai/coach-memory.db-spec.ts b/packages/backend/src/ai/coach-memory.db-spec.ts index 0de4872..2f301f5 100644 --- a/packages/backend/src/ai/coach-memory.db-spec.ts +++ b/packages/backend/src/ai/coach-memory.db-spec.ts @@ -3,6 +3,12 @@ import { TestDb } from '../test-utils/db'; import { AdaptiveService } from '../progress/adaptive.service'; import { TrendsService } from '../progress/trends.service'; import { AIService } from './ai.service'; +import type { WorkoutsService } from '../workouts/workouts.service'; + +// The coach's strength lines aren't what these tests are about +const noWorkouts = { + coachLines: () => Promise.resolve([]), +} as unknown as WorkoutsService; /** * A model that streams a fixed reply for chat requests and returns `notes` @@ -51,7 +57,7 @@ describe('Coach memory (database)', () => { add: ['Has a sore left knee; avoid jumping'], remove: [], }); - const ai = new AIService(db.prisma, client, 'test', adaptive); + const ai = new AIService(db.prisma, client, 'test', adaptive, noWorkouts); const events = await collect( ai.streamMessage(u.supabaseId, 'My left knee hurts when I jump', 0), @@ -87,7 +93,7 @@ describe('Coach memory (database)', () => { add: ['Knee has healed; back to running'], remove: [old.id], }); - const ai = new AIService(db.prisma, client, 'test', adaptive); + const ai = new AIService(db.prisma, client, 'test', adaptive, noWorkouts); await ai.updateMemories(u.id, 'My knee is all better now, running again'); expect((await ai.listMemories(u.supabaseId)).map((n) => n.text)).toEqual([ 'Knee has healed; back to running', @@ -97,7 +103,7 @@ describe('Coach memory (database)', () => { it("doesn't ask about short messages, and skips the event when nothing is new", async () => { const u = await db.user(); const { client, calls } = fakeModel({ add: [], remove: [] }); - const ai = new AIService(db.prisma, client, 'test', adaptive); + const ai = new AIService(db.prisma, client, 'test', adaptive, noWorkouts); const short = await collect(ai.streamMessage(u.supabaseId, 'thanks!', 0)); expect(short.map((e) => e.type)).toEqual(['delta', 'delta', 'done']); expect(calls.filter((c) => !c.stream)).toHaveLength(0); @@ -111,7 +117,13 @@ describe('Coach memory (database)', () => { it('lets the user add, delete and clear notes', async () => { const u = await db.user(); - const ai = new AIService(db.prisma, fakeModel({}).client, 'test', adaptive); + const ai = new AIService( + db.prisma, + fakeModel({}).client, + 'test', + adaptive, + noWorkouts, + ); const note = await ai.addMemory(u.supabaseId, ' Allergic to peanuts '); expect([note.text, note.source]).toEqual(['Allergic to peanuts', 'user']); await expect( @@ -160,7 +172,7 @@ describe('Coach memory (database)', () => { ], }); const { client, calls } = fakeModel({ add: [], remove: [] }); - const ai = new AIService(db.prisma, client, 'test', adaptive); + const ai = new AIService(db.prisma, client, 'test', adaptive, noWorkouts); await collect(ai.streamMessage(u.supabaseId, 'hi', 0)); const chat = calls.find((c) => c.stream)!; expect(chat.instructions).toContain('Food logged on 2 of the last 7 days'); diff --git a/packages/backend/src/ai/coach-memory.ts b/packages/backend/src/ai/coach-memory.ts index 8407046..802bc80 100644 --- a/packages/backend/src/ai/coach-memory.ts +++ b/packages/backend/src/ai/coach-memory.ts @@ -42,7 +42,7 @@ Read the person's latest message. Return: - add: new lasting facts worth remembering for future coaching: injuries or health conditions, foods they avoid, dislike or are allergic to, foods they love, their schedule or when they can train, equipment they have, how they like to be coached, life context (shift work, new baby, training for an event). Write each as a short third-person note under 15 words, e.g. "Has a sore left knee; avoid jumping" or "Trains before work, around 6am". - remove: ids of notes the message makes wrong or out of date (e.g. the knee has healed). If a fact changed, remove the old note and add the new one. -Don't note today's numbers, meals or workouts (the app tracks those), passing moods, questions, or anything already in the notes. Most messages contain nothing new: then return empty lists.`; +Don't note today's numbers, meals or workouts (the app tracks those), passing moods, questions, or anything already in the notes. Never note anything about periods, menstrual cycles, ovulation or fertility. Most messages contain nothing new: then return empty lists.`; } const key = (text: string) => @@ -75,7 +75,7 @@ export function planMemoryUpdate( for (const raw of update.add) { const text = cleanMemory(raw); const k = key(text); - if (k.length < 3 || seen.has(k)) continue; + if (k.length < 3 || seen.has(k) || isCycleNote(text)) continue; seen.add(k); add.push(text); } @@ -97,6 +97,16 @@ export function planMemoryUpdate( return { remove: [...remove], add }; } +// Cycle data is never kept in coach memory, even if the model proposes it +// ("period" alone is too common: "short rest periods") +const CYCLE_WORDS = + /\bmenstrua\w*|\bmenses\b|\bovulat\w*|\bfertility\b|\bpms\b|\bpmdd\b|\bluteal\b|\bfollicular\b|\bcycle days?\b|\btime of the month\b|\b(?:painful|heavy|irregular|light) periods?\b|\bperiods? (?:pain|cramps|symptoms)\b|\b(?:on|during|before|after) (?:her|their|my|his) period\b|\bperiod cramps\b/i; + +/** A note about someone's menstrual cycle, which coach memory never keeps. */ +export function isCycleNote(text: string) { + return CYCLE_WORDS.test(text); +} + /** Worth asking the model about: more than a couple of words. */ export function mayHoldFacts(message: string): boolean { return message.trim().split(/\s+/).length >= 4; diff --git a/packages/backend/src/app.module.ts b/packages/backend/src/app.module.ts index 5fafed4..24dd1c2 100644 --- a/packages/backend/src/app.module.ts +++ b/packages/backend/src/app.module.ts @@ -19,6 +19,7 @@ import { WorkoutPlanModule } from './workout-plan/workout-plan.module'; import { AlertsModule } from './alerts/alerts.module'; import { ProgressModule } from './progress/progress.module'; import { HealthModule } from './health/health.module'; +import { WorkoutsModule } from './workouts/workouts.module'; import { AppController } from './app.controller'; import { validateEnv } from './config/env'; import { AllExceptionsFilter } from './observability/all-exceptions.filter'; @@ -54,6 +55,7 @@ import { UserThrottlerGuard } from './observability/throttler.guard'; AlertsModule, ProgressModule, HealthModule, + WorkoutsModule, ], controllers: [AppController], providers: [ diff --git a/packages/backend/src/common/parse-quota.ts b/packages/backend/src/common/parse-quota.ts new file mode 100644 index 0000000..b3a8433 --- /dev/null +++ b/packages/backend/src/common/parse-quota.ts @@ -0,0 +1,53 @@ +import { HttpException, HttpStatus } from '@nestjs/common'; +import type { PrismaService } from '../prisma/prisma.service'; + +// Each AI reading (a meal for Smart log, sets for Say it) is a model call, so +// they share one cap per day +export const DAILY_PARSES = 30; + +/** + * Takes one of today's AI readings, or refuses. Two conditional updates, so + * parallel requests can't both take the last one. + */ +export async function takeParse( + prisma: PrismaService, + userId: string, + today: string, +) { + const fresh = await prisma.user.updateMany({ + where: { + id: userId, + OR: [{ aiParseDay: null }, { aiParseDay: { not: today } }], + }, + data: { aiParseDay: today, aiParseCount: 1 }, + }); + if (fresh.count) return; + const more = await prisma.user.updateMany({ + where: { + id: userId, + aiParseDay: today, + aiParseCount: { lt: DAILY_PARSES }, + }, + data: { aiParseCount: { increment: 1 } }, + }); + if (!more.count) { + throw new HttpException( + `You can use smart logging ${DAILY_PARSES} times a day. Add the rest by hand for today.`, + HttpStatus.TOO_MANY_REQUESTS, + ); + } +} + +/** A reading that failed on our side doesn't count. */ +export async function giveBackParse( + prisma: PrismaService, + userId: string, + today: string, +) { + await prisma.user + .updateMany({ + where: { id: userId, aiParseDay: today, aiParseCount: { gt: 0 } }, + data: { aiParseCount: { decrement: 1 } }, + }) + .catch(() => undefined); +} diff --git a/packages/backend/src/common/safety.db-spec.ts b/packages/backend/src/common/safety.db-spec.ts index 8fad87e..faee11e 100644 --- a/packages/backend/src/common/safety.db-spec.ts +++ b/packages/backend/src/common/safety.db-spec.ts @@ -8,6 +8,12 @@ import { TrendsService } from '../progress/trends.service'; import { AIService } from '../ai/ai.service'; import { MealParseService } from '../meal-parse/meal-parse.service'; import type { FoodService } from '../food/food.service'; +import type { WorkoutsService } from '../workouts/workouts.service'; + +// The coach's strength lines aren't what these tests are about +const noWorkouts = { + coachLines: () => Promise.resolve([]), +} as unknown as WorkoutsService; /** A model that must never be called. */ const noModel = { @@ -28,7 +34,7 @@ describe('Safety and consent (database)', () => { it('refuses AI features without consent, and allows them after', async () => { const u = await db.user({ aiConsent: false }); - const ai = new AIService(db.prisma, noModel, 'test', adaptive); + const ai = new AIService(db.prisma, noModel, 'test', adaptive, noWorkouts); const meals = new MealParseService( db.prisma, {} as FoodService, diff --git a/packages/backend/src/exercises/exercises.controller.ts b/packages/backend/src/exercises/exercises.controller.ts index 47692cb..80dd6da 100644 --- a/packages/backend/src/exercises/exercises.controller.ts +++ b/packages/backend/src/exercises/exercises.controller.ts @@ -10,7 +10,7 @@ export class ExercisesController { @Get() search(@Query() q: ExerciseSearchDto) { - return this.exercises.search(q.q, q.muscle, q.equipment); + return this.exercises.search(q.q, q.muscle, q.equipment, 50, q.pattern); } @Get(':id') diff --git a/packages/backend/src/exercises/exercises.dto.ts b/packages/backend/src/exercises/exercises.dto.ts index 8e051c7..a023433 100644 --- a/packages/backend/src/exercises/exercises.dto.ts +++ b/packages/backend/src/exercises/exercises.dto.ts @@ -15,4 +15,10 @@ export class ExerciseSearchDto { @IsString() @Length(1, 40) equipment?: string; + + // Same movement, for swapping one exercise for another + @IsOptional() + @IsString() + @Length(1, 40) + pattern?: string; } diff --git a/packages/backend/src/exercises/exercises.service.ts b/packages/backend/src/exercises/exercises.service.ts index e44db8a..173fb4e 100644 --- a/packages/backend/src/exercises/exercises.service.ts +++ b/packages/backend/src/exercises/exercises.service.ts @@ -65,10 +65,17 @@ export class ExercisesService implements OnModuleInit { return rows.length; } - search(q?: string, muscle?: string, equipment?: string, limit = 50) { + search( + q?: string, + muscle?: string, + equipment?: string, + limit = 50, + pattern?: string, + ) { const terms = q?.trim(); return this.prisma.exercise.findMany({ where: { + ...(pattern ? { pattern } : {}), ...(terms ? { name: { contains: terms, mode: 'insensitive' as const } } : {}), diff --git a/packages/backend/src/health/health.controller.ts b/packages/backend/src/health/health.controller.ts index e355feb..2861824 100644 --- a/packages/backend/src/health/health.controller.ts +++ b/packages/backend/src/health/health.controller.ts @@ -12,7 +12,7 @@ type Me = { supabaseId: string }; export class HealthController { constructor(private health: HealthService) {} - /** Workouts, daily steps and sleep, and weigh-ins from the phone's health app. */ + /** Workouts, daily steps and sleep, weigh-ins and recovery metrics from the phone's health app. */ @Post('import') import( @CurrentUser() user: Me, @@ -26,4 +26,10 @@ export class HealthController { recent(@CurrentUser() user: Me, @UtcOffset() offset: number) { return this.health.recent(user.supabaseId, offset); } + + /** Whether cycle data is on, and how many days of it are stored. */ + @Get('cycle') + cycle(@CurrentUser() user: Me) { + return this.health.cycleSummary(user.supabaseId); + } } diff --git a/packages/backend/src/health/health.db-spec.ts b/packages/backend/src/health/health.db-spec.ts index 3a9e81c..351b43e 100644 --- a/packages/backend/src/health/health.db-spec.ts +++ b/packages/backend/src/health/health.db-spec.ts @@ -3,6 +3,8 @@ import { addDays, dateMarker, localToday } from '../common/day'; import { WeightService } from '../progress/weight.service'; import { ChallengesService } from '../challenges/challenges.service'; import { HealthService } from './health.service'; +import { UsersService } from '../users/users.service'; +import { ageOn } from '../common/safety'; describe('HealthService (database)', () => { const db = new TestDb(); @@ -31,6 +33,7 @@ describe('HealthService (database)', () => { workouts: [run('hk-1', 30), run('hk-2', 20)], days: [], weights: [], + metrics: [], }, 0, ); @@ -42,6 +45,7 @@ describe('HealthService (database)', () => { workouts: [run('hk-1', 35)], days: [], weights: [], + metrics: [], }, 0, ); @@ -75,6 +79,7 @@ describe('HealthService (database)', () => { { date: today, weightKg: 79.4 }, { date: yesterday, weightKg: 80 }, ], + metrics: [], }, 0, ); @@ -86,6 +91,7 @@ describe('HealthService (database)', () => { workouts: [], days: [{ date: today, steps: 6100 }], weights: [], + metrics: [], }, 0, ); @@ -120,6 +126,7 @@ describe('HealthService (database)', () => { workouts: [run('old-1', 30, old)], days: [{ date: addDays(today, -90), steps: 9000 }], weights: [], + metrics: [], }, 0, ); @@ -127,6 +134,7 @@ describe('HealthService (database)', () => { workouts: { created: 0, updated: 0 }, days: 0, weights: 0, + metrics: { stored: 0, skipped: 0 }, }); }); @@ -168,4 +176,137 @@ describe('HealthService (database)', () => { const view = await challenges.getChallenge(u.supabaseId, c.id); expect(view.totalProgress).toBe(7000); }); + it('uses heart rate for calories when the device gave none, and a second sync changes nothing', async () => { + const u = await db.user(); + await db.prisma.user.update({ + where: { id: u.id }, + data: { + weightKg: 80, + gender: 'male', + dateOfBirth: new Date('1996-01-01'), + }, + }); + const at = new Date(Date.now() - 3_600_000).toISOString(); + const body = { + source: 'health_connect' as const, + workouts: [ + { + ...run('hc-hr', 60), + startedAt: at, + avgHeartRate: 140, + distanceM: 9800.4, + }, + { + ...run('hc-dev', 30), + startedAt: at, + caloriesBurned: 250, + avgHeartRate: 150, + }, + { ...run('hc-low', 30), startedAt: at, avgHeartRate: 80 }, + ], + days: [{ date: today, steps: 4000, sleepMinutes: 420 }], + weights: [], + metrics: [ + { date: today, metric: 'resting_hr', value: 54 }, + { + date: today, + metric: 'hrv', + type: 'rmssd', + value: 61.2, + device: 'Pixel Watch 3', + }, + { date: today, metric: 'vo2max', value: 48 }, + // Out of range, and HRV without its type: both skipped + { date: today, metric: 'resting_hr', value: 400 }, + { date: addDays(today, -1), metric: 'hrv', value: 50 }, + // Cycle data without its consent: skipped + { date: today, metric: 'menstrual_flow', value: 2 }, + ], + }; + const first = await health.import(u.supabaseId, body, 0); + expect(first.workouts).toEqual({ created: 3, updated: 0 }); + expect(first.metrics).toEqual({ stored: 3, skipped: 3 }); + + const logs = await db.prisma.activityLog.findMany({ + where: { userId: u.id }, + }); + const by = (id: string) => logs.find((l) => l.externalId === id)!; + // Keytel et al.: (-55.0969 + 0.6309×140 + 0.1988×80 + 0.2017×age) / 4.184 per minute + const age = ageOn(new Date('1996-01-01'), new Date(at)); + const perMin = + (-55.0969 + 0.6309 * 140 + 0.1988 * 80 + 0.2017 * age) / 4.184; + expect(by('hc-hr')).toMatchObject({ + calorieMethod: 'heart_rate', + caloriesBurned: Math.round(perMin * 60), + avgHeartRate: 140, + distanceM: 9800, + }); + // The device's own figure comes first + expect(by('hc-dev')).toMatchObject({ + calorieMethod: 'device', + caloriesBurned: 250, + }); + // Below the equation's range: the MET estimate + expect(by('hc-low').calorieMethod).toBe('met'); + + const again = await health.import(u.supabaseId, body, 0); + expect(again).toMatchObject({ + workouts: { created: 0, updated: 0 }, + days: 0, + metrics: { stored: 0, skipped: 3 }, + }); + + const recent = await health.recent(u.supabaseId, 0); + expect( + recent.recovery.map((m) => [m.metric, m.type, m.latest]).sort(), + ).toEqual([ + ['hrv', 'rmssd', 61.2], + ['resting_hr', null, 54], + ['vo2max', null, 48], + ]); + }); + + it('keeps cycle data only with its own consent, and deletes it when withdrawn', async () => { + const u = await db.user(); + const users = new UsersService( + db.prisma, + {} as never, + new WeightService(db.prisma), + ); + await users.updateUser(u.supabaseId, { consentCycleData: true }); + const res = await health.import( + u.supabaseId, + { + source: 'healthkit', + workouts: [], + days: [], + weights: [], + metrics: [ + { date: today, metric: 'menstrual_flow', value: 2 }, + { date: addDays(today, -1), metric: 'menstrual_flow', value: 3 }, + { date: today, metric: 'resting_hr', value: 60 }, + ], + }, + 0, + ); + expect(res.metrics).toEqual({ stored: 3, skipped: 0 }); + expect(await health.cycleSummary(u.supabaseId)).toEqual({ + consent: true, + days: 2, + }); + // Never in the recovery summary the coach and app read + const recent = await health.recent(u.supabaseId, 0); + expect(recent.recovery.map((m) => m.metric)).toEqual(['resting_hr']); + + await users.updateUser(u.supabaseId, { consentCycleData: false }); + expect(await health.cycleSummary(u.supabaseId)).toEqual({ + consent: false, + days: 0, + }); + expect( + await db.prisma.healthMetric.count({ + where: { userId: u.id, metric: 'resting_hr' }, + }), + ).toBe(1); + }); }); diff --git a/packages/backend/src/health/health.dto.ts b/packages/backend/src/health/health.dto.ts index 5ddf360..770c939 100644 --- a/packages/backend/src/health/health.dto.ts +++ b/packages/backend/src/health/health.dto.ts @@ -16,6 +16,7 @@ import { } from 'class-validator'; import { ACTIVITY_TYPES } from '../activity/activity.constants'; import { IsNotFuture } from '../common/validators'; +import { METRIC_NAMES } from './heart-rate'; const DATE = /^\d{4}-\d{2}-\d{2}$/; @@ -48,6 +49,42 @@ export class HealthWorkoutDto { @Min(0) @Max(300000) steps?: number; + + // Average over the workout, from the watch + @IsOptional() + @IsInt() + @Min(30) + @Max(230) + avgHeartRate?: number; + + @IsOptional() + @IsNumber() + @Min(0) + @Max(1000000) + distanceM?: number; +} + +/** One day's value of a recovery or cycle metric. */ +export class HealthMetricDto { + @Matches(DATE) + date: string; + + @IsIn(METRIC_NAMES) + metric: string; + + // HRV only: sdnn (Apple) or rmssd (Health Connect) + @IsOptional() + @IsIn(['sdnn', 'rmssd', '']) + type?: string; + + @IsNumber() + value: number; + + // The app or device that recorded it + @IsOptional() + @IsString() + @Length(0, 80) + device?: string; } export class HealthDayDto { @@ -98,4 +135,10 @@ export class HealthImportDto { @ValidateNested({ each: true }) @Type(() => HealthWeightDto) weights: HealthWeightDto[] = []; + + @IsArray() + @ArrayMaxSize(600) + @ValidateNested({ each: true }) + @Type(() => HealthMetricDto) + metrics: HealthMetricDto[] = []; } diff --git a/packages/backend/src/health/health.service.ts b/packages/backend/src/health/health.service.ts index f6e6bc8..fe6384e 100644 --- a/packages/backend/src/health/health.service.ts +++ b/packages/backend/src/health/health.service.ts @@ -2,16 +2,129 @@ import { Injectable, NotFoundException } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { WeightService } from '../progress/weight.service'; import { addDays, dateMarker, localToday } from '../common/day'; -import { MET } from '../activity/activity.constants'; -import type { HealthImportDto } from './health.dto'; +import { ageOn } from '../common/safety'; +import { metFor } from '../activity/activity.constants'; +import { + CYCLE_METRICS, + heartRateKcal, + METRICS, + type MetricName, +} from './heart-rate'; +import type { HealthImportDto, HealthWorkoutDto } from './health.dto'; // Older data isn't imported: the app sends at most a month at a time const MAX_AGE_DAYS = 62; +type ImportUser = { + id: string; + weightKg: number | null; + gender: string | null; + dateOfBirth: Date | null; +}; + +/** + * Calories for an imported workout: the device's own figure if it gave one, + * then the heart-rate equation, then the activity's MET value. + */ +export function workoutCalories(w: HealthWorkoutDto, user: ImportUser) { + if (w.caloriesBurned != null) { + return { caloriesBurned: w.caloriesBurned, calorieMethod: 'device' }; + } + const fromHeart = w.avgHeartRate + ? heartRateKcal(w.avgHeartRate, w.durationMin, { + ageYears: user.dateOfBirth + ? ageOn(user.dateOfBirth, new Date(w.startedAt)) + : null, + weightKg: user.weightKg, + gender: user.gender, + }) + : null; + if (fromHeart != null) { + return { caloriesBurned: fromHeart, calorieMethod: 'heart_rate' }; + } + return { + caloriesBurned: Math.round( + metFor(w.activityType) * (user.weightKg ?? 70) * (w.durationMin / 60), + ), + calorieMethod: 'met', + }; +} + +type MetricRow = { + metric: string; + type: string; + unit: string; + value: number; + day: Date; +}; + +/** Each metric's latest value and its average, oldest rows first in. */ +export function summarizeMetrics(rows: MetricRow[]) { + const groups = new Map(); + for (const r of rows) { + const k = `${r.metric}|${r.type}`; + groups.set(k, [...(groups.get(k) ?? []), r]); + } + return [...groups.values()].map((g) => { + const latest = g[g.length - 1]; + return { + metric: latest.metric, + type: latest.type || null, + unit: latest.unit, + latest: latest.value, + latestDate: latest.day.toISOString().slice(0, 10), + average: + Math.round((g.reduce((t, r) => t + r.value, 0) / g.length) * 10) / 10, + days: g.length, + }; + }); +} + +const METRIC_LABELS: Record = { + resting_hr: 'Resting heart rate', + hrv: 'Heart rate variability', + respiratory_rate: 'Breathing rate during sleep', + sleep_temp_deviation: 'Sleeping temperature vs usual', + vo2max: 'VO2max', +}; +const UNIT_LABELS: Record = { + ms: 'ms', + bpm: 'bpm', + breaths_min: 'breaths/min', + degC: '°C', + ml_kg_min: 'mL/kg/min', +}; + +/** Lines for the coach about recent recovery metrics (never cycle data). */ +export function recoveryLines( + summary: ReturnType, + today: string, +) { + return summary + .filter( + (m) => METRIC_LABELS[m.metric] && m.latestDate >= addDays(today, -2), + ) + .map((m) => { + const unit = UNIT_LABELS[m.unit] ?? m.unit; + const label = `${METRIC_LABELS[m.metric]}${m.type ? ` (${m.type.toUpperCase()})` : ''}`; + return `- ${label}: ${m.latest} ${unit}${m.days >= 7 ? ` (30-day average ${m.average})` : ''}`; + }); +} + +const sameWorkout = (a: Record, b: Record) => + Object.keys(b).every((k) => { + const x = a[k]; + const y = b[k]; + return x instanceof Date && y instanceof Date + ? x.getTime() === y.getTime() + : x === y; + }); + /** * Takes what the phone read from Apple Health or Health Connect and stores * it. Safe to send the same data again: workouts are matched on the health - * app's ID, days and weigh-ins on their date. + * app's ID, days, weigh-ins and metrics on their date, and anything that + * hasn't changed is left alone. */ @Injectable() export class HealthService { @@ -31,18 +144,13 @@ export class HealthService { for (const w of dto.workouts) { const loggedAt = new Date(w.startedAt); if (loggedAt < new Date(`${oldest}T00:00:00Z`)) continue; - const caloriesBurned = - w.caloriesBurned ?? - Math.round( - (MET[w.activityType] ?? 5) * - (user.weightKg ?? 70) * - (w.durationMin / 60), - ); const data = { activityType: w.activityType, durationMin: w.durationMin, - caloriesBurned, + ...workoutCalories(w, user), steps: w.steps ?? null, + avgHeartRate: w.avgHeartRate ?? null, + distanceM: w.distanceM != null ? Math.round(w.distanceM) : null, loggedAt, source, }; @@ -50,9 +158,9 @@ export class HealthService { where: { userId_externalId: { userId: user.id, externalId: w.externalId }, }, - select: { id: true }, }); if (existing) { + if (sameWorkout(existing, data)) continue; await this.prisma.activityLog.update({ where: { id: existing.id }, data, @@ -80,8 +188,19 @@ export class HealthService { : {}), source, }; + const where = { + userId_day: { userId: user.id, day: dateMarker(d.date) }, + }; + const row = await this.prisma.healthDay.findUnique({ where }); + if ( + row && + (d.steps === undefined || row.steps === d.steps) && + (d.sleepMinutes === undefined || row.sleepMinutes === d.sleepMinutes) && + row.source === source + ) + continue; await this.prisma.healthDay.upsert({ - where: { userId_day: { userId: user.id, day: dateMarker(d.date) } }, + where, update: values, create: { ...values, userId: user.id, day: dateMarker(d.date) }, }); @@ -102,7 +221,88 @@ export class HealthService { } } - return { workouts: { created, updated }, days, weights }; + const metrics = await this.importMetrics(user, dto, oldest); + return { workouts: { created, updated }, days, weights, metrics }; + } + + /** Recovery and cycle values, one per metric per day. */ + private async importMetrics( + user: { id: string; consentCycleData: boolean }, + dto: HealthImportDto, + oldest: string, + ) { + let stored = 0; + let skipped = 0; + const incoming = dto.metrics.filter((m) => { + const spec = METRICS[m.metric as MetricName]; + const ok = + m.date >= oldest && + !!spec && + Number.isFinite(m.value) && + m.value >= spec.min && + m.value <= spec.max && + // Cycle data only with its own consent + (!CYCLE_METRICS.has(m.metric) || user.consentCycleData) && + (m.metric === 'hrv' ? m.type === 'sdnn' || m.type === 'rmssd' : true); + if (!ok) skipped++; + return ok; + }); + if (!incoming.length) return { stored, skipped }; + + const existing = await this.prisma.healthMetric.findMany({ + where: { + userId: user.id, + day: { gte: dateMarker(oldest) }, + metric: { in: [...new Set(incoming.map((m) => m.metric))] }, + }, + }); + const key = (day: string, metric: string, type: string) => + `${day}|${metric}|${type}`; + const have = new Map( + existing.map((r) => [ + key(r.day.toISOString().slice(0, 10), r.metric, r.type), + r, + ]), + ); + for (const m of incoming) { + const type = m.metric === 'hrv' ? m.type! : ''; + const value = Math.round(m.value * 100) / 100; + const device = m.device?.trim() || null; + const row = have.get(key(m.date, m.metric, type)); + if ( + row && + row.value === value && + row.device === device && + row.source === dto.source + ) + continue; + const data = { + value, + unit: METRICS[m.metric as MetricName].unit, + source: dto.source, + device, + }; + await this.prisma.healthMetric.upsert({ + where: { + userId_day_metric_type: { + userId: user.id, + day: dateMarker(m.date), + metric: m.metric, + type, + }, + }, + update: data, + create: { + ...data, + userId: user.id, + day: dateMarker(m.date), + metric: m.metric, + type, + }, + }); + stored++; + } + return { stored, skipped }; } /** The last week of synced days, for the app and the coach. */ @@ -132,6 +332,34 @@ export class HealthService { (latest, r) => (!latest || r.updatedAt > latest ? r.updatedAt : latest), null, ), + recovery: await this.recovery(user.id, today), }; } + + /** + * Each recovery metric's latest value and its 30-day average, for the + * app and the coach. HRV is compared only with the same type. Cycle data + * isn't included. + */ + async recovery(userId: string, today: string) { + const rows = await this.prisma.healthMetric.findMany({ + where: { + userId, + day: { gte: dateMarker(addDays(today, -30)) }, + metric: { notIn: [...CYCLE_METRICS] }, + }, + orderBy: { day: 'asc' }, + }); + return summarizeMetrics(rows); + } + + /** What's been imported of cycle data, for the settings screen. */ + async cycleSummary(supabaseId: string) { + const user = await this.prisma.user.findUnique({ where: { supabaseId } }); + if (!user) throw new NotFoundException('User not found'); + const days = await this.prisma.healthMetric.count({ + where: { userId: user.id, metric: { in: [...CYCLE_METRICS] } }, + }); + return { consent: user.consentCycleData, days }; + } } diff --git a/packages/backend/src/health/heart-rate.spec.ts b/packages/backend/src/health/heart-rate.spec.ts new file mode 100644 index 0000000..24c2b40 --- /dev/null +++ b/packages/backend/src/health/heart-rate.spec.ts @@ -0,0 +1,43 @@ +import { heartRateKcal } from './heart-rate'; +import { isCycleNote, planMemoryUpdate } from '../ai/coach-memory'; + +describe('heart-rate calories (Keytel et al., 2005)', () => { + const man = { ageYears: 30, weightKg: 80, gender: 'male' }; + const woman = { ageYears: 30, weightKg: 60, gender: 'female' }; + + it('uses the equation for each sex', () => { + // (-55.0969 + 0.6309×140 + 0.1988×80 + 0.2017×30) / 4.184 = 13.19 kcal/min + expect(heartRateKcal(140, 60, man)).toBe(791); + // (-20.4022 + 0.4472×140 − 0.1263×60 + 0.074×30) / 4.184 = 8.81 kcal/min + expect(heartRateKcal(140, 60, woman)).toBe(528); + // Neither: the average of the two + expect(heartRateKcal(140, 60, { ...man, gender: null })).toBe( + Math.round( + ((791 / 60 + + (-20.4022 + 0.4472 * 140 - 0.1263 * 80 + 0.074 * 30) / 4.184) / + 2) * + 60, + ), + ); + }); + + it("doesn't apply outside its range or without age and weight", () => { + expect(heartRateKcal(85, 60, man)).toBeNull(); + expect(heartRateKcal(210, 60, man)).toBeNull(); + expect(heartRateKcal(140, 60, { ...man, ageYears: null })).toBeNull(); + expect(heartRateKcal(140, 60, { ...man, weightKg: null })).toBeNull(); + }); +}); + +describe('cycle data and coach memory', () => { + it('never keeps a note about the menstrual cycle', () => { + expect(isCycleNote('Has painful periods')).toBe(true); + expect(isCycleNote('Tracks her menstrual cycle')).toBe(true); + expect(isCycleNote('Prefers short rest periods')).toBe(false); + const { add } = planMemoryUpdate([], { + add: ['Trains less during her period', 'Has a sore left knee'], + remove: [], + }); + expect(add).toEqual(['Has a sore left knee']); + }); +}); diff --git a/packages/backend/src/health/heart-rate.ts b/packages/backend/src/health/heart-rate.ts new file mode 100644 index 0000000..6bfe60e --- /dev/null +++ b/packages/backend/src/health/heart-rate.ts @@ -0,0 +1,62 @@ +/** + * Calories from a workout's average heart rate: Keytel et al. (2005), + * "Prediction of energy expenditure from heart rate monitoring during + * submaximal exercise", J Sports Sci 23(3). Separate equations for men and + * women; the average of the two otherwise. Validated for heart rates of + * about 90–150 bpm, so outside 90–200 the MET estimate is used instead. + */ + +export interface Person { + ageYears: number | null; + weightKg: number | null; + gender: string | null; +} + +export const MIN_HR = 90; +export const MAX_HR = 200; + +/** Kilocalories for the workout, or null when the equation doesn't apply. */ +export function heartRateKcal( + avgHeartRate: number, + durationMin: number, + p: Person, +): number | null { + if ( + !p.ageYears || + !p.weightKg || + durationMin <= 0 || + avgHeartRate < MIN_HR || + avgHeartRate > MAX_HR + ) { + return null; + } + const hr = avgHeartRate; + const male = + (-55.0969 + 0.6309 * hr + 0.1988 * p.weightKg + 0.2017 * p.ageYears) / + 4.184; + const female = + (-20.4022 + 0.4472 * hr - 0.1263 * p.weightKg + 0.074 * p.ageYears) / 4.184; + const perMin = + p.gender === 'male' + ? male + : p.gender === 'female' + ? female + : (male + female) / 2; + return perMin > 0 ? Math.round(perMin * durationMin) : null; +} + +// The metrics GRIT keeps, with their units and believable ranges +export const METRICS = { + hrv: { unit: 'ms', min: 1, max: 300 }, + resting_hr: { unit: 'bpm', min: 25, max: 150 }, + respiratory_rate: { unit: 'breaths_min', min: 4, max: 40 }, + sleep_temp_deviation: { unit: 'degC', min: -5, max: 5 }, + vo2max: { unit: 'ml_kg_min', min: 10, max: 100 }, + // 0 flow recorded without a level, 1 light, 2 medium, 3 heavy + menstrual_flow: { unit: 'level', min: 0, max: 3 }, +} as const; +export type MetricName = keyof typeof METRICS; +export const METRIC_NAMES = Object.keys(METRICS) as MetricName[]; + +// Cycle data: own consent, never in the feed, challenges or coach memory +export const CYCLE_METRICS = new Set(['menstrual_flow']); diff --git a/packages/backend/src/meal-parse/meal-parse.service.ts b/packages/backend/src/meal-parse/meal-parse.service.ts index f3b9310..9f3c214 100644 --- a/packages/backend/src/meal-parse/meal-parse.service.ts +++ b/packages/backend/src/meal-parse/meal-parse.service.ts @@ -1,8 +1,6 @@ import { BadGatewayException, BadRequestException, - HttpException, - HttpStatus, Inject, Injectable, Logger, @@ -13,6 +11,7 @@ import { PrismaService } from '../prisma/prisma.service'; import { AI_MODEL } from '../ai/azure-openai'; import { localToday } from '../common/day'; import { assertAiConsent } from '../common/ai-consent'; +import { giveBackParse, takeParse } from '../common/parse-quota'; import { FoodService } from '../food/food.service'; import { groundItem, @@ -26,8 +25,7 @@ import { } from './meal-parse'; import type { LogParsedMealDto, ParseMealDto } from './meal-parse.dto'; -// Each reading is a model call (with a photo, a large one), so cap it per day -export const DAILY_PARSES = 30; +export { DAILY_PARSES } from '../common/parse-quota'; const MAX_ITEMS = 12; @Injectable() @@ -50,45 +48,6 @@ export class MealParseService { return user.id; } - /** - * Takes one of today's readings, or refuses. Two conditional updates, so - * parallel requests can't both take the last one. - */ - private async takeParse(userId: string, today: string) { - const fresh = await this.prisma.user.updateMany({ - where: { - id: userId, - OR: [{ aiParseDay: null }, { aiParseDay: { not: today } }], - }, - data: { aiParseDay: today, aiParseCount: 1 }, - }); - if (fresh.count) return; - const more = await this.prisma.user.updateMany({ - where: { - id: userId, - aiParseDay: today, - aiParseCount: { lt: DAILY_PARSES }, - }, - data: { aiParseCount: { increment: 1 } }, - }); - if (!more.count) { - throw new HttpException( - `You can use smart logging ${DAILY_PARSES} times a day. Search or add foods by hand for the rest of today.`, - HttpStatus.TOO_MANY_REQUESTS, - ); - } - } - - /** A reading that failed on our side doesn't count. */ - private async giveBack(userId: string, today: string) { - await this.prisma.user - .updateMany({ - where: { id: userId, aiParseDay: today, aiParseCount: { gt: 0 } }, - data: { aiParseCount: { decrement: 1 } }, - }) - .catch(() => undefined); - } - /** The first database product with calories for a branded item. */ private async lookupBranded(item: ModelItem): Promise { if (!item.brand) return undefined; @@ -124,7 +83,7 @@ export class MealParseService { assertAiConsent(user); const userId = user.id; const today = localToday(offset); - await this.takeParse(userId, today); + await takeParse(this.prisma, userId, today); const known = await this.prisma.foodMemory.findMany({ where: { userId }, orderBy: [{ uses: 'desc' }, { updatedAt: 'desc' }], @@ -172,7 +131,7 @@ export class MealParseService { if (!Array.isArray(parsed.items)) throw new Error('No items'); } catch (err) { this.logger.warn(`Meal parse failed: ${(err as Error).message}`); - await this.giveBack(userId, today); + await giveBackParse(this.prisma, userId, today); throw new BadGatewayException( "Couldn't read that meal right now. Try again, or add it by hand.", ); diff --git a/packages/backend/src/social/social.service.ts b/packages/backend/src/social/social.service.ts index 699b51e..5388bfa 100644 --- a/packages/backend/src/social/social.service.ts +++ b/packages/backend/src/social/social.service.ts @@ -453,6 +453,10 @@ export class SocialService { user: { select: userSelect }, // Whether the viewer has already given kudos kudos: { where: { userId: viewerId }, select: { id: true } }, + // Counts only: the sets and weights stay private + workoutSession: { + select: { title: true, setCount: true, prCount: true }, + }, }, orderBy: [{ loggedAt: 'desc' }, { id: 'desc' }], take: limit, @@ -498,6 +502,7 @@ export class SocialService { steps: l.steps, kudosCount: l.kudosCount, kudosGiven: l.kudos.length > 0, + workout: l.workoutSession, }, })), ...habitLogs.map((l) => ({ diff --git a/packages/backend/src/users/users.dto.ts b/packages/backend/src/users/users.dto.ts index 0ea1572..e90e18b 100644 --- a/packages/backend/src/users/users.dto.ts +++ b/packages/backend/src/users/users.dto.ts @@ -207,6 +207,11 @@ export class UpdateUserDto { @IsOptional() @IsBoolean() consentOffSharing?: boolean; + + // Reading menstrual data from the health app; turning it off deletes it + @IsOptional() + @IsBoolean() + consentCycleData?: boolean; } export class SyncUserDto { diff --git a/packages/backend/src/users/users.service.ts b/packages/backend/src/users/users.service.ts index 320c35d..d8ae6e3 100644 --- a/packages/backend/src/users/users.service.ts +++ b/packages/backend/src/users/users.service.ts @@ -5,6 +5,7 @@ import { } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PrismaService } from '../prisma/prisma.service'; +import { CYCLE_METRICS } from '../health/heart-rate'; import { WeightService } from '../progress/weight.service'; import type { UpdateUserDto } from './users.dto'; import { @@ -98,6 +99,13 @@ export class UsersService { await this.weight.logForUser(user.id, data.weightKg, offset); } + // Withdrawing cycle consent deletes the cycle data already imported + if (data.consentCycleData === false) { + await this.prisma.healthMetric.deleteMany({ + where: { userId: user.id, metric: { in: [...CYCLE_METRICS] } }, + }); + } + // Going public approves everyone who was waiting if (data.isPrivate === false) { await this.prisma.follow.updateMany({ diff --git a/packages/backend/src/workout-plan/workout-plan.service.ts b/packages/backend/src/workout-plan/workout-plan.service.ts index e3ee949..7593df4 100644 --- a/packages/backend/src/workout-plan/workout-plan.service.ts +++ b/packages/backend/src/workout-plan/workout-plan.service.ts @@ -200,11 +200,11 @@ User profile: ${profile.map((l) => `- ${l}`).join('\n')} Rules: -- Return exactly 7 days, "mon" to "sun", with exactly ${daysPerWeek} training days and the rest as rest days. Spread training days out; avoid more than 3 in a row. +- Return exactly 7 days, "mon" to "sun", with exactly ${daysPerWeek} training days and the rest as rest days. Spread training days out; avoid more than 3 in a row. The app runs training days in order as session 1, 2, 3…, so a missed day doesn't skip a session; make each session work whatever day it lands on. - Training happens ${location === 'gym' ? 'at a gym with standard equipment' : 'at home with no equipment beyond a mat'}. - Keep each session close to the active-minutes goal, never over 90 minutes. Match the level: a sedentary beginner gets gentle, short sessions. - Address the obstacle: short efficient sessions for "not enough time", the same simple routine on fixed days for consistency, variety for low motivation, clear progression for "no clear plan". -- Each training day has a short title, an activityType from the allowed list that best describes it, a durationMin, and 3 to 8 exercises. ${library.length ? 'Each exercise is an exerciseId from the exercise list below' : 'Each exercise has a name'} and a short detail like "3 × 12", "20 min easy pace" or "4 × 30 s on / 30 s off".${ +- Each training day has a short title, an activityType from the allowed list that best describes it, a durationMin, and 3 to 8 exercises. ${library.length ? 'Each exercise is an exerciseId from the exercise list below' : 'Each exercise has a name'} and a short detail: a rep range for strength work like "3 × 8–12" (lower reps for heavy compound lifts, e.g. "4 × 5–8"), seconds for holds like "3 × 30 s", or a duration or intervals for cardio like "20 min easy pace" or "4 × 30 s on / 30 s off".${ library.length ? ` @@ -268,6 +268,8 @@ ${library.map((e) => `- ${e.id}: ${e.name} (${e.equipment.join('/')}${e.pattern days: days as unknown as Prisma.InputJsonValue, generationDay: today, generationsToday: usedToday + 1, + // A new plan starts from its first session + nextSession: 1, }; return this.prisma.workoutPlan.upsert({ where: { userId: user.id }, @@ -293,6 +295,11 @@ ${library.map((e) => `- ${e.id}: ${e.name} (${e.equipment.join('/')}${e.pattern data: { days: days as unknown as Prisma.InputJsonValue, daysPerWeek: days.filter((d) => !d.rest).length, + // Still a session that exists after a day is made a rest day + nextSession: Math.min( + plan.nextSession, + Math.max(1, days.filter((d) => !d.rest).length), + ), }, }); } diff --git a/packages/backend/src/workouts/progression.spec.ts b/packages/backend/src/workouts/progression.spec.ts new file mode 100644 index 0000000..98c7b4b --- /dev/null +++ b/packages/backend/src/workouts/progression.spec.ts @@ -0,0 +1,260 @@ +import { + deloadWeight, + nextWeight, + NO_RECOVERY, + suggest, + type ExerciseFacts, + type PastSession, + type Recovery, +} from './progression'; + +const squat: ExerciseFacts = { + name: 'Barbell Squat', + equipment: ['barbell'], + pattern: 'squat', + primary: ['quadriceps'], +}; +const bench: ExerciseFacts = { + name: 'Bench Press', + equipment: ['barbell'], + pattern: 'horizontal_press', + primary: ['chest'], +}; +const dbPress: ExerciseFacts = { + name: 'Dumbbell Shoulder Press', + equipment: ['dumbbell'], + pattern: 'vertical_press', + primary: ['shoulders'], +}; +const pullups: ExerciseFacts = { + name: 'Pullups', + equipment: ['bodyweight'], + pattern: 'vertical_pull', + primary: ['lats'], +}; +const range = { sets: 3, repsLow: 8, repsHigh: 12 }; +const session = ( + date: string, + weightKg: number | null, + ...reps: number[] +): PastSession => ({ + date, + sets: reps.map((r) => ({ reps: r, weightKg })), +}); +const TODAY = '2026-11-20'; + +describe('progression rules', () => { + it('starts with no history', () => { + const s = suggest(bench, [], range, NO_RECOVERY, TODAY); + expect(s.action).toBe('start'); + expect(s.weightKg).toBeNull(); + expect(s.reps).toBe(8); + }); + + it('adds a step once every set reaches the top of the range', () => { + const s = suggest( + bench, + [session('2026-11-17', 80, 12, 12, 12)], + range, + NO_RECOVERY, + TODAY, + ); + expect(s).toMatchObject({ action: 'increase', weightKg: 82.5, reps: 8 }); + expect(s.reasons[0]).toContain('up to 82.5 kg'); + // Lower body moves in bigger steps + expect( + suggest( + squat, + [session('2026-11-17', 120, 12, 12, 12)], + range, + NO_RECOVERY, + TODAY, + ).weightKg, + ).toBe(125); + }); + + it('holds the weight until every set gets there', () => { + const s = suggest( + bench, + [session('2026-11-17', 80, 12, 11, 9)], + range, + NO_RECOVERY, + TODAY, + ); + expect(s).toMatchObject({ action: 'hold', weightKg: 80, reps: 10 }); + // Fewer sets than planned isn't "every set" + expect( + suggest( + bench, + [session('2026-11-17', 80, 12, 12)], + range, + NO_RECOVERY, + TODAY, + ).action, + ).toBe('hold'); + }); + + it('never jumps more than 5% or one step', () => { + // 5% of 40 kg is 2 kg, less than the 5 kg lower-body step + expect(nextWeight(40, squat)).toBe(42); + expect(nextWeight(200, squat)).toBe(205); + // A 2 kg dumbbell jump is over 5% below 40 kg: add reps instead + expect(nextWeight(20, dbPress)).toBeNull(); + const s = suggest( + dbPress, + [session('2026-11-17', 20, 12, 12, 12)], + range, + NO_RECOVERY, + TODAY, + ); + expect(s).toMatchObject({ action: 'reps', weightKg: 20, reps: 13 }); + expect(nextWeight(8, bench)).toBeNull(); + }); + + it('deloads 10% after two sessions without progress', () => { + const stuck = [ + session('2026-11-17', 100, 10, 9, 8), + session('2026-11-10', 100, 10, 9, 8), + session('2026-11-03', 100, 10, 9, 8), + ]; + const s = suggest(squat, stuck, range, NO_RECOVERY, TODAY); + expect(s).toMatchObject({ action: 'deload', weightKg: 90 }); + expect(s.reasons[0]).toContain('two sessions'); + // One more rep counts as progress + const moving = [session('2026-11-17', 100, 10, 9, 9), ...stuck.slice(1)]; + expect(suggest(squat, moving, range, NO_RECOVERY, TODAY).action).toBe( + 'hold', + ); + // The session after a deload isn't a stall + const afterDeload = [ + session('2026-11-17', 90, 10, 9, 8), + ...stuck.slice(1), + ]; + expect(suggest(squat, afterDeload, range, NO_RECOVERY, TODAY).action).toBe( + 'hold', + ); + }); + + it('deloads after two missed weekly sessions', () => { + const s = suggest( + bench, + [session('2026-10-28', 80, 12, 12, 12)], + range, + NO_RECOVERY, + TODAY, + ); + expect(s).toMatchObject({ action: 'deload', weightKg: 72 }); + expect(s.reasons[0]).toContain('3 weeks'); + expect(deloadWeight(22, dbPress)).toBe(20); + }); + + it('holds increases in a big deficit, on low protein and after short sleep', () => { + const ready = [session('2026-11-17', 80, 12, 12, 12)]; + const deficit: Recovery = { ...NO_RECOVERY, dailyBalanceKcal: -650 }; + const s1 = suggest(bench, ready, range, deficit, TODAY); + expect(s1).toMatchObject({ + action: 'hold', + weightKg: 80, + holds: ['deficit'], + }); + expect(s1.reasons[0]).toContain('650 kcal'); + + const protein: Recovery = { + ...NO_RECOVERY, + loggedDays: 6, + lowProteinDays: 4, + proteinTargetG: 128, + }; + expect(suggest(bench, ready, range, protein, TODAY).reasons[0]).toContain( + '128 g on 4 of 6', + ); + // Too few logged days to say + expect( + suggest( + bench, + ready, + range, + { ...protein, loggedDays: 3, lowProteinDays: 3 }, + TODAY, + ).action, + ).toBe('increase'); + + const sleep: Recovery = { ...NO_RECOVERY, sleepMinutes: 310 }; + const s3 = suggest(bench, ready, range, sleep, TODAY); + expect(s3.holds).toEqual(['sleep']); + expect(s3.reasons[0]).toBe( + "You slept 5 h 10 m last night: keeping today's weights.", + ); + + // A 400 kcal deficit is fine + expect( + suggest( + bench, + ready, + range, + { ...NO_RECOVERY, dailyBalanceKcal: -400 }, + TODAY, + ).action, + ).toBe('increase'); + }); + + it("holds instead of deloading a stall that's expected in a deficit", () => { + const stuck = [ + session('2026-11-17', 100, 10, 9, 8), + session('2026-11-10', 100, 10, 9, 8), + session('2026-11-03', 100, 10, 9, 8), + ]; + const s = suggest( + squat, + stuck, + range, + { ...NO_RECOVERY, dailyBalanceKcal: -700 }, + TODAY, + ); + expect(s).toMatchObject({ action: 'hold', weightKg: 100 }); + }); + + it('progresses bodyweight exercises by reps', () => { + const s = suggest( + pullups, + [session('2026-11-17', null, 10, 8, 7)], + range, + NO_RECOVERY, + TODAY, + ); + expect(s).toMatchObject({ action: 'reps', weightKg: null, reps: 11 }); + }); + + it('never suggests more than 5% over the last weight, over scripted histories', () => { + const exercises = [squat, bench, dbPress, pullups]; + const recoveries: Recovery[] = [ + NO_RECOVERY, + { ...NO_RECOVERY, dailyBalanceKcal: -800 }, + { ...NO_RECOVERY, sleepMinutes: 300 }, + ]; + let checked = 0; + for (const e of exercises) { + for (let w = 5; w <= 250; w += 2.5) { + for (const reps of [ + [12, 12, 12], + [8, 8, 8], + [12, 12, 11], + [12, 12], + ]) { + for (const r of recoveries) { + const history = [ + session('2026-11-17', w, ...reps), + session('2026-11-10', w, ...reps), + ]; + const s = suggest(e, history, range, r, TODAY); + if (s.weightKg != null) { + expect(s.weightKg).toBeLessThanOrEqual(w * 1.05 + 1e-9); + } + checked++; + } + } + } + } + expect(checked).toBeGreaterThan(1000); + }); +}); diff --git a/packages/backend/src/workouts/progression.ts b/packages/backend/src/workouts/progression.ts new file mode 100644 index 0000000..86d4614 --- /dev/null +++ b/packages/backend/src/workouts/progression.ts @@ -0,0 +1,314 @@ +/** + * Progression rules (Phase 6.2): what to lift next time, and why. + * Deterministic rules, not a model, so they can be tested and explained: + * + * - Double progression: once every set reaches the top of the rep range, + * add the smallest step the equipment allows (2.5 kg, or 5 kg for the + * lower body), never more than 5% of the weight in one go. + * - Stalls: two sessions in a row with no progress, or two missed weekly + * sessions, drop the weight by 10% for a session, then build back up. + * - Recovery: a deficit of more than 500 kcal a day (Murphy and Koehler, + * 2022), protein under 1.6 g/kg on most days (Morton et al., 2018) or a + * night under 6 h of sleep hold the weight instead of adding to it. + */ +import { round1, type PlanTarget } from './strength'; + +export interface PastSession { + /** Local YYYY-MM-DD */ + date: string; + /** Working sets only (no warm-ups) */ + sets: { reps: number; weightKg: number | null }[]; +} + +export interface Recovery { + /** Average daily intake minus the adaptive estimate, over logged days; negative is a deficit */ + dailyBalanceKcal: number | null; + /** Logged days in the last 7, and how many were under the protein level */ + loggedDays: number; + lowProteinDays: number; + /** 1.6 g × body weight, for the explanation */ + proteinTargetG: number | null; + /** Last night, from the health app */ + sleepMinutes: number | null; +} + +export const NO_RECOVERY: Recovery = { + dailyBalanceKcal: null, + loggedDays: 0, + lowProteinDays: 0, + proteinTargetG: null, + sleepMinutes: null, +}; + +export interface ExerciseFacts { + name: string; + equipment: string[]; + pattern: string | null; + primary: string[]; +} + +export type Action = 'start' | 'increase' | 'reps' | 'hold' | 'deload'; +export type HoldReason = 'deficit' | 'protein' | 'sleep'; + +export interface Suggestion { + action: Action; + /** The weight to use, or null for bodyweight or a first session */ + weightKg: number | null; + sets: number; + /** Reps to aim for in each set */ + reps: number; + repsLow: number; + repsHigh: number; + holds: HoldReason[]; + /** One line each, for the app and the coach */ + reasons: string[]; +} + +export const DEFICIT_LIMIT_KCAL = 500; +export const PROTEIN_G_PER_KG = 1.6; +export const SHORT_SLEEP_MIN = 6 * 60; +export const MAX_JUMP = 0.05; +export const DELOAD = 0.9; +// Two missed weekly sessions +export const MISSED_DAYS = 21; + +const LOWER_PATTERNS = new Set(['squat', 'hip_hinge', 'lunge', 'calf_raise']); +const LOWER_MUSCLES = new Set([ + 'quadriceps', + 'hamstrings', + 'glutes', + 'calves', + 'adductors', + 'abductors', +]); +// Equipment that comes in fixed weights: no fractional plates +const FIXED = new Set(['dumbbell', 'kettlebell']); + +export function isLowerBody(e: ExerciseFacts) { + if (e.pattern) return LOWER_PATTERNS.has(e.pattern); + return e.primary.some((m) => LOWER_MUSCLES.has(m)); +} + +/** The smallest usual step for the equipment. */ +export function equipmentStep(e: ExerciseFacts) { + if (e.equipment.includes('kettlebell')) return 4; + if (e.equipment.includes('dumbbell')) return 2; + return isLowerBody(e) ? 5 : 2.5; +} + +const roundDown = (n: number, to: number) => Math.floor(n / to + 1e-9) * to; +const roundNearest = (n: number, to: number) => Math.round(n / to) * to; + +/** + * The next weight up: one equipment step or 5%, whichever is smaller. + * Null when even the smallest loadable jump would be more than 5% (light + * dumbbells, kettlebells): then they add reps instead. + */ +export function nextWeight(weightKg: number, e: ExerciseFacts) { + const step = equipmentStep(e); + const cap = weightKg * MAX_JUMP; + if (e.equipment.some((q) => FIXED.has(q))) { + return step <= cap ? round1(weightKg + step) : null; + } + const jump = roundDown(Math.min(step, cap), 0.5); + return jump >= 0.5 ? round1(weightKg + jump) : null; +} + +export function deloadWeight(weightKg: number, e: ExerciseFacts) { + const to = e.equipment.some((q) => FIXED.has(q)) ? 1 : 0.5; + return round1(Math.min(roundNearest(weightKg * DELOAD, to), weightKg - to)); +} + +const topWeight = (s: PastSession) => + Math.max(0, ...s.sets.map((x) => x.weightKg ?? 0)); +const repsAt = (s: PastSession, w: number) => + s.sets.filter((x) => (x.weightKg ?? 0) === w).reduce((t, x) => t + x.reps, 0); + +/** Whether `later` beat `earlier`: more weight, or more reps at the same weight. */ +export function progressed(later: PastSession, earlier: PastSession) { + const a = topWeight(later); + const b = topWeight(earlier); + if (a !== b) return a > b; + return repsAt(later, a) > repsAt(earlier, b); +} + +const daysBetween = (a: string, b: string) => + Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000); + +const fmtKg = (n: number) => `${round1(n)} kg`; +const fmtSleep = (m: number) => + `${Math.floor(m / 60)} h${m % 60 ? ` ${m % 60} m` : ''}`; + +/** Which recovery signals say to hold the weight, with their explanations. */ +export function holdsFor(r: Recovery): { + holds: HoldReason[]; + reasons: string[]; +} { + const holds: HoldReason[] = []; + const reasons: string[] = []; + if (r.dailyBalanceKcal != null && r.dailyBalanceKcal < -DEFICIT_LIMIT_KCAL) { + holds.push('deficit'); + reasons.push( + `You're averaging ${Math.round(-r.dailyBalanceKcal)} kcal a day under your burn, so this is a "preserve" week: hold the weight and keep the sets.`, + ); + } + if (r.loggedDays >= 4 && r.lowProteinDays > r.loggedDays / 2) { + holds.push('protein'); + reasons.push( + `Protein was under ${r.proteinTargetG ? `${Math.round(r.proteinTargetG)} g` : '1.6 g per kg'} on ${r.lowProteinDays} of ${r.loggedDays} logged days: holding the weight until it's up.`, + ); + } + if (r.sleepMinutes != null && r.sleepMinutes < SHORT_SLEEP_MIN) { + holds.push('sleep'); + reasons.push( + `You slept ${fmtSleep(r.sleepMinutes)} last night: keeping today's weights.`, + ); + } + return { holds, reasons }; +} + +/** + * What to do next time for one exercise, from its recent sessions (most + * recent first), the plan's target, recovery, and today's date. + */ +export function suggest( + e: ExerciseFacts, + history: PastSession[], + target: PlanTarget, + recovery: Recovery, + today: string, +): Suggestion { + const base = { + sets: target.sets, + repsLow: target.repsLow, + repsHigh: target.repsHigh, + }; + const sessions = history.filter((s) => s.sets.length); + const last = sessions[0]; + const { holds, reasons: holdReasons } = holdsFor(recovery); + + if (!last) { + return { + ...base, + action: 'start', + weightKg: null, + reps: target.repsLow, + holds: [], + reasons: [ + `First time: pick a weight you could lift for ${target.repsLow} reps with about 2 more in the tank.`, + ], + }; + } + + const weight = topWeight(last); + const bestReps = Math.max(...last.sets.map((s) => s.reps)); + + // Bodyweight: progress by reps + if (weight === 0) { + if (holds.length) { + return { + ...base, + action: 'hold', + weightKg: null, + reps: Math.min(bestReps, target.repsHigh), + holds, + reasons: holdReasons, + }; + } + return { + ...base, + action: 'reps', + weightKg: null, + reps: bestReps + 1, + holds: [], + reasons: [`Last time your best set was ${bestReps}: aim for one more.`], + }; + } + + const gap = daysBetween(last.date, today); + if (gap >= MISSED_DAYS) { + const w = deloadWeight(weight, e); + return { + ...base, + action: 'deload', + weightKg: w, + reps: target.repsLow, + holds, + reasons: [ + `It's been ${Math.floor(gap / 7)} weeks since your last ${e.name}: starting 10% lighter at ${fmtKg(w)} to ease back in.`, + ], + }; + } + + const atTop = last.sets.filter( + (s) => (s.weightKg ?? 0) === weight && s.reps >= target.repsHigh, + ).length; + const allAtTop = atTop >= target.sets; + + if (allAtTop && !holds.length) { + const up = nextWeight(weight, e); + if (up == null) { + return { + ...base, + action: 'reps', + weightKg: weight, + reps: target.repsHigh + 1, + holds: [], + reasons: [ + `You hit ${target.repsHigh} on every set. The next ${e.equipment.includes('kettlebell') ? 'kettlebell' : 'dumbbell'} up is more than a 5% jump, so add a rep first.`, + ], + }; + } + return { + ...base, + action: 'increase', + weightKg: up, + reps: target.repsLow, + holds: [], + reasons: [ + `You hit ${target.repsHigh} reps on every set last time: up to ${fmtKg(up)}.`, + ], + }; + } + + // Two sessions in a row with no progress at the same weight + const [, prev, before] = sessions; + const stalled = + !!prev && + !!before && + topWeight(prev) === weight && + topWeight(before) === weight && + !progressed(last, prev) && + !progressed(prev, before) && + daysBetween(before.date, last.date) <= 42; + if (stalled && !holds.length) { + const w = deloadWeight(weight, e); + return { + ...base, + action: 'deload', + weightKg: w, + reps: target.repsLow, + holds: [], + reasons: [ + `No progress on ${e.name} for two sessions: dropping 10% to ${fmtKg(w)} this week, then building back up.`, + ], + }; + } + + const reps = Math.min( + target.repsHigh, + Math.max(target.repsLow, Math.min(...last.sets.map((s) => s.reps)) + 1), + ); + return { + ...base, + action: 'hold', + weightKg: weight, + reps: holds.length ? Math.min(bestReps, target.repsHigh) : reps, + holds, + reasons: holds.length + ? holdReasons + : [ + `Same ${fmtKg(weight)}: aim for ${reps} reps a set, up to ${target.repsHigh} before adding weight.`, + ], + }; +} diff --git a/packages/backend/src/workouts/say-it.ts b/packages/backend/src/workouts/say-it.ts new file mode 100644 index 0000000..bfe306e --- /dev/null +++ b/packages/backend/src/workouts/say-it.ts @@ -0,0 +1,272 @@ +/** + * "Say it" for workouts: turns "bench 80 for 8, 8, 7" into three sets. + * Common phrasings are read here, without a model call; anything else goes + * to the model with WORKOUT_SCHEMA. + */ + +export interface SessionExercise { + id: string; + name: string; +} + +export interface SpokenSet { + exerciseId: string; + reps: number; + weightKg: number | null; + durationSec: number | null; +} + +const LB = 0.45359237; +const UNIT = '(kg|kgs|kilo|kilos|lb|lbs|pound|pounds)'; +const NUM = '(\\d+(?:\\.\\d+)?)'; +const LIST = '(\\d+(?:(?: ?, ?| and | )\\d+)*)'; +const SEP = '(?: ?(?:for|x|@|,))?'; +const AT = '(?: (?:at|@|with|x) ' + NUM + ' ?' + UNIT + '?)?'; + +const UNIT_RE = new RegExp(`^ ?${UNIT}`); + +const RE = { + // 100kg 5x5, 100 for 3 x 8 + weightSetsReps: new RegExp( + `^${NUM} ?${UNIT}?${SEP} ?(\\d+) ?x ?(\\d+)(?: reps?)?$`, + ), + // 80 for 3 sets of 8 + weightSetsOf: new RegExp( + `^${NUM} ?${UNIT}?${SEP} ?(\\d+) sets? of (\\d+)(?: reps?)?$`, + ), + // 80 for 8, 8, 7 + weightList: new RegExp(`^${NUM} ?${UNIT}?${SEP} ?${LIST}(?: reps?)?$`), + // 3 x 10, 3x10 at 20kg + setsReps: new RegExp(`^(\\d+) ?x ?(\\d+)(?: reps?)?${AT}$`), + // 3 sets of 10 at 20 + setsOf: new RegExp(`^(\\d+) sets? of (\\d+)(?: reps?)?${AT}$`), + // 10, 10, 8 or 8 8 7 at 80 + list: new RegExp(`^${LIST}(?: reps?)?${AT}$`), + // 45 seconds, 3 x 30 s, 2 min + timed: /^(?:(\d+) ?x ?)?(\d+) ?(s|sec|secs|seconds|min|mins|minutes)$/, +}; + +// Everyday names for lifts, matched against the session's exercise names +const ALIASES: Record = { + rdl: ['romanian deadlift'], + rdls: ['romanian deadlift'], + ohp: ['military press', 'shoulder press', 'overhead press'], + dl: ['deadlift'], + dls: ['deadlift'], + bench: ['bench press'], + pullups: ['pullup', 'pull-up', 'pull up'], + chinups: ['chin-up', 'chinup'], + pushups: ['pushup', 'push-up', 'push up'], +}; + +const compact = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, ''); +const stem = (w: string) => (w.length > 3 ? w.replace(/(es|s)$/, '') : w); + +/** + * The session exercise a spoken name means, or null. Every word said has to + * be in the name (or be a known short name for it), so "leg press" doesn't + * match the bench press. + */ +export function matchExercise(spoken: string, exercises: SessionExercise[]) { + const words = spoken + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter((w) => w && !STOP.has(w)); + if (!words.length) return null; + let best: { e: SessionExercise; score: number } | null = null; + for (const e of exercises) { + const name = compact(e.name); + let score = 0; + for (const w of words) { + const direct = name.includes(compact(stem(w))); + const alias = (ALIASES[w] ?? []).some((a) => name.includes(compact(a))); + if (!direct && !alias) { + score = 0; + break; + } + score += alias ? 2 : 1; + } + if (score > (best?.score ?? 0)) best = { e, score }; + } + return best?.e ?? null; +} + +const STOP = new Set([ + 'the', + 'some', + 'my', + 'did', + 'then', + 'and', + 'of', + 'a', + 'on', +]); + +const toKg = (n: number, unit?: string) => + unit?.startsWith('lb') || unit?.startsWith('pound') + ? Math.round(n * LB * 10) / 10 + : n; +const listOf = (s: string) => + s + .split(/ ?, ?| and | /) + .filter(Boolean) + .map(Number); + +// A first number above this is a weight, not a rep count +const MAX_PLAIN_REPS = 30; + +/** The sets in what follows the exercise name, or null if it can't be read. */ +export function readSets( + rest: string, +): + | { reps: number; weightKg: number | null; durationSec: number | null }[] + | null { + const r = rest + .toLowerCase() + .replace(/×/g, 'x') + .replace(/(\d) ?x ?(\d)/g, '$1 x $2') + .replace(/[.!?]+$/, '') + .replace(/\s+/g, ' ') + .trim(); + const sets = (n: number, reps: number, w: number | null) => + Array.from({ length: n }, () => ({ reps, weightKg: w, durationSec: null })); + let m: RegExpExecArray | null; + + if ((m = RE.timed.exec(r))) { + const n = m[1] ? +m[1] : 1; + const sec = +m[2] * (m[3].startsWith('m') ? 60 : 1); + return Array.from({ length: n }, () => ({ + reps: 0, + weightKg: null, + durationSec: sec, + })); + } + const explicitWeight = (first: string, unit?: string) => + !!unit || first.includes('.') || +first > MAX_PLAIN_REPS; + // "25, 10" is two sets of reps; "25 for 10" is a weight and reps + const hasSep = (s: string) => /^ ?(for|x|@)( |$)/.test(s); + + if ((m = RE.setsOf.exec(r))) { + return sets(+m[1], +m[2], m[3] ? toKg(+m[3], m[4]) : null); + } + if ((m = RE.weightSetsOf.exec(r))) { + return sets(+m[3], +m[4], toKg(+m[1], m[2])); + } + if ((m = RE.weightSetsReps.exec(r)) && explicitWeight(m[1], m[2])) { + return sets(+m[3], +m[4], toKg(+m[1], m[2])); + } + if ((m = RE.setsReps.exec(r)) && +m[1] <= 10 && !explicitWeight(m[1])) { + return sets(+m[1], +m[2], m[3] ? toKg(+m[3], m[4]) : null); + } + if ( + (m = RE.weightList.exec(r)) && + (explicitWeight(m[1], m[2]) || + hasSep(r.slice(m[1].length).replace(UNIT_RE, ''))) + ) { + return listOf(m[3]).map((reps) => ({ + reps, + weightKg: toKg(+m![1], m![2]), + durationSec: null, + })); + } + if ((m = RE.list.exec(r))) { + const w = m[2] ? toKg(+m[2], m[3]) : null; + return listOf(m[1]).map((reps) => ({ + reps, + weightKg: w, + durationSec: null, + })); + } + return null; +} + +const valid = (s: { + reps: number; + weightKg: number | null; + durationSec: number | null; +}) => + (s.durationSec + ? s.durationSec > 0 && s.durationSec <= 3600 + : s.reps >= 1 && s.reps <= 100) && + (s.weightKg == null || (s.weightKg > 0 && s.weightKg <= 500)); + +/** + * Reads the whole phrase: one or more " " parts, split on + * "then", "and then", ";" or new lines. Null if any part can't be read, + * so the caller can ask the model instead. + */ +export function parseSpokenSets( + text: string, + exercises: SessionExercise[], +): SpokenSet[] | null { + const parts = text + .split(/\n|;|\band then\b|\bthen\b|\. /i) + .map((p) => p.trim()) + .filter(Boolean); + if (!parts.length || parts.length > 12) return null; + const out: SpokenSet[] = []; + let lastExercise: SessionExercise | null = null; + for (const part of parts) { + const at = part.search(/\d/); + if (at < 0) return null; + const name = part.slice(0, at).trim(); + // "then 85 for 6" carries on with the last exercise + const exercise: SessionExercise | null = name + ? matchExercise(name, exercises) + : lastExercise; + if (!exercise) return null; + const sets = readSets(part.slice(at)); + if (!sets?.length || sets.length > 10 || !sets.every(valid)) return null; + out.push(...sets.map((s) => ({ ...s, exerciseId: exercise.id }))); + lastExercise = exercise; + } + return out.length ? out : null; +} + +// For the model: sets as a list, with the session's exercise ids, or "" and +// a name for an exercise that isn't in the session +export function workoutSchema(exerciseIds: string[]) { + return { + type: 'object', + additionalProperties: false, + required: ['sets'], + properties: { + sets: { + type: 'array', + items: { + type: 'object', + additionalProperties: false, + required: [ + 'exerciseId', + 'exerciseName', + 'reps', + 'weight', + 'unit', + 'durationSec', + ], + properties: { + exerciseId: { type: 'string', enum: [...exerciseIds, ''] }, + exerciseName: { type: 'string' }, + reps: { type: 'integer' }, + weight: { type: ['number', 'null'] }, + unit: { type: 'string', enum: ['kg', 'lb'] }, + durationSec: { type: ['integer', 'null'] }, + }, + }, + }, + }, + }; +} + +export function workoutInstructions(exercises: SessionExercise[]) { + return `You read what someone says about the sets they just lifted, for a workout log. + +Exercises in today's session: +${exercises.map((e) => `- ${e.id}: ${e.name}`).join('\n') || '(none)'} + +Return one entry per set, in order. "bench 80 for 8, 8, 7" is three sets of bench press at 80 with 8, 8 and 7 reps; "3x10 pull-ups" is three sets of 10 with no weight; "plank 45 seconds" is one set with durationSec 45 and reps 0. +- exerciseId: the matching exercise from the list, or "" if it isn't there (then give its usual name in exerciseName). +- weight: the number they said, or null for bodyweight; unit: "lb" only if they said pounds or lbs, otherwise "kg". +- Ignore anything that isn't a set. If they describe no sets, return an empty list.`; +} diff --git a/packages/backend/src/workouts/strength.spec.ts b/packages/backend/src/workouts/strength.spec.ts new file mode 100644 index 0000000..72a4d71 --- /dev/null +++ b/packages/backend/src/workouts/strength.spec.ts @@ -0,0 +1,156 @@ +import { + epley, + markPrs, + NO_RECORDS, + parseDetail, + recordsOf, + volumeKg, +} from './strength'; +import { matchExercise, parseSpokenSets, readSets } from './say-it'; +import { cleanTitle } from './workouts.service'; + +describe('estimated one-rep max', () => { + it('uses Epley up to 10 reps', () => { + expect(epley(100, 1)).toBe(100); + expect(epley(100, 5)).toBe(116.7); + expect(epley(80, 10)).toBe(106.7); + expect(epley(80, 11)).toBeNull(); + expect(epley(null, 5)).toBeNull(); + }); +}); + +describe('personal records', () => { + const sets = [ + { exerciseId: 'bench', reps: 10, weightKg: 40, warmup: true }, + { exerciseId: 'bench', reps: 8, weightKg: 80 }, + { exerciseId: 'bench', reps: 6, weightKg: 85 }, + { exerciseId: 'pullups', reps: 12 }, + ]; + + it('ignores warm-ups in the records', () => { + expect(recordsOf(sets.filter((s) => s.exerciseId === 'bench'))).toEqual({ + e1rm: 102, + weightKg: 85, + reps: null, + }); + }); + + it("doesn't mark a first session as a page of PRs", () => { + expect(markPrs(sets, new Map())).toEqual([null, null, null, null]); + }); + + it('marks heavier sets, better estimates and more bodyweight reps', () => { + const history = new Map([ + ['bench', { e1rm: 100, weightKg: 82.5, reps: null }], + ['pullups', { e1rm: null, weightKg: null, reps: 10 }], + ]); + expect(markPrs(sets, history)).toEqual([null, 'e1rm', 'weight', 'reps']); + }); + + it('updates as the session goes, so a repeat of a new PR is not one', () => { + const history = new Map([ + ['bench', { ...NO_RECORDS, e1rm: 90, weightKg: 75 }], + ]); + const repeat = [ + { exerciseId: 'bench', reps: 5, weightKg: 80 }, + { exerciseId: 'bench', reps: 5, weightKg: 80 }, + ]; + expect(markPrs(repeat, history)).toEqual(['weight', null]); + }); + + it('adds up volume from working sets', () => { + expect(volumeKg(sets)).toBe(80 * 8 + 85 * 6); + }); +}); + +describe('plan details', () => { + it('reads sets and rep ranges', () => { + expect(parseDetail('3 × 8–12')).toEqual({ + kind: 'reps', + target: { sets: 3, repsLow: 8, repsHigh: 12 }, + }); + expect(parseDetail('4x6')).toEqual({ + kind: 'reps', + target: { sets: 4, repsLow: 6, repsHigh: 6 }, + }); + expect(parseDetail('3 x 10-15 each side')?.target).toEqual({ + sets: 3, + repsLow: 10, + repsHigh: 15, + }); + }); + + it('reads timed sets and ignores the rest', () => { + expect(parseDetail('3 × 30 s')).toEqual({ + kind: 'timed', + target: { sets: 3, seconds: 30 }, + }); + expect(parseDetail('4 × 30 s on / 30 s off')?.kind).toBe('timed'); + expect(parseDetail('20 min easy pace')).toBeNull(); + expect(parseDetail('3 × 20 min')).toBeNull(); + }); +}); + +describe('Say it', () => { + const session = [ + { + id: 'Barbell_Bench_Press_-_Medium_Grip', + name: 'Barbell Bench Press - Medium Grip', + }, + { id: 'Barbell_Squat', name: 'Barbell Squat' }, + { id: 'Pullups', name: 'Pullups' }, + { id: 'Romanian_Deadlift', name: 'Romanian Deadlift' }, + { id: 'Plank', name: 'Plank' }, + ]; + const sets = (text: string) => + parseSpokenSets(text, session)?.map((s) => + [s.exerciseId, s.reps, s.weightKg, s.durationSec].join(' '), + ) ?? null; + + it('reads "bench 80 for 8, 8, 7" as three sets', () => { + expect(sets('bench 80 for 8, 8, 7')).toEqual([ + 'Barbell_Bench_Press_-_Medium_Grip 8 80 ', + 'Barbell_Bench_Press_-_Medium_Grip 8 80 ', + 'Barbell_Bench_Press_-_Medium_Grip 7 80 ', + ]); + }); + + it('reads the common ways of saying sets', () => { + expect(sets('squat 100kg 5x5')).toHaveLength(5); + expect(sets('squat 100 for 3 sets of 8')?.[0]).toBe('Barbell_Squat 8 100 '); + expect(sets('3 sets of 10 pull ups')).toBeNull(); // the name comes first + expect(sets('pull ups 3x10')).toEqual(Array(3).fill('Pullups 10 ')); + expect(sets('pullups 12, 10, 8')).toEqual([ + 'Pullups 12 ', + 'Pullups 10 ', + 'Pullups 8 ', + ]); + expect(sets('rdl 8 8 8 at 60')).toEqual( + Array(3).fill('Romanian_Deadlift 8 60 '), + ); + expect(sets('plank 45 seconds')).toEqual(['Plank 0 45']); + expect(sets('plank 3 x 30 s')).toHaveLength(3); + }); + + it('converts pounds and carries on with "then"', () => { + expect(sets('bench 185 lbs for 5 then 195 for 3')).toEqual([ + 'Barbell_Bench_Press_-_Medium_Grip 5 83.9 ', + 'Barbell_Bench_Press_-_Medium_Grip 3 195 ', + ]); + }); + + it('leaves what it cannot read to the model', () => { + expect(sets('did a few heavy ones')).toBeNull(); + expect(sets('leg press 200 for 10')).toBeNull(); // not in the session + expect(readSets('for a while')).toBeNull(); + expect(matchExercise('curls', session)).toBeNull(); + }); +}); + +describe('workout titles', () => { + it('drops pro-eating-disorder titles, which followers would see', () => { + expect(cleanTitle(' Push day ')).toBe('Push day'); + expect(cleanTitle('thinspo legs')).toBeNull(); + expect(cleanTitle('')).toBeNull(); + }); +}); diff --git a/packages/backend/src/workouts/strength.ts b/packages/backend/src/workouts/strength.ts new file mode 100644 index 0000000..5daa232 --- /dev/null +++ b/packages/backend/src/workouts/strength.ts @@ -0,0 +1,152 @@ +/** + * Strength maths: estimated one-rep max, personal records and the rep range + * in a plan's "3 × 8–12". Pure functions, so they're easy to test. + */ + +export interface LoggedSet { + exerciseId: string; + reps: number; + weightKg?: number | null; + durationSec?: number | null; + warmup?: boolean; +} + +/** The best a lifter has done on one exercise before now. */ +export interface Records { + e1rm: number | null; + weightKg: number | null; + // For bodyweight exercises, the most reps in one set + reps: number | null; +} + +export const NO_RECORDS: Records = { e1rm: null, weightKg: null, reps: null }; + +// Epley's estimate gets unreliable past about 10 reps +export const MAX_E1RM_REPS = 10; + +/** Epley's estimated one-rep max, or null for sets it doesn't suit. */ +export function epley(weightKg: number | null | undefined, reps: number) { + if (!weightKg || weightKg <= 0 || reps < 1 || reps > MAX_E1RM_REPS) { + return null; + } + return reps === 1 ? weightKg : round1(weightKg * (1 + reps / 30)); +} + +export const round1 = (n: number) => Math.round(n * 10) / 10; + +const isWorking = (s: LoggedSet) => !s.warmup && s.reps > 0; + +/** The records in a list of sets for one exercise (warm-ups don't count). */ +export function recordsOf(sets: LoggedSet[]): Records { + const working = sets.filter(isWorking); + const max = (xs: (number | null)[]) => { + const vals = xs.filter((x): x is number => x != null); + return vals.length ? Math.max(...vals) : null; + }; + const weighted = working.filter((s) => s.weightKg && s.weightKg > 0); + return { + e1rm: max(weighted.map((s) => epley(s.weightKg, s.reps))), + weightKg: max(weighted.map((s) => s.weightKg ?? null)), + reps: max(working.filter((s) => !s.weightKg).map((s) => s.reps)), + }; +} + +export type PrKind = 'e1rm' | 'weight' | 'reps'; + +/** + * Which record, if any, a set beats, given the records before it. A set + * only counts once there's history to beat: a first session sets the + * baseline rather than a page of PRs. + */ +export function prOf(set: LoggedSet, before: Records): PrKind | null { + if (!isWorking(set)) return null; + if (set.weightKg && set.weightKg > 0) { + if (before.weightKg == null) return null; + if (set.weightKg > before.weightKg) return 'weight'; + const e = epley(set.weightKg, set.reps); + if (e != null && before.e1rm != null && e > before.e1rm) return 'e1rm'; + return null; + } + if (set.durationSec) return null; + return before.reps != null && set.reps > before.reps ? 'reps' : null; +} + +/** Each set's PR, in order, with records updating as the session goes. */ +export function markPrs( + sets: LoggedSet[], + history: Map, +): (PrKind | null)[] { + const current = new Map(history); + const hasHistory = (id: string) => { + const r = history.get(id); + return !!r && (r.e1rm != null || r.weightKg != null || r.reps != null); + }; + return sets.map((s) => { + const before = current.get(s.exerciseId) ?? NO_RECORDS; + const pr = hasHistory(s.exerciseId) ? prOf(s, before) : null; + if (isWorking(s)) { + const merged = recordsOf([s]); + current.set(s.exerciseId, { + e1rm: maxOrNull(before.e1rm, merged.e1rm), + weightKg: maxOrNull(before.weightKg, merged.weightKg), + reps: maxOrNull(before.reps, merged.reps), + }); + } + return pr; + }); +} + +const maxOrNull = (a: number | null, b: number | null) => + a == null ? b : b == null ? a : Math.max(a, b); + +/** Total kilograms moved in working sets. */ +export function volumeKg(sets: LoggedSet[]) { + return Math.round( + sets.filter(isWorking).reduce((t, s) => t + (s.weightKg ?? 0) * s.reps, 0), + ); +} + +export interface PlanTarget { + sets: number; + // The rep range; a single number like "3 × 10" is a range of one + repsLow: number; + repsHigh: number; +} + +export interface TimedTarget { + sets: number; + seconds: number; +} + +/** + * Reads a plan exercise's detail: "3 × 8–12", "4x6", "3 × 10" (sets and + * reps) or "3 × 30 s" (timed). Null for anything else ("20 min easy"). + */ +export function parseDetail( + detail: string, +): + | { kind: 'reps'; target: PlanTarget } + | { kind: 'timed'; target: TimedTarget } + | null { + const d = detail.toLowerCase().replace(/\s+/g, ' ').trim(); + const timed = /^(\d{1,2}) ?[x×] ?(\d{1,3}) ?(s|sec|secs|seconds)\b/.exec(d); + if (timed) { + return { + kind: 'timed', + target: { sets: +timed[1], seconds: +timed[2] }, + }; + } + const m = + /^(\d{1,2}) ?[x×] ?(\d{1,3})(?: ?(?:-|–|—|to) ?(\d{1,3}))?(?!\d)(?! ?(?:s|sec|secs|seconds|min|mins|m)\b)/.exec( + d, + ); + if (!m) return null; + const sets = +m[1]; + const a = +m[2]; + const b = m[3] ? +m[3] : a; + if (!sets || !a || sets > 10 || b > 50) return null; + return { + kind: 'reps', + target: { sets, repsLow: Math.min(a, b), repsHigh: Math.max(a, b) }, + }; +} diff --git a/packages/backend/src/workouts/workouts.controller.ts b/packages/backend/src/workouts/workouts.controller.ts new file mode 100644 index 0000000..fc5f80e --- /dev/null +++ b/packages/backend/src/workouts/workouts.controller.ts @@ -0,0 +1,94 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + Param, + Post, + Put, + Query, + UseGuards, +} from '@nestjs/common'; +import { Throttle } from '@nestjs/throttler'; +import { AuthGuard } from '../auth/auth.guard'; +import { CurrentUser } from '../common/current-user.decorator'; +import { UtcOffset } from '../common/utc-offset.decorator'; +import { WorkoutsService } from './workouts.service'; +import { + ParseSetsDto, + PrepareWorkoutDto, + SaveWorkoutDto, + UpdateWorkoutDto, + WorkoutListDto, +} from './workouts.dto'; + +type Me = { supabaseId: string }; + +@Controller('workouts') +@UseGuards(AuthGuard) +export class WorkoutsController { + constructor(private workouts: WorkoutsService) {} + + /** Saves a finished workout. Safe to retry with the same clientId. */ + @Post() + save(@CurrentUser() user: Me, @Body() body: SaveWorkoutDto) { + return this.workouts.save(user.supabaseId, body); + } + + @Get() + list(@CurrentUser() user: Me, @Query() q: WorkoutListDto) { + return this.workouts.list(user.supabaseId, q.limit ?? 20, q.before); + } + + /** Last time's sets, records and today's targets for the exercises about to be done. */ + @Post('prepare') + @HttpCode(200) + prepare( + @CurrentUser() user: Me, + @Body() body: PrepareWorkoutDto, + @UtcOffset() offset: number, + ) { + return this.workouts.prepare(user.supabaseId, body, offset); + } + + /** "bench 80 for 8, 8, 7" → sets */ + @Post('parse') + @HttpCode(200) + @Throttle({ default: { limit: 20, ttl: 60_000 } }) + parse( + @CurrentUser() user: Me, + @Body() body: ParseSetsDto, + @UtcOffset() offset: number, + ) { + return this.workouts.parse(user.supabaseId, body, offset); + } + + @Get('exercises/:exerciseId/history') + history( + @CurrentUser() user: Me, + @Param('exerciseId') exerciseId: string, + @UtcOffset() offset: number, + ) { + return this.workouts.history(user.supabaseId, exerciseId, offset); + } + + @Get(':id') + detail(@CurrentUser() user: Me, @Param('id') id: string) { + return this.workouts.detail(user.supabaseId, id); + } + + @Put(':id') + update( + @CurrentUser() user: Me, + @Param('id') id: string, + @Body() body: UpdateWorkoutDto, + ) { + return this.workouts.update(user.supabaseId, id, body); + } + + @Delete(':id') + remove(@CurrentUser() user: Me, @Param('id') id: string) { + return this.workouts.remove(user.supabaseId, id); + } +} diff --git a/packages/backend/src/workouts/workouts.db-spec.ts b/packages/backend/src/workouts/workouts.db-spec.ts new file mode 100644 index 0000000..3be92a7 --- /dev/null +++ b/packages/backend/src/workouts/workouts.db-spec.ts @@ -0,0 +1,375 @@ +import type OpenAI from 'openai'; +import { TestDb } from '../test-utils/db'; +import { ExercisesService } from '../exercises/exercises.service'; +import { AdaptiveService } from '../progress/adaptive.service'; +import { TrendsService } from '../progress/trends.service'; +import { SocialService } from '../social/social.service'; +import { PrivacyService } from '../social/privacy.service'; +import { ChallengesService } from '../challenges/challenges.service'; +import { dateMarker, localToday } from '../common/day'; +import { WorkoutsService } from './workouts.service'; + +const BENCH = 'Barbell_Bench_Press_-_Medium_Grip'; +const SQUAT = 'Barbell_Squat'; +const PULLUPS = 'Pullups'; + +// The model, for the phrasings the rules can't read +function fakeModel(reply: unknown) { + const calls: unknown[] = []; + const client = { + responses: { + create: (req: unknown) => { + calls.push(req); + return Promise.resolve({ output_text: JSON.stringify(reply) }); + }, + }, + } as unknown as OpenAI; + return { client, calls }; +} + +describe('WorkoutsService (database)', () => { + const db = new TestDb(); + const exercises = new ExercisesService(db.prisma); + const adaptive = new AdaptiveService(db.prisma, new TrendsService(db.prisma)); + const model = fakeModel({ sets: [] }); + const workouts = new WorkoutsService( + db.prisma, + adaptive, + model.client, + 'test', + ); + const privacy = new PrivacyService(db.prisma); + const social = new SocialService(db.prisma, privacy, db.notifications); + const challenges = new ChallengesService(db.prisma, db.notifications); + beforeAll(async () => { + if ((await db.prisma.exercise.count()) < 800) await exercises.seed(); + }, 60_000); + afterAll(() => db.cleanup()); + + let n = 0; + const at = (daysAgo: number, hour = 9) => { + const d = new Date(Date.now() - daysAgo * 86_400_000); + d.setUTCHours(hour, 0, 0, 0); + if (d > new Date()) d.setUTCDate(d.getUTCDate() - 1); + return d; + }; + const save = ( + supabaseId: string, + daysAgo: number, + sets: { + exerciseId: string; + reps: number; + weightKg?: number; + warmup?: boolean; + }[], + extra: Record = {}, + ) => + workouts.save(supabaseId, { + clientId: `client-${++n}-${Date.now()}`, + startedAt: at(daysAgo).toISOString(), + endedAt: new Date(at(daysAgo).getTime() + 50 * 60_000).toISOString(), + sets, + ...extra, + }); + const three = (exerciseId: string, weightKg: number, ...reps: number[]) => + reps.map((r) => ({ exerciseId, reps: r, weightKg })); + + it('saves a workout once, as an activity log with sets', async () => { + const u = await db.user(); + await db.prisma.user.update({ + where: { id: u.id }, + data: { weightKg: 80 }, + }); + const dto = { + clientId: 'phone-abc-123', + title: 'Upper body', + startedAt: at(1).toISOString(), + endedAt: new Date(at(1).getTime() + 45 * 60_000).toISOString(), + sets: [ + { exerciseId: BENCH, reps: 10, weightKg: 40, warmup: true }, + ...three(BENCH, 80, 8, 8, 7), + { exerciseId: PULLUPS, reps: 10 }, + ], + }; + const first = await workouts.save(u.supabaseId, dto); + // Sent again after a dropped connection: the same workout, not a copy + const again = await workouts.save(u.supabaseId, dto); + expect(again.id).toBe(first.id); + expect( + await db.prisma.workoutSession.count({ where: { userId: u.id } }), + ).toBe(1); + + expect(first).toMatchObject({ + title: 'Upper body', + setCount: 4, + volumeKg: 80 * 23, + prCount: 0, + }); + expect(first.sets.map((s) => s.exerciseName)[1]).toBe( + 'Barbell Bench Press - Medium Grip', + ); + const log = await db.prisma.activityLog.findUnique({ + where: { id: first.activityLog.id }, + }); + expect(log).toMatchObject({ + activityType: 'strength_training', + durationMin: 45, + calorieMethod: 'met', + }); + // 5 MET × 80 kg × 0.75 h + expect(log?.caloriesBurned).toBe(300); + }); + + it('marks PRs against earlier sessions and shows counts in the feed', async () => { + const u = await db.user({ isPrivate: false }); + const friend = await db.user(); + await db.prisma.follow.create({ + data: { followerId: friend.id, followingId: u.id, status: 'accepted' }, + }); + await save(u.supabaseId, 8, three(BENCH, 80, 8, 8, 8)); + const s = await save(u.supabaseId, 1, [ + ...three(BENCH, 82.5, 8, 8, 6), + { exerciseId: PULLUPS, reps: 12 }, + ]); + expect(s.sets.map((x) => x.pr)).toEqual(['weight', null, null, null]); + expect(s.prCount).toBe(1); + + const feed = await social.getFeed(friend.supabaseId); + const item = feed.find((f) => f.id === s.activityLog.id); + expect(item?.data).toMatchObject({ + activityType: 'strength_training', + workout: { title: null, setCount: 4, prCount: 1 }, + }); + // No weights in the feed + expect(JSON.stringify(item?.data)).not.toContain('82.5'); + }); + + it('counts toward workout challenges like any other workout', async () => { + const u = await db.user(); + const c = await challenges.createChallenge( + u.supabaseId, + { title: 'Lift', type: 'workouts', goalValue: 3, durationDays: 7 }, + 0, + ); + await save(u.supabaseId, 0, three(SQUAT, 100, 5, 5, 5)); + const board = await challenges.getChallenge(u.supabaseId, c.id); + expect(board.totalProgress).toBe(1); + }); + + it('runs the plan by session order, wrapping round the week', async () => { + const u = await db.user(); + const day = (d: string, rest: boolean) => ({ + day: d, + rest, + title: rest ? 'Rest' : `Day ${d}`, + activityType: rest ? 'other' : 'strength_training', + durationMin: rest ? 0 : 45, + exercises: rest + ? [] + : [{ exerciseId: SQUAT, name: 'Barbell Squat', detail: '3 × 5–8' }], + }); + await db.prisma.workoutPlan.create({ + data: { + userId: u.id, + summary: '', + daysPerWeek: 2, + location: 'gym', + generationDay: localToday(0), + days: ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'].map((d) => + day(d, !['mon', 'thu'].includes(d)), + ), + }, + }); + const next = async () => + (await db.prisma.workoutPlan.findUnique({ where: { userId: u.id } }))! + .nextSession; + expect(await next()).toBe(1); + await save(u.supabaseId, 2, three(SQUAT, 100, 5, 5, 5), { planSession: 1 }); + expect(await next()).toBe(2); + await save(u.supabaseId, 1, three(SQUAT, 100, 5, 5, 5), { planSession: 2 }); + expect(await next()).toBe(1); + }); + + it('prepares last time, records and targets, borrowing history for a swap', async () => { + const u = await db.user(); + await db.prisma.user.update({ + where: { id: u.id }, + data: { weightKg: 80 }, + }); + await save(u.supabaseId, 7, three(BENCH, 80, 12, 12, 12)); + const res = await workouts.prepare( + u.supabaseId, + { + exercises: [ + { exerciseId: BENCH, detail: '3 × 8–12' }, + // Same movement and equipment, never done: borrows the bench's history + { + exerciseId: 'Barbell_Incline_Bench_Press_-_Medium_Grip', + detail: '3 × 8–12', + }, + { exerciseId: 'Plank', detail: '3 × 30 s' }, + ].filter(Boolean), + }, + 0, + ); + const [bench, wide, plank] = res.exercises; + expect(bench.last?.sets).toHaveLength(3); + expect(bench.records.weightKg).toBe(80); + expect(bench.suggestion).toMatchObject({ + action: 'increase', + weightKg: 82.5, + }); + expect(wide.historyFrom?.id).toBe(BENCH); + expect(wide.suggestion?.action).toBe('increase'); + expect(plank.timed).toEqual({ sets: 3, seconds: 30 }); + expect(plank.suggestion).toBeNull(); + }); + + it('holds the weight after a short night', async () => { + const u = await db.user(); + await save(u.supabaseId, 7, three(BENCH, 80, 12, 12, 12)); + await db.prisma.healthDay.create({ + data: { + userId: u.id, + day: dateMarker(localToday(0)), + sleepMinutes: 300, + source: 'healthkit', + }, + }); + const res = await workouts.prepare( + u.supabaseId, + { exercises: [{ exerciseId: BENCH, detail: '3 × 8–12' }] }, + 0, + ); + expect(res.exercises[0].suggestion).toMatchObject({ + action: 'hold', + weightKg: 80, + holds: ['sleep'], + }); + const lines = await workouts.coachLines(u, 0); + expect(lines).toEqual([]); // no plan, no PRs this week + }); + + it('edits, then deletes with its activity log', async () => { + const u = await db.user(); + const s = await save(u.supabaseId, 3, three(SQUAT, 100, 5, 5, 5)); + const edited = await workouts.update(u.supabaseId, s.id, { + title: 'Legs', + sets: three(SQUAT, 100, 5, 5, 4), + }); + expect(edited).toMatchObject({ + title: 'Legs', + setCount: 3, + volumeKg: 1400, + }); + const history = await workouts.history(u.supabaseId, SQUAT, 0); + expect(history.sessions[0]).toMatchObject({ + topWeightKg: 100, + bestE1rm: 116.7, + }); + + await workouts.remove(u.supabaseId, s.id); + expect(await db.prisma.workoutSet.count({ where: { userId: u.id } })).toBe( + 0, + ); + expect(await db.prisma.activityLog.count({ where: { userId: u.id } })).toBe( + 0, + ); + // Someone else's workout isn't found + const other = await db.user(); + const theirs = await save(other.supabaseId, 1, three(SQUAT, 60, 5)); + await expect(workouts.remove(u.supabaseId, theirs.id)).rejects.toThrow( + 'not found', + ); + }); + + it('refuses exercises that are not in the library', async () => { + const u = await db.user(); + await expect( + save(u.supabaseId, 1, [ + { exerciseId: 'Made_Up_Lift', reps: 5, weightKg: 50 }, + ]), + ).rejects.toThrow('Unknown exercise'); + }); + + it('reads simple phrasings without the model or AI consent', async () => { + const u = await db.user({ aiConsent: false }); + const before = model.calls.length; + const res = await workouts.parse( + u.supabaseId, + { text: 'bench 80 for 8, 8, 7', exerciseIds: [BENCH, SQUAT] }, + 0, + ); + expect(res.source).toBe('rules'); + expect(res.sets.map((s) => [s.exerciseId, s.reps, s.weightKg])).toEqual([ + [BENCH, 8, 80], + [BENCH, 8, 80], + [BENCH, 7, 80], + ]); + expect(model.calls.length).toBe(before); + // Anything else needs consent for the model + await expect( + workouts.parse( + u.supabaseId, + { text: 'did a few heavy ones', exerciseIds: [BENCH] }, + 0, + ), + ).rejects.toMatchObject({ status: 403 }); + }); + + it('asks the model for the rest, converting pounds and finding exercises by name', async () => { + const u = await db.user(); + const m = fakeModel({ + sets: [ + { + exerciseId: BENCH, + exerciseName: 'bench', + reps: 5, + weight: 185, + unit: 'lb', + durationSec: null, + }, + { + exerciseId: '', + exerciseName: 'Leg Press', + reps: 12, + weight: 140, + unit: 'kg', + durationSec: null, + }, + { + exerciseId: '', + exerciseName: 'Nonsense lift', + reps: 5, + weight: 10, + unit: 'kg', + durationSec: null, + }, + ], + }); + const w = new WorkoutsService(db.prisma, adaptive, m.client, 'test'); + const res = await w.parse( + u.supabaseId, + { + text: 'did bench, 185 pounds five times, then some leg press', + exerciseIds: [BENCH], + }, + 0, + ); + expect(res.source).toBe('ai'); + expect(res.sets.map((s) => [s.exerciseId, s.reps, s.weightKg])).toEqual([ + [BENCH, 5, 83.9], + ['Leg_Press', 12, 140], + ]); + const row = await db.prisma.user.findUnique({ where: { id: u.id } }); + expect(row?.aiParseCount).toBe(1); + }); + + it('finds exercises by everyday names', async () => { + const find = async (n: string) => (await workouts.findByName(n))?.id; + expect(await find('Pull-ups')).toBe('Pullups'); + expect(await find('pull ups')).toBe('Pullups'); + expect(await find('Leg Press')).toBe('Leg_Press'); + expect(await find('barbell squat')).toBe('Barbell_Squat'); + }); +}); diff --git a/packages/backend/src/workouts/workouts.dto.ts b/packages/backend/src/workouts/workouts.dto.ts new file mode 100644 index 0000000..707f276 --- /dev/null +++ b/packages/backend/src/workouts/workouts.dto.ts @@ -0,0 +1,173 @@ +import { Type } from 'class-transformer'; +import { + ArrayMaxSize, + IsArray, + IsBoolean, + IsIn, + IsInt, + IsISO8601, + IsNumber, + IsOptional, + IsString, + Length, + Max, + Min, + ValidateNested, +} from 'class-validator'; +import { ACTIVITY_TYPES } from '../activity/activity.constants'; +import { IsNotFuture } from '../common/validators'; + +export class WorkoutSetDto { + @IsString() + @Length(1, 120) + exerciseId: string; + + // 0 for a timed set + @IsInt() + @Min(0) + @Max(100) + reps: number; + + // Leave out (or null) for bodyweight + @IsOptional() + @IsNumber() + @Min(0) + @Max(500) + weightKg?: number | null; + + @IsOptional() + @IsInt() + @Min(1) + @Max(3600) + durationSec?: number | null; + + // Effort, 6 (easy) to 10 (nothing left) + @IsOptional() + @IsNumber() + @Min(1) + @Max(10) + rpe?: number | null; + + @IsOptional() + @IsBoolean() + warmup?: boolean; + + // Sets sharing one are a superset or circuit + @IsOptional() + @IsString() + @Length(1, 40) + supersetId?: string | null; +} + +/** A finished workout, sent whole from the phone. */ +export class SaveWorkoutDto { + // Made on the phone; sending the same one again doesn't log it twice + @IsString() + @Length(8, 64) + clientId: string; + + // Which session of the plan this was (1, 2, 3…) + @IsOptional() + @IsInt() + @Min(1) + @Max(7) + planSession?: number; + + @IsOptional() + @IsString() + @Length(0, 60) + title?: string; + + // strength_training unless it was a plan's run or ride, logged without sets + @IsOptional() + @IsIn(ACTIVITY_TYPES) + activityType?: string; + + @IsISO8601({ strict: true }) + @IsNotFuture() + startedAt: string; + + @IsISO8601({ strict: true }) + @IsNotFuture() + endedAt: string; + + @IsArray() + @ArrayMaxSize(200) + @ValidateNested({ each: true }) + @Type(() => WorkoutSetDto) + sets: WorkoutSetDto[]; +} + +/** Edits to a saved workout: what's given replaces what was there. */ +export class UpdateWorkoutDto { + @IsOptional() + @IsString() + @Length(0, 60) + title?: string; + + @IsOptional() + @IsISO8601({ strict: true }) + @IsNotFuture() + startedAt?: string; + + @IsOptional() + @IsISO8601({ strict: true }) + @IsNotFuture() + endedAt?: string; + + @IsOptional() + @IsArray() + @ArrayMaxSize(200) + @ValidateNested({ each: true }) + @Type(() => WorkoutSetDto) + sets?: WorkoutSetDto[]; +} + +export class PrepareExerciseDto { + @IsString() + @Length(1, 120) + exerciseId: string; + + // The plan's "3 × 8–12"; 3 × 8–12 when left out + @IsOptional() + @IsString() + @Length(0, 60) + detail?: string; +} + +/** The exercises about to be done, to get last time's sets and today's targets. */ +export class PrepareWorkoutDto { + @IsArray() + @ArrayMaxSize(16) + @ValidateNested({ each: true }) + @Type(() => PrepareExerciseDto) + exercises: PrepareExerciseDto[]; +} + +/** "bench 80 for 8, 8, 7", read into sets. */ +export class ParseSetsDto { + @IsString() + @Length(1, 300) + text: string; + + // The session's exercises, so names can be matched to them + @IsArray() + @ArrayMaxSize(16) + @IsString({ each: true }) + @Length(1, 120, { each: true }) + exerciseIds: string[]; +} + +export class WorkoutListDto { + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(50) + limit?: number; + + // Sessions that started before this time, for paging + @IsOptional() + @IsISO8601({ strict: true }) + before?: string; +} diff --git a/packages/backend/src/workouts/workouts.module.ts b/packages/backend/src/workouts/workouts.module.ts new file mode 100644 index 0000000..a18e943 --- /dev/null +++ b/packages/backend/src/workouts/workouts.module.ts @@ -0,0 +1,13 @@ +import { Module } from '@nestjs/common'; +import { azureOpenAIProviders } from '../ai/azure-openai'; +import { ProgressModule } from '../progress/progress.module'; +import { WorkoutsController } from './workouts.controller'; +import { WorkoutsService } from './workouts.service'; + +@Module({ + imports: [ProgressModule], + controllers: [WorkoutsController], + providers: [...azureOpenAIProviders, WorkoutsService], + exports: [WorkoutsService], +}) +export class WorkoutsModule {} diff --git a/packages/backend/src/workouts/workouts.service.ts b/packages/backend/src/workouts/workouts.service.ts new file mode 100644 index 0000000..8944418 --- /dev/null +++ b/packages/backend/src/workouts/workouts.service.ts @@ -0,0 +1,843 @@ +import { + BadGatewayException, + BadRequestException, + Inject, + Injectable, + Logger, + NotFoundException, +} from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import OpenAI from 'openai'; +import { PrismaService } from '../prisma/prisma.service'; +import { AI_MODEL } from '../ai/azure-openai'; +import { assertAiConsent } from '../common/ai-consent'; +import { hasProEdTerm } from '../common/safety'; +import { giveBackParse, takeParse } from '../common/parse-quota'; +import { + addDays, + dateMarker, + dayRange, + localDateOf, + localToday, +} from '../common/day'; +import { metFor } from '../activity/activity.constants'; +import { COMMON_EXERCISES } from '../exercises/exercise-tags'; +import { AdaptiveService } from '../progress/adaptive.service'; +import { + markPrs, + parseDetail, + recordsOf, + round1, + volumeKg, + epley, + NO_RECORDS, + type LoggedSet, + type PlanTarget, +} from './strength'; +import { + NO_RECOVERY, + PROTEIN_G_PER_KG, + suggest, + type PastSession, + type Recovery, + type Suggestion, +} from './progression'; +import { + parseSpokenSets, + workoutInstructions, + workoutSchema, + type SpokenSet, +} from './say-it'; +import type { + ParseSetsDto, + PrepareWorkoutDto, + SaveWorkoutDto, + UpdateWorkoutDto, + WorkoutSetDto, +} from './workouts.dto'; + +const DEFAULT_TARGET: PlanTarget = { sets: 3, repsLow: 8, repsHigh: 12 }; +// How many past sessions of an exercise the rules look at +const HISTORY_SESSIONS = 3; +const LB = 0.45359237; + +const EXERCISE_FACTS = { + id: true, + name: true, + equipment: true, + pattern: true, + primary: true, + imageUrl: true, +} as const; + +type SetRow = { + exerciseId: string; + reps: number; + weightKg: number | null; + durationSec: number | null; + warmup: boolean; +}; + +/** + * A workout's title shows in followers' feeds, so it gets the same check as + * display names: a pro-eating-disorder title is dropped. + */ +export function cleanTitle(title: string | undefined | null) { + const t = title?.trim().slice(0, 60); + return t && !hasProEdTerm(t) ? t : null; +} + +/** The plan's training days, in order: session 1 is the first. */ +export function trainingDays(days: unknown): T[] { + return Array.isArray(days) ? (days as T[]).filter((d) => !d.rest) : []; +} + +@Injectable() +export class WorkoutsService { + private readonly logger = new Logger(WorkoutsService.name); + + constructor( + private prisma: PrismaService, + private adaptive: AdaptiveService, + private openai: OpenAI, + @Inject(AI_MODEL) private model: string, + ) {} + + private async resolveUser(supabaseId: string) { + const user = await this.prisma.user.findUnique({ where: { supabaseId } }); + if (!user) throw new NotFoundException('User not found'); + return user; + } + + private async checkExercises(ids: string[]) { + const unique = [...new Set(ids)]; + if (!unique.length) return new Map(); + const found = await this.prisma.exercise.findMany({ + where: { id: { in: unique } }, + select: { id: true, name: true }, + }); + if (found.length !== unique.length) { + const known = new Set(found.map((e) => e.id)); + throw new BadRequestException( + `Unknown exercise: ${unique.find((id) => !known.has(id))}`, + ); + } + return new Map(found.map((e) => [e.id, e])); + } + + /** The best each exercise had been lifted before a time. */ + private async recordsBefore(userId: string, ids: string[], before: Date) { + const rows = await this.prisma.workoutSet.findMany({ + where: { + userId, + exerciseId: { in: [...new Set(ids)] }, + warmup: false, + session: { startedAt: { lt: before } }, + }, + select: { exerciseId: true, reps: true, weightKg: true }, + }); + const by = new Map(); + for (const r of rows) { + by.set(r.exerciseId, [...(by.get(r.exerciseId) ?? []), r]); + } + return new Map( + [...by.entries()].map(([id, sets]) => [id, recordsOf(sets)] as const), + ); + } + + private async setsWithPrs( + userId: string, + sets: WorkoutSetDto[], + startedAt: Date, + ) { + const history = await this.recordsBefore( + userId, + sets.map((s) => s.exerciseId), + startedAt, + ); + const prs = markPrs(sets, history); + return sets.map((s, i) => ({ + userId, + exerciseId: s.exerciseId, + order: i, + reps: s.reps, + weightKg: s.weightKg ?? null, + durationSec: s.durationSec ?? null, + rpe: s.rpe ?? null, + warmup: s.warmup ?? false, + supersetId: s.supersetId ?? null, + pr: prs[i], + })); + } + + private times(startedAt: string, endedAt: string) { + const start = new Date(startedAt); + const end = new Date(endedAt); + if (end < start) { + throw new BadRequestException("A workout can't end before it starts"); + } + const durationMin = Math.min( + 1440, + Math.max(1, Math.round((end.getTime() - start.getTime()) / 60_000)), + ); + return { start, end, durationMin }; + } + + private calories( + activityType: string, + durationMin: number, + weightKg: number | null, + ) { + return Math.round( + metFor(activityType) * (weightKg ?? 70) * (durationMin / 60), + ); + } + + /** + * Saves a finished workout: the sets, with any PRs marked, and the + * ActivityLog that puts it in the feed, challenges and calories. Sending + * the same clientId again returns the saved one instead of a copy. + */ + async save(supabaseId: string, dto: SaveWorkoutDto) { + const user = await this.resolveUser(supabaseId); + const existing = await this.prisma.workoutSession.findUnique({ + where: { userId_clientId: { userId: user.id, clientId: dto.clientId } }, + select: { id: true }, + }); + if (existing) return this.detailById(user.id, existing.id); + + await this.checkExercises(dto.sets.map((s) => s.exerciseId)); + const { start, end, durationMin } = this.times(dto.startedAt, dto.endedAt); + const sets = await this.setsWithPrs(user.id, dto.sets, start); + const activityType = dto.activityType ?? 'strength_training'; + + let sessionId: string; + try { + sessionId = await this.prisma.$transaction(async (tx) => { + const log = await tx.activityLog.create({ + data: { + userId: user.id, + activityType, + durationMin, + caloriesBurned: this.calories( + activityType, + durationMin, + user.weightKg, + ), + calorieMethod: 'met', + source: 'manual', + loggedAt: start, + }, + }); + const session = await tx.workoutSession.create({ + data: { + userId: user.id, + clientId: dto.clientId, + activityLogId: log.id, + planSession: dto.planSession ?? null, + title: cleanTitle(dto.title), + startedAt: start, + endedAt: end, + setCount: sets.filter((s) => !s.warmup).length, + volumeKg: volumeKg(sets), + prCount: sets.filter((s) => s.pr).length, + sets: { createMany: { data: sets } }, + }, + }); + if (dto.planSession) + await this.advancePlan(tx, user.id, dto.planSession); + return session.id; + }); + } catch (err) { + // The same workout sent twice at once: the other request saved it + if ( + err instanceof Prisma.PrismaClientKnownRequestError && + err.code === 'P2002' + ) { + const saved = await this.prisma.workoutSession.findUnique({ + where: { + userId_clientId: { userId: user.id, clientId: dto.clientId }, + }, + select: { id: true }, + }); + if (saved) return this.detailById(user.id, saved.id); + } + throw err; + } + return this.detailById(user.id, sessionId); + } + + /** After session k, the plan's next one is k + 1, wrapping round the week. */ + private async advancePlan( + tx: Prisma.TransactionClient, + userId: string, + done: number, + ) { + const plan = await tx.workoutPlan.findUnique({ where: { userId } }); + if (!plan) return; + const n = trainingDays(plan.days).length; + if (!n || done > n) return; + await tx.workoutPlan.update({ + where: { id: plan.id }, + data: { nextSession: (done % n) + 1 }, + }); + } + + private async detailById(userId: string, id: string) { + const s = await this.prisma.workoutSession.findFirst({ + where: { id, userId }, + include: { + sets: { orderBy: { order: 'asc' } }, + activityLog: { + select: { id: true, caloriesBurned: true, durationMin: true }, + }, + }, + }); + if (!s) throw new NotFoundException('Workout not found'); + const names = await this.exerciseNames(s.sets.map((x) => x.exerciseId)); + return { + id: s.id, + clientId: s.clientId, + title: s.title, + planSession: s.planSession, + startedAt: s.startedAt, + endedAt: s.endedAt, + setCount: s.setCount, + volumeKg: s.volumeKg, + prCount: s.prCount, + activityLog: s.activityLog, + sets: s.sets.map((x) => ({ + id: x.id, + exerciseId: x.exerciseId, + exerciseName: names.get(x.exerciseId) ?? x.exerciseId, + reps: x.reps, + weightKg: x.weightKg, + durationSec: x.durationSec, + rpe: x.rpe, + warmup: x.warmup, + supersetId: x.supersetId, + pr: x.pr, + })), + }; + } + + private async exerciseNames(ids: string[]) { + const rows = await this.prisma.exercise.findMany({ + where: { id: { in: [...new Set(ids)] } }, + select: { id: true, name: true }, + }); + return new Map(rows.map((r) => [r.id, r.name])); + } + + async detail(supabaseId: string, id: string) { + const user = await this.resolveUser(supabaseId); + return this.detailById(user.id, id); + } + + /** Recent workouts, newest first, with the exercises in each. */ + async list(supabaseId: string, limit = 20, before?: string) { + const user = await this.resolveUser(supabaseId); + const rows = await this.prisma.workoutSession.findMany({ + where: { + userId: user.id, + ...(before ? { startedAt: { lt: new Date(before) } } : {}), + }, + orderBy: { startedAt: 'desc' }, + take: limit, + include: { + sets: { select: { exerciseId: true }, orderBy: { order: 'asc' } }, + }, + }); + const names = await this.exerciseNames( + rows.flatMap((r) => r.sets.map((s) => s.exerciseId)), + ); + return rows.map((r) => ({ + id: r.id, + title: r.title, + planSession: r.planSession, + startedAt: r.startedAt, + endedAt: r.endedAt, + setCount: r.setCount, + volumeKg: r.volumeKg, + prCount: r.prCount, + exercises: [...new Set(r.sets.map((s) => s.exerciseId))].map( + (id) => names.get(id) ?? id, + ), + })); + } + + /** Replaces a saved workout's sets, title or times; PRs are worked out again. */ + async update(supabaseId: string, id: string, dto: UpdateWorkoutDto) { + const user = await this.resolveUser(supabaseId); + const s = await this.prisma.workoutSession.findFirst({ + where: { id, userId: user.id }, + include: { activityLog: true }, + }); + if (!s) throw new NotFoundException('Workout not found'); + const { start, end, durationMin } = this.times( + dto.startedAt ?? s.startedAt.toISOString(), + dto.endedAt ?? s.endedAt.toISOString(), + ); + if (dto.sets) await this.checkExercises(dto.sets.map((x) => x.exerciseId)); + const sets = dto.sets + ? await this.setsWithPrs(user.id, dto.sets, start) + : null; + + await this.prisma.$transaction(async (tx) => { + if (sets) { + await tx.workoutSet.deleteMany({ where: { sessionId: id } }); + await tx.workoutSet.createMany({ + data: sets.map((x) => ({ ...x, sessionId: id })), + }); + } + await tx.workoutSession.update({ + where: { id }, + data: { + title: dto.title !== undefined ? cleanTitle(dto.title) : undefined, + startedAt: start, + endedAt: end, + ...(sets + ? { + setCount: sets.filter((x) => !x.warmup).length, + volumeKg: volumeKg(sets), + prCount: sets.filter((x) => x.pr).length, + } + : {}), + }, + }); + if (durationMin !== s.activityLog.durationMin || dto.startedAt) { + await tx.activityLog.update({ + where: { id: s.activityLogId }, + data: { + durationMin, + loggedAt: start, + caloriesBurned: this.calories( + s.activityLog.activityType, + durationMin, + user.weightKg, + ), + }, + }); + } + }); + return this.detailById(user.id, id); + } + + /** Deletes the workout and its activity log. */ + async remove(supabaseId: string, id: string) { + const user = await this.resolveUser(supabaseId); + const s = await this.prisma.workoutSession.findFirst({ + where: { id, userId: user.id }, + select: { activityLogId: true }, + }); + if (!s) throw new NotFoundException('Workout not found'); + // Deleting the log deletes the session and its sets + await this.prisma.activityLog.delete({ where: { id: s.activityLogId } }); + return { ok: true }; + } + + private async pastSessions( + userId: string, + exerciseId: string, + offset: number, + take = HISTORY_SESSIONS, + ): Promise { + const sessions = await this.prisma.workoutSession.findMany({ + where: { userId, sets: { some: { exerciseId, warmup: false } } }, + orderBy: { startedAt: 'desc' }, + take, + select: { + startedAt: true, + sets: { + where: { exerciseId, warmup: false }, + orderBy: { order: 'asc' }, + select: { reps: true, weightKg: true, durationSec: true }, + }, + }, + }); + return sessions.map((s) => ({ + date: localDateOf(s.startedAt, offset), + sets: s.sets, + })); + } + + /** What the rules need about recovery: deficit, protein and last night's sleep. */ + async recovery( + user: { id: string; supabaseId: string; weightKg: number | null }, + offset: number, + ): Promise { + const today = localToday(offset); + const start = dayRange(addDays(today, -7), offset).start; + const end = dayRange(today, offset).start; + const [foods, health, checkIn] = await Promise.all([ + this.prisma.foodLog.findMany({ + where: { userId: user.id, loggedAt: { gte: start, lt: end } }, + select: { loggedAt: true, calories: true, proteinG: true }, + }), + this.prisma.healthDay.findUnique({ + where: { userId_day: { userId: user.id, day: dateMarker(today) } }, + select: { sleepMinutes: true }, + }), + this.adaptive.checkIn(user.supabaseId, offset).catch(() => null), + ]); + const byDay = new Map(); + for (const f of foods) { + const d = localDateOf(f.loggedAt, offset); + const day = byDay.get(d) ?? { kcal: 0, protein: 0 }; + day.kcal += f.calories; + day.protein += f.proteinG; + byDay.set(d, day); + } + const days = [...byDay.values()]; + const proteinTargetG = user.weightKg + ? user.weightKg * PROTEIN_G_PER_KG + : null; + const tdee = checkIn?.estimate?.tdee ?? null; + return { + dailyBalanceKcal: + tdee && days.length >= 3 + ? Math.round( + days.reduce((t, d) => t + d.kcal, 0) / days.length - tdee, + ) + : null, + loggedDays: days.length, + lowProteinDays: proteinTargetG + ? days.filter((d) => d.protein < proteinTargetG).length + : 0, + proteinTargetG, + sleepMinutes: health?.sleepMinutes ?? null, + }; + } + + /** + * For each exercise about to be done: last time's sets, the records to + * beat, and what the progression rules suggest today. An exercise with no + * history of its own borrows it from the same movement on the same + * equipment (a swap from one barbell row to another), so a swap doesn't + * start from zero. + */ + async prepare(supabaseId: string, dto: PrepareWorkoutDto, offset: number) { + const user = await this.resolveUser(supabaseId); + const ids = dto.exercises.map((e) => e.exerciseId); + await this.checkExercises(ids); + const facts = await this.prisma.exercise.findMany({ + where: { id: { in: ids } }, + select: EXERCISE_FACTS, + }); + const byId = new Map(facts.map((f) => [f.id, f])); + const recovery = await this.recovery(user, offset).catch(() => NO_RECOVERY); + const today = localToday(offset); + const records = await this.recordsBefore(user.id, ids, new Date()); + + const exercises = []; + for (const item of dto.exercises) { + const e = byId.get(item.exerciseId)!; + const parsed = parseDetail(item.detail ?? ''); + let history = await this.pastSessions(user.id, e.id, offset); + let historyFrom: { id: string; name: string } | null = null; + if (!history.length && e.pattern) { + const similar = await this.similarWithHistory(user.id, e); + if (similar) { + history = await this.pastSessions(user.id, similar.id, offset); + historyFrom = similar; + } + } + const target = parsed?.kind === 'reps' ? parsed.target : DEFAULT_TARGET; + const suggestion: Suggestion | null = + parsed?.kind === 'timed' + ? null + : suggest(e, history, target, recovery, today); + exercises.push({ + exerciseId: e.id, + name: e.name, + equipment: e.equipment, + pattern: e.pattern, + imageUrl: e.imageUrl, + detail: item.detail ?? null, + timed: parsed?.kind === 'timed' ? parsed.target : null, + last: history[0] ?? null, + historyFrom, + records: records.get(e.id) ?? NO_RECORDS, + suggestion, + }); + } + return { today, exercises }; + } + + /** The exercise on the same movement and equipment done most recently. */ + private async similarWithHistory( + userId: string, + e: { id: string; pattern: string | null; equipment: string[] }, + ) { + if (!e.pattern || !e.equipment.length) return null; + const sameMovement = await this.prisma.exercise.findMany({ + where: { + pattern: e.pattern, + equipment: { hasSome: e.equipment }, + id: { not: e.id }, + }, + select: { id: true, name: true }, + }); + if (!sameMovement.length) return null; + const set = await this.prisma.workoutSet.findFirst({ + where: { + userId, + warmup: false, + exerciseId: { in: sameMovement.map((x) => x.id) }, + }, + orderBy: { session: { startedAt: 'desc' } }, + select: { exerciseId: true }, + }); + return set ? sameMovement.find((x) => x.id === set.exerciseId)! : null; + } + + /** One exercise's history: each session's sets, best estimate and top weight. */ + async history(supabaseId: string, exerciseId: string, offset: number) { + const user = await this.resolveUser(supabaseId); + const exercise = await this.prisma.exercise.findUnique({ + where: { id: exerciseId }, + select: EXERCISE_FACTS, + }); + if (!exercise) throw new NotFoundException('Exercise not found'); + const sessions = await this.prisma.workoutSession.findMany({ + where: { userId: user.id, sets: { some: { exerciseId } } }, + orderBy: { startedAt: 'desc' }, + take: 50, + select: { + id: true, + startedAt: true, + sets: { + where: { exerciseId }, + orderBy: { order: 'asc' }, + select: { + reps: true, + weightKg: true, + durationSec: true, + warmup: true, + pr: true, + }, + }, + }, + }); + const all: SetRow[] = sessions.flatMap((s) => + s.sets.map((x) => ({ ...x, exerciseId })), + ); + return { + exercise, + records: recordsOf(all), + sessions: sessions.map((s) => { + const working = s.sets.filter((x) => !x.warmup); + const e1rms = working + .map((x) => epley(x.weightKg, x.reps)) + .filter((x): x is number => x != null); + const weights = working + .map((x) => x.weightKg) + .filter((x): x is number => x != null); + return { + sessionId: s.id, + date: localDateOf(s.startedAt, offset), + sets: s.sets, + bestE1rm: e1rms.length ? Math.max(...e1rms) : null, + topWeightKg: weights.length ? Math.max(...weights) : null, + bestReps: working.length + ? Math.max(...working.map((x) => x.reps)) + : null, + }; + }), + }; + } + + /** + * "bench 80 for 8, 8, 7" → sets. Common phrasings are read here; the rest + * go to the model, which needs AI consent and uses a smart-logging turn. + */ + async parse(supabaseId: string, dto: ParseSetsDto, offset: number) { + const user = await this.resolveUser(supabaseId); + const exercises = ( + await this.prisma.exercise.findMany({ + where: { id: { in: dto.exerciseIds } }, + select: { id: true, name: true }, + }) + ).sort( + (a, b) => dto.exerciseIds.indexOf(a.id) - dto.exerciseIds.indexOf(b.id), + ); + + const local = parseSpokenSets(dto.text, exercises); + if (local) + return { sets: await this.named(local), source: 'rules' as const }; + + assertAiConsent(user); + const today = localToday(offset); + await takeParse(this.prisma, user.id, today); + let parsed: { + sets: { + exerciseId: string; + exerciseName: string; + reps: number; + weight: number | null; + unit: 'kg' | 'lb'; + durationSec: number | null; + }[]; + }; + try { + const response = await this.openai.responses.create({ + model: this.model, + instructions: workoutInstructions(exercises), + input: dto.text, + max_output_tokens: 3000, + reasoning: { effort: 'low' }, + store: false, + text: { + format: { + type: 'json_schema', + name: 'workout_sets', + strict: true, + schema: workoutSchema( + exercises.map((e) => e.id), + ) as unknown as Record, + }, + }, + }); + parsed = JSON.parse(response.output_text) as typeof parsed; + if (!Array.isArray(parsed.sets)) throw new Error('No sets'); + } catch (err) { + this.logger.warn(`Set parse failed: ${(err as Error).message}`); + await giveBackParse(this.prisma, user.id, today); + throw new BadGatewayException( + "Couldn't read those sets right now. Try again, or add them by hand.", + ); + } + + const sets: SpokenSet[] = []; + for (const s of parsed.sets.slice(0, 30)) { + let id = s.exerciseId; + if (!id && s.exerciseName?.trim()) { + const hit = await this.findByName(s.exerciseName); + id = hit?.id ?? ''; + } + const reps = Math.round(s.reps); + const durationSec = + s.durationSec && s.durationSec > 0 + ? Math.min(3600, Math.round(s.durationSec)) + : null; + const weightKg = + s.weight && s.weight > 0 + ? round1(s.unit === 'lb' ? s.weight * LB : s.weight) + : null; + if (!id || (!durationSec && (reps < 1 || reps > 100))) continue; + if (weightKg != null && weightKg > 500) continue; + sets.push({ + exerciseId: id, + reps: durationSec ? 0 : reps, + weightKg, + durationSec, + }); + } + return { sets: await this.named(sets), source: 'ai' as const }; + } + + /** + * The library exercise a name means: exact (ignoring spaces and hyphens, + * so "pull-ups" is "Pullups"), then a common lift, then the shortest match. + */ + async findByName(raw: string) { + const name = raw.trim(); + const squash = (t: string) => t.toLowerCase().replace(/[^a-z0-9]/g, ''); + const variants = [ + ...new Set([ + name, + name.replace(/[-\s]+/g, ''), + name.replace(/\s+/g, '-'), + ]), + ].filter((v) => v.length >= 2); + const rows = await this.prisma.exercise.findMany({ + where: { + OR: variants.map((v) => ({ + name: { contains: v, mode: 'insensitive' as const }, + })), + }, + select: { id: true, name: true }, + take: 60, + }); + const target = squash(name); + const rank = (e: { id: string; name: string }) => { + if (squash(e.name) === target) return -1000; + const common = COMMON_EXERCISES.indexOf(e.id); + if (common >= 0) return -500 + common; + return (squash(e.name).startsWith(target) ? 0 : 100) + e.name.length; + }; + return rows.sort((a, b) => rank(a) - rank(b))[0] ?? null; + } + + private async named(sets: SpokenSet[]) { + const names = await this.exerciseNames(sets.map((s) => s.exerciseId)); + return sets.map((s) => ({ + ...s, + exerciseName: names.get(s.exerciseId) ?? s.exerciseId, + })); + } + + /** + * For the coach: what's next in the plan and what the rules say about it, + * plus this week's PRs. Empty when there's nothing to say. + */ + async coachLines( + user: { id: string; supabaseId: string; weightKg: number | null }, + offset: number, + ): Promise { + const plan = await this.prisma.workoutPlan.findUnique({ + where: { userId: user.id }, + }); + const lines: string[] = []; + const weekAgo = dayRange(addDays(localToday(offset), -7), offset).start; + const prs = await this.prisma.workoutSet.findMany({ + where: { + userId: user.id, + pr: { not: null }, + session: { startedAt: { gte: weekAgo } }, + }, + select: { exerciseId: true, reps: true, weightKg: true }, + take: 5, + }); + if (prs.length) { + const names = await this.exerciseNames(prs.map((p) => p.exerciseId)); + lines.push( + `- PRs this week: ${prs.map((p) => `${names.get(p.exerciseId)} ${p.weightKg ? `${p.weightKg} kg × ${p.reps}` : `${p.reps} reps`}`).join('; ')}`, + ); + } + const days = trainingDays<{ + rest: boolean; + title: string; + exercises: { exerciseId?: string; detail: string }[]; + }>(plan?.days); + if (!plan || !days.length) return lines; + const n = Math.min(Math.max(plan.nextSession, 1), days.length); + const next = days[n - 1]; + const items = next.exercises.filter((e) => e.exerciseId).slice(0, 8); + if (!items.length) return lines; + const prepared = await this.prepare( + user.supabaseId, + { + exercises: items.map((e) => ({ + exerciseId: e.exerciseId!, + detail: e.detail, + })), + }, + offset, + ).catch(() => null); + if (!prepared) return lines; + lines.push( + `- Next up in their plan: session ${n} of ${days.length}, "${next.title}"`, + ); + for (const e of prepared.exercises) { + if (!e.suggestion || e.suggestion.action === 'start') continue; + const w = e.suggestion.weightKg + ? `${e.suggestion.weightKg} kg` + : 'bodyweight'; + lines.push( + `- ${e.name}: ${e.suggestion.action} → ${w} × ${e.suggestion.reps}. ${e.suggestion.reasons.join(' ')}`, + ); + } + return lines; + } +}