```
**Common breakpoints:**
- `sm:` - 640px (small tablets)
- `md:` - 768px (tablets)
- `lg:` - 1024px (large tablets/laptops)
---
## Common Development Tasks
### Adding a New Feature
1. **Define types** in `src/types/`
2. **Create service** in `src/services/` if API integration needed
3. **Create context** in `src/contexts/` for state management
4. **Build components** in `src/components/[feature]/`
5. **Create page** in `src/pages/`
6. **Add route** in `src/App.tsx`
7. **Add to FAB menu** in `src/components/layout/FABMenu.tsx`
### Adding a New Microsoft Graph API Endpoint
```typescript
// 1. Add to graph.service.ts
async getNewResource(accessToken: string): Promise {
return this.get('/me/newresource', accessToken);
}
// 2. Create specialized service
class NewResourceService {
async fetchResources(accessToken: string, accountId: string): Promise {
const response = await graphService.getNewResource(accessToken);
return response.value.map(item => this.mapToResource(item, accountId));
}
}
// 3. Add to context
export const NewResourceProvider: React.FC = ({ children }) => {
const { accounts, getAccessToken } = useAuth();
const [resources, setResources] = useState([]);
const syncResources = useCallback(async () => {
const all: Resource[] = [];
for (const account of accounts) {
const token = await getAccessToken(account.homeAccountId);
const items = await newResourceService.fetchResources(token, account.homeAccountId);
all.push(...items);
}
setResources(all);
}, [accounts, getAccessToken]);
return (
{children}
);
};
```
### Debugging Authentication Issues
**Check token validity:**
```typescript
// In browser console
const accounts = JSON.parse(localStorage.getItem('planner_auth_accounts') || '[]');
console.log(accounts);
// Check expiry
accounts.forEach(acc => {
const expiresIn = acc.expiresOn - Date.now();
console.log(`${acc.email}: expires in ${Math.floor(expiresIn / 60000)} minutes`);
});
```
**Test token manually:**
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" https://graph.microsoft.com/v1.0/me
```
### Adding a New Calendar View
1. Create component: `src/components/calendar/NewView.tsx`
2. Add to CalendarPage view switcher
3. Implement event rendering logic
4. Use `useCalendar()` hook for data
```typescript
export const CustomView: React.FC = ({ onCreateEvent }) => {
const { events, calendars, selectedCalendars } = useCalendar();
const filteredEvents = useMemo(() =>
events.filter(event => selectedCalendars.includes(event.calendarId)),
[events, selectedCalendars]
);
return (
{/* Custom rendering logic */}
);
};
```
---
## Troubleshooting
### Port Already in Use
**Problem:** `Port 5173 is already in use`
**Solutions:**
```bash
# Option 1: Kill process on port 5173
lsof -ti:5173 | xargs kill -9
# Option 2: Find and kill manually
lsof -i:5173 # Find PID
kill -9
# Option 3: Change port (requires updating Azure AD redirect URI)
# Edit vite.config.ts, change port to 3000 or other
```
### Build Errors
**Problem:** `Module not found` or build failures
**Solutions:**
```bash
# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install
# Clear Vite cache
rm -rf node_modules/.vite
npm run dev
```
### Tailwind Classes Not Working
**Problem:** Tailwind classes not applying or build errors
**Checklist:**
- Verify `tailwind.config.js` content paths include all source files
- Ensure `@tailwind` directives present in `index.css`
- Check for typos in class names
- Use Tailwind 3.4 (not v4 - PostCSS compatibility issue)
```javascript
// tailwind.config.js
module.exports = {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}", // Important: include all source files
],
// ...
};
```
### Authentication Failures
**Problem:** "Failed to sign in" or "Authentication initialization failed"
**Checklist:**
1. Verify Azure AD client ID in `.env` is correct
2. Check redirect URI matches in both:
- `.env` → `VITE_MICROSOFT_REDIRECT_URI`
- Azure AD app registration → Redirect URIs
3. Ensure all required API permissions granted and consented
4. Clear LocalStorage: `localStorage.clear()` in browser console
5. Check browser console for detailed MSAL errors
### Microsoft Graph API Errors
**401 Unauthorized:**
- Token expired → Sign out and back in
- Insufficient permissions → Check Azure AD app permissions
**403 Forbidden:**
- Missing consent → Grant admin consent in Azure AD
- Scope not included in token → Verify scope in `app.config.ts`
**429 Too Many Requests:**
- Rate limited → Wait and implement exponential backoff
**404 Not Found:**
- Resource doesn't exist or wrong endpoint
- Check accountId/calendarId is valid
### Azure OpenAI Errors
**Problem:** Recipe generation failing
**Checklist:**
1. Verify endpoint, key, and deployment name in `.env`
2. Check Azure OpenAI resource is deployed and active
3. Ensure deployment model supports chat completions (GPT-4, GPT-3.5-turbo)
4. Check Azure OpenAI quota and limits
5. Test endpoint with curl:
```bash
curl -X POST "YOUR_ENDPOINT/openai/deployments/YOUR_DEPLOYMENT/chat/completions?api-version=2024-02-15-preview" \
-H "Content-Type: application/json" \
-H "api-key: YOUR_KEY" \
-d '{"messages":[{"role":"user","content":"Hello"}]}'
```
### Wake Lock Not Working
**Problem:** Screen still sleeps on tablet
**Possible causes:**
- Browser doesn't support Wake Lock API (check compatibility)
- Page not in foreground (wake lock only works when visible)
- User hasn't interacted with page yet (security restriction)
**Check support:**
```javascript
// In browser console
console.log('Wake Lock API:', 'wakeLock' in navigator);
```
---
## Testing Checklist
### Manual Testing
**Authentication:**
- [ ] Sign in with first account
- [ ] Sign in with second account
- [ ] View both accounts in settings
- [ ] Sign out one account
- [ ] Token refresh after 55+ minutes
**Calendar:**
- [ ] View week/day/month views
- [ ] Create event in different calendars
- [ ] Events display with correct colors
- [ ] Calendar filter toggles work
- [ ] Sync button refreshes data
- [ ] Events from both accounts visible
**Photos:**
- [ ] Browse OneDrive folder tree
- [ ] Select folder with images
- [ ] Slideshow auto-advances
- [ ] Pause/play controls work
- [ ] Navigate previous/next
- [ ] Fullscreen mode
**Meals:**
- [ ] Add ingredients to fridge
- [ ] Remove ingredients
- [ ] Generate recipes with AI
- [ ] Favorite recipes
- [ ] View saved recipes
**Tasks:**
- [ ] View To Do lists from both accounts
- [ ] Create new task
- [ ] Toggle task completion
- [ ] Delete task
- [ ] Filter by active/completed
**Tablet:**
- [ ] All touch targets minimum 44px
- [ ] FAB menu accessible with thumb
- [ ] Wake lock prevents sleep
- [ ] Responsive on tablet screen size
- [ ] Network access on actual device
### Edge Cases
- [ ] No internet connection (offline mode)
- [ ] Token refresh during active request
- [ ] Very long event titles
- [ ] All-day events
- [ ] Events spanning multiple days
- [ ] Multiple accounts with duplicate calendar names
- [ ] Large photo folders (1000+ images)
- [ ] Empty fridge inventory (recipe generation)
---
## Performance Optimization
### Best Practices
**Memoization:**
```typescript
// Expensive calculations
const weekDays = useMemo(() => dateHelpers.getWeekDays(currentWeek), [currentWeek]);
// Callbacks to prevent re-renders
const handleClick = useCallback(() => { /* ... */ }, [dependencies]);
```
**Lazy Loading:**
```typescript
// Future enhancement: lazy load calendar views
const WeekView = lazy(() => import('./components/calendar/WeekView'));
```
**Debouncing:**
```typescript
// Debounce search/filter inputs
const debouncedSearch = useMemo(
() => debounce((query: string) => { /* search logic */ }, 300),
[]
);
```
**Pagination:**
- Limit initial calendar event fetch to visible date range
- Load older/future events on demand
- Paginate OneDrive folder contents (50 items at a time)
---
## Environment Variables
**Required Configuration (`.env`):**
```bash
# Microsoft OAuth (Azure AD App Registration)
VITE_MICROSOFT_CLIENT_ID=your_azure_ad_client_id_here
VITE_MICROSOFT_REDIRECT_URI=http://localhost:5173/auth/callback
# Azure OpenAI (for meal planning AI)
VITE_AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
VITE_AZURE_OPENAI_KEY=your_api_key_here
VITE_AZURE_OPENAI_DEPLOYMENT=your_deployment_name_here
```
**Setup Steps:**
1. Copy `.env.example` to `.env`
2. Fill in your Azure AD client ID
3. Fill in your Azure OpenAI credentials
4. Restart dev server (`npm run dev`)
---
## Future Enhancements
**Potential features (not yet implemented):**
- [ ] Push notifications for upcoming events
- [ ] Grocery list generation from recipes
- [ ] Recipe search/database integration
- [ ] Calendar event sharing links
- [ ] Export meal plan to PDF
- [ ] Voice commands via Web Speech API
- [ ] Smart home integration (lights, displays)
- [ ] Recurring event support (Graph API supports this)
- [ ] Event reminders
- [ ] Dark mode theme toggle
- [ ] Gesture-based navigation (swipe between views)
- [ ] Offline queue for write operations
- [ ] Service worker for true PWA offline support
---
## Key Files Reference
**Must-read files for understanding the codebase:**
1. `src/config/app.config.ts` - All configuration constants
2. `src/contexts/AuthContext.tsx` - Multi-account authentication
3. `src/services/graph.service.ts` - Microsoft Graph API client
4. `src/components/layout/FABMenu.tsx` - Navigation pattern
5. `src/App.tsx` - Routing and context providers
6. `vite.config.ts` - Build configuration
7. `tailwind.config.js` - Theme configuration
---
## AI Agent Development Best Practices
### Critical Git Rules
1. **NEVER `git push` without explicit user approval.** Always commit locally and inform the user. Only push when the user explicitly says to push.
2. **ALWAYS run `npm run build` before committing.** This runs `tsc -b && vite build` and catches TypeScript errors that `tsc --noEmit` may miss. Do not commit if the build fails.
3. **ALWAYS stop the dev server before building, then restart it after.** Stop the running `npm run dev` process, run `npm run build`, then start `npm run dev` again. This ensures a clean build and a fresh dev server.
4. **ALWAYS clear the Vite cache before starting the dev server.** Run `rm -rf node_modules/.vite` before `npm run dev` to avoid stale HMR cache errors (e.g., missing exports).
### Workflow for Implementing UI Features
When working on this project as an AI agent, follow this standard workflow:
#### 1. **Always Start the Dev Server**
```bash
npm run dev
```
The app will be available at http://localhost:5173 (fixed port).
#### 2. **Use Playwright MCP to Visually Verify**
After making UI changes, immediately verify them visually:
```typescript
// Navigate to the page
await browser_navigate({ url: "http://localhost:5173" });
// Take a screenshot to see current state
await browser_take_screenshot({ filename: "before-change.png" });
// Make your code changes...
// Refresh and verify
await browser_navigate({ url: "http://localhost:5173" });
await browser_take_screenshot({ filename: "after-change.png" });
// Get accessibility snapshot to verify structure
await browser_snapshot();
```
#### 3. **Verify Touch Targets**
For any new buttons or interactive elements:
```typescript
await browser_evaluate({
function: `() => {
const newButton = document.querySelector('[data-testid="new-button"]');
const rect = newButton.getBoundingClientRect();
return {
width: rect.width,
height: rect.height,
meetsTouchRequirement: rect.width >= 44 && rect.height >= 44
};
}`
});
```
#### 4. **Test User Flows**
Don't just verify static UI - test interactions:
```typescript
// Example: Testing FAB menu interaction
await browser_navigate({ url: "http://localhost:5173" });
await browser_take_screenshot({ filename: "1-homepage.png" });
// Click FAB button
await browser_click({ element: "FAB menu button", ref: "..." });
await browser_take_screenshot({ filename: "2-menu-open.png" });
// Click calendar option
await browser_click({ element: "Calendar menu item", ref: "..." });
await browser_take_screenshot({ filename: "3-calendar-page.png" });
// Verify calendar loaded
await browser_snapshot();
```
#### 5. **Check Responsive Behavior**
Test at tablet viewport size:
```typescript
// Resize to Surface Pro dimensions
await browser_resize({ width: 1280, height: 800 });
await browser_take_screenshot({ filename: "tablet-view.png" });
// Check desktop view
await browser_resize({ width: 1920, height: 1080 });
await browser_take_screenshot({ filename: "desktop-view.png" });
```
### Common MCP Commands for This Project
**Navigation:**
```typescript
browser_navigate({ url: "http://localhost:5173" })
browser_navigate({ url: "http://localhost:5173/calendar" })
browser_navigate({ url: "http://localhost:5173/settings" })
```
**Screenshots:**
```typescript
// Full page
browser_take_screenshot({ filename: "full-page.png", fullPage: true })
// Viewport only
browser_take_screenshot({ filename: "viewport.png" })
// Specific element
browser_take_screenshot({
filename: "fab-menu.png",
element: "FAB menu",
ref: "..."
})
```
**Accessibility Snapshots:**
```typescript
// Get full page structure
browser_snapshot()
// Save to file for reference
browser_snapshot({ filename: "page-structure.md" })
```
**Interactions:**
```typescript
// Click
browser_click({ element: "Button name", ref: "[data-testid='button-id']" })
// Type text
browser_type({
element: "Input field",
ref: "[name='email']",
text: "test@example.com"
})
// Evaluate JavaScript
browser_evaluate({
function: `() => { return document.title; }`
})
```
### When to Use Visual Verification
**ALWAYS verify visually when:**
- Creating new components
- Modifying layouts or styles
- Adding new pages or routes
- Changing responsive breakpoints
- Updating the FAB menu
- Modifying calendar views
- Working on modals or overlays
- Adjusting touch target sizes
- Implementing new color schemes
- Debugging CSS issues
**Quick verification is acceptable for:**
- Small text changes
- Code refactoring without UI changes
- Adding types or interfaces
- Updating service logic
- Fixing TypeScript errors
### Integration with Development Workflow
**Standard Pattern:**
1. Read relevant files to understand current implementation
2. Make code changes
3. **Start dev server** (`npm run dev`)
4. **Navigate to page** with Playwright MCP
5. **Take screenshots** before and after
6. **Verify touch targets** if adding interactive elements
7. **Test user flows** for new features
8. Document changes
**Example: Adding a New Button**
```bash
# 1. Make code changes
# Edit src/components/example/NewFeature.tsx
# 2. Verify visually
npm run dev
# 3. Use MCP to verify
# - Navigate to http://localhost:5173
# - Take screenshot
# - Click the new button
# - Verify it works
# - Check button size >= 44x44px
```
### Tips for Effective Visual Verification
1. **Take screenshots at key steps** - Don't just test the final state, capture the journey
2. **Name screenshots descriptively** - `fab-menu-open.png` not `screenshot1.png`
3. **Use accessibility snapshots** - They provide structured data that's easier to verify than pixels
4. **Test multiple viewports** - Desktop, tablet, and mobile sizes
5. **Verify error states** - Not just happy paths
6. **Check loading states** - Ensure spinners and skeletons display correctly
7. **Test with real data** - Don't just test with empty states
### Debugging UI Issues with MCP
When a UI issue is reported:
```typescript
// 1. Navigate to the problematic page
await browser_navigate({ url: "http://localhost:5173/problem-page" });
// 2. Take a screenshot to see the issue
await browser_take_screenshot({ filename: "issue-screenshot.png" });
// 3. Get the accessibility snapshot
await browser_snapshot({ filename: "page-structure.md" });
// 4. Inspect specific elements
await browser_evaluate({
function: `() => {
const element = document.querySelector('.problematic-element');
const styles = window.getComputedStyle(element);
return {
display: styles.display,
position: styles.position,
width: styles.width,
height: styles.height,
// ... other relevant styles
};
}`
});
// 5. Check console for errors
await browser_console_messages({ level: "error" });
```
### Best Practices Summary
✅ **DO:**
- Start dev server before implementing UI changes
- Use Playwright MCP to verify all UI changes visually
- Take screenshots at multiple steps of user flows
- Verify touch target sizes programmatically
- Test at multiple viewport sizes
- Check accessibility snapshots for semantic correctness
- Document visual verification steps in commit messages
❌ **DON'T:**
- Make UI changes without visual verification
- Assume UI looks correct based on code alone
- Skip testing on tablet viewport
- Forget to verify touch target sizes
- Only test happy paths - test error states too
- Leave debug screenshots in the codebase
---
## Reporting Standards
### Report Directory Structure
All reports, summaries, and analysis documents MUST be stored in the `.reports/` directory with a standardized naming convention.
### Naming Convention
**Format:** `YYYY-MM-DD_{REPORT_NAME}.md`
**Rules:**
- Always use ISO date format (YYYY-MM-DD)
- Use underscores for spaces in report name
- Use UPPERCASE_WITH_UNDERSCORES for report name
- Always use `.md` extension (Markdown)
**Examples:**
```
.reports/2026-01-05_UI_TEST_RESULTS.md
.reports/2026-01-10_PERFORMANCE_ANALYSIS.md
.reports/2026-01-15_SECURITY_AUDIT.md
.reports/2026-02-01_FEATURE_IMPLEMENTATION_SUMMARY.md
.reports/2026-03-15_BUG_INVESTIGATION_REPORT.md
```
### When to Create Reports
Create a report in `.reports/` when:
✅ **Testing & Validation**
- Completing comprehensive UI testing
- Running performance benchmarks
- Conducting security audits
- Performing accessibility validation
- Executing integration tests
✅ **Implementation & Development**
- Finishing significant features
- Completing major refactors
- Making architectural decisions
- Migrating to new technologies
- Implementing breaking changes
✅ **Analysis & Audits**
- Code quality analysis
- Dependency audits
- Bundle size analysis
- Database optimization
- API performance review
✅ **Incidents & Issues**
- Investigating complex bugs
- Post-mortem analysis
- Root cause investigations
- Critical incident reports
✅ **AI Agent Work Sessions**
- Major feature implementations by AI
- Significant debugging sessions
- Architecture design sessions
- Large-scale refactoring work
### Report Structure Template
```markdown
# [Report Title]
## Date
YYYY-MM-DD
## Summary
Brief 2-3 sentence overview of the report.
## Details
### Section 1: [Topic]
Detailed information about the first major topic...
### Section 2: [Topic]
More detailed information...
## Findings
- ✅ Key finding 1
- ✅ Key finding 2
- ⚠️ Warning/concern 1
- ❌ Issue found 1
## Action Items
- [ ] Action 1 - Description
- [ ] Action 2 - Description
- [ ] Action 3 - Description
## Recommendations
1. Recommendation 1 with rationale
2. Recommendation 2 with rationale
3. Recommendation 3 with rationale
## Conclusion
Final assessment, overall status, and next steps.
---
**Reported By:** [Name/AI Agent/Tool]
**Report Type:** [Test/Implementation/Analysis/Incident]
**Status:** [Complete/In Progress/Requires Follow-up]
```
### Report Categories
**Test Reports:**
- UI validation results
- Integration test results
- Performance test results
- Accessibility audit results
- Security test results
**Implementation Reports:**
- Feature completion summaries
- Architecture decision records (ADR)
- Migration completion reports
- Refactoring summaries
- Deployment reports
**Analysis Reports:**
- Code quality analysis
- Performance profiling
- Security audit results
- Dependency audit reports
- Bundle size analysis
**Incident Reports:**
- Bug investigation reports
- Post-mortem analysis
- Root cause analysis
- Incident response reports
### Report Best Practices
✅ **DO:**
- Use the standardized naming convention
- Include date in both filename and content
- Write clear, concise summaries
- Document all findings and action items
- Include screenshots/evidence when relevant
- Tag reports with status (Complete/In Progress)
- Reference related files with line numbers
- Keep reports in version control
❌ **DON'T:**
- Create reports outside `.reports/` directory
- Use inconsistent naming conventions
- Skip the date in filename
- Write vague or ambiguous summaries
- Omit action items or next steps
- Delete old reports (they're historical record)
- Leave reports as drafts indefinitely
### Viewing Reports
**List all reports:**
```bash
ls -lh .reports/
```
**Search reports by keyword:**
```bash
grep -r "keyword" .reports/
```
**View recent reports:**
```bash
ls -lt .reports/ | head -10
```
### Report Retention
- ✅ Keep all reports in version control (Git)
- ✅ Reports serve as project history
- ✅ Old reports remain valuable for reference
- ✅ Use reports to track progress over time
- ❌ Do not delete reports unless truly obsolete
### Integration with Development Workflow
**After Major Work:**
1. Complete the implementation/testing
2. Create a report in `.reports/` with proper naming
3. Document findings, issues, and resolutions
4. Include action items for follow-up work
5. Commit the report with descriptive message
**Example Workflow:**
```bash
# After completing UI testing
touch .reports/2026-01-05_UI_TEST_RESULTS.md
# Write the report...
git add .reports/2026-01-05_UI_TEST_RESULTS.md
git commit -m "Add UI test results report for 2026-01-05"
```
---
## Contact & Support
**For issues or questions:**
1. Check this AGENTS.md file first
2. Review README.md for user-facing documentation
3. Check browser console for error messages
4. Verify Azure AD app configuration
5. Test API endpoints with curl/Postman
---
## Version History
- **v0.0.0** (Current) - Initial implementation with all core features
- Multi-account calendar sync
- OneDrive photo slideshow
- AI meal planning
- Microsoft To Do integration
- Fixed port configuration (5173)
- **Playwright MCP server integration for visual verification**
- **Comprehensive Playwright test suite with automated UI validation**
- **Standardized reporting system (.reports/ directory with YYYY-MM-DD naming)**
- Comprehensive documentation with AI agent best practices
---
**Last Updated:** 2026-01-05