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
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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 |
Expand Down Expand Up @@ -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` |
Expand All @@ -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.

Expand Down
43 changes: 42 additions & 1 deletion apps/mobile/__tests__/healthTransform.test.ts
Original file line number Diff line number Diff line change
@@ -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);

Expand Down Expand Up @@ -47,11 +47,52 @@ 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 },
]);
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 }]);
});
});
45 changes: 45 additions & 0 deletions apps/mobile/__tests__/strength.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
16 changes: 13 additions & 3 deletions apps/mobile/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}
],
Expand Down
53 changes: 48 additions & 5 deletions apps/mobile/app/(tabs)/activity.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 (
<View style={{ backgroundColor: Colors.surface, borderRadius: 16, borderWidth: 1, borderColor: Colors.border, padding: 14, marginBottom: 12, gap: 8 }} accessibilityLiveRegion="polite">
{pending.map((p) => (
<View key={p.body.clientId} style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
<Text style={{ flex: 1, color: p.error ? Colors.error : Colors.muted, fontFamily: 'DMSans-Medium', fontSize: 13 }}>
{p.body.title || 'Workout'}: {p.error ? `not saved (${p.error})` : online ? 'saving…' : "waiting for a connection. It's safe on your phone."}
</Text>
{!!p.error && (
<Pressable onPress={() => retryWorkout(p.body.clientId)} accessibilityRole="button">
<Text style={{ color: Colors.orange, fontFamily: 'DMSans-Bold', fontSize: 13 }}>Retry</Text>
</Pressable>
)}
</View>
))}
</View>
);
}

export default function ActivityScreen() {
const startWorkout = useStartWorkout();
const today = localDateStr();
const thisWeek = weekStartStr(today);
const [week, setWeek] = useState(thisWeek);
Expand Down Expand Up @@ -278,8 +310,17 @@ export default function ActivityScreen() {
>
<Text style={{ color: '#fff', fontFamily: 'DMSans-Bold', fontSize: 14 }}>+ Log workout</Text>
</Pressable>
<Pressable
accessibilityRole="button"
onPress={() => startWorkout()}
style={({ pressed }) => ({ marginTop: 8, borderRadius: 999, paddingVertical: 11, alignItems: 'center', borderWidth: 1.5, borderColor: Colors.orange, opacity: pressed ? 0.7 : 1 })}
>
<Text style={{ color: Colors.orange, fontFamily: 'DMSans-Bold', fontSize: 14 }}>Start a strength workout</Text>
</Pressable>
</View>

<PendingWorkouts />

{/* Workouts logged this week: tap to edit or delete */}
<View style={{ backgroundColor: Colors.surface, borderRadius: 20, borderWidth: 1, borderColor: Colors.border, padding: 18, marginBottom: 12, gap: 12 }}>
<Text style={{ color: Colors.text, fontFamily: 'DMSans-Bold', fontSize: 16 }}>Workouts</Text>
Expand All @@ -291,18 +332,20 @@ export default function ActivityScreen() {
[...(weekly?.logs ?? [])].reverse().map((log) => (
<Pressable
key={log.id}
onPress={() => 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 })}
>
<View style={{ flex: 1 }}>
<Text style={{ color: Colors.text, fontFamily: 'DMSans-Medium', fontSize: 14 }}>
{ACTIVITY_LABELS[log.activityType] ?? log.activityType}
{log.workoutSession?.title || ACTIVITY_LABELS[log.activityType] || log.activityType}
</Text>
<Text style={{ color: Colors.muted, fontFamily: 'DMSans-Regular', fontSize: 12, marginTop: 1 }}>
{dayLabel(localDateStr(new Date(log.loggedAt)), today)} · {log.durationMin} min
{log.workoutSession?.setCount ? ` · ${log.workoutSession.setCount} sets` : ''}
{log.workoutSession?.prCount ? ` · 🏆 ${log.workoutSession.prCount}` : ''}
</Text>
</View>
<Text style={{ color: Colors.teal, fontFamily: 'JetBrainsMono-Regular', fontSize: 14 }}>
Expand Down
Loading
Loading