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
26 changes: 16 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# GRIT

A full-stack fitness and nutrition tracking app for people serious about body composition. GRIT combines macro tracking, habit building, activity logging, social challenges, and an AI coach into a single opinionated dark-mode mobile experience.
A full-stack fitness and nutrition tracking app for people serious about body composition. GRIT combines macro tracking, habit building, activity logging, social challenges, and an AI coach into a single opinionated mobile experience, in dark or light.

---

Expand Down Expand Up @@ -36,18 +36,22 @@ grit/
| `/onboarding/advanced` | Earnback calories toggle, rollover toggle |
| `/onboarding/notifications` | Notification preferences |
| `/onboarding/reveal` | Personalised TDEE + macro plan reveal |
| `/onboarding/signup` | Account creation (email + password) |
| `/(auth)/login` | Returning user login |
| `/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)/food` | Food log — any day, meal sections, edit entries, barcode scanner |
| `/(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 — 7D/30D/3M trends for calories, protein, activity and weight, then any week's workouts |
| `/(tabs)/activity` | Stats — adaptive calorie target, 7D/30D/3M trends for calories, protein, activity and weight, then any week's workouts |
| `/(tabs)/social` | Feed, challenges and leaderboard |
| `/(tabs)/profile` | User profile + settings |
| `/settings/goals` | Goals & Targets — goal, body stats, calories, macros, earnback/rollover |
| `/settings/notifications` | Daily reminders and alert preferences |
| `/settings/account` | Units, password reset, log out, delete account |
| `/settings/account` | Appearance (system, light, dark), units, password reset, log out, delete account |
| `/settings/privacy` | Private account and blocked people |
| `/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 |
| `/friends` | Search people, follow requests, followers and following |
| `/profile/[id]` | Someone's profile: follow state, this week's stats and recent activity (if allowed) |
Expand Down Expand Up @@ -107,18 +111,20 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS).
| `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` |
| `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` |
| `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` |
| `ai` | `POST /ai/message` (streamed), `GET /ai/messages`, `GET /ai/nudge` — AI coach |
| `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` |
| `ai` | `POST /ai/message` (streamed), `GET /ai/messages`, `GET /ai/nudge`, `GET/POST/DELETE /ai/memories`, `DELETE /ai/memories/:id` — AI coach and its notes |
| `notifications` | `GET /notifications`, `GET /notifications/unread-count`, `POST /notifications/read`, `POST/DELETE /notifications/register` (one row per phone), Expo push sending |
| `app` | `GET /health`, `POST /client-errors` (crash reports from the app, no sign-in, throttled) |
| `alerts` | Hourly job: challenge results, 8pm streak-at-risk and Sunday 6pm weekly check-in, in each user's local time |
| `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 · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood
**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · CoachMemory · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood · FoodMemory · HealthDay

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

Expand Down
57 changes: 57 additions & 0 deletions apps/mobile/__tests__/healthTransform.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { androidExerciseType, appleWorkoutType, latestWeightPerDay, sleepByNight, toImportPayload } from '@/lib/health/transform';

const at = (iso: string) => new Date(iso);

describe('health transform', () => {
it('maps workout types from both platforms', () => {
expect(appleWorkoutType(37)).toBe('running');
expect(appleWorkoutType(50)).toBe('strength_training');
expect(appleWorkoutType(9999)).toBe('other');
expect(androidExerciseType(79)).toBe('walking');
expect(androidExerciseType(54)).toBe('rowing');
expect(androidExerciseType(-1)).toBe('other');
});

it('counts overlapping sleep once and removes awake time', () => {
const nights = sleepByNight([
// Phone and watch both recorded 23:00–07:00
{ start: at('2026-11-03T23:00:00'), end: at('2026-11-04T07:00:00'), asleep: true },
{ start: at('2026-11-04T00:00:00'), end: at('2026-11-04T06:30:00'), asleep: true },
// 30 minutes awake in the middle
{ start: at('2026-11-04T03:00:00'), end: at('2026-11-04T03:30:00'), asleep: false },
]);
expect(nights).toEqual({ '2026-11-04': 450 });
});

it('keeps the last weigh-in of each day and drops silly values', () => {
expect(
latestWeightPerDay([
{ at: at('2026-11-04T07:00:00'), kg: 80.2 },
{ at: at('2026-11-04T20:00:00'), kg: 80.9 },
{ at: at('2026-11-03T07:00:00'), kg: 81 },
{ at: at('2026-11-02T07:00:00'), kg: 2 },
]),
).toEqual([
{ date: '2026-11-03', weightKg: 81 },
{ date: '2026-11-04', weightKg: 80.9 },
]);
});

it('builds the import body, merging steps and sleep per day', () => {
const now = at('2026-11-04T12:00:00');
const body = toImportPayload('healthkit', {
workouts: [
{ id: 'hk:1', activityType: 'running', start: at('2026-11-04T07:00:00'), end: at('2026-11-04T07:32:30'), kcal: 310.6 },
{ id: 'hk:future', activityType: 'yoga', start: at('2026-11-05T07:00:00'), end: at('2026-11-05T08:00:00') },
],
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 }],
}, now);
expect(body.workouts).toEqual([
{ externalId: 'hk:1', activityType: 'running', startedAt: at('2026-11-04T07:00:00').toISOString(), durationMin: 33, caloriesBurned: 311 },
]);
expect(body.days).toEqual([{ date: '2026-11-04', steps: 6400, sleepMinutes: 420 }]);
expect(body.weights).toEqual([{ date: '2026-11-04', weightKg: 80.21 }]);
});
});
3 changes: 3 additions & 0 deletions apps/mobile/__tests__/notificationRoute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ describe('where an alert opens', () => {
expect(notificationRoute('challenge_ended', { challengeId: 'c1' })).toEqual({ pathname: '/challenge/[id]', params: { id: 'c1' } });
expect(notificationRoute('streak_at_risk')).toBe('/(tabs)/habits');
expect(notificationRoute('weekly_progress')).toBe('/(tabs)/activity');
expect(notificationRoute('coach_checkin', { screen: 'food' })).toBe('/(tabs)/food');
expect(notificationRoute('coach_checkin', { screen: 'stats' })).toBe('/(tabs)/activity');
expect(notificationRoute('coach_checkin', {})).toBe('/coach');
});
it('falls back to the inbox when ids are missing or the type is unknown', () => {
expect(notificationRoute('follow')).toBe('/notifications');
Expand Down
9 changes: 9 additions & 0 deletions apps/mobile/__tests__/smartLog.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { mealForHour } from '@/lib/meals';

describe('mealForHour', () => {
it('picks the meal for the time of day', () => {
expect([6, 10, 11, 14, 15, 16, 17, 21, 22, 2].map(mealForHour)).toEqual([
'breakfast', 'breakfast', 'lunch', 'lunch', 'snack', 'snack', 'dinner', 'dinner', 'snack', 'snack',
]);
});
});
35 changes: 30 additions & 5 deletions apps/mobile/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scheme": "grit",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "dark",
"userInterfaceStyle": "automatic",
"splash": {
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
Expand Down Expand Up @@ -57,7 +57,11 @@
"foregroundImage": "./assets/android-icon-foreground.png"
},
"permissions": [
"android.permission.CAMERA"
"android.permission.CAMERA",
"android.permission.health.READ_EXERCISE",
"android.permission.health.READ_STEPS",
"android.permission.health.READ_WEIGHT",
"android.permission.health.READ_SLEEP"
],
"blockedPermissions": [
"android.permission.RECORD_AUDIO"
Expand All @@ -74,7 +78,7 @@
[
"expo-camera",
{
"cameraPermission": "GRIT uses your camera to scan food barcodes.",
"cameraPermission": "GRIT uses your camera to scan food barcodes and photograph meals.",
"microphonePermission": false,
"recordAudioAndroid": false
}
Expand All @@ -90,10 +94,31 @@
[
"expo-image-picker",
{
"photosPermission": "GRIT uses your photos so you can choose a profile picture.",
"cameraPermission": false,
"photosPermission": "GRIT uses your photos so you can choose a profile picture or log a meal from a photo.",
"cameraPermission": "GRIT uses your camera to photograph meals so it can estimate what's in them.",
"microphonePermission": false
}
],
"expo-apple-authentication",
"expo-web-browser",
[
"@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,
"background": false
}
],
"react-native-health-connect",
[
"expo-build-properties",
{
"android": {
"compileSdkVersion": 36,
"targetSdkVersion": 36,
"minSdkVersion": 26
}
}
]
],
"extra": {
Expand Down
52 changes: 9 additions & 43 deletions apps/mobile/app/(auth)/login.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@
import React, { useState } from 'react';
import {
View,
Platform,
Text,
KeyboardAvoidingView,
Platform,
ScrollView,
Pressable,
Alert,
} from 'react-native';
import { Link, router } from 'expo-router';
import { supabase } from '@/lib/supabase';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/authStore';
import { syncOnboardingProfile } from '@/lib/onboardingProfile';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { notify } from '@/lib/confirm';
import { sendPasswordReset } from '@/lib/passwordReset';
import { Colors } from '@/constants/colors';
import { afterSignIn } from '@/lib/postSignIn';
import { SocialSignIn } from '@/components/auth/SocialSignIn';

export default function LoginScreen() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const { setOnboardingComplete } = useAuthStore();

async function handleEmailLogin() {
if (!email || !password) {
Expand All @@ -32,15 +30,11 @@ export default function LoginScreen() {
}
setLoading(true);
try {
const { error } = await supabase.auth.signInWithPassword({ email, password });
const { data, error } = await supabase.auth.signInWithPassword({ email, password });
if (error) throw error;
await setOnboardingComplete();
// Sync user record with backend (creates if first login)
await api.post('/auth/sync');
// Save any plan answered before signing up (e.g. pending email confirmation)
await syncOnboardingProfile().catch(() => {
// Kept on the device and retried at the next login
});
// Creates the backend user on first login and saves any plan answered
// before signing up (e.g. while the email was being confirmed)
await afterSignIn(data.session);
router.replace('/(tabs)/');
} catch (err: any) {
Alert.alert('Login failed', err.message ?? 'Something went wrong.');
Expand Down Expand Up @@ -126,36 +120,8 @@ export default function LoginScreen() {
/>
</View>

{/* Divider */}
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 12 }}>
<View style={{ flex: 1, height: 1, backgroundColor: Colors.border }} />
<Text style={{ color: Colors.muted, fontFamily: 'DMSans-Regular', fontSize: 13 }}>
or
</Text>
<View style={{ flex: 1, height: 1, backgroundColor: Colors.border }} />
</View>

{/* OAuth */}
<View style={{ gap: 12 }}>
<Button
label="Continue with Google"
variant="secondary"
onPress={() => {
// TODO Phase A+: implement Google OAuth via expo-auth-session
Alert.alert('Coming soon', 'Google sign-in coming soon.');
}}
/>
{Platform.OS === 'ios' && (
<Button
label="Continue with Apple"
variant="secondary"
onPress={() => {
// TODO Phase A+: implement Apple Sign-In via expo-apple-authentication
Alert.alert('Coming soon', 'Apple sign-in coming soon.');
}}
/>
)}
</View>
{/* Google and Apple, once switched on in Supabase */}
<SocialSignIn />

{/* Sign up link */}
<View style={{ flexDirection: 'row', justifyContent: 'center', gap: 6 }}>
Expand Down
6 changes: 5 additions & 1 deletion apps/mobile/app/(tabs)/activity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ScreenSkeleton } from '@/components/ui/Skeleton';
import { ACTIVITY_LABELS, LogActivitySheet } from '@/components/activity/LogActivitySheet';
import { DateNavigator } from '@/components/ui/DateNavigator';
import { TrendsCard } from '@/components/stats/TrendsCard';
import { AdaptiveCard } from '@/components/stats/AdaptiveCard';
import { LogWeightSheet } from '@/components/stats/LogWeightSheet';
import { usePullToRefresh } from '@/hooks/usePullToRefresh';
import { Colors } from '@/constants/colors';
Expand Down Expand Up @@ -96,7 +97,7 @@ export default function ActivityScreen() {
const { data: habitSummary } = useHabitSummary();
const [showSheet, setShowSheet] = useState(false);
const [showWeight, setShowWeight] = useState(false);
const { refreshing, onRefresh } = usePullToRefresh([['activity-week'], ['food-week'], ['me'], ['habits'], ['habit-streaks'], ['trends'], ['weight']]);
const { refreshing, onRefresh } = usePullToRefresh([['activity-week'], ['food-week'], ['me'], ['habits'], ['habit-streaks'], ['trends'], ['weight'], ['adaptive']]);

useFocusEffect(
React.useCallback(() => {
Expand Down Expand Up @@ -154,6 +155,9 @@ export default function ActivityScreen() {
</Text>
</View>

{/* What you actually burn, and a suggested target */}
<AdaptiveCard unit={me?.weightUnit ?? 'kg'} />

{/* Longer-range trends and weight */}
<TrendsCard unit={me?.weightUnit ?? 'kg'} onLogWeight={() => setShowWeight(true)} />

Expand Down
16 changes: 16 additions & 0 deletions apps/mobile/app/(tabs)/food.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { addDaysStr, dayLabel, localDateStr } from '@/lib/date';
import { confirmAction } from '@/lib/confirm';
import { DateNavigator } from '@/components/ui/DateNavigator';
import { EditFoodSheet } from '@/components/food/EditFoodSheet';
import { SmartLogSheet } from '@/components/food/SmartLogSheet';
import { useMe } from '@/hooks/useMe';
import { ErrorNotice, useQueriesStatus } from '@/components/ui/QueryStatus';
import { ScreenSkeleton } from '@/components/ui/Skeleton';
Expand Down Expand Up @@ -104,6 +105,7 @@ export default function FoodScreen() {
const { data: me } = useMe();
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 [selectedFood, setSelectedFood] = useState<NormalizedFood | null>(null);
const [selectedMeal, setSelectedMeal] = useState<(typeof MEAL_ORDER)[number] | undefined>();

Expand Down Expand Up @@ -177,6 +179,19 @@ export default function FoodScreen() {
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, paddingTop: 6 }}>
<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)}
style={({ pressed }) => ({
opacity: pressed ? 0.7 : 1,
height: 40, borderRadius: 12, paddingHorizontal: 12,
backgroundColor: Colors.surface,
borderWidth: 1, borderColor: `${Colors.orange}80`,
flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 4,
})}
>
<Text style={{ fontSize: 15 }}>✨</Text>
<Text style={{ color: Colors.orange, fontFamily: 'DMSans-Bold', fontSize: 13 }}>Smart log</Text>
</Pressable>
<Pressable accessibilityLabel="Scan a barcode" accessibilityRole="button"
onPress={() => router.push('/barcode-scanner' as never)}
style={({ pressed }) => ({
Expand Down Expand Up @@ -333,6 +348,7 @@ export default function FoodScreen() {
{selectedFood && (
<LogFoodSheet food={selectedFood} initialMeal={selectedMeal} date={date} onClose={() => setSelectedFood(null)} />
)}
{smartOpen && <SmartLogSheet date={date} onClose={() => setSmartOpen(false)} />}
{editingLog && <EditFoodSheet key={editingLog.id} log={editingLog} onClose={() => setEditingLog(null)} />}
</SafeAreaView>
);
Expand Down
Loading
Loading