Home · Developers · Guides · WebSocket Client Library

Interfaces

WebSocket Client Library

WS client contract

Architecture note (2026-11): novacoder/web/static/js/websocket-client.js (WebSocketManager) has been removed. In the React SPA, realtime updates use novacoder/web/react/src/hooks/useEventStream.ts, a reconnecting WebSocket hook over the /ws/{channel} channels (/ws/chat, /ws/agents, /ws/workspace, /ws/system) with optional novacoder-token.* subprotocol auth; the interactive terminal uses a direct WebSocket to /ws/terminal in components/ide/TerminalPanel.tsx. The WebSocketManager API documented below no longer exists.

The Nova Coder web interface includes a comprehensive WebSocket client library for real-time communication with the server. The library provides automatic reconnection, message handling, room management, and channel-specific clients for different use cases.

Overview

The WebSocket client library is implemented in novacoder/web/static/js/websocket-client.js and provides:

  • Base WebSocketClient: Core client with automatic reconnection
  • Channel-specific clients: Pre-configured clients for different channels
  • 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

Usage

The WebSocket client library is loaded in index.html before app.js and is available globally as WebSocketManager:

// Get a client for a specific channel
const chatClient = WebSocketManager.getClient('chat');

// Use the client
chatClient.connect();
chatClient.send({ type: 'message', content: 'Hello' });

Base WebSocketClient

Constructor

const client = new WebSocketClient();

Properties

  • ws (WebSocket): The underlying WebSocket connection
  • connectionId (string): Unique connection ID assigned by server
  • channel (string): Current channel
  • reconnectAttempts (number): Number of reconnection attempts
  • maxReconnectAttempts (number): Maximum reconnection attempts (default: 5)
  • reconnectDelay (number): Reconnection delay in ms (default: 1000)
  • messageHandlers (object): Registered message handlers
  • connectionState (string): Current connection state
  • userId (string): Generated user ID

Methods

connect()

Connect to a WebSocket channel:

client.connect(channel, options)

Parameters:

  • channel (string): Channel to connect to (default: default)
  • options (object): Connection options

Example:

client.connect('chat');

disconnect()

Disconnect from the server:

client.disconnect()

Example:

client.disconnect();

send()

Send a message to the server:

client.send(message)

Parameters:

  • message (object): Message to send

Example:

client.send({ type: 'message', content: 'Hello' });

on()

Register a message handler:

client.on(messageType, handler)

Parameters:

  • messageType (string): Message type to handle
  • handler (function): Handler function

Example:

client.on('connected', (data) => {
    console.log('Connected:', data);
});

off()

Remove a message handler:

client.off(messageType, handler)

Parameters:

  • messageType (string): Message type
  • handler (function): Handler function to remove

Example:

client.off('connected', handler);

getState()

Get current connection state:

const state = client.getState()

Returns: Connection state string (disconnected, connecting, connected, error)

isConnected()

Check if connected:

const connected = client.isConnected()

Returns: Boolean

joinRoom()

Join a collaboration room:

client.joinRoom(roomId)

Parameters:

  • roomId (string): Room ID to join

Example:

client.joinRoom('session_123');

leaveRoom()

Leave a collaboration room:

client.leaveRoom(roomId)

Parameters:

  • roomId (string): Room ID to leave

Example:

client.leaveRoom('session_123');

sendToRoom()

Send a message to a room:

client.sendToRoom(roomId, message)

Parameters:

  • roomId (string): Room ID
  • message (object): Message content

Example:

client.sendToRoom('session_123', { type: 'update', data: {...} });

Channel-Specific Clients

ChatWebSocketClient

Client for chat streaming:

const chatClient = new ChatWebSocketClient();

Methods:

  • sendMessage(content): Send a chat message

Example:

const chatClient = new ChatWebSocketClient();
chatClient.sendMessage('Hello, world!');

AgentWebSocketClient

Client for agent updates:

const agentClient = new AgentWebSocketClient();

Methods:

  • subscribeToAgent(agentId): Subscribe to agent updates
  • unsubscribeFromAgent(agentId): Unsubscribe from agent updates

Example:

const agentClient = new AgentWebSocketClient();
agentClient.subscribeToAgent('coder');

WorkspaceWebSocketClient

Client for workspace updates:

const workspaceClient = new WorkspaceWebSocketClient();

Methods:

  • subscribeToPath(path): Subscribe to path updates

Example:

const workspaceClient = new WorkspaceWebSocketClient();
workspaceClient.subscribeToPath('/src');

SystemWebSocketClient

Client for system monitoring:

const systemClient = new SystemWebSocketClient();

CollaborationWebSocketClient

Client for collaboration features:

const collabClient = new CollaborationWebSocketClient();

Methods:

  • joinSession(sessionId): Join a collaboration session
  • leaveSession(sessionId): Leave a collaboration session
  • sendCursorUpdate(sessionId, position): Send cursor position
  • sendEdit(sessionId, edit): Send edit operation

Example:

const collabClient = new CollaborationWebSocketClient();
collabClient.joinSession('session_123');
collabClient.sendCursorUpdate('session_123', { line: 10, column: 5 });
collabClient.sendEdit('session_123', {
    type: 'text',
    range: { start: 0, end: 10 },
    text: 'replacement'
});

DashboardWebSocketClient

