> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch35-web-console-ui/35.3-webchat-implementation.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 35.3 WebChat Implementation

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~160k tokens, Output \~7k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

The previous section analyzed the overall architecture of the Control UI. This section focuses on WebChat—the chat interface within the console, which is the primary entry point for users to directly converse with the AI assistant. We'll analyze how WebChat functions as a Gateway WebSocket client and the complete workflow of chat history loading and message sending.

## 35.3.1 WebChat as Gateway WS Client

### WebChat's Positioning

WebChat is not an independent chat service—it's essentially a client of the Gateway WebSocket protocol, at the same level as channels like Telegram and Discord. The difference is:

| Feature           | WebChat                           | Telegram/Discord etc.                     |
| ----------------- | --------------------------------- | ----------------------------------------- |
| Connection Method | Browser WebSocket                 | Server-side persistent connection/Webhook |
| Client Mode       | `mode: "webchat"`                 | `mode: "channel"`                         |
| Role              | `role: "operator"`                | `role: "channel"`                         |
| Authentication    | Ed25519 device signature + Token  | API Token/OAuth                           |
| Session Selection | User can freely switch sessionKey | Platform message auto-routes              |

When WebChat connects to Gateway, it declares itself as an `openclaw-control-ui` client with mode `webchat` and role `operator`:

```typescript
// ui/src/ui/gateway.ts (connection parameters)
const params = {
  minProtocol: 3,
  maxProtocol: 3,
  client: {
    id: "openclaw-control-ui",
    mode: "webchat",
    platform: navigator.platform ?? "web",
  },
  role: "operator",
  scopes: ["operator.admin", "operator.approvals", "operator.pairing"],
};
```

The `operator` role has full administrative permissions, including admin operations, execution approvals, and device pairing. This means WebChat can not only chat but also control session lifecycle through chat commands (like `/new`, `/stop`).

### Session Key (Session Key)

The core concept of WebChat is **sessionKey**—it determines the context of the user's current conversation. A sessionKey is a string identifier, for example `"main"`, `"agent:researcher:main"`, etc. Users can freely switch sessions in the UI.

```typescript
// ui/src/ui/app-chat.ts
function resolveAgentIdForSession(host: ChatHost): string | null {
  // Parse agentId from sessionKey (e.g., "agent:researcher:main" → "researcher")
  const parsed = parseAgentSessionKey(host.sessionKey);
  if (parsed?.agentId) return parsed.agentId;
  // Fall back to default agent
  return snapshot?.sessionDefaults?.defaultAgentId || "main";
}
```

When switching sessionKey, the UI clears the current chat draft, streaming content, running state, and tool stream, then reloads the history messages and avatar for the corresponding session:

```typescript
// ui/src/ui/app-render.ts (callback for session switching)
onSessionKeyChange: (next) => {
  state.sessionKey = next;
  state.chatMessage = "";
  state.chatAttachments = [];
  state.chatStream = null;
  state.chatRunId = null;
  state.chatQueue = [];
  state.resetToolStream();
  state.resetChatScroll();
  state.applySettings({
    ...state.settings,
    sessionKey: next,
    lastActiveSessionKey: next,
  });
  void loadChatHistory(state);
  void refreshChatAvatar(state);
},
```

### Event-Driven Chat Updates

After sending a message, the UI doesn't synchronously wait for a complete reply. Instead, it updates the interface in real-time through `chat` events pushed by Gateway:

```typescript
// ui/src/ui/controllers/chat.ts
export type ChatEventPayload = {
  runId: string;          // Unique identifier for this conversation turn
  sessionKey: string;     // Target session
  state: "delta" | "final" | "aborted" | "error";
  message?: unknown;      // Partial response when delta
  errorMessage?: string;  // Error message when error
};
```

The event state machine transitions:

```
Send message → chatRunId set
   │
   ├─ delta → accumulate chatStream (streaming text)
   ├─ delta → accumulate chatStream
   ├─ ...
   │
   ├─ final → clear stream/runId → refresh history
   ├─ aborted → clear stream/runId
   └─ error → clear stream/runId → show error
```

