聊天系统
- 作者仓库星标 22
- 许可证 Apache-2.0
- 作者仓库 unity-explorer
- 领域
- 通用
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 94 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @decentraland · Apache-2.0
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 运行环境要求
- 未检出明确要求
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 命令执行
- 网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
# Chat System
## Sources
- `docs/chat.md` — Chat architecture (MVP, state machine, commands, services, event bus, auto-translation)
- `docs/chat-emojis.md` — Emoji atlas creation with TextMesh Pro, noto-emoji font
- `docs/chat-history-local-storage.md` — Local encrypted chat history persistence, feature flag control
---
## Architecture Overview
The chat system uses **MVP + State Machine + EventBus + Commands**:
- **View** (MonoBehaviour): draw-only; forwards UI events
- **Presenter** (POCO): listens to View + EventBus, delegates to Commands/Services, updates View
- **Model**: embodied by Services and data stores (`IChatHistory`)
- **Commands**: single-purpose business logic (e.g., `SendMessageCommand`)
- **Services**: long-lived shared state or I/O boundaries (history, member lists, input blocking)
- **EventBus**: decoupled comms via `ChatEvents` (no tight coupling between Presenters)
- **State Machine**: `ChatStateMachine` controls top-level UI mode; replaces boolean soup
- **Composition root**: `ChatPlugin` wires Views, Presenters, Commands, Services, and State Machine
### Component Map
| Layer | Key Classes |
|-------|------------|
| Composition | `ChatPlugin`, `ChatMainSharedAreaController` |
| Presenters | `ChatPanelPresenter`, `ChatTitlebarPresenter`, `ChatInputPresenter`, `ChatMessageFeedPresenter`, `ChatChannelsPresenter`, `ChatMemberListPresenter` |
| Commands | `SendMessageCommand`, `SelectChannelCommand`, `InitializeChatSystemCommand`, `GetMessageHistoryCommand`, `ResolveInputStateCommand`, ~20 more |
| Services | `CurrentChannelService`, `ChatHistoryService`, `ChatMemberListService`, `ChatInputBlockingService`, `ChatContextMenuService`, `ChatWorldBubbleService` |
| State Machine | `ChatStateMachine` with `Init`, `Default`, `Focused`, `Members`, `Minimized`, `Hidden` states |
### Message Send Flow
1. `ChatInputView` raises `onSubmit("Hello")`
2. `ChatInputPresenter` calls `SendMessageCommand`
3. Command pulls active channel from `CurrentChannelService`, calls `IChatMessagesBus`
4. Bus echoes `MessageAdded` locally (optimistic UI)
5. `ChatHistoryService` persists to `IChatHistory`
6. `ChatMessageFeedPresenter` maps via `CreateMessageViewModelCommand` and updates View
---
## Message Bus Decorator Chain
`IChatMessagesBus` is wrapped in decorators, each adding a concern. The chain is composed in `DynamicWorldContainer`.
### Decorator Responsibilities
| Decorator | Role |
|-----------|------|
| `MultiplayerChatMessagesBus` | Core transport: sends via LiveKit pipes (Island/Scene/Chat), receives from subscribed pipes, deduplicates, rate-limits, buffers nearby messages |
| `SelfResendChatMessageBus` | On `Send()`, also fires `MessageAdded` for the sender's own message (optimistic local echo) |
| `IgnoreWithSymbolsChatMessageBus` | Filters messages containing forbidden control characters (`\u2410`, `\u2406`, `\u2411`) |
| `CommandsHandleChatMessageBus` | Intercepts `/`-prefixed messages, parses command + args, dispatches to `IChatCommand`, sends system response |
### Interface
```csharp
public interface IChatMessagesBus : IDisposable
{
event Action<ChatChannel.ChannelId, ChatChannel.ChatChannelType, ChatMessage> MessageAdded;
void Send(ChatChannel channel, string message, ChatMessageOrigin origin, double timestamp);
}
```
Each decorator wraps `origin.Send()` and forwards `origin.MessageAdded` events, adding its own logic before or after.
---
## Chat Command Pattern
### Interface
```csharp
public interface IChatCommand
{
string Command { get; }
string Description { get; }
bool DebugOnly => false;
bool ValidateParameters(string[] parameters) => parameters.Length == 0;
UniTask<string> ExecuteCommandAsync(string[] parameters, CancellationToken ct);
}
```
### Existing Commands
| Command | Class | Debug? |
|---------|-------|--------|
| `/goto <x,y\|random\|crowd\|world>` | `GoToChatCommand` | No |
| `/help` | `HelpChatCommand` | No |
| `/version` | `VersionChatCommand` | No |
| `/gotolocal <x,y>` | `GoToLocalChatCommand` | Yes |
| `/reloadscene` | `ReloadSceneChatCommand` | Yes |
| `/debugpanel` | `DebugPanelChatCommand` | Yes |
| `/showentity <id>` | `ShowEntityChatCommand` | Yes |
| `/logs <category> <level>` | `LogsChatCommand` | Yes |
| `/logmatrix` | `LogMatrixChatCommand` | Yes |
| `/rooms` | `RoomsChatCommand` | Yes |
| `/loadpx <urn>` | `LoadPortableExperienceChatCommand` | Yes |
| `/killpx <urn>` | `KillPortableExperienceChatCommand` | Yes |
| `/appargs` | `AppArgsChatCommand` | Yes |
Commands are registered in `DynamicWorldContainer` as `IReadOnlyList<IChatCommand>` and looked up by name in a dictionary.
---
## Input State Machine
`ChatStateMachine` manages 6 UI states via `MVCStateMachine<ChatState>`. Each state class contains only logic relevant to that state.
### State Transitions
```
Init --> Default (on view show)
Default --> Focused (click inside / focus requested)
Default --> Minimized (close requested)
Default --> Members (toggle members)
Focused --> Default (click outside)
Focused --> Minimized (close requested)
Focused --> Members (toggle members)
Members --> Default (click outside)
Members --> Focused (close/back/toggle)
Minimized --> Focused (focus requested / minimize toggle)
Hidden <-- (SharedSpaceManager hides chat when other panels open)
Hidden --> Default (SharedSpaceManager restores chat)
```
All states inherit `ChatState` which provides virtual no-op methods: `OnClickOutside`, `OnClickInside`, `OnCloseRequested`, `OnFocusRequested`, `OnMinimizeRequested`, `OnToggleMembers`, `OnPointerEnter`, `OnPointerExit`. States override only the transitions they handle.
---
## Auto-Translation
Translation is orchestrated by `TranslationService` with modular components:
| Component | Role |
|-----------|------|
| `ITranslationService` | Central orchestrator for auto and manual translation |
| `ITranslationProvider` (`DclTranslationProvider`) | External API adapter |
| `IMessageProcessor` (`ChatMessageProcessor`) | Tokenizes complex messages, protects non-translatable parts |
| `IConversationTranslationPolicy` | Decides if auto-translate applies (global flag + per-conversation toggle) |
| `ITranslationCache` (`InMemoryTranslationCache`) | Prevents redundant API calls; capacity configured via `ChatConfig.TranslationCacheCapacity` (default 200) |
| `ITranslationMemory` (`InMemoryTranslationMemory`) | Tracks per-message translation state (`Original`, `Pending`, `Success`, `Failed`); capacity 200 |
### Configuration (ChatConfig ScriptableObject)
```csharp
[field: SerializeField] public int TranslationMaxRetries { get; set; } = 1;
[field: SerializeField] public float TranslationTimeoutSeconds { get; set; } = 10.0f;
public int TranslationMemoryCapacity = 200;
public int TranslationCacheCapacity = 200;
```
### Flow
1. `TranslationService.ProcessIncomingMessage()` checks `IConversationTranslationPolicy`
2. Creates `MessageTranslation` with `Pending` state in `ITranslationMemory`
3. Publishes `TranslationEvents.MessageTranslationRequested`
4. Checks `ITranslationCache` for existing result
5. Runs `RequiresProcessing()` -- if text has TMP tags, emojis, dates, or slash commands, uses `IMessageProcessor` (tokenize, protect, batch-translate); otherwise calls `ITranslationProvider` directly
6. Stores result in cache + memory, publishes `TranslationEvents.MessageTranslated`
7. On failure, sets `Failed` state, publishes `TranslationEvents.MessageTranslationFailed`
Concurrency: per-sender serialization via leader/follower gates, global cap of 10 in-flight translations.
---
## Encrypted History
Feature flag: `explorer-alfa-chat-history-local-storage`. Core classes in `Explorer/Assets/DCL/Chat/History/`.
### Storage Layout
```
{persistentDataPath}/c/
{Base64(AES(walletAddress))}/ <-- per-account folder
{Base64(AES("UserConversationSettings"))} <-- encrypted JSON: open channels + order
{Base64(AES(channelId))} <-- encrypted CSV per conversation
```
### Key Behaviors
- **Per-account isolation**: wallet address is the encryption key; folder name is `Base64(AES(address))`
- **Lazy file I/O**: files stay open for 5 seconds after last write, then auto-close
- **Background processing**: message queue processed on a thread pool via `UniTask.RunOnThreadPool`
- **Rehydration**: on first DM message, snapshots session messages, loads history from disk, replays session tail to avoid data loss
- **Nearby excluded**: only `ChatChannelType.USER` conversations are persisted
---
## Detailed Reference
For detailed code examples, see [reference.md](reference.md).
---
## Cross-References
- **mvc-and-ui-architecture** -- MVC controller pattern, `SharedSpaceManager` panel coordination
- **web-requests** -- `IWebRequestController` used by `DclTranslationProvider` and `GoToChatCommand` for API calls
- **feature-flags-and-configuration** -- `FeatureFlagsStrings.CHAT_HISTORY_LOCAL_STORAGE` gates history; `FeaturesRegistry` gates rate limiting and message buffering
章节与文件索引
按说明文件中的顺序排列。
来源
架构概述
组件图
消息发送流程
消息总线装饰链
文件/命令 -> docs/chat.md · docs/chat-emojis.md · docs/chat-history-local-storage.md · IChatHistory · SendMessageCommand · ChatEvents · ChatStateMachine · ChatPlugin
内容校验值 -> d73c4bec54ac
当前原文的自动摘译,尚未人工审校。
来源
docs/chat.md— 聊天架构(MVP、状态机、命令、服务、事件总线、自动翻译)docs/chat-emojis.md— 使用 TextMesh Pro 创建表情符号图集,noto-emoji 字体docs/chat-history-local-storage.md— 本地加密聊天历史记录持久化,功能标志控制架构概述
聊天系统使用MVP + State Machine + EventBus + Commands:View(MonoBehaviour):draw-only;转发 UI 事件 Presenter (POCO):监听 View + EventBus,委托命令/服务,更新视图模型:由服务和数据存储体现(
IChatHistory) 命令:单一用途业务逻辑(例如,SendMessageCommand)组件图
层·关键类组成·
ChatPlugin,ChatMainSharedAreaController演示者·ChatPanelPresenter,ChatTitlebarPresenter,ChatInputPresenter,ChatMessageFeedPresenter,ChatChannelsPresenter,ChatMemberListPresenter命令·SendMessageCommand,SelectChannelCommand,InitializeChatSystemCommand、GetMessageHistoryCommand、ResolveInputStateCommand、~20 个以上服务 ·CurrentChannelService、ChatHistoryService、ChatMemberListService、ChatInputBlockingService、ChatContextMenuService、ChatWorldBubbleService消息发送流程
ChatInputView引发onSubmit("Hello")``ChatInputPresenter调用SendMessageCommand命令从CurrentChannelService拉动活动通道,调用IChatMessagesBus总线在本地回显MessageAdded(乐观的UI)ChatHistoryService持续到IChatHistory消息总线装饰链
IChatMessagesBus被包装在装饰器中,每个装饰器添加一个关注点。该链由DynamicWorldContainer组成。