Client for dashboard updates:

const dashboardClient = new DashboardWebSocketClient();

NotificationWebSocketClient

Client for notifications:

const notificationClient = new NotificationWebSocketClient();

Global WebSocketManager

The global WebSocketManager manages multiple WebSocket connections:

getClient()

Get or create a client for a channel:

const client = WebSocketManager.getClient(channel)

Parameters:

  • channel (string): Channel name

Returns: WebSocket client instance

Example:

const chatClient = WebSocketManager.getClient('chat');
const agentClient = WebSocketManager.getClient('agents');

disconnectAll()

Disconnect all clients:

WebSocketManager.disconnectAll()

Example:

WebSocketManager.disconnectAll();

getStatus()

Get connection status for all channels:

const status = WebSocketManager.getStatus()

Returns: Object with channel names and connection states

Example:

const status = WebSocketManager.getStatus();
// Returns: { chat: 'connected', agents: 'disconnected', ... }

Message Handling

Built-in Message Types

The client automatically handles these message types:

  • connected: Connection established
  • disconnected: Connection closed
  • error: Connection error
  • message: Generic message

Custom Message Handlers

Register handlers for custom message types:

client.on('custom_type', (message) => {
    console.log('Custom message:', message);
});

Message Format

Messages from the server include:

{
    "type": "message_type",
    "content": "message content",
    "timestamp": "2024-01-01T00:00:00Z"
}

Connection Events

connected

Fired when connection is established:

client.on('connected', (data) => {
    console.log('Connected:', data.connectionId);
    console.log('Channel:', data.channel);
});

disconnected

Fired when connection is closed:

client.on('disconnected', (data) => {
    console.log('Disconnected:', data.code, data.reason);
});

error

Fired when connection error occurs:

client.on('error', (data) => {
    console.error('Connection error:', data.error);
});

message

Fired for all messages:

client.on('message', (message) => {
    console.log('Received:', message);
});

Automatic Reconnection

The client automatically attempts to reconnect on disconnection:

  • Exponential backoff: Delay doubles with each attempt
  • Maximum attempts: 5 attempts by default
  • Configurable: Can be customized via maxReconnectAttempts and reconnectDelay

Example:

const client = new WebSocketClient();
client.maxReconnectAttempts = 10;
client.reconnectDelay = 2000;

Room Management

Joining a Room

client.joinRoom('session_123');

Server response:

{
    "type": "user_joined",
    "room_id": "session_123",
    "user_id": "user_abc",
    "member_count": 3,
    "timestamp": "2024-01-01T00:00:00Z"
}

Leaving a Room

client.leaveRoom('session_123');

Server response:

{
    "type": "user_left",
    "room_id": "session_123",
    "user_id": "user_abc",
    "member_count": 2,
    "timestamp": "2024-01-01T00:00:00Z"
}

Sending to Room

client.sendToRoom('session_123', { type: 'update', data: {...} });

Example Usage

Basic Chat Client

const chatClient = WebSocketManager.getClient('chat');

// Register handlers
chatClient.on('connected', (data) => {
    console.log('Connected to chat');
});

chatClient.on('message', (message) => {
    if (message.type === 'chat_chunk') {
        console.log('Chat chunk:', message.content);
    }
});

// Send message
chatClient.send({ type: 'message', content: 'Hello' });

Agent Monitoring

const agentClient = WebSocketManager.getClient('agents');

// Subscribe to agent
agentClient.subscribeToAgent('coder');

// Handle agent updates
agentClient.on('message', (message) => {
    if (message.type === 'agent_update') {
        console.log('Agent status:', message.status);
    }
});

Collaboration Session

const collabClient = WebSocketManager.getClient('collaboration');

// Join session
collabClient.joinSession('session_123');

// Handle room events
collabClient.on('message', (message) => {
    if (message.type === 'user_joined') {
        console.log('User joined:', message.user_id);
    } else if (message.type === 'cursor_update') {
        console.log('Cursor moved:', message.position);
    }
});

// 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');

Multiple Connections

// Get multiple clients
const chatClient = WebSocketManager.getClient('chat');
const agentClient = WebSocketManager.getClient('agents');
const systemClient = WebSocketManager.getClient('system');

// Check status
const status = WebSocketManager.getStatus();
console.log('Connection status:', status);

// Disconnect all when done
WebSocketManager.disconnectAll();

Integration

The WebSocket client library is integrated into the web interface through:

  1. HTML Loading: Loaded in index.html before app.js
  2. Global Access: Available as WebSocketManager global object
  3. User ID: Automatically generated and included in connection URL
  4. Protocol Detection: Automatically uses ws:// or wss:// based on page protocol

Best Practices

Connection Management

  • Always disconnect clients when no longer needed
  • Use WebSocketManager.disconnectAll() on page unload
  • Check connection state before sending messages

Error Handling

  • Register error handlers for all clients
  • Handle disconnection gracefully
  • Implement fallback mechanisms for critical features

Performance

  • Reuse clients instead of creating new ones
  • Use channel-specific clients for better organization
  • Clean up message handlers when no longer needed

Security

  • Validate all incoming messages
  • Sanitize message content before rendering
  • Use secure WebSocket (wss://) in production

Source: wiki/web-interface-websocket-client.md · rendered 2026-11-10