The handling of `delta` events has a clever design—it doesn't append text but replaces with longer text:

```typescript
if (payload.state === "delta") {
  const next = extractText(payload.message);
  if (typeof next === "string") {
    const current = state.chatStream ?? "";
    // Only update if new text is longer (prevent disorder)
    if (!current || next.length >= current.length) {
      state.chatStream = next;
    }
  }
}
```

This "full replacement" pattern avoids text corruption from out-of-order delta packets in streaming transmission.

### Cross-Run Event Filtering

A detail is that `handleChatEvent` checks whether the event's `runId` matches the current run:

```typescript
// final event from other runs (e.g., sub-agent announce)
if (payload.runId && state.chatRunId && payload.runId !== state.chatRunId) {
  if (payload.state === "final") return "final";  // Still trigger history refresh
  return null;  // Ignore other states
}
```

When a sub-agent completes running in the background and sends a message via announce, the current WebChat receives a `final` event but the `runId` doesn't match. At this point, the UI doesn't update the streaming state, but still triggers a chat history refresh—ensuring the user sees the new message.

## 35.3.2 Chat History Loading and Message Sending

### History Loading

Chat history is fetched from Gateway via the `chat.history` RPC method:

```typescript
// ui/src/ui/controllers/chat.ts
export async function loadChatHistory(state: ChatState) {
  if (!state.client || !state.connected) return;
  state.chatLoading = true;
  try {
    const res = await state.client.request<{
      messages?: Array<unknown>;
      thinkingLevel?: string;
    }>("chat.history", {
      sessionKey: state.sessionKey,
      limit: 200,       // Load at most 200 history messages
    });
    state.chatMessages = Array.isArray(res.messages) ? res.messages : [];
    state.chatThinkingLevel = res.thinkingLevel ?? null;
  } catch (err) {
    state.lastError = String(err);
  } finally {
    state.chatLoading = false;
  }
}
```

The returned `thinkingLevel` determines whether the current session has reasoning/thinking mode enabled—if `reasoningLevel` is not `"off"`, the UI displays thinking-related token output.

### Message Rendering Pipeline

The loaded raw messages go through a **normalization → grouping → rendering** pipeline:

```
Raw message array (chatMessages)
        │
        ▼
   normalizeMessage()       ← Unify different message formats
        │
        ▼
   normalizeRoleForGrouping()  ← Unify role names (tool_result → tool)
        │
        ▼
   buildChatItems()         ← Build ChatItem list + inject streaming/loading indicators
        │
        ▼
   groupMessages()          ← Group by consecutive role into MessageGroup
        │
        ▼
   renderMessageGroup()     ← Lit template rendering: avatar + bubble + Markdown
```

**Message normalization** is a key step. Messages returned by Gateway may have multiple formats (from different channels or API versions):

```typescript
// ui/src/ui/chat/message-normalizer.ts
export function normalizeMessage(message: unknown): NormalizedMessage {
  const m = message as Record<string, unknown>;
  let role = typeof m.role === "string" ? m.role : "unknown";

  // Detect multiple forms of tool messages
  const hasToolId = typeof m.toolCallId === "string" || typeof m.tool_call_id === "string";
  const hasToolName = typeof m.toolName === "string" || typeof m.tool_name === "string";
  if (hasToolId || hasToolName) role = "toolResult";

  // Unify content format
  let content: MessageContentItem[] = [];
  if (typeof m.content === "string") {
    content = [{ type: "text", text: m.content }];
  } else if (Array.isArray(m.content)) {
    content = m.content.map((item) => ({
      type: item.type || "text",
      text: item.text, name: item.name, args: item.args || item.arguments,
    }));
  } else if (typeof m.text === "string") {
    content = [{ type: "text", text: m.text }];
  }
  
  return { role, content, timestamp, id };
}
```

**Message grouping** merges consecutive messages with the same role into a `MessageGroup`, sharing avatar and timestamp during rendering:

