Chat System

PadawanForge features a comprehensive chat system that supports both public room-based conversations and private direct messaging between players.

System Overview

Chat Types

  • Room Chat: Public conversations within game sessions and lobbies
  • Direct Messages: Private conversations between individual players
  • NPC Chat: AI-powered conversations with non-player characters
  • System Messages: Administrative and notification messages

Real-time Features

  • WebSocket-based real-time messaging
  • Message persistence and history
  • Read receipts and delivery status
  • Message threading and reactions
  • File attachments and rich content

Room Chat System

Architecture

Room chat is built on Durable Objects for real-time communication:

  • ChatLobby: Manages WebSocket connections and message routing
  • RoomManager: Handles room state and participant management
  • Message Persistence: Stores chat history in Cloudflare D1

Features

  • Multi-room Support: Separate chat rooms for different game sessions
  • Player Limits: Configurable maximum participants per room
  • Message Types: Text, system, action, NPC, and announcement messages
  • Moderation Tools: Content filtering and administrative controls
  • Connection Management: Automatic reconnection and error recovery

API Endpoints

// Room chat endpoints
GET  /api/lobby/[id]/messages     // Get room message history
POST /api/lobby/[id]/messages     // Send message to room
GET  /api/lobby/[id]/join         // Join room
POST /api/lobby/[id]/leave        // Leave room

Direct Messages System

Current Status: πŸ”΄ Investigation Required

The direct messages system has complete infrastructure but is reported as non-functional. Investigation is ongoing to identify and resolve the root causes.

Complete Infrastructure

  • βœ… Database Schema: direct_messages table properly defined
  • βœ… API Endpoints: All 5 required endpoints implemented
  • βœ… Frontend Components: DirectMessages component with full UI
  • βœ… Page Integration: /messages route properly configured
  • βœ… Authentication: Session-based auth integrated throughout

Identified Issues

  1. Missing Error Handling: API endpoints lack withErrorHandling wrapper
  2. Silent Failures: Errors not properly logged or displayed to users
  3. Complex Queries: Conversations endpoint uses complex CTE that could fail
  4. Session Issues: getPlayerSession() may be failing silently

API Endpoints

// Direct message endpoints (all implemented)
POST /api/messages/message_send        // Send direct message
GET  /api/messages/conversation/{uuid} // Get conversation history  
GET  /api/messages/conversations       // List all conversations
GET  /api/messages/unread-count       // Get unread message count
PUT  /api/messages/{id}/read          // Mark message as read

Database Schema

CREATE TABLE direct_messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    sender_player_uuid TEXT NOT NULL,
    recipient_player_uuid TEXT NOT NULL,
    content TEXT NOT NULL,
    is_read BOOLEAN DEFAULT FALSE,
    read_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    -- Enhanced fields from v1.2.6
    conversation_id TEXT,                             -- Group conversations by ID
    priority TEXT DEFAULT 'normal' CHECK (priority IN ('low', 'normal', 'high', 'urgent')),
    delivery_status TEXT DEFAULT 'sent' CHECK (delivery_status IN ('pending', 'sent', 'delivered', 'failed')),
    delivery_attempts INTEGER DEFAULT 0,
    expires_at TIMESTAMP,                             -- Message expiration
    is_archived_by_sender BOOLEAN DEFAULT FALSE,
    is_archived_by_recipient BOOLEAN DEFAULT FALSE,
    FOREIGN KEY (sender_player_uuid) REFERENCES players(uuid) ON DELETE CASCADE,
    FOREIGN KEY (recipient_player_uuid) REFERENCES players(uuid) ON DELETE CASCADE
);

Frontend Implementation

// DirectMessages component with full functionality
export function DirectMessages({ player, onMessageRead }: DirectMessagesProps) {
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [messages, setMessages] = useState<DirectMessage[]>([]);
  const [selectedConversation, setSelectedConversation] = useState<string | null>(null);
  const [newMessage, setNewMessage] = useState('');

  // Fetch conversations, send messages, mark as read, etc.
  // Full implementation with error handling and real-time updates
}

Investigation Plan

Phase 1: Diagnostic Logging

  • Add comprehensive logging to all direct message API endpoints
  • Verify getPlayerSession() authentication flow
  • Test frontend API calls with detailed error reporting
  • Validate database queries against actual schema

