MindGuard AI Study Focus Tracker by Lingaraj PatilMindGuard AI Study Focus Tracker by Lingaraj Patil

MindGuard AI Study Focus Tracker

Lingaraj Patil

Lingaraj Patil

๐Ÿง  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 Chrome
Enable Developer mode (toggle in top-right)
Click Load unpacked โ†’ select the extension/ folder
Pin 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/api
All 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

Create 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 & Response
Request:

Response (201):

POST /api/auth/login

Authenticate and receive a JWT token.
Field Type Required email string โœ… password string โœ… Example Request & Response
Request:

Response (200):

Token expires in 30 days. Payload: { userId }.

GET /api/auth/profile ๐Ÿ”’

Get the authenticated user's profile.
Example Response

Sessions

All session endpoints require authentication ๐Ÿ”’

POST /api/sessions/start

Start 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

Log a focus/distraction event during a session.
Field Type Required Description focused boolean โœ… true = focused, false = distracted

POST /api/sessions/phone/:id

Log a phone detection event during a session.
Field Type Required Description detected boolean โœ… true = phone visible, false = phone gone

POST /api/sessions/end/:id

End 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 ร— streakMultiplier
Streak 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

Pause an active session.

PATCH /api/sessions/notes/:id

Update session notes.
Field Type Required Constraints notes string โœ… Max 1000 characters

GET /api/sessions/active ๐Ÿ”’

Returns the currently active session (if any), or null.

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 records

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 todo

POST /api/todos โ€” Create Todo

Field 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 blocklist

POST /api/blocked-sites โ€” Add Domain

Field Type Required Constraints url string โœ… 3โ€“255 chars. Auto-sanitized: strips http(s)://, www., path segments. Lowercased. Duplicate check per user. Example
Request:

Stored as: reddit.com

Cognitive Analytics

All cognitive endpoints require authentication ๐Ÿ”’

GET /api/cognitive/cognitive-profile

Alias: 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

Returns per-minute focus analysis for a single session.

Returns 422 if session is too short (< 60s) or has fewer than 2 focus events.

Response Schema

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

No 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 creation

Session

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 timestamp

BlockedSite

Field Type Default Description userId ObjectId โ†’ User โ€” Site owner domain String โ€” Blocked domain (3โ€“255 chars) createdAt Date now When blocked
Index: { 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 resolution
MediaPipe 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ร—640
RGB 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 fires
Enforcement 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 matches

Burnout 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 stats
Query 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 sessions

Blocking 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 immediately

Extension โ†” 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)

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 production

Frontend (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
Like this project

Posted Aug 6, 2026

Developed an AI-powered study focus tracker running entirely in the browser.