```
User message A ─┐
User message B ─┤─→ MessageGroup { role: "user", messages: [A, B] }
                │
Assistant message C ─┤─→ MessageGroup { role: "assistant", messages: [C] }
```

### Message Sending Flow

The complete flow of sending a message involves three layers:

```
handleSendChat()           ← UI layer: draft management, command recognition, queuing
  └─ sendChatMessageNow()  ← Control layer: optimistic update, tool stream reset
       └─ sendChatMessage() ← Network layer: RPC call chat.send
```

**First Layer: Command Recognition and Queuing**

```typescript
// ui/src/ui/app-chat.ts
export async function handleSendChat(host: ChatHost, messageOverride?: string) {
  const message = (messageOverride ?? host.chatMessage).trim();
  
  // Stop command (stop/esc/abort/wait/exit or /stop)
  if (isChatStopCommand(message)) {
    await handleAbortChat(host);
    return;
  }
  
  // New session command (/new or /reset)
  const refreshSessions = isChatResetCommand(message);
  
  // If busy (already have running conversation), enqueue
  if (isChatBusy(host)) {
    enqueueChatMessage(host, message, attachments, refreshSessions);
    return;
  }

  await sendChatMessageNow(host, message, { ... });
}
```

The message queue mechanism lets users continue typing while the assistant is replying. Messages in the queue are automatically sent one by one after the current turn completes:

```typescript
// Auto-flush queue when turn ends
async function flushChatQueue(host: ChatHost) {
  if (!host.connected || isChatBusy(host)) return;
  const [next, ...rest] = host.chatQueue;
  if (!next) return;
  host.chatQueue = rest;
  const ok = await sendChatMessageNow(host, next.text, { ... });
  if (!ok) host.chatQueue = [next, ...host.chatQueue]; // Put back if failed
}
```

> **Sidebar — Optimistic Update**
>
> In web applications, "optimistic update" means updating the UI before server confirmation. When a user sends a message, it immediately appears in the chat list (rather than waiting for Gateway response). If sending fails, the UI rolls back. This makes the interface feel more responsive, eliminating the "lag" feeling from network latency.

**Second Layer: Optimistic Update and RPC Call**

```typescript
// ui/src/ui/controllers/chat.ts
export async function sendChatMessage(
  state: ChatState,
  message: string,
  attachments?: ChatAttachment[],
): Promise<string | null> {
  // Optimistic update: immediately add user message to list
  state.chatMessages = [...state.chatMessages, {
    role: "user",
    content: contentBlocks,  // text + images
    timestamp: Date.now(),
  }];

  // Generate run ID, enter streaming receive state
  const runId = generateUUID();
  state.chatRunId = runId;
  state.chatStream = "";
  state.chatStreamStartedAt = Date.now();

  try {
    await state.client.request("chat.send", {
      sessionKey: state.sessionKey,
      message: msg,
      deliver: false,         // Don't deliver through other channels
      idempotencyKey: runId,  // Idempotency key, prevent duplicate sends
      attachments: apiAttachments,
    });
    return runId;
  } catch (err) {
    // Send failed: clear running state, show error message
    state.chatRunId = null;
    state.chatStream = null;
    state.chatMessages = [...state.chatMessages, {
      role: "assistant",
      content: [{ type: "text", text: "Error: " + error }],
    }];
    return null;
  }
}
```

Key parameter explanations:

* `deliver: false`—WebChat messages are only processed internally in Gateway, not delivered to other channels
* `idempotencyKey: runId`—If network jitter causes request retransmission, Gateway can deduplicate using this key

### Image Attachments

WebChat supports adding image attachments via paste (Ctrl+V):

```typescript
// ui/src/ui/views/chat.ts
function handlePaste(e: ClipboardEvent, props: ChatProps) {
  const items = e.clipboardData?.items;
  for (const item of items) {
    if (item.type.startsWith("image/")) {
      e.preventDefault();
      const file = item.getAsFile();
      const reader = new FileReader();
      reader.addEventListener("load", () => {
        const dataUrl = reader.result as string;
        props.onAttachmentsChange([...current, {
          id: generateAttachmentId(),
          dataUrl,
          mimeType: file.type,
        }]);
      });
      reader.readAsDataURL(file);
    }
  }
}
```

