The Nova Coder API supports WebSocket connections for real-time updates and streaming.
Overview
WebSocket support enables real-time bidirectional communication between clients and the server, allowing for live updates, streaming responses, and efficient push notifications. The enhanced WebSocket system includes connection metadata tracking, room management for collaboration, and timestamp tracking for all messages.
WebSocket Endpoints
Chat WebSocket
- Endpoint:
ws://localhost:8000/ws/chat?user_id={id} - Purpose: Real-time chat streaming
- Channel:
chat - Parameters:
user_id(optional) - User identifier for connection tracking
Agents WebSocket
- Endpoint:
ws://localhost:8000/ws/agents?user_id={id} - Purpose: Real-time agent execution updates
- Channel:
agents - Parameters:
user_id(optional) - User identifier for connection tracking
Workspace WebSocket
- Endpoint:
ws://localhost:8000/ws/workspace?user_id={id} - Purpose: Real-time workspace updates
- Channel:
workspace - Parameters:
user_id(optional) - User identifier for connection tracking
System WebSocket
- Endpoint:
ws://localhost:8000/ws/system?user_id={id} - Purpose: Real-time system monitoring
- Channel:
system - Parameters:
user_id(optional) - User identifier for connection tracking
Authentication
WebSocket connections require authentication, the HTTP token middleware does not cover /ws/*, so the handshake itself is checked in routes_websocket.py:
- Session cookie: a valid
novacoder_sessioncookie (set byPOST /api/auth/login) is accepted automatically for same-origin clients, this is how the React SPA authenticates. - Token: the API token may be supplied via the
tokenquery parameter or thex-api-token/Authorization: Bearerhandshake headers. - Unauthenticated handshakes are rejected with HTTP 403 before the socket opens.
Event Delivery
api/websocket.py bridges the kernel EventBus into channel clients during the lifespan (wire_event_bus(loop)):
- Channel routing:
AgentRun*/Workflow*events →agents;Index*/Workspace*events →workspace;Service*/Application*events →system; chat/messages →chat. - History replay: the most recent events per channel are replayed to new subscribers on connect.
- Burst coalescing: rapid-fire events are coalesced so bursty services cannot flood clients; suppressed events arrive as an aggregate count.
- Connection metadata: each socket receives a
connectedwelcome frame containingconnection_id,channel, and timestamps. - Real progress events:
AgentRunStarted,WorkflowExecutionStarted/Completed/Failed, andIndexScanStartedare published from the API entry points (routes_agents.py,routes_workflows_2.py,routes_indexing.py).
React consumption
novacoder/web/react/src/hooks/useEventStream.ts wraps reconnect/auth/state for SPA pages and is consumed by the Layout topbar (live indicator), Indexing/Workspace (scan progress), Workflows/Agents (execution feed), and System (service lifecycle) pages. Polling remains as fallback.
WebSocket Channels
The system uses predefined channels for different types of updates:
- chat: Chat messages and streaming responses
- agents: Agent execution updates
- workspace: Workspace changes and scan results
- memory: Memory updates
- system: System health and metrics
- tools: Tool execution updates
- collaboration: Real-time collaboration features (NEW)
- dashboard: Real-time dashboard updates (NEW)
- notifications: Real-time notifications (NEW)
Enhanced Features
Connection Metadata Tracking
Each WebSocket connection is tracked with metadata:
{
"connection_id": "uuid",
"channel": "chat",
"user_id": "user_abc123",
"connected_at": "2024-01-01T00:00:00Z",
"last_activity": "2024-01-01T00:00:00Z"
}
Room Management
The WebSocket manager supports room-based collaboration:
# Join a room
await manager.join_room(websocket, room_id="session_123", user_id="user_abc")
# Leave a room
await manager.leave_room(websocket, room_id="session_123", user_id="user_abc")
# Send message to room
await manager.send_to_room({"type": "update", "data": {...}}, room_id="session_123")
Timestamp Tracking
All messages include automatic timestamps:
{
"type": "message",
"content": "Hello",
"timestamp": "2024-01-01T00:00:00Z"
}
Usage Examples
Basic WebSocket Connection
const ws = new WebSocket('ws://localhost:8000/ws/chat?user_id=user_123');
ws.onopen = () => {
console.log('WebSocket connected');
ws.send(JSON.stringify({ message: 'Hello' }));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
ws.onclose = () => {
console.log('WebSocket disconnected');
};
Using the WebSocket Client Library
// Get a client for a specific channel
const chatClient = WebSocketManager.getClient('chat');
// Register message handlers
chatClient.on('connected', (data) => {
console.log('Connected:', data);
});
chatClient.on('message', (message) => {
console.log('Received:', message);
});
// Send a message
chatClient.send({ type: 'message', content: 'Hello' });
// Disconnect
chatClient.disconnect();
Collaboration Room Example
const collabClient = WebSocketManager.getClient('collaboration');
// Join a collaboration session
collabClient.joinSession('session_123');
// Send cursor updates
collabClient.sendCursorUpdate('session_123', { line: 10, column: 5 });
// Send edits
collabClient.sendEdit('session_123', {
type: 'text',
range: { start: 0, end: 10 },
text: 'replacement'
});
// Leave session
collabClient.leaveSession('session_123');
Python WebSocket Client
import asyncio
import websockets
import json
async def chat_websocket():
uri = "ws://localhost:8000/ws/chat?user_id=user_123"
async with websockets.connect(uri) as websocket:
# Send message
await websocket.send(json.dumps({"message": "Hello"}))
# Receive response
response = await websocket.recv()
data = json.loads(response)
print(f"Received: {data}")
asyncio.run(chat_websocket())
Message Format
Client to Server
{
"type": "message",
"content": "Your message here"
}
Server to Client
{
"type": "chat_chunk",
"content": "Partial response",
"timestamp": "2024-01-01T00:00:00Z"
}
Connection Welcome Message
{
"type": "connected",
"connection_id": "uuid",
"channel": "chat",
"timestamp": "2024-01-01T00:00:00Z"
}
Room Messages
{
"type": "user_joined",
"room_id": "session_123",
"user_id": "user_abc",
"member_count": 3,
"timestamp": "2024-01-01T00:00:00Z"
}
Implementation
The WebSocket support is implemented via the enhanced WebSocketManager in novacoder/api/websocket.py:
from novacoder.api.websocket import WebSocketManager, WebSocketChannels
manager = WebSocketManager()
# Connect with user tracking
connection_id = await manager.connect(websocket, channel="chat", user_id="user_123")
# Get connection info
info = manager.get_connection_info(websocket)
# Get all connections in a channel
connections = manager.get_channel_connections("chat")
Connection Management
The WebSocket manager handles:
- Connection lifecycle (connect/disconnect)
- Connection metadata tracking (connection_id, user_id, timestamps)
- Channel-based message routing
- Broadcasting to multiple clients with exclude option
- Personal messaging to specific clients
- Room management for collaboration
- Connection count tracking
- Connection info retrieval
WebSocket Client Library
The JavaScript WebSocket client library provides:
- Base WebSocketClient: Automatic reconnection with exponential backoff
- Channel-specific clients: Chat, Agent, Workspace, System, Collaboration, Dashboard, Notification
- Message handlers: Register handlers for specific message types
- Room management: Join/leave rooms, send messages to rooms
- Connection state tracking: Monitor connection status
- Global WebSocketManager: Manage multiple connections
See WebSocket Client Library for detailed documentation.
Security
WebSocket connections inherit the same authentication as HTTP endpoints. Use the same token-based authentication when establishing WebSocket connections. The user_id parameter is optional and defaults to "anonymous" if not provided.
Related Documentation
- REST API
- API Versioning
- API Reference
- WebSocket Client Library
- Standardized API Responses
Debugging Status
✅ Verified Working: All WebSocket components have been debugged and verified:
- WebSocketManager class works correctly
- WebSocketChannels constants work correctly
- Connection management works correctly
- Channel-based broadcasting works correctly
- Connection metadata tracking works correctly
- Room management for collaboration works correctly
- Timestamp tracking works correctly
- 4 WebSocket endpoints registered in _routes.py
- No import conflicts with existing systems
- Integration with FastAPI works correctly