
๐ง MindGuard AI
AI-powered study focus tracker with on-device computer vision
Monitor attention ยท Detect phone distractions ยท Gamify study sessions โ all privacy-first, running entirely in your browser.
Built for students, by students. Zero video leaves your device โ ever.
๐ Frontend mindguard-ai-tan.vercel.app โก Backend API ai-study-tracker.vercel.app ๐ง Demo Email
demo@mindguard.ai ๐ Demo Password demo1234๐ Table of Contents
โจ Features
๐ฏ Core Capabilities
Feature Description On-Device Face Tracking MediaPipe FaceLandmarker detects gaze direction & face presence โ no cloud, no latency Phone Detection YOLOv8-nano ONNX model identifies phone usage in real-time at ~2 FPS Smart Timer Configurable focus sessions (15 / 30 / 45 / 60 / 90 min) with auto-pause on distraction XP & Leveling Earn 10 XP/min with streak multipliers (ร1.5 at 3 days, ร2 at 7, ร3 at 30) Streak System Daily streak tracking with automatic reset at midnight UTC Site Blocking Chrome extension blocks distracting sites during active sessions
๐ Intelligence & Analytics
Feature Description Cognitive Profile AI-generated study behaviour analysis โ Consistency Index, Flow State Detection, Fatigue Curve Focus Heatmap Visual timeline showing focused vs distracted periods throughout a session Session Analytics Detailed breakdown per session โ focus %, phone events, duration, XP earned Burnout Detection Multi-signal burnout risk score (0โ100) with LOW / MODERATE / HIGH / CRITICAL levels Phone Correlation Measures how phone presence impacts your focus score and recovery time Leaderboard Compete with other users on focus score, XP, and streaks
๐ Gamification
Feature Description 16 Achievements Unlock badges like Marathon Mind, Laser Focus, Phone-Free Champion, Unstoppable Level Progression XP-based leveling (formula:
level = floor(sqrt(xp / 100)) + 1) with visual progress bar Confetti Celebration Canvas-confetti burst on session completion ๐ Streak Multipliers 1.5ร at 3 days ยท 2ร at 7 days ยท 3ร at 30 days๐ Privacy-First Design
Guarantee How Zero cloud video All vision processing runs in-browser via WebAssembly No frames stored Camera feed is processed and immediately discarded Boolean signals only Backend receives
{ focused: true/false }, never pixels or images Webcam optional App works without camera (manual tracking mode) No biometrics Face landmarks are used locally for gaze math, never stored or transmitted๐ System Architecture
Data Flow โ Study Session Lifecycle
๐ก Tech Stack
Layer Technology Purpose Frontend React 18, React Router v6 SPA with protected routes Styling Tailwind CSS 3, Lucide Icons Utility-first CSS, icon library Vision (Face) MediaPipe FaceLandmarker (WASM) 478-landmark face tracking via WebAssembly Vision (Phone) YOLOv8-nano, ONNX Runtime Web Object detection in browser (6 MB model) State Custom
createStore() + useSyncExternalStore Zero-dependency pub/sub state management Backend Node.js 18+, Express 4 REST API server Security Helmet, express-rate-limit HTTP hardening, brute-force protection Database MongoDB + Mongoose 8 Document database with schema validation Auth JWT (jsonwebtoken) + bcryptjs Stateless authentication, password hashing Extension Chrome MV3 (Service Worker) Distraction blocking during sessions Scheduling node-cron Streak resets, zombie session cleanup Effects canvas-confetti Session completion celebrations๐ Getting Started
Prerequisites
Requirement Version Notes Node.js โฅ 18 Required for backend and frontend tooling MongoDB โฅ 6.0 Local install or MongoDB Atlas (free tier works) Google Chrome Latest Required for the site-blocking extension Webcam Any Optional โ app works without camera
Installation
Configuration
Create
.env files in both backend/ and frontend/ directories:Backend
backend/.env Frontend
frontend/.env Running the App
Chrome Extension (Optional)
Navigate to
chrome://extensions in ChromeEnable Developer mode (toggle in top-right)
Click Load unpacked โ select the
extension/ folderPin the MindGuard AI icon in the toolbar
Login with your MindGuard credentials in the extension popup
๐ Project Structure
๐ก API Reference
Base URL:
http://localhost:5000/apiAll authenticated endpoints require the header:
Standard error response format:
Authentication
Rate limited: 20 requests per 15-minute window on all auth routes.
POST /api/auth/register
POST /api/auth/registerCreate a new user account.
Field Type Required Constraints
name string โ
2โ100 characters, trimmed email string โ
Must contain @, lowercased, unique password string โ
6โ128 characters Example Request & ResponseRequest:
Response (
201):POST /api/auth/login
POST /api/auth/loginAuthenticate and receive a JWT token.
Field Type Required
email string โ
password string โ
Example Request & ResponseRequest:
Response (
200):Token expires in 30 days. Payload:{ userId }.
GET /api/auth/profile ๐
GET /api/auth/profile ๐Get the authenticated user's profile.
Example Response
Sessions
All session endpoints require authentication ๐
POST /api/sessions/start
POST /api/sessions/startStart a new focus session.
Field Type Required Default Constraints
plannedDuration number No 3600 60โ28800 seconds notes string No โ Max 1000 characters Example Response POST /api/sessions/focus/:id
POST /api/sessions/focus/:idLog a focus/distraction event during a session.
Field Type Required Description
focused boolean โ
true = focused, false = distractedPOST /api/sessions/phone/:id
POST /api/sessions/phone/:idLog a phone detection event during a session.
Field Type Required Description
detected boolean โ
true = phone visible, false = phone gonePOST /api/sessions/end/:id
POST /api/sessions/end/:idEnd an active session. Automatically calculates:
Duration โ actual seconds elapsed
Focus score โ percentage of focused events (defaults to 100% if no events)
XP earned โ
floor(durationMinutes) ร 10 ร streakMultiplierStreak update โ increments or maintains current/longest streak
Example Response
XP Multiplier Table:
Streak Multiplier < 3 days 1ร โฅ 3 days 1.5ร โฅ 7 days 2ร โฅ 30 days 3ร
POST /api/sessions/pause/:id
POST /api/sessions/pause/:idPause an active session.
PATCH /api/sessions/notes/:id
PATCH /api/sessions/notes/:idUpdate session notes.
Field Type Required Constraints
notes string โ
Max 1000 charactersGET /api/sessions/active ๐
GET /api/sessions/active ๐Returns the currently active session (if any), or
null.GET /api/sessions/history ๐
GET /api/sessions/history ๐Get paginated session history.
Query Param Type Default Constraints
limit number 50 Max results per page offset number 0 Skip N recordsGET /api/sessions/:id ๐
GET /api/sessions/:id ๐Get full details for a specific session, including all focus and phone events.
Todos
All todo endpoints require authentication ๐
Method Endpoint Description
GET /api/todos List all todos (sorted by creation date, newest first) POST /api/todos Create a new todo PATCH /api/todos/:id/toggle Toggle completion status PATCH /api/todos/:id Update todo text/priority DELETE /api/todos/:id Delete a todoPOST /api/todos โ Create Todo
POST /api/todos โ Create TodoField Type Required Default Constraints
text string โ
โ 1โ500 characters, trimmed sessionId ObjectId No โ Links todo to a specific session priority string No "medium" "low" | "medium" | "high"Blocked Sites
All blocked site endpoints require authentication ๐
Method Endpoint Description
GET /api/blocked-sites List all blocked domains POST /api/blocked-sites Add a domain to blocklist DELETE /api/blocked-sites/:id Remove a domain from blocklistPOST /api/blocked-sites โ Add Domain
POST /api/blocked-sites โ Add DomainField Type Required Constraints
url string โ
3โ255 chars. Auto-sanitized: strips http(s)://, www., path segments. Lowercased. Duplicate check per user. ExampleRequest:
Stored as:
reddit.comCognitive Analytics
All cognitive endpoints require authentication ๐
GET /api/cognitive/cognitive-profile
GET /api/cognitive/cognitive-profileAlias:GET /api/analytics/cognitive-profile
Returns a comprehensive AI-generated cognitive profile based on all historical sessions.
Full Response Schema
GET /api/cognitive/session/:id
GET /api/cognitive/session/:idReturns per-minute focus analysis for a single session.
Returns422if session is too short (< 60s) or has fewer than 2 focus events.
Response Schema
Leaderboard
GET /api/leaderboard ๐
GET /api/leaderboard ๐Query Param Type Default Options
period string "all" "all" | "week" | "month" limit number 20 Max 50 Example Response Sorting:
"all" โ by XP descending; "week" / "month" โ by total minutes descending.Health Check
GET /api/health
GET /api/healthNo authentication required.
๐ฆ Data Models
User
Field Type Default Description
name String โ Display name (2โ100 chars) email String โ Unique, lowercased, trimmed password String โ bcrypt hashed xp Number 0 Total experience points level Number 1 Current level currentStreak Number 0 Consecutive study days longestStreak Number 0 All-time best streak lastStudyDate Date โ Last session end date createdAt Date now Account creationSession
Field Type Default Description
userId ObjectId โ User โ Session owner startTime Date now Session start endTime Date โ Session end duration Number 0 Actual duration (seconds) focusScore Number 100 Focus percentage (0โ100) xpEarned Number 0 XP awarded notes String โ User notes (max 1000 chars) plannedDuration Number 3600 Target duration (seconds) focusEvents Array [] [{ focused: bool, timestamp: Date }] phoneEvents Array [] [{ detected: bool, timestamp: Date }] todos ObjectId[] โ Todo [] Linked tasks isActive Boolean true Session in progress?Indexes:
userId, { userId, isActive }Todo
Field Type Default Description
userId ObjectId โ User โ Task owner sessionId ObjectId โ Session โ Linked session (optional) text String โ Task description (1โ500 chars) completed Boolean false Completion status priority String "medium" "low" / "medium" / "high" createdAt Date now Creation timestampBlockedSite
Field Type Default Description
userId ObjectId โ User โ Site owner domain String โ Blocked domain (3โ255 chars) createdAt Date now When blockedIndex:
{ userId, domain } (unique compound)๐ Vision System Deep Dive
The Vision System (
VisionSystem.jsx โ 897 lines) is the most complex component, running two parallel detection loops entirely in-browser.Two-Loop Architecture
Loop Technology Interval Effective FPS Purpose Face/Gaze MediaPipe FaceLandmarker 350ms ~2.86 Face presence + iris-based gaze direction Phone YOLOv8-nano (ONNX Runtime) 500ms ~2 Cell phone object detection
Face & Gaze Detection (Loop 1)
Model: MediaPipe FaceLandmarker (float16), loaded from CDN via dynamic ESM
import().Pipeline:
getUserMedia captures webcam at native resolutionMediaPipe extracts 478 face landmarks (468 base + 10 iris)
Custom gaze algorithm (
calculateGazeDirection):Computes horizontal iris offset (landmarks 468, 473, 33, 133, 263, 362)
Computes vertical iris offset (landmarks 159, 145, 386, 374)
Thresholds: horizontal > 0.38 OR vertical > 0.35 โ "looking away"
Consecutive-frame state machine:
No Face: 8 consecutive frames (~2.8s) + 2s grace window
Looking Away: 3 consecutive frames (~1.05s)
Focused: 2 consecutive frames (~0.7s) to regain focus
Phone Detection (Loop 2)
Model: YOLOv8-nano (
yolov8n.onnx, ~6 MB), loaded as a module-level singleton โ survives component re-mounts.Pipeline:
Video frame drawn to hidden
<canvas> at 640ร640RGB normalized to [0, 1] float32, transposed HWC โ CHW
ONNX inference: input
[1, 3, 640, 640] โ output [1, 84, 8400]Post-processing checks two COCO classes:
Class 67: "cell phone" (weight 1.0)
Class 65: "remote" (weight 0.85 โ catches phone backs)
Confidence threshold: 0.25, min bbox area: 0.8% of frame
Greedy NMS with IoU threshold 0.45
Sliding Window Persistence (Anti-Flicker):
Window: 12 frames (~6 seconds)
Appear: โฅ 3 of last 12 frames โ phone confirmed (~1.5s lag)
Dismiss: โค 1 of last 12 frames โ phone gone (~6s to dismiss)
Hysteresis between thresholds retains current state
Enforcement Chain:
Phone stable โ
onPhoneDetected callback firesEnforcement timer starts (1s interval)
After 15s continuous detection โ auto-pause session
Phone gone โ enforcement stops
Privacy Architecture
๐งฌ Cognitive Engine
The Cognitive Engine (
cognitiveEngine.js + cognitiveHelpers.js) performs pure server-side computation on boolean focus/phone event data to generate rich analytics.Session-Level Analysis
Metric Description Per-minute Bucketing Groups focus events into 1-minute buckets with carry-forward for empty minutes Phase Scoring Splits session into early (first 5 min), mid, and late (last 5 min) phases Distraction Frequency Distraction events per minute Recovery Time Average seconds from distraction start to focus regain Focus Volatility Standard deviation of per-minute focus percentages Strongest Window Sliding 5-minute window with highest average focus score
Pattern Classification
Each session receives one or more labels:
Pattern Condition
WarmUpPattern Early focus โช Late focus (โฅ 20% gap) FatiguePattern Late focus โช Early focus (โฅ 20% gap) FragmentedAttention Distraction frequency > 3/min StableFocus Volatility < 10 AND focus โฅ 70% SlowRecovery Average recovery > 30 seconds Normal Fallback when no other pattern matchesBurnout Risk Score (0โ100)
Weighted multi-signal formula:
Signal Weight Declining focus slope (weekly) 30% Duration drop (trend) 20% Increasing distraction trend 20% Focus volatility 15% Streak instability 15% Phone correlation bonus Up to +7.5
Score Range Risk Level 0โ30 ๐ข LOW 31โ60 ๐ก MODERATE 61โ80 ๐ HIGH 81โ100 ๐ด CRITICAL
Cognitive Health Score (0โ100)
Component Weight Average focus score (all-time) 30% Consistency (inverse of focus stddev) 20% Recovery efficiency 15% Session regularity 20% Task completion rate 15%
Phone-Distraction Correlation
Splits sessions into phone-present vs phone-absent groups and computes:
Signal Weight Ratio of focus-loss events temporally near phone events 40% Focus score delta between groups 30% Volatility increase with phone present 30%
Scalability Strategy
The cognitive profile uses a two-query approach:
Query 1: ALL completed sessions (lightweight projection, no
focusEvents) โ aggregate statsQuery 2: Last 30 days (full documents) โ detailed per-minute analysis
This keeps response times fast even with thousands of sessions.
๐ Chrome Extension
Architecture
The Chrome MV3 extension uses a Service Worker background script with these capabilities:
Feature Mechanism Site Blocking Redirects matching navigations to
blocked.html Session Awareness Polls /api/sessions/active every 15 seconds Blocklist Sync Fetches /api/blocked-sites every 5 minutes Domain Matching Strips www., checks exact match + subdomain Active-Only Blocking Sites are only blocked during active study sessionsBlocking Triggers
Trigger Chrome API Navigation attempt
chrome.webNavigation.onBeforeNavigate (main frame only) Tab URL update chrome.tabs.onUpdated (on "complete" status) Tab switch chrome.tabs.onActivated Session start Scans ALL open tabs immediatelyExtension โ Popup Communication
Action Direction Purpose
toggleExtension Popup โ Background Enable/disable blocking setToken Popup โ Background Set/clear auth token syncSites Popup โ Background Manual sync trigger getStatus Popup โ Background Get full status snapshot sessionUpdate Popup โ Background Notify of session start/stop checkSession Popup โ Background Force session status check๐ Achievement System
16 unlockable achievements stored in
localStorage under key mindguard_achievements:Badge Title Condition ๐ First Steps Complete 1 session ๐ Getting Started Complete 5 sessions โ๏ธ Study Warrior Complete 20 sessions ๐ Knowledge Seeker Complete 50 sessions ๐ง Deep Focus Complete a 60-minute session ๐ Marathon Mind Complete a 120-minute session ๐ฅ On a Roll Reach a 3-day streak ๐ช Weekly Champion Reach a 7-day streak ๐ Unstoppable Reach a 30-day streak ๐ฏ Laser Focus Achieve 90%+ focus score ๐ Perfect Focus 100% focus in a 10+ min session โญ Rising Star Earn 1,000 XP ๐ Bright Mind Earn 5,000 XP ๐ Scholar Reach level 5 ๐ Master Reach level 10 ๐ต Phone Free Complete a session with zero phone detections
โฐ Background Jobs
Two cron jobs run on the backend:
Job Schedule Description Zombie Session Cleanup Every 30 minutes Finds sessions with
isActive: true and startTime > 6 hours ago. Auto-ends them with calculated duration, marks isActive: false, appends "[Auto-closed]" to notes. Streak Reset Daily at midnight UTC Iterates all users. If lastStudyDate is neither yesterday nor today, resets currentStreak to 0.๐ Security
Measure Implementation Helmet Sets security HTTP headers (X-Frame-Options, CSP, etc.) CORS Whitelist:
localhost:3000/3001 (dev), FRONTEND_URL (prod), chrome-extension://* Rate Limiting 20 requests / 15 min on /api/auth/* routes JWT 30-day expiry, HS256 signing, userId payload only Password Hashing bcryptjs with auto-generated salt Input Validation Length limits, type checks, email format validation on all routes No Pixel Data Backend never receives, processes, or stores any image/video data๐ง Environment Variables
Backend (backend/.env)
backend/.env)Variable Required Default Description
MONGODB_URI โ
โ MongoDB connection string JWT_SECRET โ
โ Secret for signing JWT tokens PORT No 5000 Server port NODE_ENV No development development | production FRONTEND_URL Production only โ Frontend URL for CORS in productionFrontend (frontend/.env)
frontend/.env)Variable Required Default Description
REACT_APP_API_URL No http://localhost:5000/api Backend API base URL๐บ Roadmap
Pomodoro Mode โ structured work/break intervals with configurable cycles
Study Groups โ collaborative focus rooms with real-time presence
Weekly Reports โ email digest with focus trends and insights
Mobile App โ React Native companion for on-the-go tracking
Dark Mode โ system-aware theme switching (foundation already built)
Export Data โ CSV/PDF session reports and analytics
Custom Achievements โ user-defined goals and milestones
Browser Extension v2 โ Firefox + Edge support
Spaced Repetition โ integrated flashcard system linked to study sessions
Focus Music โ ambient soundscapes that adapt to focus state
๐ค Contributing
Contributions are welcome! Here's how to get started:
Fork the repository
Create a feature branch (
git checkout -b feature/amazing-feature)Commit your changes (
git commit -m 'Add amazing feature')Push to the branch (
git push origin feature/amazing-feature)Open a Pull Request
Development Tips
Backend hot-reload:
cd backend && npm run dev (uses nodemon)Frontend hot-reload:
cd frontend && npm start (Create React App)The YOLO model singleton persists across React hot reloads โ no repeated loading
Vision system throttles React state updates to โค 1/s to prevent render storms
๐ License
This project is licensed under the MIT License โ see the LICENSE file for details.
โญ Star this repo if MindGuard AI helps you study better!
MindGuard AI โ Focus smarter, not harder. ๐ง โจ
Made with โค๏ธ by Lingaraj Patil
0 likes ยท 9 views ยท Aug 6, 2026
Developed an AI-powered study focus tracker running entirely in the browser.