Overview
The UserSession class is the central object that represents an active user connection in MentraOS Cloud. It encapsulates all session-related state, managers, and functionality for a single user, serving as the hub for all user interactions. File:packages/cloud/src/services/session/UserSession.ts
Architecture
Core Properties
Identification and State
Manager Instances
Each UserSession contains dedicated manager instances:Lifecycle Management
Creation
UserSessions are created when a user connects:Reconnection Handling
When glasses reconnect, the existing session is updated:Disposal
Clean resource cleanup on session end:Heartbeat System
Maintains connection health with periodic ping/pong:Hardware Capabilities
Model Updates
Updates device model and capabilities:Compatibility Enforcement
Stops apps that require unavailable hardware:Audio Management
Audio Buffering
Static Methods
Session Access
Error Handling
Send errors to glasses with specific codes:Client Data Transformation
Prepare session data for API responses:Best Practices
- Always use managers for specialized functionality
- Check WebSocket state before sending messages
- Dispose resources properly to prevent memory leaks
- Log with context using the session logger
- Handle reconnections gracefully by preserving state
- Validate hardware compatibility when models change
Thread Safety
UserSession is designed for single-threaded access within the Bun runtime event loop. All operations should be performed on the main thread.Related Documentation
- SessionService: Creates and manages UserSessions
- SessionStorage: Storage mechanism
- AppManager: App lifecycle management
- All Managers: Individual manager documentation