This commit is contained in:
morteza-mortezai
2025-11-30 11:52:38 +03:30
parent ace84fcfb2
commit 9a8515d7ab
3 changed files with 424 additions and 266 deletions
+371
View File
@@ -0,0 +1,371 @@
# Frontend WebSocket Chatbot Implementation Prompt
Create a modern, responsive frontend application for a real-time chatbot system using Socket.IO. The chatbot is designed for an Electrical Power Panels (تابلو برق) e-commerce platform that provides product guidance in Persian/Farsi.
## Technical Requirements
### 1. WebSocket Connection Setup
- **Connection Path**: `/ws-chatbot`
- **Library**: Use Socket.IO client library (socket.io-client)
- **Connection Options**:
- Support both authenticated (with JWT token) and anonymous connections
- Token can be provided via:
- Query parameter: `?token=YOUR_JWT_TOKEN`
- Authorization header: `Authorization: Bearer YOUR_JWT_TOKEN`
- For anonymous users, the system uses a ULID stored in cookies (`chatbot_session_id`)
- CORS is enabled with credentials support
### 2. WebSocket Events to Implement
#### Connection Events
- `connect` - Socket connected successfully
- `disconnect` - Socket disconnected
- `connection_failed` - Connection failed
#### Authentication Events
- **Emit**: `authenticate` (if using token-based auth)
- **Listen**: `authenticated` - Authentication successful
```json
{
"message": "authenticated",
"userId": "user_id",
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
- **Listen**: `unauthorized` - Authentication failed
```json
{
"message": "error_message",
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
#### Session Management Events
- **Emit**: `create_session` - Create a new chat session
- **Listen**: `session_created` - Session created successfully
```json
{
"status": "success",
"data": {
"id": "session_ulid",
"status": "active",
"createdAt": "2024-01-01T00:00:00.000Z",
"lastMessageAt": "2024-01-01T00:00:00.000Z",
"messages": []
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
- **Emit**: `join_chat` - Join an existing chat session (pass sessionId as string)
- **Listen**: `chat_joined` - Successfully joined chat session
```json
{
"status": "success",
"data": {
"id": "session_ulid",
"status": "active",
"createdAt": "2024-01-01T00:00:00.000Z",
"lastMessageAt": "2024-01-01T00:00:00.000Z",
"messages": [
{
"id": "message_ulid",
"content": "message content",
"type": "user" | "bot" | "system",
"status": "sent" | "delivered" | "read" | "failed",
"createdAt": "2024-01-01T00:00:00.000Z",
"responseToId": "optional_message_id",
"metadata": {},
"tokensUsed": 0
}
]
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
- **Emit**: `leave_chat` - Leave a chat session (pass sessionId as string)
- **Listen**: `chat_left` - Successfully left chat session
#### Message Events
- **Emit**: `send_message` - Send a regular message
```json
{
"content": "user message text",
"sessionId": "session_ulid",
"responseToId": "optional_message_id_to_reply_to",
"metadata": {}
}
```
- **Emit**: `send_message_stream` - Send a message and receive streaming response
```json
{
"content": "user message text",
"sessionId": "session_ulid",
"responseToId": "optional_message_id_to_reply_to",
"metadata": {}
}
```
- **Listen**: `message_received` - User message received and saved
```json
{
"status": "success",
"data": {
"id": "message_ulid",
"content": "message content",
"type": "user",
"status": "sent",
"createdAt": "2024-01-01T00:00:00.000Z",
"responseToId": null,
"metadata": {},
"tokensUsed": 0
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
#### Streaming Response Events (for `send_message_stream`)
- **Listen**: `bot_response_start` - Bot started generating response
```json
{
"status": "success",
"data": {
"userMessageId": "message_ulid"
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
- **Listen**: `bot_response_chunk` - Receive a chunk of bot response (streaming)
```json
{
"status": "success",
"data": {
"chunk": "partial text chunk",
"userMessageId": "message_ulid"
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
- **Listen**: `bot_response_end` - Bot finished generating response
```json
{
"status": "success",
"data": {
"userMessageId": "message_ulid",
"fullResponse": "complete bot response text"
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
#### Non-Streaming Bot Response (for `send_message`)
- **Listen**: `bot_response` - Complete bot response received
```json
{
"status": "success",
"data": {
"id": "message_ulid",
"content": "complete bot response",
"type": "bot",
"status": "sent",
"createdAt": "2024-01-01T00:00:00.000Z",
"responseToId": "user_message_ulid",
"metadata": {
"confidence": 0.95,
"sources": [],
"llmContext": {}
},
"tokensUsed": 150
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
#### Typing Indicators
- **Emit**: `typing_start` - User started typing (pass sessionId as string)
- **Emit**: `typing_stop` - User stopped typing (pass sessionId as string)
- **Listen**: `typing_start` - Another user started typing
- **Listen**: `typing_stop` - Another user stopped typing
#### User Presence Events
- **Listen**: `user_joined` - Another user joined the session
- **Listen**: `user_left` - Another user left the session
#### Error Events
- **Listen**: `error` - General error
- **Listen**: `websocket_error` - WebSocket connection error
- **Listen**: `session_error` - Session-related error
- **Listen**: `message_error` - Message-related error
All error events follow this format:
```json
{
"status": "error",
"message": "error message",
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
### 3. REST API Endpoints (Optional - for session management)
The backend also provides REST endpoints that can be used for session management:
- `POST /chatbot/sessions` - Create a new chat session
- `GET /chatbot/sessions?limit=10` - Get user's chat sessions (paginated)
- `GET /chatbot/sessions/:sessionId` - Get a specific chat session with messages
- `POST /chatbot/messages` - Send a message (non-streaming)
- `POST /chatbot/messages/stream` - Send a message and get Server-Sent Events (SSE) streaming
- `PUT /chatbot/sessions/:sessionId/close` - Close a chat session
- `PUT /chatbot/sessions/:sessionId/messages/read` - Mark messages as read
### 4. UI/UX Requirements
#### Design
- Modern, clean, and responsive design
- Support for Persian/Farsi (RTL) text direction
- Mobile-first approach with desktop support
- Dark mode support (optional but recommended)
- Smooth animations and transitions
#### Chat Interface Components
1. **Session List Sidebar** (optional)
- List of all chat sessions
- Show last message preview
- Show unread message count
- Show session status (active/closed)
- Create new session button
2. **Chat Window**
- Message list with scroll-to-bottom functionality
- Message bubbles:
- User messages: Right-aligned (or left in RTL), distinct styling
- Bot messages: Left-aligned (or right in RTL), distinct styling
- System messages: Centered, muted styling
- Show message timestamps (relative or absolute)
- Show message status indicators (sent, delivered, read, failed)
- Support for message replies (if responseToId is provided)
- Markdown rendering for bot messages (if applicable)
- Copy message functionality
3. **Input Area**
- Text input field with character counter (max 2000 characters)
- Send button
- Support for Enter key to send (Shift+Enter for new line)
- Typing indicator display
- File upload support (if needed in future)
- Emoji picker (optional)
4. **Streaming Response Display**
- Show typing indicator when `bot_response_start` is received
- Display streaming text character-by-character or word-by-word as chunks arrive
- Smooth animation for streaming text
- Show completion when `bot_response_end` is received
- Handle errors gracefully during streaming
5. **Connection Status**
- Visual indicator for connection status (connected/disconnected/reconnecting)
- Auto-reconnect functionality with exponential backoff
- Show connection errors to user
6. **Error Handling**
- Display user-friendly error messages
- Retry mechanisms for failed operations
- Toast notifications for errors
- Persian/Farsi error messages
#### Features
- **Real-time Updates**: All messages should appear in real-time
- **Message Persistence**: Load previous messages when joining a session
- **Auto-scroll**: Automatically scroll to bottom when new messages arrive
- **Typing Indicators**: Show when bot is generating response
- **Message Status**: Display sent/delivered/read status for user messages
- **Session Management**: Create, join, leave, and close sessions
- **Responsive Design**: Works on mobile, tablet, and desktop
- **Accessibility**: WCAG 2.1 AA compliance
- **Performance**: Optimize for smooth scrolling with many messages (virtual scrolling if needed)
### 5. State Management
Implement proper state management for:
- WebSocket connection state
- Current active session
- Message list for current session
- Session list
- Typing indicators
- Connection status
- Error states
### 6. Technical Stack Recommendations
- **Framework**: React, Vue, or Angular (your choice)
- **State Management**: Redux, Zustand, Pinia, or Context API
- **WebSocket**: socket.io-client
- **Styling**: Tailwind CSS, Material-UI, or styled-components
- **Icons**: React Icons, Heroicons, or similar
- **Date Formatting**: date-fns or moment.js
- **HTTP Client**: Axios or fetch API
- **Build Tool**: Vite, Create React App, or Next.js
### 7. Implementation Notes
- Handle reconnection automatically
- Store ULID in cookies for anonymous users
- Implement proper cleanup on component unmount
- Debounce typing indicators (send `typing_stop` after 3 seconds of inactivity)
- Implement message queuing for offline scenarios
- Add loading states for all async operations
- Implement proper error boundaries
- Add analytics/tracking (optional)
- Support for keyboard shortcuts (optional)
### 8. Testing Requirements
- Unit tests for WebSocket event handlers
- Integration tests for message flow
- E2E tests for critical user flows
- Test reconnection scenarios
- Test error handling
- Test streaming response display
### 9. Additional Features (Optional)
- Message search within a session
- Export chat history
- Share session link
- Voice input (speech-to-text)
- Message reactions
- Rich text formatting in messages
- Product cards/embeds in bot responses
- Quick reply buttons
### 10. Example Flow
1. User opens the application
2. Application connects to WebSocket (`/ws-chatbot`)
3. If authenticated, token is sent; otherwise, ULID is used from cookie or generated
4. User creates a new session or joins an existing one
5. Previous messages are loaded and displayed
6. User types a message and sends it
7. Message appears immediately in the chat
8. Bot response starts streaming (if using streaming) or arrives as complete message
9. User can continue the conversation
10. Connection is maintained and auto-reconnects if dropped
## Deliverables
Create a complete, production-ready frontend application with:
- Clean, maintainable code structure
- Comprehensive error handling
- Responsive design
- Real-time WebSocket integration
- TypeScript support (recommended)
- Documentation and comments
- README with setup instructions