Problem:
- MSAL was throwing runtime errors when Azure credentials were incomplete
- Script error in browser due to invalid MSAL configuration
- PublicClientApplication constructor failing with empty/undefined values
Solution:
- Added tenant ID validation in addition to client ID check
- Wrapped MSAL initialization in try-catch to handle configuration errors gracefully
- Log warning instead of crashing when MSAL cannot be initialized
- Allow application to continue with simple login when Azure is not configured
Changes:
- Check both REACT_APP_AZURE_CLIENT_ID and REACT_APP_AZURE_TENANT_ID
- Use try-catch when creating PublicClientApplication instance
- Set msalInstance to null on initialization failure
- Console warning for debugging when Azure AD is not properly configured
This prevents runtime errors and allows the application to work in test mode
without requiring valid Azure AD configuration.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Problem:
- MSAL library was causing crypto errors in browser
- Black screen on load due to MSAL initialization failure
- Error: crypto module not available in browser environment
Solution:
- Made MSAL initialization conditional based on Azure AD configuration
- Only initialize MSAL if REACT_APP_AZURE_CLIENT_ID is properly configured
- Allow simple login to work without MSAL for testing purposes
- Gracefully handle both MSAL and simple login modes
Changes:
- frontend/src/context/AuthContext.tsx:
* Check if Azure AD is configured before initializing MSAL
* Set msalInstance to null when Azure is not configured
* Updated all MSAL calls to check for null before use
* Simple login works independently of MSAL
- frontend/package.json:
* Added crypto polyfills as devDependencies (for future use)
* Packages: crypto-browserify, buffer, stream-browserify, etc.
- frontend/src/styles/theme.css:
* Added login form styles (login-container, login-card, form-group, etc.)
Benefits:
- No more crypto errors in browser
- Simple login works without Azure AD configuration
- Easy testing with test accounts (admin/user)
- Production Azure AD login still supported when configured
- Graceful fallback for environments without Azure setup
Testing:
- Frontend compiles successfully without crypto errors
- All services running: backend, frontend, postgres, redis
- Simple login working with test accounts
- No black screen on load
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Features:
- New UserDetailsView component with expandable conversations
- Each conversation shows all messages with token usage and cost
- User information section (email, role, status, last login)
- Token usage statistics grid (8 stat cards)
- Message content truncation for long messages (500 chars)
- Role-based styling (user: blue, assistant: gold)
Backend:
- New GET /admin/users/{user_id}/details endpoint
- Complex SQL queries with joins for user stats and conversations
- Pydantic schemas: UserDetails, ConversationDetail, MessageDetail
- Per-message and per-conversation token tracking
Frontend:
- React Router integration for /admin/users/:userId route
- Navigation from Usage page "View" button to user details
- Back button to return to admin panel
- Proper error handling and loading states
- Responsive CSS styling with hover effects
Changes:
- backend/app/api/v1/endpoints/admin.py: Added getUserDetails endpoint
- frontend/src/components/UserDetailsView.tsx: New component
- frontend/src/App.tsx: Added route for user details page
- frontend/src/components/TokenUsageDashboard.tsx: Added navigation handler
- frontend/src/services/api.ts: Added adminAPI.getUserDetails method
- frontend/src/styles/admin.css: Added comprehensive styling for user details
- frontend/package.json: Added react-router-dom dependency
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Backend changes:
- Add admin analytics endpoints for daily usage per user
- Add GET /tokens/daily-users endpoint with date/user breakdown
- Update OpenAI SDK from 1.58.1 to 2.6.1
- Switch from Assistants API to Responses API with file_search tool
- Implement strict RAG-only system instructions
- Add citation validation to prevent hallucinations
- Add get_daily_usage_by_user repository method
- Add DailyUserUsage schema for admin analytics
Frontend changes:
- Implement comprehensive admin usage dashboard
- Add overall system statistics (users, conversations, messages, tokens, cost)
- Add daily usage table with per-user breakdown
- Add chat state clearing on logout and user change for isolation
- Center welcome message and input field in chat interface
- Add admin-specific styling for usage analytics tables
- Fix useCallback dependencies to prevent infinite loops
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Update token pricing with actual gpt-5-nano-2025-08-07 prices:
* Input: $0.05 per 1M = $0.00005 per 1K
* Cached: $0.005 per 1M = $0.000005 per 1K
* Output: $0.40 per 1M = $0.0004 per 1K
- Add cached_tokens support in OpenAI service
- Update cost calculation to use cached token pricing
- Add cached_tokens column to token_usage table (migration)
- Fix chat interface keyboard handling:
* Send message on Enter key
* New line on Shift+Enter
* Change onKeyPress to onKeyDown for better support
- Add textarea auto-resize with maxHeight limit
- Improve responsive styles for mobile devices
- Add iOS-specific fixes (prevent zoom on input focus)
Changes:
1. Hide "📊 Usage" button from regular users - only admins can see statistics
2. Updated .env.example with detailed pricing documentation
3. Clarified that OpenAI API does NOT return costs, only token counts
4. Cost is calculated locally: (tokens / 1000) × price_per_1k
Cost Calculation:
- OpenAI API returns only usage.input_tokens and usage.output_tokens
- We calculate cost based on PROMPT_TOKEN_COST and COMPLETION_TOKEN_COST from .env
- Current values are placeholders - need to update with real prices from OpenAI pricing page
- Formula: cost = (prompt_tokens / 1000) × PROMPT_TOKEN_COST + (completion_tokens / 1000) × COMPLETION_TOKEN_COST
Admin-only features:
- 📊 Usage (token statistics)
- 👨💼 Admin (user management & analytics)
Regular users only see:
- 💬 Chat
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Fixed email validation and token hashing:
- Changed test user emails from @test.local to @example.com (valid domain)
- Replaced passlib bcrypt for JWT token hashing with SHA-256 (no length limit)
- Improved error handling in SimpleLogin component for validation errors
- Deleted old test users and recreated with valid emails
Credentials:
- Admin: admin@example.com / admin
- User: user@example.com / user
Note: bcrypt still used for password hashing (in auth_service.py),
but SHA-256 for JWT token hashing to avoid 72-byte limit.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Implemented simple authentication for testing and admin panel for user management:
Backend:
- Add simple email/password login for test users (admin@test.local, user@test.local)
- Implement RBAC (Role-Based Access Control) with Permission enum
- Create admin endpoints for user management and system analytics
- Add bcrypt password hashing for test users
- Create script to generate test users in database
Frontend:
- Add SimpleLogin component for test authentication
- Create AdminPanel with user management and system analytics
- Add role-based navigation (Admin tab visible only for admins)
- Update AuthContext to support both MSAL and simple login
- Add API methods for admin operations
Features:
- Admins can view all users, manage roles, activate/deactivate accounts
- Admins can view system-wide analytics (users, conversations, tokens, costs)
- Regular users only see their own chats and usage
- Role badges in UI show user role (user/admin/superadmin)
Note: Simple authentication is for testing only. Production uses Azure AD MSAL.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Alembic Migration:
- 001_initial_migration.py - Create all database tables
- Users, Sessions, Conversations, Messages, TokenUsage, UserMemory
- Proper indexes and foreign keys with cascade deletes
- Ready for production deployment
ChatList Sidebar:
- List all conversations with last message date
- Click to select and load conversation
- New Chat button at top
- Inline title editing (click ✏️ Rename)
- Archive conversations (hidden from list)
- Delete conversations with confirmation
- Dropdown menu (⋮) for actions
- Active conversation highlighting
- Empty state with helpful message
TokenUsageDashboard:
- Total tokens and cost display
- 7/30/90 days period selector
- Bar chart visualization for last 7 days
- Detailed daily breakdown table
- Average tokens per day calculation
- Hover tooltips on chart bars
- Responsive grid layout
App Layout:
- Sidebar toggle button (☰)
- Navigation tabs: 💬 Chat | 📊 Usage
- Collapsible sidebar (mobile friendly)
- User info and logout in header
- Full-height layout with proper overflow
- Persistent sidebar state
Layout Styles (layout.css):
- Complete app structure (header, sidebar, main content)
- Responsive sidebar (full-screen on mobile)
- Chat list item styles with hover effects
- Dropdown menu positioning
- Token dashboard cards and charts
- Chart bar animations
- Mobile-optimized breakpoints
UI Features:
- Sidebar can be toggled on/off
- Switch between Chat and Usage views
- Conversations load on app start
- Active conversation tracked in sidebar
- Inline editing with ✓/✕ buttons
- Confirmation dialog for deletions
- Loading states for all operations
- Error handling with user feedback
Theme Updates:
- Chat container now full-height
- Removed max-width restriction
- Better integration with sidebar layout
All functionality now complete:
✅ MSAL authentication
✅ Conversation management (CRUD)
✅ Message sending with AI responses
✅ Sidebar with conversation list
✅ Token usage analytics dashboard
✅ Navigation between views
✅ Responsive design
✅ Full RAG enforcement
✅ Citation validation
✅ Multi-turn conversations
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
React Components:
- LoginButton: MSAL login trigger with loading state
- ChatInterface: Main chat UI with message list and input
- App: Complete app with authentication flow and routing
Features:
- Full authentication flow (login → loading → chat)
- Message display with markdown support
- Real-time typing indicator during AI response
- Auto-scroll to latest message
- User/assistant message distinction
- Warning display for unverified responses
- Keyboard shortcuts (Enter to send, Shift+Enter for newline)
- Loading states for all async operations
- User info display with logout button
Styling (components.css):
- Login screen with centered card
- Loading spinner animation
- Message bubbles with avatars
- Typing indicator animation
- User header with logout button
- Responsive design for mobile
- Warning banners for unverified content
- Markdown styling (code blocks, lists, etc.)
App Structure:
- AuthProvider wraps entire app
- ChatProvider for chat state
- AppContent handles auth routing
- Auto-load conversations on login
- Context-based state management
UX Enhancements:
- Smooth animations (slideIn, pulse, bounce)
- Disabled states for buttons during loading
- Error handling with user-friendly messages
- Session persistence across refreshes
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
MSAL Configuration:
- Azure AD authentication setup with MSAL.js
- Session storage for security
- Microsoft Graph API scopes (User.Read, openid, profile, email)
API Service (axios):
- Configured axios client with interceptors
- Automatic Bearer token injection
- Token refresh on 401 errors
- Complete API methods for auth, conversations, messages, tokens
Auth Context:
- AuthProvider with MSAL integration
- Login/logout functionality with popup flow
- Backend JWT session management
- Automatic session verification on mount
- User state management
Chat Context:
- ChatProvider for conversation and message state
- CRUD operations for conversations
- Message sending with AI response handling
- Real-time state updates
- Error handling and loading states
Features:
- Automatic token refresh
- Session persistence in localStorage
- Error recovery with automatic logout
- Type-safe API calls
- Reactive state management
Context Hooks:
- useAuth() - Access authentication state
- useChat() - Access chat functionality
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>