This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
FamilyLifeHub is a self-hosted family life data hub for tracking and analyzing health and work metrics. The system uses a FastAPI backend with SQLite and a Next.js 14 frontend with TypeScript and Tailwind CSS.
此项目使用自定义 SSH 密钥进行 GitHub 认证。推送时必须指定密钥文件:
# Windows CMD
set GIT_SSH_COMMAND=ssh -i "C:\Users\guopengwei\.ssh\id_rsa_github" && git push origin master
# Windows PowerShell
$env:GIT_SSH_COMMAND='ssh -i "C:\Users\guopengwei\.ssh\id_rsa_github"'; git push origin master
# Git Bash / WSL
GIT_SSH_COMMAND='ssh -i /c/Users/guopengwei/.ssh/id_rsa_github' git push origin master# Start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
# Rebuild containers
docker-compose build --no-cachecd backend
# Setup virtual environment (first time)
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
# Run backend server
python main.py # Runs on http://localhost:8000
# Access API documentation
# http://localhost:8000/docs (Swagger UI)cd frontend
# Install dependencies (first time)
npm install
# Run development server
npm run dev # Runs on http://localhost:3000
# Build for production
npm run build
# Run production build
npm start
# Lint code
npm run lintThe backend follows a layered architecture pattern:
main.py: Application entry point, FastAPI app initialization, CORS configuration, and router registrationapp/core/: Core infrastructureconfig.py: Environment configuration using Pydantic settingsdatabase.py: SQLAlchemy engine, session management, andget_db()dependencysecurity.py: API key authentication viaX-API-Keyheader
app/models/: SQLAlchemy ORM models (User, HealthMetric, WorkMetric)app/schemas/: Pydantic schemas for request validation and response serializationapp/api/v1/: API endpoint routersusers.py: User management (create, list, get by ID)ingest.py: Data ingestion endpoints (health and work metrics)dashboard.py: Dashboard data endpoints (overview, trends)
app/services/: Business logic layerdashboard.py: Data aggregation and calculations for dashboard
The frontend uses Next.js 14 App Router:
app/: Next.js pages and layoutspage.tsx: Main dashboard pagelayout.tsx: Root layout with global stylesglobals.css: Global CSS and Tailwind directives
components/: React componentsoverview-panel.tsx: Today's metrics displaytrend-chart.tsx: Recharts-based trend visualizationui/: Shadcn/ui components (card, etc.)
lib/: Utilities and API clientapi.ts: API client with typed fetch wrappersutils.ts: Utility functions (cn for className merging)
types/: TypeScript type definitionsapi.ts: API response types matching backend schemas
- Data Ingestion: External sources (Garmin, desktop client) → POST to
/api/v1/ingest/*→ SQLAlchemy models → SQLite - Dashboard Display: Frontend → GET
/api/v1/dashboard/*→ Service layer aggregates data → Pydantic schemas → Frontend components - Authentication: Write endpoints require
X-API-Keyheader validated byverify_api_key()dependency
- User: Family members (id, name, avatar, created_at)
- HealthMetric: Daily health data per user (sleep_hours, resting_heart_rate, stress_level, exercise_minutes)
- One record per user per day (upsert on duplicate date)
- WorkMetric: Work activity data per user (screen_time_minutes, focus_score, active_window_category)
- Multiple records per user per day (heartbeat packets from desktop client)
All timestamps are stored in UTC.
IMPORTANT: When working on this project, use the local development setup:
-
Backend: Runs in Python virtual environment at
D:\ai\family_life_hub\backend- Activate:
venv\Scripts\activate - Run:
python main.py - URL:
http://localhost:8000
- Activate:
-
Frontend: Runs in development mode at
D:\ai\family_life_hub\frontend- Run:
npm run dev - URL:
http://localhost:3000
- Run:
-
Docker: NOT used for active development unless explicitly requested
- Docker is only used when deploying to production
This project uses git worktrees for parallel branch development. The main worktree is at D:\ai\family_life_hub, and additional worktrees (like D:\ai\data_details) share the same virtual environment to save space and avoid compatibility issues.
For non-main worktrees, use the provided activation script:
# In the worktree directory (e.g., D:/ai/data_details/backend)
activate_dev.batThis script:
- Activates the virtual environment from the main worktree (
D:\ai\family_life_hub\backend\venv) - Sets
PYTHONPATHto the current worktree's backend directory - Keeps the terminal open for development
Or manually set up:
call D:\ai\family_life_hub\backend\venv\Scripts\activate.bat
set PYTHONPATH=D:\ai\data_details\backend
python main.pyLocated in backend/.env:
DATABASE_URL: SQLite database path (default:sqlite:///./family_life_hub.db)API_KEY: Secret key for write endpoint authenticationALLOWED_ORIGINS: CORS allowed origins (comma-separated)APP_NAME: Application nameDEBUG: Enable debug mode (True/False)
Located in frontend/.env.local:
NEXT_PUBLIC_API_URL: Backend API URL (default:http://localhost:8000)
Use backend/generate_sample_data.py to populate the database with sample data for testing:
cd backend
python generate_sample_data.pyWrite endpoints (POST /api/v1/users, POST /api/v1/ingest/*) require API key authentication:
curl -X POST http://localhost:8000/api/v1/ingest/health \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"user_id": 1, "date": "2024-01-31", "sleep_hours": 7.5}'Read endpoints (GET /api/v1/users, GET /api/v1/dashboard/*) are public.
- Dependency Injection: FastAPI's
Depends()for database sessions and authentication - Service Layer: Business logic separated from API endpoints (see
app/services/) - Schema Validation: Pydantic models for all request/response data
- Upsert Pattern: Health metrics use upsert (update if exists, insert if not) based on user_id + date
- Aggregation: Work metrics are aggregated daily in the service layer (sum screen time, average focus score)
- Define Pydantic schemas in
app/schemas/__init__.py - Create endpoint in appropriate router (
app/api/v1/*.py) - Add business logic to service layer if needed (
app/services/) - Update frontend API client (
frontend/lib/api.ts) - Add TypeScript types (
frontend/types/api.ts)
- Define SQLAlchemy model in
app/models/__init__.py - Create corresponding Pydantic schemas in
app/schemas/__init__.py - Database tables are auto-created on startup via
Base.metadata.create_all() - For production, consider using Alembic migrations
- Update service layer calculations in
app/services/dashboard.py - Update Pydantic response schemas in
app/schemas/__init__.py - Update frontend types in
frontend/types/api.ts - Update React components in
frontend/components/
The SQLite database file is located at backend/family_life_hub.db.
To reset the database:
# Stop services
docker-compose down
# Remove database file
rm backend/family_life_hub.db
# Restart (database will be recreated)
docker-compose up -dCRITICAL: When writing frontend API functions that use fetch() directly (not the fetchAPI wrapper), you MUST:
- Check
res.okorres.statusbefore parsing JSON - Throw a proper error with status code for the caller to handle
Bad pattern (causes silent failures and page refresh loops):
const res = await fetch(url, options);
const response = await res.json() as SomeType; // Fails on 401/400!
return response;Correct pattern:
const res = await fetch(url, options);
if (!res.ok) {
const error = await res.json().catch(() => ({ detail: 'Unknown error' }));
const errorObj = new Error(error.detail || `HTTP ${res.status}`) as any;
errorObj.status = res.status;
throw errorObj;
}
const response = await res.json() as SomeType;
return response;Why this matters: When login fails with 401, the error response is {"detail": "Incorrect email or password"}, not a Token. Without checking res.ok, the code tries to access response.access_token (undefined), stores garbage, then redirects to首页 where the invalid token causes another redirect back to login.
When asked to "restart" the project:
- ALWAYS kill existing processes on ports 3000, 3001, 8000 first
- Then start fresh backend and frontend
- Use:
netstat -ano | grep -E ":3000|:3001|:8000" | awk '{print $5}' | sort -u | xargs -I {} cmd.exe /c "taskkill /F /PID {} 2>nul"
The dashboard supports viewing other family members' data:
- currentUser: The logged-in user (from AuthContext)
- viewingUser: The user whose data is currently displayed
- By default, viewingUser = currentUser
- Users can switch via dropdown in SiteHeader
- "切换到我自己" button quickly switches back to currentUser
All dashboard endpoints accept optional user_id parameter:
- GET /api/v1/dashboard/summary?user_id={id}
- GET /api/v1/dashboard/overview?user_id={id}
- GET /api/v1/dashboard/trends?user_id={id}
- UserSelectDropdown: Dropdown to select viewing user, shows (我) badge for current user
- SwitchToMeButton: Quick button to switch back to current user's data
- SiteHeader: Integrates user switcher in center section
The codebase is designed to support:
- Desktop client (C++) for automatic work metrics collection
- Garmin Connect integration for health data
- Mobile app for quick data entry
- Advanced analytics and ML-based insights