> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/events-and-message-handling.md).

# 在 TypeScript 中处理事件和消息

订阅 Convai Web SDK 客户端的连接、状态和消息事件，并在无框架页面中渲染对话。

订阅客户端事件，让不依赖框架的 UI 与对话保持同步。当你自行渲染状态、消息或实时转录，而不是使用聊天组件时，请参阅此页面。

### 前提条件

* 如 `ConvaiClient` 按 [使用原生 TypeScript 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript.md).

### 订阅和取消订阅

`client.on(event, callback)` 会返回一个用于取消订阅的函数。 `client.off(event, callback)` 则通过引用移除订阅。

```typescript
const unsubscribe = client.on('message', handleMessage);

// 稍后
unsubscribe();
// 或者
client.off('message', handleMessage);
```

在调用 `connect()` 之前先进行订阅，以免错过会话的首批事件。

### 跟踪连接状态

`stateChange` 会在 `ConvaiClientState` 的任意字段发生变化时触发。 `state.agentState` 会将各项活动标志合并为一个值： `'disconnected'`, `'connected'`, `'listening'`, `'thinking'`或 `'speaking'`.

```typescript
import type { ConvaiClientState } from '@convai/web-sdk/vanilla';

client.on('stateChange', (state: ConvaiClientState) => {
  statusEl.textContent = state.isConnected ? state.agentState : 'disconnected';
});
```

`client.state` 可随时返回相同的状态。

### 发送消息前等待角色就绪

`connect` 会在传输连接建立时触发。角色可能还需要一些时间才能就绪，而 `sendUserTextMessage` 在传输尚未就绪时不会执行任何操作。请在 `botReady`事件触发时发送第一条消息，或检查 `client.isBotReady`.

```typescript
client.on('connect', () => console.log('Transport connected'));

client.on('botReady', () => {
  client.sendUserTextMessage('Hello!');
});

client.on('disconnect', (reason) => {
  console.log('Disconnected with reason', reason);
});
```

### 渲染对话

`message` 会在有最新消息时触发 `ChatMessage`. `messagesChange` 触发时会传入整个数组，包括仍在流式传输的消息更新。对于聊天记录，可从 `messagesChange` 重新渲染，并按 `type`:

```typescript
import type { ChatMessage } from '@convai/web-sdk/vanilla';

const SHOWN = new Set(['user-llm-text', 'user-transcription', 'bot-llm-text', 'bot-output']);

client.on('messagesChange', (messages: ChatMessage[]) => {
  chatEl.replaceChildren(
    ...messages
      .filter((m) => SHOWN.has(m.type) && m.content.trim())
      .map((m) => {
        const div = document.createElement('div');
        div.className = m.type.startsWith('user') ? 'user' : 'bot';
        div.textContent = m.content;
        return div;
      }),
  );
});
```

聊天界面通常显示的消息类型：

| 类型              | 内容                                                      |
| --------------- | ------------------------------------------------------- |
| `user-llm-text` | 你通过 `sendUserTextMessage`.                              |
| `发送的文本消息`       | 从语音转录的用户发言内容。最终片段会累积在同一条消息中，直到角色作出回复。                   |
| `bot-llm-text`  | 角色生成的回复，会在生成过程中以流式方式传输。 `isStreaming` 会是 `true` 直到回复定稿。 |
| `bot-output`    | 角色说出的回复汇总后的内容。只有当回复尚未以 `bot-llm-text`.                  |

其他类型还包含情绪、动作、空闲警告和无响应轮次。完整列表请参阅 [配置与类型参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/best-practices-and-type-definitions.md#chatmessage) 。

### 显示实时转录

`userTranscriptionChange` 会在用户说话时触发，并提供截至当前的转录文本。话语结束时，会以空字符串触发。

```typescript
client.on('userTranscriptionChange', (text: string) => {
  liveTranscriptEl.textContent = text;
});
```

### 处理错误

`error` 会在连接失败以及角色未能及时报告就绪时触发。其负载是抛出的任意内容，因此读取 `message`.

```typescript
client.on('error', (error: unknown) => {
  console.error(error instanceof Error ? error.message : error);
});
```

### 后续步骤

{% content-ref url="/pages/8c6e3631e7e7da5b3c9acf5a0019d7737dc79e19" %}
[Web SDK 事件参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/548c1fa63be041ce888c5b5dc2a5a0f245175f1a" %}
[在 TypeScript 中构建自定义 UI](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/building-a-custom-ui-typescript.md)
{% endcontent-ref %}

{% content-ref url="/pages/1ef8009eea712d4c41fd7a2a07e473a277395698" %}
[处理错误和断开连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md)
{% endcontent-ref %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/events-and-message-handling.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
