Overview
User sessions in MentraOS Cloud follow a well-defined lifecycle from initial connection through active use, reconnection scenarios, and eventual cleanup. Understanding this lifecycle is crucial for proper resource management and user experience.Lifecycle Stages
1. Initial Connection
WebSocket Upgrade
When glasses connect to/glasses-ws:
Authentication Validation
The JWT token must contain:email: User’s email address (used as userId)sub: Subject identifier- Valid signature with
AUGMENTOS_AUTH_JWT_SECRET
2. Session Creation
New Session
When no existing session exists:Reconnection
When user reconnects to existing session:3. Active Session State
Manager Initialization
Each UserSession initializes specialized managers:Heartbeat Monitoring
Maintains connection health:Connection Acknowledgment
Send initial connection success:4. Disconnection Handling
Grace Period
When connection is lost:Reconnection During Grace Period
If user reconnects within grace period:- Cancel cleanup timer
- Update WebSocket connection
- Clear disconnection timestamp
- Resume normal operation
- No app restarts needed
5. Session Disposal
Trigger Conditions
Sessions are disposed when:- Grace period expires after disconnection
- Server shutdown
- Manual cleanup request
- Fatal errors
Disposal Process
6. Resource Cleanup
Manager Disposal
Each manager cleans up its resources:Subscription Cleanup
Remove all app subscriptions:Session State Tracking
Connection States
Metrics Collection
Sessions track:- Connection duration: Total time connected
- Reconnection count: Number of reconnections
- Active apps: Apps used during session
- Data processed: Audio, transcripts, etc.
Best Practices
- Always handle reconnections gracefully - Preserve state when possible
- Set appropriate grace periods - Balance resource usage vs user experience
- Clean up all resources - Prevent memory leaks
- Track metrics - Monitor session health and patterns
- Log lifecycle events - Aid debugging and monitoring
- Handle edge cases - Concurrent connections, rapid reconnects
Error Handling
Connection Errors
Disposal Errors
Always attempt full cleanup even if individual components fail:Related Documentation
- UserSession Class: Core session implementation
- SessionService: Session management service
- WebSocketService: Connection handling
- Manager Overview: Manager lifecycle