Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ grit/
| `/onboarding/age` | Age (scroll picker) |
| `/onboarding/body` | Height + weight |
| `/onboarding/activity` | Activity level selection |
| `/onboarding/wellbeing` | One private question about eating disorders; "yes" turns off weight-loss goals |
| `/onboarding/goal` | Primary goal + desired weight |
| `/onboarding/pace` | Pace selection with live calorie preview |
| `/onboarding/friction` | Biggest obstacle (used for AI coach context) |
Expand All @@ -47,12 +48,14 @@ grit/
| `/settings/goals` | Goals & Targets — goal, body stats, calories, macros, earnback/rollover |
| `/settings/notifications` | Daily reminders and alert preferences |
| `/settings/account` | Appearance (system, light, dark), units, password reset, log out, delete account |
| `/settings/privacy` | Private account and blocked people |
| `/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/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 |
| `/plan` | Weekly workout plan built by the coach from the exercise library |
| `/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 |
Expand Down Expand Up @@ -111,13 +114,14 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS).
| Module | Routes |
|---|---|
| `auth` | Guard that verifies Supabase access tokens, `POST /auth/sync` |
| `users` | `GET/PUT/DELETE /users/me` (delete removes the account and its Supabase sign-in) |
| `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` |
| `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` |
| `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`, `PUT /workout-plan/days/:day` |
| `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 |
| `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` |
Expand All @@ -126,10 +130,12 @@ 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
**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · CoachMemory · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood · FoodMemory · HealthDay · SearchEvent · Exercise

See [`docs/ROADMAP.md`](./docs/ROADMAP.md) for what's done and what's next.

AI features (Smart log, the coach, plan building) need the user's consent first and return `403 { code: "ai_consent_required" }` without it; see [`docs/TRUST_AND_SAFETY.md`](./docs/TRUST_AND_SAFETY.md).

Requests send an `x-utc-offset` header (minutes ahead of UTC) so days and weeks follow the user's local time. Row level security is enabled on every table; only the API reads and writes them.

### Run
Expand Down
4 changes: 4 additions & 0 deletions apps/mobile/__tests__/tdee.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ describe('calorie maths', () => {
expect(calcAdjustedCalories(2500, 'build_muscle', 'slow')).toBe(2775);
expect(calcAdjustedCalories(2500, 'maintain', 'aggressive')).toBe(2500);
expect(calcAdjustedCalories(1500, 'lose_weight', 'aggressive')).toBe(1200);
// A man's floor is 1,500
expect(calcAdjustedCalories(1700, 'lose_weight', 'aggressive', { gender: 'male' })).toBe(1500);
// Aggressive (1 kg a week) is capped at 1% of a 60 kg person's weight: 660 kcal a day
expect(calcAdjustedCalories(2500, 'lose_weight', 'aggressive', { weightKg: 60 })).toBe(1840);
});

it('macro splits match the backend', () => {
Expand Down
30 changes: 29 additions & 1 deletion apps/mobile/app/(tabs)/food.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import { confirmAction } from '@/lib/confirm';
import { DateNavigator } from '@/components/ui/DateNavigator';
import { EditFoodSheet } from '@/components/food/EditFoodSheet';
import { SmartLogSheet } from '@/components/food/SmartLogSheet';
import { DRINKS } from '@/lib/drinks';
import { useEnsureAiConsent } from '@/hooks/useAiConsent';
import { useMe } from '@/hooks/useMe';
import { ErrorNotice, useQueriesStatus } from '@/components/ui/QueryStatus';
import { ScreenSkeleton } from '@/components/ui/Skeleton';
Expand Down Expand Up @@ -106,6 +108,7 @@ export default function FoodScreen() {
const { refreshing, onRefresh } = usePullToRefresh([['food-logs', date], ['me'], ['food-recent'], ['food-favorites']]);
const [editingLog, setEditingLog] = useState<FoodLog | null>(null);
const [smartOpen, setSmartOpen] = useState(false);
const ensureAiConsent = useEnsureAiConsent();
const [selectedFood, setSelectedFood] = useState<NormalizedFood | null>(null);
const [selectedMeal, setSelectedMeal] = useState<(typeof MEAL_ORDER)[number] | undefined>();

Expand Down Expand Up @@ -135,6 +138,8 @@ export default function FoodScreen() {
const proteinG = data?.totals?.proteinG ?? 0;
const carbsG = data?.totals?.carbsG ?? 0;
const fatG = data?.totals?.fatG ?? 0;
const caffeineMg = Math.round(data?.totals?.caffeineMg ?? 0);
const alcoholG = Math.round(data?.totals?.alcoholG ?? 0);

// Targets follow the goal focus chosen in onboarding (from the backend)
const fallback = calcMacros(calorieGoal, me?.goalFocus);
Expand Down Expand Up @@ -180,7 +185,7 @@ export default function FoodScreen() {
<Text style={{ color: Colors.text, fontFamily: 'DMSans-Bold', fontSize: 28, letterSpacing: -0.5 }}>Food</Text>
<View style={{ flexDirection: 'row', gap: 8 }}>
<Pressable accessibilityLabel="Smart log: describe or photograph a meal" accessibilityRole="button"
onPress={() => setSmartOpen(true)}
onPress={async () => { if (await ensureAiConsent()) setSmartOpen(true); }}
style={({ pressed }) => ({
opacity: pressed ? 0.7 : 1,
height: 40, borderRadius: 12, paddingHorizontal: 12,
Expand Down Expand Up @@ -256,13 +261,36 @@ export default function FoodScreen() {
<Text style={{ fontSize: 11, color: Colors.muted, fontFamily: 'DMSans-Regular', marginTop: 2 }}>
{Math.round(Math.max(0, calorieGoal - eaten))} kcal remaining
</Text>
{(caffeineMg > 0 || alcoholG > 0) && (
<Text style={{ fontSize: 11, color: Colors.muted, fontFamily: 'DMSans-Regular' }} accessibilityLabel={`${caffeineMg} milligrams of caffeine and ${alcoholG} grams of alcohol today`}>
{caffeineMg > 0 ? `☕ ${caffeineMg} mg caffeine` : ''}
{caffeineMg > 0 && alcoholG > 0 ? ' · ' : ''}
{alcoholG > 0 ? `🍷 ${alcoholG} g alcohol` : ''}
</Text>
)}
</View>
</View>
</View>

{/* Search bar */}
<FoodSearchBar onSelect={(food) => { setSelectedMeal(undefined); setSelectedFood(food); }} />

{/* Quick drinks: coffee, tea, beer, wine */}
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 8, paddingVertical: 10 }} keyboardShouldPersistTaps="handled">
{DRINKS.map((d) => (
<Pressable
key={d.food.name}
onPress={() => { setSelectedMeal('snack'); setSelectedFood(d.food); }}
accessibilityRole="button"
accessibilityLabel={`Log ${d.food.name}`}
style={{ flexDirection: 'row', alignItems: 'center', gap: 5, paddingHorizontal: 12, paddingVertical: 7, borderRadius: 999, backgroundColor: Colors.surface, borderWidth: 1, borderColor: Colors.border }}
>
<Text style={{ fontSize: 13 }}>{d.emoji}</Text>
<Text style={{ color: Colors.text, fontFamily: 'DMSans-Medium', fontSize: 13 }}>{d.food.name}</Text>
</Pressable>
))}
</ScrollView>

{/* Recent and favourite foods */}
<QuickAddCard
onPick={(food, meal) => {
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/app/(tabs)/profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ function EditSheet({ user, onClose }: { user: BackendUser; onClose: () => void }
const SETTINGS_ROWS = [
{ icon: '🎯', color: 'orange' as const, label: 'Goals & Targets', sub: 'Calories, macros and weight goal', href: '/settings/goals' as const },
{ icon: '🏋️', color: 'teal' as const, label: 'Workout Plan', sub: 'Your weekly plan from the coach', href: '/plan' as const },
{ icon: '📚', color: 'blue' as const, label: 'Exercise library', sub: 'How to do 800+ exercises', href: '/exercises' as const },
{ icon: '👥', color: 'orange' as const, label: 'Friends', sub: 'Find people, requests and followers', href: '/friends' as const },
{ icon: '🔒', color: 'blue' as const, label: 'Privacy', sub: 'Private account and blocked people', href: '/settings/privacy' as const },
{ icon: '❤️', color: 'error' as const, label: Platform.OS === 'android' ? 'Health Connect' : Platform.OS === 'ios' ? 'Apple Health' : 'Health data', sub: 'Sync workouts, steps, sleep and weight', href: '/settings/health' as const },
Expand Down
6 changes: 6 additions & 0 deletions apps/mobile/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import { Toast } from '@/components/ui/Toast';
import { Colors, applyColorScheme } from '@/constants/colors';
import { useThemeStore } from '@/stores/themeStore';
import { OfflineBanner } from '@/components/ui/OfflineBanner';
import { AiConsentSheet } from '@/components/ui/AiConsentSheet';
import { ProfileGate } from '@/components/ProfileGate';
import { CrashScreen } from '@/components/ui/CrashScreen';
import { installGlobalCrashHandler, setCrashScreen } from '@/lib/crashReporter';

Expand Down Expand Up @@ -163,9 +165,13 @@ export default function RootLayout() {
<Stack.Screen name="settings/privacy" />
<Stack.Screen name="settings/health" />
<Stack.Screen name="notifications" />
<Stack.Screen name="exercises" />
<Stack.Screen name="welcome-check" options={{ gestureEnabled: false }} />
</Stack>
<Toast />
<OfflineBanner />
<AiConsentSheet />
{session && <ProfileGate />}
</GestureHandlerRootView>
</QueryClientProvider>
);
Expand Down
23 changes: 20 additions & 3 deletions apps/mobile/app/coach.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import { router } from 'expo-router';
import * as Haptics from 'expo-haptics';
import { useAIMessages, useStreamMessage } from '@/hooks/useAICoach';
import { useEnsureAiConsent } from '@/hooks/useAiConsent';
import { useMe } from '@/hooks/useMe';
import { ErrorNotice } from '@/components/ui/QueryStatus';
import { ChatBubble } from '@/components/coach/ChatBubble';
import { Colors } from '@/constants/colors';
Expand All @@ -27,13 +29,27 @@
const [streamingContent, setStreamingContent] = useState('');
const scrollRef = useRef<ScrollView>(null);
const pendingNote = useRef<string | null>(null);
const ensureAiConsent = useEnsureAiConsent();
const { data: me } = useMe();

// Ask before the first chat; without permission there's nothing to show here
const asked = useRef(false);
useEffect(() => {
if (!me || me.aiConsentAt || asked.current) return;
asked.current = true;
ensureAiConsent().then((ok) => {
if (ok) return;
if (router.canGoBack()) router.back();
else router.replace('/(tabs)/');
});
}, [me, ensureAiConsent]);

// Sync history into local messages once loaded
useEffect(() => {
if (history && localMessages.length === 0) {
setLocalMessages(history.map((m) => ({ id: m.id, role: m.role, content: m.content })));
}
}, [history]);

Check warning on line 52 in apps/mobile/app/coach.tsx

View workflow job for this annotation

GitHub Actions / Mobile

React Hook useEffect has a missing dependency: 'localMessages.length'. Either include it or remove the dependency array

function scrollToBottom() {
setTimeout(() => scrollRef.current?.scrollToEnd({ animated: true }), 50);
Expand All @@ -42,6 +58,7 @@
async function handleSend() {
const text = input.trim();
if (!text || isStreaming) return;
if (!(await ensureAiConsent())) return;

Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
setInput('');
Expand Down Expand Up @@ -121,7 +138,7 @@
GRIT Coach
</Text>
<Text style={{ color: Colors.muted, fontFamily: 'DMSans-Regular', fontSize: 12 }}>
10 messages / day
AI coach · 10 messages / day
</Text>
</View>
<Pressable
Expand Down Expand Up @@ -154,13 +171,13 @@
<View style={{ alignItems: 'center', marginTop: 60, gap: 12 }}>
<Text style={{ fontSize: 40 }}>🤖</Text>
<Text style={{ color: Colors.text, fontFamily: 'DMSans-Bold', fontSize: 18 }}>
Hey, I'm your GRIT Coach
Hey, I'm GRIT's AI coach
</Text>
<Text style={{
color: Colors.muted, fontFamily: 'DMSans-Regular',
fontSize: 14, textAlign: 'center', lineHeight: 22,
}}>
Ask me anything about your nutrition, activity, or habits. I have your data.
Ask me anything about your nutrition, activity, or habits. I can see your logs. I'm an AI, not a doctor or dietitian, so I can make mistakes.
</Text>
</View>
) : (
Expand Down
80 changes: 80 additions & 0 deletions apps/mobile/app/exercises.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import React, { useState } from 'react';
import { View, Text, TextInput, FlatList, Pressable, Image, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ScreenHeader, ChipGroup } from '@/components/settings/SettingsUI';
import { ErrorNotice } from '@/components/ui/QueryStatus';
import { ExerciseSheet } from '@/components/exercises/ExerciseSheet';
import { useExerciseSearch, type Exercise } from '@/hooks/useExercises';
import { Colors } from '@/constants/colors';

const EQUIPMENT = [
{ value: '', label: 'Any' },
{ value: 'bodyweight', label: 'Bodyweight' },
{ value: 'dumbbell', label: 'Dumbbell' },
{ value: 'barbell', label: 'Barbell' },
{ value: 'kettlebell', label: 'Kettlebell' },
{ value: 'machine', label: 'Machine' },
{ value: 'cable', label: 'Cable' },
{ value: 'band', label: 'Band' },
];

/** The exercise library: search by name and filter by equipment. */
export default function ExercisesScreen() {
const [q, setQ] = useState('');
const [equipment, setEquipment] = useState('');
const [open, setOpen] = useState<string | null>(null);
const { data, isLoading, isError, refetch } = useExerciseSearch(q, { equipment: equipment || undefined });

const renderItem = ({ item }: { item: Exercise }) => (
<Pressable
onPress={() => setOpen(item.id)}
accessibilityRole="button"
accessibilityLabel={item.name}
style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: Colors.border }}
>
{item.imageUrl ? (
<Image source={{ uri: item.imageUrl }} style={{ width: 52, height: 52, borderRadius: 10, backgroundColor: Colors.surface2 }} />
) : (
<View style={{ width: 52, height: 52, borderRadius: 10, backgroundColor: Colors.surface2 }} />
)}
<View style={{ flex: 1, gap: 2 }}>
<Text style={{ color: Colors.text, fontFamily: 'DMSans-Bold', fontSize: 15 }}>{item.name}</Text>
<Text style={{ color: Colors.muted, fontFamily: 'DMSans-Regular', fontSize: 12, textTransform: 'capitalize' }}>
{item.primary.join(', ')} · {item.equipment.join(', ')}
</Text>
</View>
</Pressable>
);

return (
<SafeAreaView edges={['top']} style={{ flex: 1, backgroundColor: Colors.dark }}>
<ScreenHeader title="Exercise library" />
<View style={{ paddingHorizontal: 20, gap: 12, flex: 1 }}>
<TextInput
value={q}
onChangeText={setQ}
placeholder="Search exercises"
placeholderTextColor={Colors.muted}
accessibilityLabel="Search exercises"
style={{ backgroundColor: Colors.surface, borderRadius: 14, paddingHorizontal: 16, paddingVertical: 12, color: Colors.text, fontFamily: 'DMSans-Regular', fontSize: 15, borderWidth: 1, borderColor: Colors.border }}
/>
<ChipGroup options={EQUIPMENT} value={equipment} onChange={setEquipment} />
{isError && !data ? (
<ErrorNotice what="the exercise library" onRetry={() => refetch()} />
) : isLoading ? (
<ActivityIndicator color={Colors.orange} style={{ marginTop: 20 }} />
) : (
<FlatList
data={data ?? []}
keyExtractor={(e) => e.id}
renderItem={renderItem}
keyboardShouldPersistTaps="handled"
contentContainerStyle={{ paddingBottom: 40 }}
ListEmptyComponent={<Text style={{ color: Colors.muted, fontFamily: 'DMSans-Regular', fontSize: 14, marginTop: 20 }}>No exercises match.</Text>}
/>
)}
</View>
<ExerciseSheet id={open} onClose={() => setOpen(null)} />
</SafeAreaView>
);
}
Loading
Loading