Goal
Transform your working application into a secure, polished, production-ready system that students can use reliably. This stage adds the protective measures, error handling, and user experience improvements that make the difference between "it works on my machine" and "students can use this every day."
By the end of this stage, you'll have a complete educational AI chat interface that handles errors gracefully, prevents abuse, displays content beautifully, and provides a polished user experience.
Before You Begin
Pre-flight checklist:
- Stage 4 is complete and working
- Review
architecture.mdsections on "API Proxy Layer" and "Security Considerations" - Review
testing.mdfor production testing strategies - Update your TODO list with Stage 5 tasks
Components to Build
1. Rate Limiting System
A mechanism that prevents abuse by limiting how frequently requests can be made from a given client.
Why it exists: Protects against runaway API costs, prevents accidental infinite loops, and discourages malicious use. Without rate limiting, one misbehaving script or malicious actor could generate thousands of API requests.
What it does:
- Tracks request timestamps per client (usually by IP address)
- Enforces minimum interval between requests (typically 1-2 seconds)
- Returns clear error message when limit exceeded
- Uses filesystem-based tracking for simplicity
2. Enhanced Error Handling
Comprehensive error detection and user-friendly error messages throughout the system.
Why it exists: Errors will happen—API timeouts, network issues, malformed requests, quota exceeded. Students should see helpful messages, not cryptic failures or blank screens.
What it covers:
- API provider errors (timeout, rate limit, invalid request, quota exceeded)
- Network connectivity issues
- Configuration errors (missing files, invalid JSON)
- Storage errors (quota exceeded, permission denied)
- Clear, actionable error messages for each scenario
3. Security Headers
HTTP headers that protect against common web vulnerabilities.
Why it exists: Defense in depth. Even though your application is relatively simple, proper security headers protect against XSS attacks, clickjacking, and other common exploits.
What to implement:
- Content Security Policy (CSP) to restrict resource loading
- X-XSS-Protection header
- X-Frame-Options to prevent clickjacking
- X-Content-Type-Options to prevent MIME sniffing
- HTTPS enforcement where possible
4. Markdown Rendering
Client-side rendering of AI responses with proper formatting, including code blocks, lists, emphasis, and links.
Why it exists: AI models return markdown-formatted text. Without rendering, students see raw markdown (**bold**, - list items, etc.). With rendering, content is readable and properly formatted.
What to use:
- Markdown rendering library (Marked, Showdown, or similar)
- Syntax highlighting for code blocks (optional but helpful)
- Proper HTML escaping to prevent XSS via rendered content
5. UI Enhancements
Polish the interface for better usability and student experience.
Why it exists: Small improvements make big differences in daily use. Keyboard shortcuts, loading states, and clear affordances make the tool feel professional and reliable.
What to add:
- Keyboard shortcuts (Enter to send, Shift+Enter for newlines)
- Clear loading indicators during API requests
- Conversation titles (editable by students)
- Timestamps on conversations
- Clear visual distinction between user and AI messages
- Empty states (helpful messages when no conversations exist)
6. Logging and Debugging Output
Server-side logging for troubleshooting and monitoring with automatic log rotation.
Why it exists: When issues occur in production, you need visibility into what happened. Logs help diagnose problems without direct access to student browsers.
What to log:
- API request/response errors
- Rate limit violations
- Configuration loading errors
- Timestamp, IP address, and error type for each incident
- Avoid logging conversation content (privacy)
Log rotation:
- Automatically clean up old logs to prevent disk space issues
- Retain recent logs (30-90 days is reasonable for text files)
- Implement rotation when log file reaches certain size or age
7. Configuration Editor
A web-based interface for editing configuration files without FTP or file manager access.
Why it exists: Makes the system accessible to educators who aren't comfortable editing JSON files directly. Essential for giving teachers autonomy to experiment with conversation frameworks and learning supports without technical barriers.
What it provides:
- View current conversation frameworks and learning supports
- Create new frameworks and supports with automatically generated unique IDs
- Edit existing frameworks and supports
- Delete frameworks and supports
- Validate configuration structure before saving
- Write updated configuration back to files
- Authentication or IP restriction (don't expose publicly)
Implementation Tasks
Update your TODO list with these tasks and track progress as you work.
Implement Rate Limiting
-Create rate limiting component
-Track request timestamps per client IP
-Enforce minimum interval (1-2 seconds recommended)
-Return HTTP 429 status when limit exceeded
-Provide clear error message to client
-Use filesystem locks or simple file-based tracking
-Test that rate limiting triggers correctly
Enhance Error Handling
-Identify all potential error points in the system
-Add try/catch blocks around API calls
-Handle specific API provider error codes (timeout, quota, invalid)
-Handle network connectivity failures
-Handle configuration read errors
-Handle storage errors on client side
-Create user-friendly error messages for each scenario
-Display errors prominently in UI
-Log errors server-side for debugging
Add Security Headers
-Implement Content Security Policy header
-Add X-XSS-Protection header
-Add X-Frame-Options header
-Add X-Content-Type-Options header
-Test headers using browser DevTools or online security scanner
-Enforce HTTPS if available in hosting environment
Implement Markdown Rendering
-Include markdown rendering library (CDN or local)
-Render AI responses as formatted HTML
-Ensure user input is HTML-escaped before display
-Test with various markdown features (bold, lists, code blocks, links)
-Optionally add syntax highlighting for code blocks
-Verify no XSS vulnerabilities in rendered content
Polish the UI
-Add keyboard shortcuts (Enter to send, Shift+Enter for newline)
-Improve loading states (spinner, disabled input during request)
-Display token usage after each response
-Make conversation titles editable
-Show last modified dates on conversations for sorting
-Improve visual distinction between user and AI messages
-Add helpful empty state messages
-Test UI on different screen sizes (mobile, tablet, desktop)
-Ensure keyboard navigation works throughout
Add Logging
-Create server-side logging mechanism
-Log API errors with timestamp and IP
-Log rate limit violations
-Log configuration errors
-Ensure logs don't contain sensitive data or conversation content
-Implement automatic log rotation (retain 30-90 days, rotate by size or age)
-Test that errors appear in logs correctly
-Verify old logs are cleaned up automatically
Build Configuration Editor
-Create web interface for configuration editing
-Load and display current configuration
-Provide forms for editing settings
-Validate JSON before saving
-Write updated configuration back to file
-Add authentication or IP restriction
-Test thoroughly before using in production
Final System Testing
-Test complete workflow: create conversation, save, load, continue
-Test all error scenarios (disconnect network, invalid API key, etc.)
-Test rate limiting by sending rapid requests
-Test on different browsers and devices
-Verify security headers present
-Check markdown rendering with complex formatting
-Verify no console errors in browser DevTools
-Test keyboard shortcuts
-Review logs to confirm error tracking works
Success Indicators
When Stage 5 is complete, you should observe these behaviors:
Rate Limiting Working
- ✓ Rapid successive requests are blocked with clear error message
- ✓ After waiting the required interval, requests succeed again
- ✓ Rate limit violations appear in server logs
Error Handling
- ✓ Network disconnection shows helpful error message (not broken interface)
- ✓ Invalid API key produces clear error
- ✓ API timeout handled gracefully
- ✓ Storage quota errors display actionable message
- ✓ All errors logged server-side for review
Security Headers
- ✓ Security headers visible in browser DevTools Network tab
- ✓ CSP policy blocks unauthorized resource loading
- ✓ Application cannot be embedded in iframe (X-Frame-Options working)
Markdown Rendering
- ✓ AI responses display with proper formatting (bold, italic, lists)
- ✓ Code blocks render with monospace font and background
- ✓ Links are clickable
- ✓ No raw markdown visible in responses
UI Polish
- ✓ Enter key sends message, Shift+Enter creates new line
- ✓ Loading indicator appears during API requests
- ✓ Token usage displays after each response
- ✓ Conversation titles are editable
- ✓ Timestamps show when conversations were last updated
- ✓ User and AI messages clearly distinguishable
- ✓ Interface works on mobile devices
Logging
- ✓ Server logs contain recent errors with timestamps
- ✓ Logs include enough information to diagnose issues
- ✓ Logs do not contain conversation content or sensitive data
Configuration Editor
- ✓ Can view current configuration through web interface
- ✓ Can edit and save configuration changes
- ✓ Invalid JSON prevented from saving
- ✓ Access restricted to authorized users/IPs
- ✓ Teachers can modify conversation frameworks and learning supports without FTP access
Overall System
- ✓ Application feels polished and professional
- ✓ Students can use it reliably without encountering confusing errors
- ✓ You can monitor and troubleshoot issues through logs
- ✓ System handles edge cases and errors gracefully
Testing and Verification
Before declaring the system production-ready:
- Stress test: Send many rapid requests to verify rate limiting
- Break things intentionally: Disconnect network, invalidate API key, corrupt config file—verify graceful handling
- Cross-browser testing: Test on Chrome, Firefox, Safari, mobile browsers
- Security audit: Check headers, test for XSS vulnerabilities, verify API key never exposed
- User acceptance testing: Have a colleague or student use the system and provide feedback
- Log review: Check that errors are being logged appropriately
- Mobile testing: Verify interface works on phones and tablets
- Accessibility check: Test keyboard navigation, screen reader compatibility (basic)
Consult testing.md for additional verification strategies and troubleshooting guidance.
Generate System Documentation
As your final task, create comprehensive technical documentation of your completed system. This documentation serves as a reference for future customization work and helps you understand the specific implementation you've built.
Why this matters: You've just built a complex system through five stages. Having detailed documentation of your specific build—file structure, JSON schemas, how components interact—makes customization and troubleshooting much easier.
Create a technical reference document (e.g., docs/system-reference.md) that includes:
- File Structure: Complete listing of all files and their purposes
- JSON Schemas: Structure and field definitions for all configuration files (config.json, conversation-frameworks.json, learning-supports.json)
- Component Interactions: How the pieces work together (configuration loading, instruction assembly, API proxy flow, storage operations)
- Key Functions: Description of important server-side and client-side functions
- Configuration Options: Available settings and their effects
- API Integration Details: How your system connects to your specific AI provider
- Storage Architecture: How conversations are stored, namespaced, and retrieved
- Customization Entry Points: Where to make common modifications
This documentation becomes part of your project and serves as a foundation for the customization work to follow.
STOP: Final Review and Deployment
Before deploying to students:
- ✓ All five stages working completely
- ✓ Security measures in place (rate limiting, headers, error handling)
- ✓ UI polished and user-friendly
- ✓ Tested across browsers and devices
- ✓ Logs working for troubleshooting
- ✓ Configuration reflects your pedagogical approach
When Stage 5 is complete:
- Update your TODO list - mark Stage 5 tasks complete
- Create a final git commit with your production-ready code