---
title: WebChat
description: Built-in WebSocket channel for custom web interfaces and CLI tools.
---

## Setup

```bash
pnpm add ws
```

## Usage

```typescript
import { webchatChannel } from '@cogitator-ai/channels';

const webchat = webchatChannel({
  port: 3100,
  path: '/ws',
  auth: (token) => token === process.env.WEBCHAT_SECRET,
});
```

## Configuration

```typescript
interface WebChatConfig {
  port: number;
  path?: string;       // default: '/ws'
  auth?: (token: string) => boolean;
}
```

## Connecting

WebSocket URL: `ws://localhost:3100/ws?token=YOUR_SECRET`

### With wscat

```bash
npx wscat -c "ws://localhost:3100/ws?token=secret"
> {"text": "Hello!"}
```

### From JavaScript

```javascript
const ws = new WebSocket('ws://localhost:3100/ws?token=secret');
ws.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  if (msg.type === 'message') console.log('Bot:', msg.text);
  if (msg.type === 'edit') console.log('Bot (updated):', msg.text);
};
ws.onopen = () => ws.send(JSON.stringify({ text: 'Hi!' }));
```

## Protocol

### Client → Server

```json
{ "text": "Hello!", "id": "optional-id" }
```

### Server → Client

| Type | Fields | Description |
|------|--------|-------------|
| `connected` | `clientId` | Connection established |
| `message` | `id`, `text` | New message |
| `edit` | `id`, `text` | Updated message (streaming) |
| `typing` | — | Agent is thinking |
| `file` | `filename`, `mimeType`, `url` | File attachment |
| `error` | `message` | Error |

## Features

| Feature | Support |
|---------|---------|
| Streaming (edit) | ✅ |
| Typing indicator | ✅ |
| Token auth | ✅ |
| File metadata | ✅ |
| Message length limit | None |
| Multiple clients | ✅ (each gets own session) |

## Tips

- Perfect for building custom chat UIs
- Auth is optional but recommended for production
- Each WebSocket connection is treated as a separate user
- Use with reverse proxy (nginx) for TLS in production