Phase 2: Error Handling Enhancement

  • Implement withErrorHandling wrapper on all message endpoints
  • Add user-visible error messages in DirectMessages component
  • Simplify complex conversation query to reduce failure points
  • Add proper error boundaries for better debugging

Phase 3: User Experience

  • Add loading states and error feedback
  • Implement proper authentication validation
  • Consider real-time WebSocket integration for live messaging
  • Add message delivery confirmation

NPC Chat System

Features

  • AI-Powered Responses: Integration with multiple AI providers
  • Conversation Memory: Context-aware conversations
  • Personality System: Customizable NPC personalities
  • Knowledge Integration: File-based knowledge for NPCs
  • Learning Analytics: Track interaction patterns and performance

API Endpoints

// NPC chat endpoints
POST /api/npcs/[id]/chat           // Send message to NPC
GET  /api/npcs/[id]/conversations  // Get conversation history
POST /api/npcs/[id]/configure      // Configure NPC settings

Message Types

Text Messages

Standard text-based communication between users.

System Messages

Administrative messages for room management and notifications.

Action Messages

Roleplay and action-based messages (e.g., β€œ/me waves hello”).

NPC Messages

Messages from AI-powered non-player characters.

Announcement Messages

Important announcements and notifications.

Message Features

Threading

Support for threaded conversations with parent-child relationships.

Reactions

Emoji reactions and message feedback system.

Mentions

Player mentions with notification system.

Attachments

File uploads and media sharing capabilities.

Editing

Message editing with history tracking.

Moderation

Content filtering and administrative controls.

Security and Privacy

Message Encryption

  • End-to-end encryption for direct messages
  • Secure transmission over WebSocket connections
  • Database encryption for message storage

Privacy Controls

  • Granular privacy settings for message visibility
  • Block and mute functionality
  • Message retention policies

Moderation Tools

  • Content filtering and keyword detection
  • Administrative message management
  • User reporting and appeal system

Performance Optimization

Message Caching

  • Redis-based message caching for frequently accessed conversations
  • Pagination for large message histories
  • Lazy loading for message attachments

Database Optimization

  • Efficient indexing for message queries
  • Message archival for old conversations
  • Database partitioning for large datasets

Real-time Performance

  • WebSocket connection pooling
  • Message batching for high-volume scenarios
  • Load balancing across multiple chat servers

Monitoring and Analytics

Message Metrics

  • Message volume and frequency tracking
  • User engagement and activity patterns
  • Conversation quality and satisfaction metrics

Performance Monitoring

  • Response time tracking for message delivery
  • WebSocket connection health monitoring
  • Database query performance analysis

Error Tracking

  • Message delivery failure monitoring
  • Authentication and authorization error tracking
  • System error correlation and alerting

Future Enhancements

Planned Features

  • Voice Messages: Audio message support
  • Video Chat: Real-time video communication
  • Group Chats: Multi-participant private conversations
  • Message Search: Advanced search and filtering
  • Message Translation: Multi-language support

Technical Improvements

  • WebRTC Integration: Peer-to-peer communication
  • Message Encryption: Enhanced security features
  • AI Moderation: Automated content moderation
  • Analytics Dashboard: Advanced reporting and insights

Troubleshooting

Common Issues

Direct Messages Not Working

Symptoms: Messages not sending or receiving Investigation Steps:

  1. Check browser console for JavaScript errors
  2. Verify API endpoint responses
  3. Check session authentication status
  4. Validate database connectivity

Room Chat Connection Issues

Symptoms: Cannot join rooms or messages not appearing Investigation Steps:

  1. Check WebSocket connection status
  2. Verify Durable Object availability
  3. Check room permissions and settings
  4. Validate user authentication

Message Delivery Delays

Symptoms: Messages taking time to appear Investigation Steps:

  1. Check network connectivity
  2. Verify server performance metrics
  3. Check database query performance
  4. Monitor WebSocket connection health

Debug Tools

  • Chat Debug Panel: Real-time connection and message monitoring
  • API Response Logging: Detailed endpoint response tracking
  • Database Query Monitoring: Performance and error tracking
  • WebSocket Connection Testing: Connection health validation
PadawanForge v1.4.1