Images are temporarily stored on the client as Data URLs (Base64 encoded). When sending, they're converted to API format:

```typescript
const apiAttachments = attachments.map(att => {
  const parsed = dataUrlToBase64(att.dataUrl);  // Parse data:image/png;base64,xxx
  return { type: "image", mimeType: parsed.mimeType, content: parsed.content };
});
```

### Abort and Commands

Users can abort an ongoing conversation in multiple ways:

| Method                                   | Trigger                         |
| ---------------------------------------- | ------------------------------- |
| Input `stop`/`abort`/`esc`/`wait`/`exit` | `isChatStopCommand` recognition |
| Input `/stop`                            | Command prefix                  |
| Click "Stop" button                      | `canAbort && chatRunId`         |

The abort operation calls the `chat.abort` RPC:

```typescript
export async function abortChatRun(state: ChatState): Promise<boolean> {
  await state.client.request("chat.abort", {
    sessionKey: state.sessionKey,
    runId: state.chatRunId,
  });
  return true;
}
```

### Chat View Layout

The `renderChat` function composes the entire chat interface layout:

```
┌──────────────────────────────────────────┐
│  [Error callout / Compaction indicator]  │
│┌────────────────────┬───────────────────┐│
││                    │                   ││
││  chat-thread       │  sidebar          ││
││  (message list)    │  (tool output)    ││
││                    │                   ││
│├────────────────────┴───────────────────┤│
│  [Queue display: Queued (N)]             │
│  [New messages ↓ button]                 │
│  ┌──────────────────────────────────────┐│
│  │ textarea: Message (↩ send, Shift+↩   ││
│  │           line break, paste images)  ││
│  │ [attachments]  [Stop/New] [Send ↵]   ││
│  └──────────────────────────────────────┘│
└──────────────────────────────────────────┘
```

The chat thread and sidebar are separated by a draggable divider `<resizable-divider>`, with the ratio saved in `splitRatio` (default 0.6, range 0.4-0.7). The sidebar displays tool call output—clicking a tool card in the chat shows its full output in the sidebar.

Rendering within the chat thread uses Lit's `repeat()` directive for efficient list updates—compared to simple `map()`, `repeat()` reuses DOM based on keys, avoiding recreating DOM nodes for all existing messages when new ones are appended.

### Streaming Output Display

When the assistant is replying, the UI shows different indicators based on the `chatStream` state:

```typescript
if (props.stream !== null) {
  if (props.stream.trim().length > 0) {
    // Has content: render streaming message bubble
    items.push({ kind: "stream", text: props.stream, startedAt });
  } else {
    // Empty content: show "thinking" three-dot animation
    items.push({ kind: "reading-indicator", key });
  }
}
```

The "thinking" indicator is three bouncing dots (CSS animation), giving users visual feedback that the assistant is processing. Once the first delta arrives, the indicator is replaced with actual streaming text.

***

## Section Summary

1. **WebChat is a client of the Gateway WebSocket protocol**, connecting with `operator` role and full administrative permissions; sessions are identified and switched via sessionKey.
2. **Event-driven updates**: After sending a message, streaming delta, final result, abort, and error notifications are received via `chat` events; delta uses full replacement mode to prevent disorder.
3. **Three-layer message sending architecture**: UI layer handles command recognition and message queuing, control layer executes optimistic update and tool stream reset, network layer initiates `chat.send` RPC call.
4. **Message rendering pipeline**: Raw messages → normalization (unify format) → grouping (merge consecutive same role) → Lit template rendering (Markdown + avatar + tool cards).
5. **Message queue** allows users to continue typing while the assistant replies; queued messages are automatically sent after the current turn completes.
6. **Image attachments** are added via clipboard paste, temporarily stored as Base64 Data URLs, converted to API format when sending.
