Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: support dm strategy (#14201)

Rdmclin2f0ba92776b03
diff --git a/docs/usage/channels/discord.mdx b/docs/usage/channels/discord.mdx
index 10b75f7484d..f44c1d28d83 100644
--- a/docs/usage/channels/discord.mdx
+++ b/docs/usage/channels/discord.mdx
@@ -123,15 +123,52 @@ By connecting a Discord channel to your LobeHub agent, users can interact with t
Back in LobeHub's channel settings for Discord, click **Test Connection** to verify everything is configured correctly. Then send a message to your bot in Discord to confirm it responds.
+## Access Policies
+
+LobeHub gates inbound traffic with three layered settings, all under **Advanced Settings** and all defaulting to permissive.
+
+### Allowed User IDs (global)
+
+A *global* user-level gate. When populated, **only** the listed users can interact with the bot — DM, group @mention, threads, all of it — regardless of DM Policy / Group Policy mode. Empty means "no user-level filter; let per-scope policies decide". Right-click a user → **Copy User ID** (Developer Mode must be enabled in **Settings → Advanced**) to grab an ID.
+
+DMs from non-allowlisted users get a "you aren't authorized" notice. Group @mentions from non-allowlisted users get the same kind of notice posted **inside the auto-created reply thread** Discord makes for the @-mention — the parent channel stays quiet.
+
+### DM Policy
+
+Controls 1:1 direct messages.
+
+- **Open (default)** — Anyone who shares a server with the bot can DM it (subject to the global allowlist when set).
+- **Allowlist** — DMs require the sender to be in **Allowed User IDs**. Differs from `Open` only when the list is empty: `Allowlist` fails closed (no DMs), `Open` still lets anyone DM.
+- **Disabled** — The bot ignores all DMs. Senders get a one-line notice pointing them at @mentioning the bot in a shared channel instead.
+
+> Discord bots can be reached by anyone in any shared server, so consider populating **Allowed User IDs** or switching DM Policy to **Disabled** if your bot is meant to be private.
+
+### Group Policy
+
+Controls @mentions in server channels and threads.
+
+- **Open (default)** — Respond to @mentions anywhere the bot can read.
+- **Allowlist** — Respond only in channels listed in **Allowed Channel IDs**. Right-click a channel → **Copy Channel ID** to grab one.
+- **Disabled** — Ignore all server traffic; the bot only responds to DMs.
+
+> The two policies are independent. You can run a DM-only bot with `groupPolicy=disabled`, a channel-only bot with `dmPolicy=disabled`, or scope both with allowlists.
+
+See the [Channels overview](/docs/usage/channels/overview#direct-message-policy) for cross-platform details.
+
## Configuration Reference
-| Field | Required | Description |
-| ------------------ | -------- | ------------------------------------------------ |
-| **Application ID** | Yes | Your Discord application's ID |
-| **Bot Token** | Yes | Authentication token for your Discord bot |
-| **Public Key** | Yes | Used to verify interaction requests from Discord |
+| Field | Required | Description |
+| ----------------------- | -------- | ------------------------------------------------------------------------------------------------- |
+| **Application ID** | Yes | Your Discord application's ID |
+| **Bot Token** | Yes | Authentication token for your Discord bot |
+| **Public Key** | Yes | Used to verify interaction requests from Discord |
+| **Allowed User IDs** | No | Comma- or whitespace-separated Discord user IDs. Global gate — applies to DMs and group @mentions |
+| **DM Policy** | No | `open` (default), `allowlist`, or `disabled` — who is allowed to DM the bot |
+| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the bot responds to @mentions |
+| **Allowed Channel IDs** | No | Comma- or whitespace-separated Discord channel IDs. Used when Group Policy is Allowlist |
## Troubleshooting
-- **Bot not responding in server:** Confirm the bot has been invited to the server with the correct permissions, and Message Content Intent is enabled.
+- **Bot not responding in server:** Confirm the bot has been invited to the server with the correct permissions, and Message Content Intent is enabled. If **Group Policy** is `Disabled` or `Allowlist`, double-check the channel is in **Allowed Channel IDs**. If **Allowed User IDs** is set, the sender's user ID must be in it.
+- **Bot not responding to DMs:** Open **Advanced Settings** and confirm **DM Policy** is not set to `Disabled`. If **Allowed User IDs** is set, make sure the sender's Discord user ID is in it.
- **Test Connection failed:** Double-check the Application ID, Bot Token, and Public Key are correct.
diff --git a/docs/usage/channels/discord.zh-CN.mdx b/docs/usage/channels/discord.zh-CN.mdx
index 7c044b6410c..f82bde463f7 100644
--- a/docs/usage/channels/discord.zh-CN.mdx
+++ b/docs/usage/channels/discord.zh-CN.mdx
@@ -122,15 +122,52 @@ tags:
返回 LobeHub 的 Discord 渠道设置,点击 **测试连接** 以验证配置是否正确。然后在 Discord 中向您的机器人发送消息,确认其是否响应。
+## 接入策略
+
+LobeHub 通过三层叠加配置控制入站消息,全部位于 **高级设置**,默认都为宽松。
+
+### 允许的用户 ID(全局)
+
+**全局**用户级闸门。填入后,**只有**列表里的用户可以与机器人交互 — 私信、群聊 @、子话题,所有入口都生效,不受 DM Policy / Group Policy 模式影响。留空则不做用户级过滤,交给各 scope 自己的策略决定。在 **设置 → 高级** 启用开发者模式后,右键用户 → **复制用户 ID** 即可获取。
+
+非白名单用户的私信会收到 "你没有权限" 的系统提示。群里被 @ 时也会收到类似提示,但是**发到 Discord 因 @ 自动创建的回复 thread 里**,不会污染父频道。
+
+### 私信策略
+
+控制 1:1 私聊。
+
+- **开放 (Open)(默认)** — 任何与机器人共享服务器的用户都可以私信(若设置了全局白名单则受其约束)。
+- **白名单 (Allowlist)** — 私信需要发送者在 **允许的用户 ID** 里。和 `Open` 的差别在白名单为空时:`Allowlist` 模式**全部拒绝**,`Open` 模式仍然放任何人私信。
+- **禁用 (Disabled)** — 机器人忽略所有私信,发起方会收到一条提示,引导其在共享频道里 @机器人。
+
+> Discord 机器人可被任意共享服务器的用户私信,如果你的机器人是私有用途,建议填入 **允许的用户 ID** 或将私信策略切到 **禁用**。
+
+### 群组策略
+
+控制服务器频道与子话题里的 @提及。
+
+- **开放 (Open)(默认)** — 在机器人能读取的任何频道里被 @就响应。
+- **白名单 (Allowlist)** — 只在 **允许的频道 ID** 列出的频道里响应。右键频道 → **复制频道 ID** 即可获取。
+- **禁用 (Disabled)** — 忽略所有服务器频道流量,只接受私信。
+
+> 两个策略相互独立。你可以做纯私信机器人(`groupPolicy=disabled`)、纯频道机器人(`dmPolicy=disabled`),也可以两边都用白名单收紧范围。
+
+跨平台细节见 [渠道概览](/docs/usage/channels/overview#direct-message-policy)。
+
## 配置参考
-| 字段 | 是否必需 | 描述 |
-| ----------- | ---- | -------------------- |
-| **应用程序 ID** | 是 | 您的 Discord 应用程序的 ID |
-| **机器人令牌** | 是 | 您的 Discord 机器人的认证令牌 |
-| **公钥** | 是 | 用于验证来自 Discord 的交互请求 |
+| 字段 | 是否必需 | 描述 |
+| ------------ | ---- | -------------------------------------------------- |
+| **应用程序 ID** | 是 | 您的 Discord 应用程序的 ID |
+| **机器人令牌** | 是 | 您的 Discord 机器人的认证令牌 |
+| **公钥** | 是 | 用于验证来自 Discord 的交互请求 |
+| **允许的用户 ID** | 否 | 逗号或空格分隔的 Discord 用户 ID。全局闸门 — 私信和群聊 @ 都受其约束 |
+| **私信策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制谁可以私信机器人 |
+| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些频道响应 |
+| **允许的频道 ID** | 否 | 逗号或空格分隔的 Discord 频道 ID。仅在群组策略为白名单时使用 |
## 故障排除
-- **机器人未在服务器中响应:** 确认机器人已被邀请到服务器并拥有正确的权限,同时启用了消息内容意图。
+- **机器人未在服务器中响应:** 确认机器人已被邀请到服务器并拥有正确的权限,同时启用了消息内容意图。如果 **群组策略** 是 `Disabled` 或 `Allowlist`,确认目标频道在 **允许的频道 ID** 列表里。如果 **允许的用户 ID** 已填,发送者的用户 ID 必须在列表里。
+- **机器人不回私信:** 打开 **高级设置**,确认 **私信策略** 不是 `Disabled`。如果 **允许的用户 ID** 已填,确认发起方的 Discord 用户 ID 在列表里。
- **测试连接失败:** 仔细检查应用程序 ID、机器人令牌和公钥是否正确。
diff --git a/docs/usage/channels/feishu.mdx b/docs/usage/channels/feishu.mdx
index 1b22c247931..22e68a9c8ab 100644
--- a/docs/usage/channels/feishu.mdx
+++ b/docs/usage/channels/feishu.mdx
@@ -174,19 +174,48 @@ By connecting a Feishu channel to your LobeHub agent, team members can interact
Back in LobeHub's channel settings, click **Test Connection** to verify the credentials. Then find your bot in Feishu by searching its name and send it a message to confirm it responds.
+## Access Policies
+
+Two independent policies gate inbound traffic. Both default to **Open**.
+
+### Allowed User IDs (global)
+
+A populated **Allowed User IDs** field is a global gate — DMs *and* group `@mentions` are restricted to listed Feishu `open_id` values. Empty means "no user-level filter". Read the `open_id` from the event payload, or copy the **User ID** displayed in the Feishu Developer Portal.
+
+### DM Policy
+
+- **Open (default)** — Any tenant member can DM the bot (subject to the global allowlist when set).
+- **Allowlist** — DMs require the sender to be in **Allowed User IDs**. Differs from `Open` only when the list is empty: `Allowlist` then fails closed (no DMs).
+- **Disabled** — The bot ignores all DMs and only responds to chat-group `@mentions`.
+
+### Group Policy
+
+Controls which Feishu chat groups the bot will respond in.
+
+- **Open (default)** — Respond to `@mentions` in any chat group the bot has been added to.
+- **Allowlist** — Respond only in chats whose `chat_id` is listed in **Allowed Channel IDs** (read it from the event payload).
+- **Disabled** — Ignore all group traffic; the bot only responds to DMs.
+
+See the [Channels overview](/docs/usage/channels/overview#direct-message-policy) for cross-platform details.
+
## Configuration Reference
-| Field | Required | Description |
-| -------------------------- | -------- | --------------------------------------------------------------- |
-| **App ID** | Yes | Your Feishu app's App ID (`cli_xxx`) |
-| **App Secret** | Yes | Your Feishu app's App Secret |
-| **Verification Token** | No | Verifies webhook event source (recommended) |
-| **Encrypt Key** | No | Decrypts encrypted event payloads |
-| **Event Subscription URL** | — | Auto-generated after saving; paste into Feishu Developer Portal |
+| Field | Required | Description |
+| -------------------------- | -------- | -------------------------------------------------------------------------------------------------------- |
+| **App ID** | Yes | Your Feishu app's App ID (`cli_xxx`) |
+| **App Secret** | Yes | Your Feishu app's App Secret |
+| **Verification Token** | No | Verifies webhook event source (recommended) |
+| **Encrypt Key** | No | Decrypts encrypted event payloads |
+| **Event Subscription URL** | — | Auto-generated after saving; paste into Feishu Developer Portal |
+| **Allowed User IDs** | No | Comma- or whitespace-separated Feishu `open_id` values. Global gate — applies to DMs and group @mentions |
+| **DM Policy** | No | `open` (default), `allowlist`, or `disabled` — who is allowed to DM the bot |
+| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the bot responds to @mentions |
+| **Allowed Channel IDs** | No | Comma- or whitespace-separated Feishu `chat_id` values. Used when Group Policy is Allowlist |
## Troubleshooting
- **Event Subscription URL verification failed:** Ensure you saved the configuration in LobeHub first, and the URL was copied correctly.
- **Bot not responding:** Verify the app is published and approved, the bot capability is enabled, and the `im.message.receive_v1` event is subscribed.
+- **Bot ignores DMs:** Open **Advanced Settings** in LobeHub and check **DM Policy**. If it is `Disabled`, switch to `Open` or `Allowlist`. If it is `Allowlist`, confirm the sender's `open_id` is listed in **Allowed User IDs**.
- **Permission errors:** Confirm all required permissions are added and approved in the Developer Portal.
- **Test Connection failed:** Double-check the App ID and App Secret.
diff --git a/docs/usage/channels/feishu.zh-CN.mdx b/docs/usage/channels/feishu.zh-CN.mdx
index 314ad08dd0e..a634cca27a7 100644
--- a/docs/usage/channels/feishu.zh-CN.mdx
+++ b/docs/usage/channels/feishu.zh-CN.mdx
@@ -170,19 +170,48 @@ tags:
回到 LobeHub 的渠道设置,点击 **测试连接** 以验证凭证。然后在飞书中搜索您的机器人名称并发送消息,确认其是否响应。
+## 接入策略
+
+两个独立的策略控制入站消息,默认都为 **开放**。
+
+### 允许的用户 ID(全局)
+
+填入 **允许的用户 ID** 后,**所有**入站消息(私信和群聊 `@提及`)都必须来自列表里的飞书 `open_id`。留空则不做用户级过滤。`open_id` 可从事件 payload 读取,或在飞书开发者后台查看 **User ID**。
+
+### 私信策略
+
+- **开放 (Open)(默认)** — 租户内任何成员都可以私信机器人(若设置了全局白名单则受其约束)。
+- **白名单 (Allowlist)** — 私信需要发送者在 **允许的用户 ID** 里。和 `Open` 的差别在白名单为空时:`Allowlist` 模式**全部拒绝**。
+- **禁用 (Disabled)** — 机器人忽略所有私信,只在群聊里被 `@提及` 时回复。
+
+### 群组策略
+
+控制机器人会在哪些飞书群里响应。
+
+- **开放 (Open)(默认)** — 在机器人加入的任何群里被 `@` 都响应。
+- **白名单 (Allowlist)** — 只在 **允许的频道 ID** 列出的会话里响应(使用事件 payload 里的 `chat_id`)。
+- **禁用 (Disabled)** — 忽略所有群聊流量,机器人只接受私信。
+
+跨平台细节见 [渠道概览](/docs/usage/channels/overview#direct-message-policy)。
+
## 配置参考
-| 字段 | 是否必需 | 描述 |
-| ---------------------- | ---- | ----------------------- |
-| **应用 ID** | 是 | 您的飞书应用的应用 ID(`cli_xxx`) |
-| **应用密钥** | 是 | 您的飞书应用的应用密钥 |
-| **Verification Token** | 否 | 验证 webhook 事件来源(推荐) |
-| **Encrypt Key** | 否 | 解密加密事件负载 |
-| **事件订阅 URL** | — | 保存后自动生成;粘贴到飞书开发者门户 |
+| 字段 | 是否必需 | 描述 |
+| ---------------------- | ---- | -------------------------------------------------- |
+| **应用 ID** | 是 | 您的飞书应用的应用 ID(`cli_xxx`) |
+| **应用密钥** | 是 | 您的飞书应用的应用密钥 |
+| **Verification Token** | 否 | 验证 webhook 事件来源(推荐) |
+| **Encrypt Key** | 否 | 解密加密事件负载 |
+| **事件订阅 URL** | — | 保存后自动生成;粘贴到飞书开发者门户 |
+| **允许的用户 ID** | 否 | 逗号或空格分隔的飞书 `open_id`。全局闸门 — 私信和群聊 @ 都受其约束 |
+| **私信策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制谁可以私信机器人 |
+| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些群中响应 |
+| **允许的频道 ID** | 否 | 逗号或空格分隔的飞书 `chat_id`。仅在群组策略为白名单时使用 |
## 故障排除
- **事件订阅 URL 验证失败:** 确保您已在 LobeHub 中保存配置,并正确复制了 URL。
- **机器人未响应:** 验证应用已发布并获得批准,机器人功能已启用,并订阅了 `im.message.receive_v1` 事件。
+- **机器人不回私信:** 在 LobeHub 的 **高级设置** 检查 **私信策略**。如果是 `Disabled`,改成 `Open` 或 `Allowlist`;如果是 `Allowlist`,确认发起方的 `open_id` 已加入 **允许的用户 ID**。
- **权限错误:** 确保所有所需权限已在开发者门户中添加并获得批准。
- **测试连接失败:** 仔细检查应用 ID 和应用密钥。
diff --git a/docs/usage/channels/lark.mdx b/docs/usage/channels/lark.mdx
index f1867ceadc6..2c4753729ab 100644
--- a/docs/usage/channels/lark.mdx
+++ b/docs/usage/channels/lark.mdx
@@ -165,19 +165,48 @@ By connecting a Lark channel to your LobeHub agent, team members can interact wi
Back in LobeHub's channel settings, click **Test Connection** to verify the credentials. Then find your bot in Lark by searching its name and send it a message to confirm it responds.
+## Access Policies
+
+Two independent policies gate inbound traffic. Both default to **Open**.
+
+### Allowed User IDs (global)
+
+A populated **Allowed User IDs** field is a global gate — DMs *and* group `@mentions` are restricted to listed Lark `open_id` values. Empty means "no user-level filter". Read the `open_id` from the event payload, or copy the **User ID** displayed in the Lark Developer Portal.
+
+### DM Policy
+
+- **Open (default)** — Any tenant member can DM the bot (subject to the global allowlist when set).
+- **Allowlist** — DMs require the sender to be in **Allowed User IDs**. Differs from `Open` only when the list is empty: `Allowlist` then fails closed (no DMs).
+- **Disabled** — The bot ignores all DMs and only responds to chat-group `@mentions`.
+
+### Group Policy
+
+Controls which Lark chat groups the bot will respond in.
+
+- **Open (default)** — Respond to `@mentions` in any chat group the bot has been added to.
+- **Allowlist** — Respond only in chats whose `chat_id` is listed in **Allowed Channel IDs** (read it from the event payload).
+- **Disabled** — Ignore all group traffic; the bot only responds to DMs.
+
+See the [Channels overview](/docs/usage/channels/overview#direct-message-policy) for cross-platform details.
+
## Configuration Reference
-| Field | Required | Description |
-| -------------------------- | -------- | ------------------------------------------------------------- |
-| **App ID** | Yes | Your Lark app's App ID (`cli_xxx`) |
-| **App Secret** | Yes | Your Lark app's App Secret |
-| **Verification Token** | No | Verifies webhook event source (recommended) |
-| **Encrypt Key** | No | Decrypts encrypted event payloads |
-| **Event Subscription URL** | — | Auto-generated after saving; paste into Lark Developer Portal |
+| Field | Required | Description |
+| -------------------------- | -------- | ------------------------------------------------------------------------------------------------------ |
+| **App ID** | Yes | Your Lark app's App ID (`cli_xxx`) |
+| **App Secret** | Yes | Your Lark app's App Secret |
+| **Verification Token** | No | Verifies webhook event source (recommended) |
+| **Encrypt Key** | No | Decrypts encrypted event payloads |
+| **Event Subscription URL** | — | Auto-generated after saving; paste into Lark Developer Portal |
+| **Allowed User IDs** | No | Comma- or whitespace-separated Lark `open_id` values. Global gate — applies to DMs and group @mentions |
+| **DM Policy** | No | `open` (default), `allowlist`, or `disabled` — who is allowed to DM the bot |
+| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the bot responds to @mentions |
+| **Allowed Channel IDs** | No | Comma- or whitespace-separated Lark `chat_id` values. Used when Group Policy is Allowlist |
## Troubleshooting
- **Event Subscription URL verification failed:** Ensure you saved the configuration in LobeHub first, and the URL was copied correctly.
- **Bot not responding:** Verify the app is published and approved, the bot capability is enabled, and the `im.message.receive_v1` event is subscribed.
+- **Bot ignores DMs:** Open **Advanced Settings** in LobeHub and check **DM Policy**. If it is `Disabled`, switch to `Open` or `Allowlist`. If it is `Allowlist`, confirm the sender's `open_id` is listed in **Allowed User IDs**.
- **Permission errors:** Confirm all required permissions are added and approved in the Developer Portal.
- **Test Connection failed:** Double-check the App ID and App Secret. Make sure you selected "Lark" (not "飞书") in LobeHub's channel settings.
diff --git a/docs/usage/channels/lark.zh-CN.mdx b/docs/usage/channels/lark.zh-CN.mdx
index 5b89411b633..15596c4a703 100644
--- a/docs/usage/channels/lark.zh-CN.mdx
+++ b/docs/usage/channels/lark.zh-CN.mdx
@@ -162,19 +162,48 @@ tags:
回到 LobeHub 的渠道设置,点击 **Test Connection** 以验证凭证。然后在 Lark 中搜索您的机器人名称并发送消息,确认其是否响应。
+## 接入策略
+
+两个独立的策略控制入站消息,默认都为 **开放**。
+
+### 允许的用户 ID(全局)
+
+填入 **允许的用户 ID** 后,**所有**入站消息(私信和群聊 `@提及`)都必须来自列表里的 Lark `open_id`。留空则不做用户级过滤。`open_id` 可从事件 payload 读取,或在 Lark 开发者后台查看 **User ID**。
+
+### 私信策略
+
+- **开放 (Open)(默认)** — 租户内任何成员都可以私信机器人(若设置了全局白名单则受其约束)。
+- **白名单 (Allowlist)** — 私信需要发送者在 **允许的用户 ID** 里。和 `Open` 的差别在白名单为空时:`Allowlist` 模式**全部拒绝**。
+- **禁用 (Disabled)** — 机器人忽略所有私信,只在群聊里被 `@提及` 时回复。
+
+### 群组策略
+
+控制机器人会在哪些 Lark 群里响应。
+
+- **开放 (Open)(默认)** — 在机器人加入的任何群里被 `@` 都响应。
+- **白名单 (Allowlist)** — 只在 **允许的频道 ID** 列出的会话里响应(使用事件 payload 里的 `chat_id`)。
+- **禁用 (Disabled)** — 忽略所有群聊流量,机器人只接受私信。
+
+跨平台细节见 [渠道概览](/docs/usage/channels/overview#direct-message-policy)。
+
## 配置参考
-| 字段 | 是否必需 | 描述 |
-| -------------------------- | ---- | ----------------------------- |
-| **App ID** | 是 | 您的 Lark 应用的 App ID(`cli_xxx`) |
-| **App Secret** | 是 | 您的 Lark 应用的 App Secret |
-| **Verification Token** | 否 | 验证 webhook 事件来源(推荐) |
-| **Encrypt Key** | 否 | 解密加密事件负载 |
-| **Event Subscription URL** | — | 保存后自动生成;粘贴到 Lark 开发者门户 |
+| 字段 | 是否必需 | 描述 |
+| -------------------------- | ---- | -------------------------------------------------- |
+| **App ID** | 是 | 您的 Lark 应用的 App ID(`cli_xxx`) |
+| **App Secret** | 是 | 您的 Lark 应用的 App Secret |
+| **Verification Token** | 否 | 验证 webhook 事件来源(推荐) |
+| **Encrypt Key** | 否 | 解密加密事件负载 |
+| **Event Subscription URL** | — | 保存后自动生成;粘贴到 Lark 开发者门户 |
+| **允许的用户 ID** | 否 | 逗号或空格分隔的 Lark `open_id`。全局闸门 — 私信和群聊 @ 都受其约束 |
+| **私信策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制谁可以私信机器人 |
+| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些群中响应 |
+| **允许的频道 ID** | 否 | 逗号或空格分隔的 Lark `chat_id`。仅在群组策略为白名单时使用 |
## 故障排除
- **Event Subscription URL 验证失败:** 确保您已在 LobeHub 中保存配置,并正确复制了 URL。
- **机器人未响应:** 验证应用已发布并获得批准,机器人功能已启用,并订阅了 `im.message.receive_v1` 事件。
+- **机器人不回私信:** 在 LobeHub 的 **高级设置** 检查 **私信策略**。如果是 `Disabled`,改成 `Open` 或 `Allowlist`;如果是 `Allowlist`,确认发起方的 `open_id` 已加入 **允许的用户 ID**。
- **权限错误:** 确保所有所需权限已在开发者门户中添加并获得批准。
- **测试连接失败:** 仔细检查 App ID 和 App Secret。确保您在 LobeHub 的渠道设置中选择了 "Lark"(而不是 "飞书")。
diff --git a/docs/usage/channels/overview.mdx b/docs/usage/channels/overview.mdx
index c6bb996522f..82b6a0c7ca0 100644
--- a/docs/usage/channels/overview.mdx
+++ b/docs/usage/channels/overview.mdx
@@ -21,21 +21,21 @@ tags:
Channels allow you to connect your LobeHub agents to external messaging platforms. Once connected, users can interact with your AI assistant directly in the chat apps they already use — no need to visit LobeHub.
-> [!NOTE]
+> \[!NOTE]
>
> WeChat currently requires an active subscription. If you are using the community edition without a subscription, the WeChat channel option may not appear in the Channels settings yet.
## Supported Platforms
-| Platform | Description |
-| ------------------------------------------ | --------------------------------------------------------------- |
-| [Discord](/docs/usage/channels/discord) | Connect to Discord servers for channel chat and direct messages |
-| [Slack](/docs/usage/channels/slack) | Connect to Slack for channel and direct message conversations |
-| [Telegram](/docs/usage/channels/telegram) | Connect to Telegram for private and group conversations |
-| [QQ](/docs/usage/channels/qq) | Connect to QQ for group chats and direct messages |
+| Platform | Description |
+| ------------------------------------------ | --------------------------------------------------------------------------------------------- |
+| [Discord](/docs/usage/channels/discord) | Connect to Discord servers for channel chat and direct messages |
+| [Slack](/docs/usage/channels/slack) | Connect to Slack for channel and direct message conversations |
+| [Telegram](/docs/usage/channels/telegram) | Connect to Telegram for private and group conversations |
+| [QQ](/docs/usage/channels/qq) | Connect to QQ for group chats and direct messages |
| [WeChat (微信)](/docs/usage/channels/wechat) | Connect to WeChat via iLink Bot for private and group chats (requires an active subscription) |
-| [Feishu (飞书)](/docs/usage/channels/feishu) | Connect to Feishu for team collaboration (Chinese version) |
-| [Lark](/docs/usage/channels/lark) | Connect to Lark for team collaboration (international version) |
+| [Feishu (飞书)](/docs/usage/channels/feishu) | Connect to Feishu for team collaboration (Chinese version) |
+| [Lark](/docs/usage/channels/lark) | Connect to Lark for team collaboration (international version) |
## How It Works
@@ -70,3 +70,61 @@ Text messages are supported across all platforms. Some features vary by platform
| Group chats | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| Reactions | Yes | Yes | Yes | No | No | Partial | Partial |
| Image/file attachments | Yes | Yes | Yes | Yes | No | Yes | Yes |
+
+## Allowed Users (global)
+
+The **Allowed Users** list at the top of **Advanced Settings** is a *global* user gate. When populated, only the listed users can interact with the bot — in DMs **and** in group `@mentions` — regardless of DM Policy or Group Policy mode. Leave it empty to disable user-level filtering and let per-scope policies decide on their own.
+
+Behaviour when populated:
+
+| Surface | Non-allowlisted sender |
+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **DM** | Blocked. Sender receives a one-line "you aren't authorized to send direct messages" notice in the same DM. |
+| **Group / channel @mention** | Blocked. A short "you aren't authorized to interact with this bot" notice is posted in the same thread the @-mention arrived on (on Discord this is the auto-created reply thread, not the parent channel). |
+
+Add one entry per row. Each row holds a platform user ID (required) and an optional **Note** — a private label that's only ever shown back to you on the settings page. The note is what saves you from having to remember whether `U01ABCXYZ` was Alice or the on-call account six months from now; the runtime ignores it entirely.
+
+> **Anti-lockout**: if you have **Your Platform User ID** set (the AI-tools field), that ID is implicitly trusted by the global allowlist. Forgetting to add yourself to **Allowed Users** when scoping the bot to friends won't lock you out.
+
+## Direct Message Policy
+
+DM Policy only governs DMs — group `@mentions` are gated independently by **Group Policy** below. The user-level filter from the global **Allowed Users** is also applied; per-scope policy stacks on top.
+
+| Policy | Behavior |
+| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Open** | Any user on the platform can DM the bot (subject to the global allowlist when set). Best for public-facing assistants. |
+| **Allowlist** | DMs require the sender to be in **Allowed Users**. Distinct from `Open` only when the list is empty: `Allowlist` then **fails closed** (no DMs); `Open` still lets anyone DM. |
+| **Disabled** | The bot ignores all DMs entirely. Use this when the bot should only reply in shared channels via `@mention`. |
+
+## Group Policy
+
+For the same group-capable platforms, each channel has a **Group Policy** that controls where the bot responds to `@mentions`. This is independent of DM Policy: a `groupPolicy=disabled` bot still accepts DMs (subject to DM Policy), and vice versa.
+
+| Policy | Behavior |
+| ------------- | ---------------------------------------------------------------------------------------------------------------------- |
+| **Open** | Respond to `@mentions` in any group, channel, or thread the bot can read. Default. |
+| **Allowlist** | Respond only when the channel / group / chat ID is in **Allowed Channels**. Use to scope a bot to specific workspaces. |
+| **Disabled** | Ignore all non-DM traffic. The bot becomes DM-only. |
+
+When **Allowlist** is selected, **Allowed Channels** appears as a row editor — one entry per channel / group / chat ID, with an optional note (e.g. `#general`) shown only to you so you can recognise each ID later.
+
+> **Discord parent channels**: an `@mention` in a Discord channel automatically spawns a reply thread, so the inbound thread ID is *not* what Discord's "Copy Channel ID" gives you. You can paste the **parent channel ID** here — the bot accepts any auto-created reply thread under it. Pasting a specific thread ID instead works too, in which case only that thread is allowed.
+
+### Per-platform defaults
+
+Every supported platform defaults to **Open** for both policies so the bot stays reachable out of the box. Tighten per-channel via **Allowlist** or **Disabled** when you want a private bot. WeChat does not expose these settings because the WeChat integration is DM-only by design.
+
+### Finding a user's platform ID
+
+- **Discord** — Enable Developer Mode in user settings, right-click the user, and choose **Copy User ID**.
+- **Slack** — Open the user's profile → click the `⋮` menu → **Copy member ID** (starts with `U`).
+- **Telegram** — Ask the user to message [@userinfobot](https://t.me/userinfobot), or read `from.id` from the bot's incoming update.
+- **QQ** — Use the `tiny_id` from the OpenAPI event payload (the public-facing QQ number is not guaranteed to be the platform ID).
+- **Feishu / Lark** — Use the `open_id` from the event payload, or the **User ID** displayed in the developer portal.
+
+### Finding a channel / group ID
+
+- **Discord** — Enable Developer Mode, right-click the channel, and choose **Copy Channel ID**.
+- **Slack** — Open the channel's About panel and copy the channel ID at the bottom (starts with `C`).
+- **Telegram** — Forward a message from the group to [@userinfobot](https://t.me/userinfobot), or read `chat.id` from the bot's incoming update (group IDs are negative).
+- **Feishu / Lark** — Use the `chat_id` from the event payload.
diff --git a/docs/usage/channels/overview.zh-CN.mdx b/docs/usage/channels/overview.zh-CN.mdx
index 5f6e20cba49..c34400c42cd 100644
--- a/docs/usage/channels/overview.zh-CN.mdx
+++ b/docs/usage/channels/overview.zh-CN.mdx
@@ -20,21 +20,21 @@ tags:
渠道功能允许您将 LobeHub 代理连接到外部消息平台。一旦连接,用户可以直接在他们已经使用的聊天应用中与您的 AI 助手互动,无需访问 LobeHub。
-> [!NOTE]
+> \[!NOTE]
>
> 微信渠道目前需要有效订阅。如果您使用的是没有订阅的社区版,**渠道**设置中可能暂时不会显示微信选项。
## 支持的平台
-| 平台 | 描述 |
-| ----------------------------------------- | -------------------------- |
-| [Discord](/docs/usage/channels/discord) | 连接到 Discord 服务器,用于频道聊天和私信 |
-| [Slack](/docs/usage/channels/slack) | 连接到 Slack,用于频道和私信对话 |
-| [Telegram](/docs/usage/channels/telegram) | 连接到 Telegram,用于私人和群组对话 |
-| [QQ](/docs/usage/channels/qq) | 连接到 QQ,用于群聊和私信 |
+| 平台 | 描述 |
+| ----------------------------------------- | ---------------------------------- |
+| [Discord](/docs/usage/channels/discord) | 连接到 Discord 服务器,用于频道聊天和私信 |
+| [Slack](/docs/usage/channels/slack) | 连接到 Slack,用于频道和私信对话 |
+| [Telegram](/docs/usage/channels/telegram) | 连接到 Telegram,用于私人和群组对话 |
+| [QQ](/docs/usage/channels/qq) | 连接到 QQ,用于群聊和私信 |
| [微信](/docs/usage/channels/wechat) | 通过 iLink Bot 连接到微信,用于私聊和群聊(需要有效订阅) |
-| [飞书](/docs/usage/channels/feishu) | 连接到飞书,用于团队协作(中国版) |
-| [Lark](/docs/usage/channels/lark) | 连接到 Lark,用于团队协作(国际版) |
+| [飞书](/docs/usage/channels/feishu) | 连接到飞书,用于团队协作(中国版) |
+| [Lark](/docs/usage/channels/lark) | 连接到 Lark,用于团队协作(国际版) |
## 工作原理
@@ -69,3 +69,61 @@ tags:
| 群组聊天 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |
| 表情反应 | 是 | 是 | 是 | 否 | 否 | 部分支持 | 部分支持 |
| 图片 / 文件附件 | 是 | 是 | 是 | 是 | 否 | 是 | 是 |
+
+## 允许的用户(全局)
+
+**高级设置** 里的 **允许的用户 (allowFrom)** 是一道**全局**用户级闸门。填入后,**所有**入站消息(私信和群聊 `@提及` 都算)都必须来自列表里的用户,无论私信策略 / 群组策略选什么都生效。留空则不做用户级过滤,由各 scope 的策略自行决定。
+
+填入后的行为:
+
+| 入口 | 不在白名单的发送者 |
+| --------------- | ------------------------------------------------------------------------------------------ |
+| **私信** | 被拒绝,对方在私信里收到一条 "您没有私信此机器人的权限" 的系统提示。 |
+| **群组 / 频道 @提及** | 被拒绝,会在 @ 所在的同一线程里发一条 "您没有与该机器人交互的权限" 的提示(Discord 上这是 @ 时自动创建的 thread,不会污染父频道;其他平台则可见于该群组)。 |
+
+每行填一个用户:左边是平台用户 ID(必填),右边是可选的 **备注** —— 这个备注只会在设置页展示给你自己,让你日后回看时不用费力辨认 `U01ABCXYZ` 到底是张三还是值班号;运行时完全不读它。
+
+> **防自我锁出**:如果你已经填了 **你的平台用户 ID**(AI 工具字段),那个 ID 会被全局白名单隐式信任。即便你把 bot 收紧到只给朋友、忘了把自己加进 **允许的用户**,也不会被锁出。
+
+## 私信策略
+
+私信策略只影响私信 — 群聊里的 `@提及` 由下面的 **群组策略** 单独管理。全局 **允许的用户** 的用户级过滤也会同时生效;各 scope 的策略叠加在上面。
+
+| 策略 | 行为 |
+| ------------------- | -------------------------------------------------------------------------------------- |
+| **开放 (Open)** | 平台上的任何用户都可以私信机器人(如设置了全局白名单则受其约束)。适合面向所有人开放的助手。 |
+| **白名单 (Allowlist)** | 私信需要发送者在 **允许的用户** 里。和 `Open` 的差别在白名单为空时:`Allowlist` 模式下会**全部拒绝**,而 `Open` 模式下任何人都能私信。 |
+| **禁用 (Disabled)** | 机器人会忽略所有私信。适合那种 " 只在群里被 `@` 时才回复 " 的场景。 |
+
+## 群组策略
+
+同样适用于支持群聊的那些平台,每个渠道都有一个 **群组策略 (Group Policy)**,用来控制机器人在群组、频道、子话题里的响应范围。它跟私信策略相互独立:`groupPolicy=disabled` 的机器人仍会接收私信(受私信策略约束),反之亦然。
+
+| 策略 | 行为 |
+| ------------------- | ---------------------------------------- |
+| **开放 (Open)** | 在机器人能读取的任何群组、频道、子话题里被 `@` 都响应(默认)。 |
+| **白名单 (Allowlist)** | 只有 **允许的频道** 里列出的频道 / 群组 / 会话才会响应,其他都忽略。 |
+| **禁用 (Disabled)** | 忽略所有非私信流量,机器人退化为纯私信模式。 |
+
+选择 **白名单** 时会出现 **允许的频道** 编辑器:每行填一个平台原生的频道 / 群组 / 会话 ID,可附带一个备注(比如 `#general`),备注只展示给你自己,方便日后辨认每个 ID 是哪个频道。
+
+> **Discord 父频道**:在 Discord 频道里 `@提及` 机器人时,平台会自动开一个 reply thread,入站 thread ID **不等于** Discord「复制频道 ID」给你的那个值。这里直接粘贴**父频道 ID** 就行 —— 它会让父频道下的所有自动 reply thread 都通过白名单。如果你只想放行某个具体 thread,也可以填那个 thread 的 ID,效果就是只放行该 thread。
+
+### 各平台默认值
+
+所有支持的平台两个策略默认都为 **开放 (Open)**,开箱即用。需要私有化时按渠道改成 **白名单 (Allowlist)** 或 **禁用 (Disabled)** 即可。微信因本身就是 DM 模式,没有这两个策略选项。
+
+### 如何获取用户的平台 ID
+
+- **Discord** — 在用户设置里开启开发者模式,右键用户头像选 **复制用户 ID**。
+- **Slack** — 打开用户资料 → 点击 `⋮` 菜单 → **复制成员 ID**(以 `U` 开头)。
+- **Telegram** — 让用户私信 [@userinfobot](https://t.me/userinfobot),或者从机器人收到的 update 里读 `from.id`。
+- **QQ** — 使用 OpenAPI 事件 payload 里的 `tiny_id`(用户对外可见的 QQ 号不一定就是平台 ID)。
+- **飞书 / Lark** — 使用事件 payload 里的 `open_id`,或开发者后台显示的 **User ID**。
+
+### 如何获取频道 / 群组 ID
+
+- **Discord** — 开启开发者模式,右键频道选 **复制频道 ID**。
+- **Slack** — 打开频道详情面板,底部能看到频道 ID(以 `C` 开头)。
+- **Telegram** — 把群里的一条消息转发给 [@userinfobot](https://t.me/userinfobot),或者从机器人收到的 update 里读 `chat.id`(群组是负数)。
+- **飞书 / Lark** — 使用事件 payload 里的 `chat_id`。
diff --git a/docs/usage/channels/qq.mdx b/docs/usage/channels/qq.mdx
index 5e26cedba52..3e2feaf3f8c 100644
--- a/docs/usage/channels/qq.mdx
+++ b/docs/usage/channels/qq.mdx
@@ -140,13 +140,41 @@ To use the bot in QQ groups:
2. @mention the bot in a message to trigger a response
3. The bot will reply in the group conversation
+## Access Policies
+
+Two independent policies gate inbound traffic. Both default to **Open**.
+
+### Allowed User IDs (global)
+
+A populated **Allowed User IDs** field is a global gate — DMs *and* group `@mentions` are restricted to listed QQ `tiny_id` values. Empty means "no user-level filter". Use the platform `tiny_id` from the OpenAPI event payload — the visible QQ number is not always the same as the platform ID.
+
+### DM Policy
+
+- **Open (default)** — Any QQ user who shares context with the bot can DM it (subject to the global allowlist when set).
+- **Allowlist** — DMs require the sender to be in **Allowed User IDs**. Differs from `Open` only when the list is empty: `Allowlist` then fails closed (no DMs).
+- **Disabled** — The bot ignores all DMs and only responds to group `@mentions`.
+
+### Group Policy
+
+Controls which QQ groups the bot will respond in.
+
+- **Open (default)** — Respond to `@mentions` in any group the bot has been added to.
+- **Allowlist** — Respond only in groups whose ID is listed in **Allowed Channel IDs** (use the platform group ID from the OpenAPI event payload).
+- **Disabled** — Ignore all group traffic; the bot only responds to DMs.
+
+See the [Channels overview](/docs/usage/channels/overview#direct-message-policy) for cross-platform details.
+
## Configuration Reference
-| Field | Required | Description |
-| ------------------- | -------- | --------------------------------------------------------------------------------------- |
-| **Application ID** | Yes | Your bot's App ID from QQ Open Platform |
-| **App Secret** | Yes | Your bot's App Secret from QQ Open Platform |
-| **Connection Mode** | No | `websocket` (default) or `webhook`. Choose based on your QQ Open Platform configuration |
+| Field | Required | Description |
+| ----------------------- | -------- | ---------------------------------------------------------------------------------------------------- |
+| **Application ID** | Yes | Your bot's App ID from QQ Open Platform |
+| **App Secret** | Yes | Your bot's App Secret from QQ Open Platform |
+| **Connection Mode** | No | `websocket` (default) or `webhook`. Choose based on your QQ Open Platform configuration |
+| **Allowed User IDs** | No | Comma- or whitespace-separated QQ `tiny_id` values. Global gate — applies to DMs and group @mentions |
+| **DM Policy** | No | `open` (default), `allowlist`, or `disabled` — who is allowed to DM the bot |
+| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the bot responds to @mentions |
+| **Allowed Channel IDs** | No | Comma- or whitespace-separated QQ group IDs. Used when Group Policy is Allowlist |
## Limitations
diff --git a/docs/usage/channels/qq.zh-CN.mdx b/docs/usage/channels/qq.zh-CN.mdx
index 69aceee63ee..a63e1966d09 100644
--- a/docs/usage/channels/qq.zh-CN.mdx
+++ b/docs/usage/channels/qq.zh-CN.mdx
@@ -137,13 +137,41 @@ LobeHub ��持两种 QQ 机器人连接模式:
2. 在消息中 @提及机器人以触发响应
3. 机器人将在群聊中回复
+## 接入策略
+
+两个独立的策略控制入站消息,默认都为 **开放**。
+
+### 允许的用户 ID(全局)
+
+填入 **允许的用户 ID** 后,**所有**入站消息(私信和群聊 `@提及`)都必须来自列表里的 QQ `tiny_id`。留空则不做用户级过滤。`tiny_id` 来自 OpenAPI 事件 payload —— 用户对外可见的 QQ 号不一定就是平台 ID。
+
+### 私信策略
+
+- **开放 (Open)(默认)** — 任何与机器人有上下文交集的 QQ 用户都可以私信(若设置了全局白名单则受其约束)。
+- **白名单 (Allowlist)** — 私信需要发送者在 **允许的用户 ID** 里。和 `Open` 的差别在白名单为空时:`Allowlist` 模式**全部拒绝**。
+- **禁用 (Disabled)** — 机器人忽略所有私信,只在群聊里被 `@提及` 时回复。
+
+### 群组策略
+
+控制机器人会在哪些 QQ 群里响应。
+
+- **开放 (Open)(默认)** — 在机器人加入的任何群里被 `@` 都响应。
+- **白名单 (Allowlist)** — 只在 **允许的频道 ID** 列出的群里响应(使用 OpenAPI 事件 payload 里的群 ID)。
+- **禁用 (Disabled)** — 忽略所有群聊流量,机器人只接受私信。
+
+跨平台细节见 [渠道概览](/docs/usage/channels/overview#direct-message-policy)。
+
## 配置参考
-| 字段 | 是否必需 | 描述 |
-| -------------- | ---- | ----------------------------------------- |
-| **应用 ID** | 是 | 来自 QQ 开放平台的 App ID |
-| **App Secret** | 是 | 来自 QQ 开放平台的 App Secret |
-| **连接模式** | 否 | `websocket`(默认)或 `webhook`,根据 QQ 开放平台配置选择 |
+| 字段 | 是否必需 | 描述 |
+| -------------- | ---- | -------------------------------------------------- |
+| **应用 ID** | 是 | 来自 QQ 开放平台的 App ID |
+| **App Secret** | 是 | 来自 QQ 开放平台的 App Secret |
+| **连接模式** | 否 | `websocket`(默认)或 `webhook`,根据 QQ 开放平台配置选择 |
+| **允许的用户 ID** | 否 | 逗号或空格分隔的 QQ `tiny_id`。全局闸门 — 私信和群聊 @ 都受其约束 |
+| **私信策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制谁可以私信机器人 |
+| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些群中响应 |
+| **允许的频道 ID** | 否 | 逗号或空格分隔的 QQ 群 ID。仅在群组策略为白名单时使用 |
## 功能限制
diff --git a/docs/usage/channels/slack.mdx b/docs/usage/channels/slack.mdx
index 3e2b6ee1852..ac52c547f6a 100644
--- a/docs/usage/channels/slack.mdx
+++ b/docs/usage/channels/slack.mdx
@@ -213,19 +213,48 @@ Use this method if your Slack app already has Event Subscriptions configured wit
Also ensure you add the `commands` scope under **OAuth & Permissions** → **Bot Token Scopes**, and enable **Interactivity & Shortcuts** with the same Webhook URL as the Request URL.
</Steps>
+## Access Policies
+
+Two independent policies gate inbound traffic. Both default to **Open**.
+
+### Allowed User IDs (global)
+
+A populated **Allowed User IDs** field is a global gate — DMs *and* channel `@mentions` are restricted to listed Slack member IDs. Empty means "no user-level filter". Open a user's profile → click `⋮` → **Copy member ID** (starts with `U`).
+
+### DM Policy
+
+- **Open (default)** — Any workspace member can DM the bot (subject to the global allowlist when set).
+- **Allowlist** — DMs require the sender to be in **Allowed User IDs**. Differs from `Open` only when the list is empty: `Allowlist` then fails closed (no DMs).
+- **Disabled** — The bot ignores all DMs and only replies to channel `@mentions`.
+
+### Group Policy
+
+Controls which Slack channels the bot will respond in.
+
+- **Open (default)** — Respond to `@mentions` in any channel the bot has been added to.
+- **Allowlist** — Respond only in channels whose ID is in **Allowed Channel IDs**. Open the channel's About panel to copy the channel ID (starts with `C`).
+- **Disabled** — Ignore all channel traffic; the bot only responds to DMs.
+
+See the [Channels overview](/docs/usage/channels/overview#direct-message-policy) for cross-platform details.
+
## Configuration Reference
-| Field | Required | Description |
-| ------------------- | ---------------- | ----------------------------------------------------- |
-| **Application ID** | Yes | Your Slack app's ID |
-| **Bot Token** | Yes | Bot User OAuth Token (`xoxb-...`) |
-| **Signing Secret** | Yes | Used to verify requests from Slack |
-| **App-Level Token** | Socket Mode only | App-level token (`xapp-...`) for WebSocket connection |
-| **Connection Mode** | No | `websocket` or `webhook` (default: `webhook`) |
+| Field | Required | Description |
+| ----------------------- | ---------------- | ------------------------------------------------------------------------------------------------------ |
+| **Application ID** | Yes | Your Slack app's ID |
+| **Bot Token** | Yes | Bot User OAuth Token (`xoxb-...`) |
+| **Signing Secret** | Yes | Used to verify requests from Slack |
+| **App-Level Token** | Socket Mode only | App-level token (`xapp-...`) for WebSocket connection |
+| **Connection Mode** | No | `websocket` or `webhook` (default: `webhook`) |
+| **Allowed User IDs** | No | Comma- or whitespace-separated Slack member IDs. Global gate — applies to DMs and channel @mentions |
+| **DM Policy** | No | `open` (default), `allowlist`, or `disabled` — who is allowed to DM the bot |
+| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the bot responds to @mentions |
+| **Allowed Channel IDs** | No | Comma- or whitespace-separated Slack channel IDs (start with `C`). Used when Group Policy is Allowlist |
## Troubleshooting
- **DM shows "Sending messages to this app has been turned off":** In the Slack API Dashboard → **App Home** → **Show Tabs**, make sure **Messages Tab** is enabled and "Allow users to send Slash commands and messages from the messages tab" is checked. This is already enabled if you created the app using the Manifest template.
+- **Bot ignores DMs even though Slack is configured correctly:** Open **Advanced Settings** in LobeHub and check **DM Policy**. If it is `Disabled`, switch to `Open` or `Allowlist`. If it is `Allowlist`, confirm the sender's Slack member ID is listed in **Allowed User IDs**.
- **Bot not responding:** Confirm the bot has been invited to the channel. For Socket Mode, ensure the App-Level Token is correct and Socket Mode is enabled in Slack app settings.
- **Test Connection failed:** Double-check the Application ID and Bot Token. Ensure the app is installed to the workspace.
- **Webhook verification failed (Webhook mode):** Make sure the Signing Secret matches and the Webhook URL is correct.
diff --git a/docs/usage/channels/slack.zh-CN.mdx b/docs/usage/channels/slack.zh-CN.mdx
index 7f7fb8aa1fb..f1dd486ce37 100644
--- a/docs/usage/channels/slack.zh-CN.mdx
+++ b/docs/usage/channels/slack.zh-CN.mdx
@@ -210,19 +210,48 @@ LobeHub 支持两种 Slack 连接模式:
同时确保在 **OAuth & Permissions** → **Bot Token Scopes** 中添加 `commands` 权限,并在 **Interactivity & Shortcuts** 中启用 Interactivity,将 Request URL 设为相同的 Webhook URL。
</Steps>
+## 接入策略
+
+两个独立的策略控制入站消息,默认都为 **开放**。
+
+### 允许的用户 ID(全局)
+
+填入 **允许的用户 ID** 后,**所有**入站消息(私信和频道 `@提及`)都必须来自列表里的 Slack 成员 ID。留空则不做用户级过滤。打开用户资料 → 点击 `⋮` → **复制成员 ID**(以 `U` 开头)。
+
+### 私信策略
+
+- **开放 (Open)(默认)** — workspace 内任何成员都可以私信机器人(若设置了全局白名单则受其约束)。
+- **白名单 (Allowlist)** — 私信需要发送者在 **允许的用户 ID** 里。和 `Open` 的差别在白名单为空时:`Allowlist` 模式**全部拒绝**。
+- **禁用 (Disabled)** — 机器人忽略所有私信,只在频道里被 `@提及` 时回复。
+
+### 群组策略
+
+控制机器人会在哪些 Slack 频道里响应。
+
+- **开放 (Open)(默认)** — 在机器人加入的任何频道里被 `@` 都响应。
+- **白名单 (Allowlist)** — 只在 **允许的频道 ID** 列出的频道里响应。打开频道详情面板,底部能看到频道 ID(以 `C` 开头)。
+- **禁用 (Disabled)** — 忽略所有频道流量,机器人只接受私信。
+
+跨平台细节见 [渠道概览](/docs/usage/channels/overview#direct-message-policy)。
+
## 配置参考
-| 字段 | 是否必需 | 描述 |
-| -------------- | ------------- | -------------------------------------- |
-| **应用 ID** | 是 | 您的 Slack 应用 ID |
-| **Bot Token** | 是 | Bot User OAuth Token(`xoxb-...`) |
-| **签名密钥** | 是 | 用于验证来自 Slack 的请求 |
-| **应用级别 Token** | 仅 Socket Mode | 应用级别 Token(`xapp-...`),用于 WebSocket 连接 |
-| **连接模式** | 否 | `websocket` 或 `webhook`(默认:`webhook`) |
+| 字段 | 是否必需 | 描述 |
+| -------------- | ------------- | --------------------------------------------------- |
+| **应用 ID** | 是 | 您的 Slack 应用 ID |
+| **Bot Token** | 是 | Bot User OAuth Token(`xoxb-...`) |
+| **签名密钥** | 是 | 用于验证来自 Slack 的请求 |
+| **应用级别 Token** | 仅 Socket Mode | 应用级别 Token(`xapp-...`),用于 WebSocket 连接 |
+| **连接模式** | 否 | `websocket` 或 `webhook`(默认:`webhook`) |
+| **允许的用户 ID** | 否 | 逗号或空格分隔的 Slack 成员 ID。全局闸门 — 私信和频道 @ 都受其约束 |
+| **私信策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制谁可以私信机器人 |
+| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些频道中响应 |
+| **允许的频道 ID** | 否 | 逗号或空格分隔的 Slack 频道 ID(以 `C` 开头)。仅在群组策略为白名单时使用 |
## 故障排除
- **私信显示 "Sending messages to this app has been turned off":** 在 Slack API 控制台 → **App Home** → **Show Tabs** 中,确保 **Messages Tab** 已启用,并勾选 "Allow users to send Slash commands and messages from the messages tab"。如果使用 Manifest 模板创建应用则默认已开启。
+- **Slack 配置正常但机器人不回私信:** 在 LobeHub 的 **高级设置** 里检查 **私信策略**。如果是 `Disabled`,改成 `Open` 或 `Allowlist`;如果是 `Allowlist`,确认发起方的 Slack 成员 ID 已加入 **允许的用户 ID**。
- **机器人未响应:** 确认机器人已被邀请到频道。Socket Mode 下请确保应用级别 Token 正确且 Socket Mode 已在 Slack 应用设置中启用。
- **测试连接失败:** 仔细检查应用 ID 和 Bot Token 是否正确。确保应用已安装到工作区。
- **Webhook 验证失败(Webhook 模式):** 确保签名密钥匹配且 Webhook URL 正确。
diff --git a/docs/usage/channels/telegram.mdx b/docs/usage/channels/telegram.mdx
index ea3f59c1de6..cfd38c9a269 100644
--- a/docs/usage/channels/telegram.mdx
+++ b/docs/usage/channels/telegram.mdx
@@ -93,16 +93,45 @@ To use the bot in Telegram groups:
**About Group Privacy Mode:** Telegram bots have privacy mode enabled by default, which means they only receive messages that @mention the bot, reply to the bot, or contain /commands. If you change the privacy mode setting after creating the bot, you **must remove and re-add the bot to the group** for the new setting to take effect in that group.
</Callout>
+## Access Policies
+
+Two independent policies gate inbound traffic. Both default to **Open**.
+
+### Allowed User IDs (global)
+
+A populated **Allowed User IDs** field acts as a global gate — DMs *and* group `@mentions` are restricted to listed Telegram numeric user IDs. Empty means "no user-level filter". Grab a user's numeric ID via [@userinfobot](https://t.me/userinfobot), or read the `from.id` field from the bot's incoming update.
+
+### DM Policy
+
+- **Open (default)** — Anyone on Telegram can DM the bot (subject to the global allowlist when set).
+- **Allowlist** — DMs require the sender to be in **Allowed User IDs**. Differs from `Open` only when the list is empty: `Allowlist` then fails closed (no DMs).
+- **Disabled** — The bot ignores all DMs and only responds to group `@mentions`.
+
+### Group Policy
+
+Controls which Telegram groups / channels the bot will respond in.
+
+- **Open (default)** — Respond in any group / channel the bot has been added to.
+- **Allowlist** — Respond only in chats whose ID is listed in **Allowed Channel IDs**. Forward a message from the chat to [@userinfobot](https://t.me/userinfobot) to grab the chat ID (group IDs are negative).
+- **Disabled** — Ignore all group traffic; the bot only responds to DMs.
+
+See the [Channels overview](/docs/usage/channels/overview#direct-message-policy) for cross-platform details.
+
## Configuration Reference
-| Field | Required | Description |
-| ------------------------ | -------- | ---------------------------------------------- |
-| **Bot Token** | Yes | API token from BotFather |
-| **Bot User ID** | Auto | Automatically derived from the bot token |
-| **Webhook Secret Token** | No | Optional secret for verifying webhook requests |
+| Field | Required | Description |
+| ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------- |
+| **Bot Token** | Yes | API token from BotFather |
+| **Bot User ID** | Auto | Automatically derived from the bot token |
+| **Webhook Secret Token** | No | Optional secret for verifying webhook requests |
+| **Allowed User IDs** | No | Comma- or whitespace-separated Telegram numeric user IDs. Global gate — applies to DMs and group @mentions |
+| **DM Policy** | No | `open` (default), `allowlist`, or `disabled` — who is allowed to DM the bot |
+| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the bot responds in groups |
+| **Allowed Channel IDs** | No | Comma- or whitespace-separated Telegram chat IDs (group IDs are negative). Used when Group Policy is Allowlist |
## Troubleshooting
- **Bot not responding:** Verify the bot token is correct and the configuration is saved. Click **Test Connection** to diagnose.
+- **Bot ignores DMs:** Open **Advanced Settings** and check **DM Policy**. If it is `Disabled`, switch to `Open` or `Allowlist`. If it is `Allowlist`, confirm the sender's Telegram user ID (from [@userinfobot](https://t.me/userinfobot)) is listed in **Allowed User IDs**.
- **Webhook registration failed:** Ensure your LobeHub subscription is active. Telegram requires HTTPS endpoints for webhooks, which LobeHub provides automatically.
- **Group chat issues:** Make sure the bot has been added to the group and has permission to read messages. Mention the bot with `@username` to trigger a response. If the bot doesn't respond in a group, try removing the bot from the group and re-adding it — Telegram's privacy mode changes require re-joining the group to take effect.
diff --git a/docs/usage/channels/telegram.zh-CN.mdx b/docs/usage/channels/telegram.zh-CN.mdx
index 4dab159adc6..8c0bcccd140 100644
--- a/docs/usage/channels/telegram.zh-CN.mdx
+++ b/docs/usage/channels/telegram.zh-CN.mdx
@@ -92,16 +92,45 @@ tags:
**关于隐私模式(Group Privacy):** Telegram 机器人默认启用隐私模式,仅接收群组中 @提及、回复机器人的消息以及 / 命令。如果您在创建机器人后更改了隐私模式设置,**必须将机器人从群组中移除后重新加入**,新的设置才会对该群组生效。
</Callout>
+## 接入策略
+
+两个独立的策略控制入站消息,默认都为 **开放**。
+
+### 允许的用户 ID(全局)
+
+填入 **允许的用户 ID** 后,**所有**入站消息(私信和群聊 `@提及`)都必须来自列表里的 Telegram 数字用户 ID。留空则不做用户级过滤。让目标用户私信 [@userinfobot](https://t.me/userinfobot) 拿到自己的数字 ID,或直接从机器人收到的 update 里读 `from.id`。
+
+### 私信策略
+
+- **开放 (Open)(默认)** — Telegram 上任何用户都可以私信机器人(若设置了全局白名单则受其约束)。
+- **白名单 (Allowlist)** — 私信需要发送者在 **允许的用户 ID** 里。和 `Open` 的差别在白名单为空时:`Allowlist` 模式**全部拒绝**。
+- **禁用 (Disabled)** — 机器人忽略所有私信,只在群组里被 `@提及` 时回复。
+
+### 群组策略
+
+控制机器人会在哪些 Telegram 群组 / 频道里响应。
+
+- **开放 (Open)(默认)** — 在机器人加入的任何群组 / 频道里都响应。
+- **白名单 (Allowlist)** — 只在 **允许的频道 ID** 列出的会话里响应。把群里的一条消息转发给 [@userinfobot](https://t.me/userinfobot) 即可拿到 chat ID(群组是负数)。
+- **禁用 (Disabled)** — 忽略所有群组流量,机器人只接受私信。
+
+跨平台细节见 [渠道概览](/docs/usage/channels/overview#direct-message-policy)。
+
## 配置参考
-| 字段 | 是否必需 | 描述 |
-| ---------------- | ---- | --------------------- |
-| **机器人令牌** | 是 | 来自 BotFather 的 API 令牌 |
-| **机器人用户 ID** | 自动 | 根据机器人令牌自动生成 |
-| **Webhook 密钥令牌** | 否 | 用于验证 Webhook 请求的可选密钥 |
+| 字段 | 是否必需 | 描述 |
+| ---------------- | ---- | --------------------------------------------------- |
+| **机器人令牌** | 是 | 来自 BotFather 的 API 令牌 |
+| **机器人用户 ID** | 自动 | 根据机器人令牌自动生成 |
+| **Webhook 密钥令牌** | 否 | 用于验证 Webhook 请求的可选密钥 |
+| **允许的用户 ID** | 否 | 逗号或空格分隔的 Telegram 数字用户 ID。全局闸门 — 私信和群聊 @ 都受其约束 |
+| **私信策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制谁可以私信机器人 |
+| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些群组中响应 |
+| **允许的频道 ID** | 否 | 逗号或空格分隔的 Telegram chat ID(群组为负数)。仅在群组策略为白名单时使用 |
## 故障排除
- **机器人未响应:** 验证机器人令牌是否正确并确保配置已保存。点击 **测试连接** 进行诊断。
+- **机器人不回私信:** 打开 **高级设置** 检查 **私信策略**。如果是 `Disabled`,改成 `Open` 或 `Allowlist`;如果是 `Allowlist`,确认发起方的 Telegram 用户 ID(可通过 [@userinfobot](https://t.me/userinfobot) 获取)已加入 **允许的用户 ID**。
- **Webhook 注册失败:** 确保您的 LobeHub 订阅处于活动状态。Telegram 要求 Webhook 使用 HTTPS 端点,LobeHub 会自动提供。
- **群组聊天问题:** 确保机器人已被添加到群组并具有读取消息的权限。使用 `@username` 提及机器人以触发响应。如果机器人在群组中没有响应,尝试将机器人从群组中移除后重新加入 ——Telegram 的隐私模式设置变更需要重新加入群组才能生效。
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 5c9f6c18f57..10f71026085 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -1,4 +1,13 @@
{
+ "channel.allowFrom": "Allowed Users",
+ "channel.allowFromAdd": "Add user",
+ "channel.allowFromEmpty": "No users added yet — anyone can interact with the bot.",
+ "channel.allowFromHint": "Only listed users can interact with the bot; your 'Platform User ID' is auto-included.",
+ "channel.allowFromIdLabel": "User ID",
+ "channel.allowFromIdPlaceholder": "Platform user ID",
+ "channel.allowFromNameLabel": "Note",
+ "channel.allowFromNamePlaceholder": "e.g. Alice (your reminder)",
+ "channel.allowListRemove": "Remove",
"channel.appSecret": "App Secret",
"channel.appSecretHint": "The App Secret of your bot application. It will be encrypted and stored securely.",
"channel.appSecretPlaceholder": "Paste your app secret here",
@@ -45,8 +54,6 @@
"channel.displayToolCalls": "Display Tool Calls",
"channel.displayToolCallsHint": "Show tool call details during AI responses. When disabled, only the final response is displayed for a cleaner experience.",
"channel.dm": "Direct Messages",
- "channel.dmEnabled": "Enable DMs",
- "channel.dmEnabledHint": "Allow the bot to receive and respond to direct messages",
"channel.dmPolicy": "DM Policy",
"channel.dmPolicyAllowlist": "Allowlist",
"channel.dmPolicyDisabled": "Disabled",
@@ -63,6 +70,19 @@
"channel.feishu.description": "Connect this assistant to Feishu for private and group chats.",
"channel.feishu.webhookMigrationDesc": "WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket in Advanced Settings. No additional configuration is needed on the Feishu/Lark Open Platform.",
"channel.feishu.webhookMigrationTitle": "Consider migrating to WebSocket mode",
+ "channel.groupAllowFrom": "Allowed Channels",
+ "channel.groupAllowFromAdd": "Add channel",
+ "channel.groupAllowFromEmpty": "No channels added yet — the bot will not respond anywhere.",
+ "channel.groupAllowFromHint": "Channel / group / chat IDs the bot may respond in.",
+ "channel.groupAllowFromIdLabel": "Channel ID",
+ "channel.groupAllowFromIdPlaceholder": "Channel / group / chat ID",
+ "channel.groupAllowFromNameLabel": "Note",
+ "channel.groupAllowFromNamePlaceholder": "e.g. #general (your reminder)",
+ "channel.groupPolicy": "Group Policy",
+ "channel.groupPolicyAllowlist": "Allowlist",
+ "channel.groupPolicyDisabled": "Disabled",
+ "channel.groupPolicyHint": "Control where the bot responds in groups, channels, and threads",
+ "channel.groupPolicyOpen": "Open",
"channel.historyLimit": "History Message Limit",
"channel.historyLimitHint": "Default number of messages to fetch when reading channel history",
"channel.importConfig": "Import Configuration",
@@ -91,8 +111,8 @@
"channel.secretToken": "Webhook Secret Token",
"channel.secretTokenHint": "Optional. Used to verify webhook requests from Telegram.",
"channel.secretTokenPlaceholder": "Optional secret for webhook verification",
- "channel.serverId": "Default Server / Guild ID",
- "channel.serverIdHint": "Your default server or guild ID on this platform. The AI uses it to list channels without asking.",
+ "channel.serverId": "Default Server (for AI tools)",
+ "channel.serverIdHint": "The server / guild ID AI tools should default to when you ask the bot to act on a server (e.g. 'list channels', 'send to #announcements'). Independent of access control — see Group Policy for that.",
"channel.settings": "Advanced Settings",
"channel.settingsResetConfirm": "Are you sure you want to reset advanced settings to default?",
"channel.settingsResetDefault": "Reset to Default",
@@ -118,8 +138,8 @@
"channel.testFailed": "Connection test failed",
"channel.testSuccess": "Connection test passed",
"channel.updateFailed": "Failed to update status",
- "channel.userId": "Your Platform User ID",
- "channel.userIdHint": "Your user ID on this platform. The AI can use it to send you direct messages.",
+ "channel.userId": "Your Platform User ID (for AI tools)",
+ "channel.userIdHint": "AI tools use this to reach you proactively (e.g. reminders, notifications); also auto-trusted by the global allowlist.",
"channel.validationError": "Please fill in Application ID and Token",
"channel.verificationToken": "Verification Token",
"channel.verificationTokenHint": "Optional. Used to verify webhook event source.",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 78e9bffc007..24f850634e0 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -1,4 +1,13 @@
{
+ "channel.allowFrom": "允许的用户",
+ "channel.allowFromAdd": "添加用户",
+ "channel.allowFromEmpty": "尚未添加任何用户——任何人都可以与机器人交互。",
+ "channel.allowFromHint": "仅列表内用户可与机器人交互,「你的平台用户 ID」会自动加入。",
+ "channel.allowFromIdLabel": "用户 ID",
+ "channel.allowFromIdPlaceholder": "平台用户 ID",
+ "channel.allowFromNameLabel": "备注",
+ "channel.allowFromNamePlaceholder": "如:张三(仅你自己可见)",
+ "channel.allowListRemove": "删除",
"channel.appSecret": "App Secret",
"channel.appSecretHint": "你的机器人应用的 App Secret,将被加密存储。",
"channel.appSecretPlaceholder": "在此粘贴你的 App Secret",
@@ -45,8 +54,6 @@
"channel.displayToolCalls": "展示工具调用",
"channel.displayToolCallsHint": "在 AI 回复过程中展示工具调用详情。关闭后仅展示最终回复,获得更简洁的体验。",
"channel.dm": "私信",
- "channel.dmEnabled": "启用私信",
- "channel.dmEnabledHint": "允许机器人接收和回复私信",
"channel.dmPolicy": "私信策略",
"channel.dmPolicyAllowlist": "白名单",
"channel.dmPolicyDisabled": "禁用",
@@ -63,6 +70,19 @@
"channel.feishu.description": "将助手连接到飞书,支持私聊和群聊。",
"channel.feishu.webhookMigrationDesc": "WebSocket 模式提供实时事件推送,无需配置公网回调地址。如需迁移,在高级设置中将连接模式切换为 WebSocket 即可,无需在飞书/Lark 开放平台进行额外配置。",
"channel.feishu.webhookMigrationTitle": "建议迁移到 WebSocket 模式",
+ "channel.groupAllowFrom": "允许的频道",
+ "channel.groupAllowFromAdd": "添加频道",
+ "channel.groupAllowFromEmpty": "尚未添加任何频道——机器人不会在任何地方响应。",
+ "channel.groupAllowFromHint": "机器人允许响应的频道 / 群组 / 会话 ID。",
+ "channel.groupAllowFromIdLabel": "频道 ID",
+ "channel.groupAllowFromIdPlaceholder": "频道 / 群组 / 会话 ID",
+ "channel.groupAllowFromNameLabel": "备注",
+ "channel.groupAllowFromNamePlaceholder": "如:#general(仅你自己可见)",
+ "channel.groupPolicy": "群组策略",
+ "channel.groupPolicyAllowlist": "白名单",
+ "channel.groupPolicyDisabled": "禁用",
+ "channel.groupPolicyHint": "控制机器人在群组、频道、子话题里的响应范围",
+ "channel.groupPolicyOpen": "开放",
"channel.historyLimit": "历史消息条数",
"channel.historyLimitHint": "读取频道历史消息时默认获取的消息数量",
"channel.importConfig": "导入平台配置",
@@ -91,8 +111,8 @@
"channel.secretToken": "Webhook 密钥",
"channel.secretTokenHint": "可选。用于验证来自 Telegram 的 Webhook 请求。",
"channel.secretTokenPlaceholder": "可选的 Webhook 验证密钥",
- "channel.serverId": "默认服务器 / Guild ID",
- "channel.serverIdHint": "你在该平台上的默认服务器或 Guild ID,AI 可以用它自动列出频道。",
+ "channel.serverId": "默认服务器(供 AI 工具使用)",
+ "channel.serverIdHint": "你让 bot 在某个服务器上做事时(比如 \"列出频道\"、\"发到 #announcements\"),AI 工具默认操作的服务器 / Guild ID。跟访问控制无关 —— 那是群组策略的事。",
"channel.settings": "高级设置",
"channel.settingsResetConfirm": "确定要将高级设置恢复为默认配置吗?",
"channel.settingsResetDefault": "恢复默认配置",
@@ -118,8 +138,8 @@
"channel.testFailed": "连接测试失败",
"channel.testSuccess": "连接测试通过",
"channel.updateFailed": "更新状态失败",
- "channel.userId": "你的平台用户 ID",
- "channel.userIdHint": "你在该平台上的用户 ID,AI 可以用它向你发送私信。",
+ "channel.userId": "你的平台用户 ID(供 AI 工具使用)",
+ "channel.userIdHint": "AI 工具用它主动联系你(如定时提醒、通知);该 ID 也会被全局白名单自动信任。",
"channel.validationError": "请填写应用 ID 和 Token",
"channel.verificationToken": "Verification Token",
"channel.verificationTokenHint": "可选。用于验证事件推送来源。",
diff --git a/src/locales/default/agent.ts b/src/locales/default/agent.ts
index 770b2054e57..4a2a122ba02 100644
--- a/src/locales/default/agent.ts
+++ b/src/locales/default/agent.ts
@@ -129,13 +129,34 @@ export default {
'channel.debounceMsHint':
'How long to wait for additional messages before dispatching to the agent (ms)',
'channel.dm': 'Direct Messages',
- 'channel.dmEnabled': 'Enable DMs',
- 'channel.dmEnabledHint': 'Allow the bot to receive and respond to direct messages',
'channel.dmPolicy': 'DM Policy',
'channel.dmPolicyHint': 'Control who can send direct messages to the bot',
'channel.dmPolicyAllowlist': 'Allowlist',
'channel.dmPolicyDisabled': 'Disabled',
'channel.dmPolicyOpen': 'Open',
+ 'channel.allowFrom': 'Allowed Users',
+ 'channel.allowFromHint':
+ "Only listed users can interact with the bot; your 'Platform User ID' is auto-included.",
+ 'channel.allowFromIdLabel': 'User ID',
+ 'channel.allowFromIdPlaceholder': 'Platform user ID',
+ 'channel.allowFromNameLabel': 'Note',
+ 'channel.allowFromNamePlaceholder': 'e.g. Alice (your reminder)',
+ 'channel.allowFromAdd': 'Add user',
+ 'channel.allowFromEmpty': 'No users added yet — anyone can interact with the bot.',
+ 'channel.groupPolicy': 'Group Policy',
+ 'channel.groupPolicyHint': 'Control where the bot responds in groups, channels, and threads',
+ 'channel.groupPolicyAllowlist': 'Allowlist',
+ 'channel.groupPolicyDisabled': 'Disabled',
+ 'channel.groupPolicyOpen': 'Open',
+ 'channel.groupAllowFrom': 'Allowed Channels',
+ 'channel.groupAllowFromHint': 'Channel / group / chat IDs the bot may respond in.',
+ 'channel.groupAllowFromIdLabel': 'Channel ID',
+ 'channel.groupAllowFromIdPlaceholder': 'Channel / group / chat ID',
+ 'channel.groupAllowFromNameLabel': 'Note',
+ 'channel.groupAllowFromNamePlaceholder': 'e.g. #general (your reminder)',
+ 'channel.groupAllowFromAdd': 'Add channel',
+ 'channel.groupAllowFromEmpty': 'No channels added yet — the bot will not respond anywhere.',
+ 'channel.allowListRemove': 'Remove',
'channel.settings': 'Advanced Settings',
'channel.settingsResetConfirm': 'Are you sure you want to reset advanced settings to default?',
'channel.settingsResetDefault': 'Reset to Default',
@@ -148,12 +169,12 @@ export default {
'Show tool call details during AI responses. When disabled, only the final response is displayed for a cleaner experience.',
'channel.historyLimit': 'History Message Limit',
'channel.historyLimitHint': 'Default number of messages to fetch when reading channel history',
- 'channel.serverId': 'Default Server / Guild ID',
+ 'channel.serverId': 'Default Server (for AI tools)',
'channel.serverIdHint':
- 'Your default server or guild ID on this platform. The AI uses it to list channels without asking.',
- 'channel.userId': 'Your Platform User ID',
+ "The server / guild ID AI tools should default to when you ask the bot to act on a server (e.g. 'list channels', 'send to #announcements'). Independent of access control — see Group Policy for that.",
+ 'channel.userId': 'Your Platform User ID (for AI tools)',
'channel.userIdHint':
- 'Your user ID on this platform. The AI can use it to send you direct messages.',
+ 'AI tools use this to reach you proactively (e.g. reminders, notifications); also auto-trusted by the global allowlist.',
'channel.refreshStatus': 'Refresh status',
'channel.runtimeDisconnected': 'Bot disconnected',
'channel.statusConnected': 'Connected',
diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsx
index c22ef040669..31558b77648 100644
--- a/src/routes/(main)/agent/channel/detail/Body.tsx
+++ b/src/routes/(main)/agent/channel/detail/Body.tsx
@@ -11,7 +11,7 @@ import {
Switch,
} from 'antd';
import { createStaticStyles } from 'antd-style';
-import { RotateCcw } from 'lucide-react';
+import { Plus, RotateCcw, Trash2 } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -93,6 +93,12 @@ const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
t(field.label)
);
+ // Array of objects (e.g. user / channel allowlist) — needs Form.List, can't
+ // be expressed as a single control inside a name-bound FormItem.
+ if (field.type === 'array' && field.items?.type === 'object') {
+ return <ObjectListField divider={divider} field={field} label={label} parentKey={parentKey} />;
+ }
+
let children: React.ReactNode;
switch (field.type) {
case 'password': {
@@ -154,6 +160,100 @@ const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
);
});
+// --------------- Object-list field (e.g. allowFrom: [{id, name?}]) ---------------
+
+interface ObjectListFieldProps {
+ divider?: boolean;
+ field: FieldSchema;
+ label: React.ReactNode;
+ parentKey: string;
+}
+
+const ObjectListField = memo<ObjectListFieldProps>(({ field, parentKey, divider, label }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+
+ // The runtime ignores anything beyond `id`, but the editor renders every
+ // declared property so future additions (e.g. a per-row note tag) flow
+ // through without code changes here.
+ const itemProps = field.items?.type === 'object' ? (field.items.properties ?? []) : [];
+
+ // Convention: the schema field key drives the per-list copy keys
+ // (`allowFrom` → `channel.allowFromAdd` / `channel.allowFromEmpty`).
+ // Avoids overloading FieldSchema with cosmetic strings while keeping each
+ // list's "Add user" / "Add channel" wording distinct.
+ const addLabel = t(`${field.label}Add` as 'channel.allowFromAdd');
+ const emptyLabel = t(`${field.label}Empty` as 'channel.allowFromEmpty');
+ const removeLabel = t('channel.allowListRemove');
+
+ return (
+ <FormItem
+ desc={field.description ? t(field.description) : undefined}
+ divider={divider}
+ label={label}
+ minWidth={'max(50%, 400px)'}
+ tag={isDev ? field.key : undefined}
+ variant="borderless"
+ >
+ <AntdForm.List initialValue={field.default as unknown[]} name={[parentKey, field.key]}>
+ {(rows, { add, remove }) => (
+ <Flexbox gap={8} style={{ width: '100%' }}>
+ {rows.length === 0 && (
+ <Flexbox style={{ fontSize: 12, opacity: 0.6, paddingBlock: 4 }}>
+ {emptyLabel}
+ </Flexbox>
+ )}
+ {rows.map(({ key, name }) => (
+ <Flexbox horizontal align="center" gap={8} key={key}>
+ {itemProps.map((sub) => (
+ // `noStyle` skips the antd FormItem chrome that the parent
+ // form's 50%-width override targets — without it each cell
+ // collapses to half the row, leaving a wide gap between
+ // the id and name inputs. The flex:1 wrapper takes over
+ // sizing, and `minWidth:0` lets the input actually shrink.
+ <div key={sub.key} style={{ flex: 1, minWidth: 0 }}>
+ <AntdForm.Item
+ noStyle
+ name={[name, sub.key]}
+ rules={
+ sub.required
+ ? [{ message: t(sub.label), required: true, whitespace: true }]
+ : undefined
+ }
+ >
+ <FormInput
+ placeholder={
+ sub.placeholder
+ ? t(sub.placeholder as 'channel.allowFromIdPlaceholder')
+ : t(sub.label)
+ }
+ />
+ </AntdForm.Item>
+ </div>
+ ))}
+ <Button
+ aria-label={removeLabel}
+ icon={<Trash2 size={14} />}
+ type="text"
+ onClick={() => remove(name)}
+ />
+ </Flexbox>
+ ))}
+ <Button
+ block
+ icon={<Plus size={14} />}
+ type="dashed"
+ onClick={() => add({ id: '', name: '' })}
+ >
+ {addLabel}
+ </Button>
+ </Flexbox>
+ )}
+ </AntdForm.List>
+ </FormItem>
+ );
+});
+
// --------------- ApplicationId field (standalone, not nested) ---------------
const ApplicationIdField = memo<{ field: FieldSchema }>(({ field }) => {
diff --git a/src/routes/(main)/agent/channel/detail/formState.test.ts b/src/routes/(main)/agent/channel/detail/formState.test.ts
index c9e7ce9a3f1..ff672a28ced 100644
--- a/src/routes/(main)/agent/channel/detail/formState.test.ts
+++ b/src/routes/(main)/agent/channel/detail/formState.test.ts
@@ -53,6 +53,47 @@ describe('getChannelFormValues', () => {
settings: {},
});
});
+
+ it('migrates a legacy comma-separated allowFrom string to object-list shape', () => {
+ // Operators on the very first cut of allowFrom stored a single string.
+ // The new editor is bound to an array — the form would crash on a string
+ // unless we lift it into `[{id}]` on read.
+ const result = getChannelFormValues({
+ settings: { allowFrom: 'alice, bob\n carol' },
+ });
+ expect(result.settings).toEqual({
+ allowFrom: [{ id: 'alice' }, { id: 'bob' }, { id: 'carol' }],
+ });
+ });
+
+ it('migrates a legacy bare string[] allowFrom into object-list shape', () => {
+ const result = getChannelFormValues({
+ settings: { groupAllowFrom: ['channel-1', ' channel-2 ', ''] },
+ });
+ expect(result.settings).toEqual({
+ groupAllowFrom: [{ id: 'channel-1' }, { id: 'channel-2' }],
+ });
+ });
+
+ it('passes through the new object-list shape unchanged (preserves names)', () => {
+ const result = getChannelFormValues({
+ settings: {
+ allowFrom: [{ id: 'alice', name: 'Alice — PM' }, { id: 'bob' }],
+ },
+ });
+ expect(result.settings).toEqual({
+ allowFrom: [{ id: 'alice', name: 'Alice — PM' }, { id: 'bob' }],
+ });
+ });
+
+ it('drops object entries with empty / missing ids during migration', () => {
+ const result = getChannelFormValues({
+ settings: {
+ allowFrom: [{ id: '' }, { id: ' ' }, { id: 'bob', name: 'Bob' }],
+ },
+ });
+ expect(result.settings).toEqual({ allowFrom: [{ id: 'bob', name: 'Bob' }] });
+ });
});
describe('extractSettingsDefaults', () => {
diff --git a/src/routes/(main)/agent/channel/detail/formState.ts b/src/routes/(main)/agent/channel/detail/formState.ts
index e4fb5b81bf7..648436dfdf4 100644
--- a/src/routes/(main)/agent/channel/detail/formState.ts
+++ b/src/routes/(main)/agent/channel/detail/formState.ts
@@ -10,9 +10,46 @@ interface ChannelFormSettings {
[key: string]: {} | undefined;
}
+/**
+ * Allowlist fields used to be stored as a comma-separated string and briefly
+ * as a bare `string[]`, before evolving into `[{ id, name? }]`. Migrate any
+ * pre-object-list payload up to the new shape on read so the array form
+ * editor can mount without crashing on a string. Still safe to write back —
+ * the runtime parser (`parseIdList`) keeps accepting all three shapes.
+ */
+const ALLOWLIST_KEYS = new Set(['allowFrom', 'groupAllowFrom']);
+
+const migrateAllowList = (value: unknown): Array<{ id: string; name?: string }> => {
+ if (typeof value === 'string') {
+ return value
+ .split(/[\s,]+/)
+ .map((id) => id.trim())
+ .filter(Boolean)
+ .map((id) => ({ id }));
+ }
+ if (Array.isArray(value)) {
+ return value
+ .map((entry) => {
+ if (typeof entry === 'string') return { id: entry.trim() };
+ if (entry && typeof entry === 'object' && 'id' in entry) {
+ const id = String((entry as { id?: unknown }).id ?? '').trim();
+ const rawName = (entry as { name?: unknown }).name;
+ const name = typeof rawName === 'string' ? rawName : undefined;
+ return name ? { id, name } : { id };
+ }
+ return { id: '' };
+ })
+ .filter((entry) => entry.id);
+ }
+ return [];
+};
+
const normalizeSettings = (settings?: Record<string, unknown> | null): ChannelFormSettings =>
Object.fromEntries(
- Object.entries(settings || {}).map(([key, value]) => [key, value ?? undefined]),
+ Object.entries(settings || {}).map(([key, value]) => [
+ key,
+ ALLOWLIST_KEYS.has(key) ? migrateAllowList(value) : (value ?? undefined),
+ ]),
);
export const getChannelFormValues = (config: ChannelConfigFormState) => ({
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.ts
index a479da5c30c..c58f1ff5f12 100644
--- a/src/server/services/bot/AgentBridgeService.ts
+++ b/src/server/services/bot/AgentBridgeService.ts
@@ -14,8 +14,9 @@ import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
import { SystemAgentService } from '@/server/services/systemAgent';
import { formatPrompt as formatPromptUtil } from './formatPrompt';
-import type { PlatformClient } from './platforms';
+import type { BotReplyLocale, PlatformClient } from './platforms';
import {
+ getBotReplyLocale,
getStepReactionEmoji,
platformRegistry,
RECEIVED_REACTION_EMOJI,
@@ -24,6 +25,7 @@ import {
import { clearReactionState, saveReactionState } from './reactionState';
import {
renderError,
+ renderErrorWithDetails,
renderFinalReply,
renderStart,
renderStepProgress,
@@ -100,6 +102,12 @@ interface BridgeHandlerOpts {
charLimit?: number;
client?: PlatformClient;
displayToolCalls?: boolean;
+ /**
+ * Locale for system-generated reply text (errors, stopped notice, etc.).
+ * Picked per platform — see `getBotReplyLocale`. When omitted we fall back
+ * to inferring from `botContext.platform`, then to English.
+ */
+ replyLocale?: BotReplyLocale;
}
/** Snapshot of the emoji currently applied to a given user message. */
@@ -313,11 +321,21 @@ export class AgentBridgeService {
error?: unknown;
operationId?: string;
progressMessage?: SentMessage;
+ replyLocale?: BotReplyLocale;
stopped?: boolean;
thread: Thread<ThreadState>;
userMessage: Message;
}): Promise<void> {
- const { client, error, operationId, progressMessage, stopped, thread, userMessage } = params;
+ const {
+ client,
+ error,
+ operationId,
+ progressMessage,
+ replyLocale,
+ stopped,
+ thread,
+ userMessage,
+ } = params;
const errorMessage =
error instanceof Error ? error.message : error ? String(error) : 'Agent execution failed';
@@ -331,7 +349,9 @@ export class AgentBridgeService {
AgentBridgeService.clearActiveThread(thread.id);
- const errorContent = stopped ? renderStopped(errorMessage) : renderError(operationId);
+ const errorContent = stopped
+ ? renderStopped(errorMessage, replyLocale)
+ : renderError(operationId, replyLocale);
if (progressMessage) {
try {
@@ -353,6 +373,15 @@ export class AgentBridgeService {
void userMessage;
}
+ /**
+ * Resolve the locale to use for system-generated reply text. Prefers the
+ * caller-provided value (passed in by BotMessageRouter), falls back to a
+ * platform-derived default so legacy callers still get the right copy.
+ */
+ private resolveReplyLocale(opts: BridgeHandlerOpts): BotReplyLocale {
+ return opts.replyLocale ?? getBotReplyLocale(opts.botContext?.platform);
+ }
+
/**
* Handle a new @mention — start a fresh conversation.
*/
@@ -362,6 +391,7 @@ export class AgentBridgeService {
opts: BridgeHandlerOpts,
): Promise<void> {
const { agentId, botContext, charLimit, displayToolCalls } = opts;
+ const replyLocale = this.resolveReplyLocale(opts);
log(
'handleMention: agentId=%s, user=%s, text=%s, attachments=%d',
@@ -419,6 +449,7 @@ export class AgentBridgeService {
charLimit,
client,
displayToolCalls,
+ replyLocale,
trigger: RequestTrigger.Bot,
});
queueHandoffSucceeded = queueMode;
@@ -432,7 +463,7 @@ export class AgentBridgeService {
} catch (error) {
log('handleMention error: %O', error);
try {
- await thread.post(renderError());
+ await thread.post(renderError(undefined, replyLocale));
} catch (postError) {
log('handleMention: failed to post error message: %O', postError);
}
@@ -456,6 +487,7 @@ export class AgentBridgeService {
opts: BridgeHandlerOpts,
): Promise<void> {
const { agentId, botContext, charLimit, displayToolCalls } = opts;
+ const replyLocale = this.resolveReplyLocale(opts);
const threadState = await thread.state;
const topicId = threadState?.topicId;
@@ -547,6 +579,7 @@ export class AgentBridgeService {
charLimit,
client: opts.client,
displayToolCalls,
+ replyLocale,
topicId,
trigger: RequestTrigger.Bot,
});
@@ -570,7 +603,7 @@ export class AgentBridgeService {
log('handleSubscribedMessage error: %O', error);
try {
- await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${errMsg}\n\`\`\``);
+ await thread.post(renderErrorWithDetails(errMsg, replyLocale));
} catch (postError) {
log('handleSubscribedMessage: failed to post error message: %O', postError);
}
@@ -600,23 +633,31 @@ export class AgentBridgeService {
charLimit?: number;
client?: PlatformClient;
displayToolCalls?: boolean;
+ replyLocale: BotReplyLocale;
topicId?: string;
trigger?: string;
},
): Promise<{ reply: string; topicId: string }> {
// Resolve bot platform context from platform registry
- let botPlatformContext:
+ const platformDef = opts.botContext?.platform
+ ? platformRegistry.getPlatform(opts.botContext.platform)
+ : undefined;
+ const botPlatformContext:
| { platformName: string; supportsMarkdown: boolean; warnings?: string[] }
- | undefined;
- if (opts.botContext?.platform) {
- const platformDef = platformRegistry.getPlatform(opts.botContext.platform);
- if (platformDef) {
- botPlatformContext = {
+ | undefined = platformDef
+ ? {
platformName: platformDef.name,
supportsMarkdown: platformDef.supportsMarkdown !== false,
- };
- }
- }
+ }
+ : undefined;
+ // Whether we can edit a previously-posted message in place. When false
+ // (QQ/WeChat today), the chat-adapter falls editMessage back to postMessage,
+ // so each step/completion edit surfaces as a NEW message — leaving the
+ // placeholder stranded and the final reply duplicated. We still post an ack
+ // so the user gets immediate feedback, but skip tracking it as
+ // `progressMessage` so downstream hooks post the final reply fresh instead
+ // of editing the placeholder.
+ const supportsMessageEdit = platformDef?.supportsMessageEdit !== false;
const {
agentId,
@@ -625,6 +666,7 @@ export class AgentBridgeService {
charLimit,
client,
displayToolCalls,
+ replyLocale,
topicId,
trigger,
} = opts;
@@ -675,10 +717,24 @@ export class AgentBridgeService {
log('executeWithWebhooks: gateway provider lookup failed: %O', err);
}
}
+ } else if (!supportsMessageEdit) {
+ // Edit-incapable platform (QQ today): the user still wants immediate
+ // feedback that we received their message, but every "edit" the
+ // adapter performs surfaces as a NEW message. So fire-and-forget the
+ // ack here without tracking it as `progressMessage` — afterStep/onComplete
+ // will see `progressMessage === undefined` and correctly post the final
+ // reply as its own message instead of editing.
+ await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
+ await safeSideEffect(
+ () => thread.post(renderStart(userMessage.text, { lng: replyLocale, timezone })),
+ 'post ack (no-edit platform)',
+ );
} else {
await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
try {
- progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
+ progressMessage = await thread.post(
+ renderStart(userMessage.text, { lng: replyLocale, timezone }),
+ );
} catch (error) {
log('executeWithWebhooks: failed to post initial placeholder message: %O', error);
}
@@ -728,6 +784,7 @@ export class AgentBridgeService {
files,
progressMessage,
prompt,
+ replyLocale,
topicId,
trigger,
webhookBody,
@@ -748,6 +805,7 @@ export class AgentBridgeService {
gatewayConnectionId,
progressMessage,
prompt,
+ replyLocale,
topicId,
trigger,
userMessage,
@@ -772,6 +830,7 @@ export class AgentBridgeService {
files?: any;
progressMessage?: SentMessage;
prompt: string;
+ replyLocale: BotReplyLocale;
topicId?: string;
trigger?: string;
webhookBody: Record<string, unknown>;
@@ -787,6 +846,7 @@ export class AgentBridgeService {
files,
progressMessage,
prompt,
+ replyLocale,
topicId,
trigger,
webhookBody,
@@ -854,6 +914,7 @@ export class AgentBridgeService {
client,
error,
progressMessage,
+ replyLocale,
stopped: isAbortError(error),
thread,
userMessage,
@@ -867,6 +928,7 @@ export class AgentBridgeService {
error: result.error,
operationId: result.operationId,
progressMessage,
+ replyLocale,
thread,
userMessage,
});
@@ -917,6 +979,7 @@ export class AgentBridgeService {
gatewayConnectionId?: string;
progressMessage?: SentMessage;
prompt: string;
+ replyLocale: BotReplyLocale;
topicId?: string;
trigger?: string;
userMessage?: Message;
@@ -935,6 +998,7 @@ export class AgentBridgeService {
files,
gatewayConnectionId,
prompt,
+ replyLocale,
topicId,
trigger,
userMessage,
@@ -988,24 +1052,27 @@ export class AgentBridgeService {
if (!event.shouldContinue || !progressMessage || displayToolCalls === false) return;
- const msgBody = renderStepProgress({
- content: event.content,
- elapsedMs: event.elapsedMs ?? getElapsedMs(),
- executionTimeMs: event.executionTimeMs ?? 0,
- lastContent: event.lastLLMContent,
- lastToolsCalling: event.lastToolsCalling,
- reasoning: event.reasoning,
- stepType: (event.stepType as 'call_llm' | 'call_tool') ?? 'call_llm',
- thinking: event.thinking ?? false,
- toolsCalling: event.toolsCalling,
- toolsResult: event.toolsResult,
- totalCost: event.totalCost ?? 0,
- totalInputTokens: event.totalInputTokens ?? 0,
- totalOutputTokens: event.totalOutputTokens ?? 0,
- totalSteps: event.totalSteps ?? 0,
- totalTokens: event.totalTokens ?? 0,
- totalToolCalls: event.totalToolCalls ?? 0,
- });
+ const msgBody = renderStepProgress(
+ {
+ content: event.content,
+ elapsedMs: event.elapsedMs ?? getElapsedMs(),
+ executionTimeMs: event.executionTimeMs ?? 0,
+ lastContent: event.lastLLMContent,
+ lastToolsCalling: event.lastToolsCalling,
+ reasoning: event.reasoning,
+ stepType: (event.stepType as 'call_llm' | 'call_tool') ?? 'call_llm',
+ thinking: event.thinking ?? false,
+ toolsCalling: event.toolsCalling,
+ toolsResult: event.toolsResult,
+ totalCost: event.totalCost ?? 0,
+ totalInputTokens: event.totalInputTokens ?? 0,
+ totalOutputTokens: event.totalOutputTokens ?? 0,
+ totalSteps: event.totalSteps ?? 0,
+ totalTokens: event.totalTokens ?? 0,
+ totalToolCalls: event.totalToolCalls ?? 0,
+ },
+ replyLocale,
+ );
const stats = {
elapsedMs: event.elapsedMs ?? getElapsedMs(),
@@ -1045,7 +1112,7 @@ export class AgentBridgeService {
errorMsg,
);
try {
- const errorText = renderError(event.operationId);
+ const errorText = renderError(event.operationId, replyLocale);
if (progressMessage) {
await progressMessage.edit(errorText);
} else {
@@ -1061,7 +1128,7 @@ export class AgentBridgeService {
if (reason === 'interrupted') {
if (progressMessage) {
try {
- await progressMessage.edit(renderStopped());
+ await progressMessage.edit(renderStopped(undefined, replyLocale));
} catch {
// ignore edit failure
}
@@ -1174,7 +1241,7 @@ export class AgentBridgeService {
if (progressMessage) {
try {
- await progressMessage.edit(renderError(result.operationId));
+ await progressMessage.edit(renderError(result.operationId, replyLocale));
} catch (error) {
log('executeWithCallback[local]: failed to edit startup error: %O', error);
}
@@ -1212,7 +1279,7 @@ export class AgentBridgeService {
if (isAbortError(error)) {
if (progressMessage) {
try {
- await progressMessage.edit(renderStopped(error.message));
+ await progressMessage.edit(renderStopped(error.message, replyLocale));
} catch (editError) {
log('executeWithCallback[local]: failed to edit stopped message: %O', editError);
}
@@ -1236,7 +1303,7 @@ export class AgentBridgeService {
if (progressMessage) {
try {
- await progressMessage.edit(renderError());
+ await progressMessage.edit(renderError(undefined, replyLocale));
} catch (editError) {
log('executeWithCallback[local]: failed to edit startup error: %O', editError);
}
diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.ts
index 8c63bf76a2c..7ea5f72bafa 100644
--- a/src/server/services/bot/BotCallbackService.ts
+++ b/src/server/services/bot/BotCallbackService.ts
@@ -9,8 +9,13 @@ import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewa
import { SystemAgentService } from '@/server/services/systemAgent';
import { AgentBridgeService } from './AgentBridgeService';
-import type { PlatformClient, PlatformMessenger, UsageStats } from './platforms';
-import { getStepReactionEmoji, platformRegistry, resolveBotProviderConfig } from './platforms';
+import type { BotReplyLocale, PlatformClient, PlatformMessenger, UsageStats } from './platforms';
+import {
+ getBotReplyLocale,
+ getStepReactionEmoji,
+ platformRegistry,
+ resolveBotProviderConfig,
+} from './platforms';
import { clearReactionState, getReactionState, saveReactionState } from './reactionState';
import {
renderError,
@@ -87,10 +92,11 @@ export class BotCallbackService {
const entry = platformRegistry.getPlatform(platform);
const canEdit = entry?.supportsMessageEdit !== false;
+ const replyLocale = getBotReplyLocale(platform);
if (type === 'step') {
if (canEdit && progressMessageId && settings.displayToolCalls !== false) {
- await this.handleStep(body, messenger, progressMessageId, client);
+ await this.handleStep(body, messenger, progressMessageId, client, replyLocale);
}
// Swap the user-message reaction to match the current step type (tool
// call vs. LLM reasoning). Runs regardless of `displayToolCalls` because
@@ -111,6 +117,7 @@ export class BotCallbackService {
messenger,
progressMessageId ?? '',
client,
+ replyLocale,
charLimit,
canEdit,
);
@@ -177,27 +184,31 @@ export class BotCallbackService {
messenger: PlatformMessenger,
progressMessageId: string,
client: PlatformClient,
+ replyLocale: BotReplyLocale,
): Promise<void> {
if (!body.shouldContinue) return;
- const msgBody = renderStepProgress({
- content: body.content,
- elapsedMs: body.elapsedMs,
- executionTimeMs: body.executionTimeMs ?? 0,
- lastContent: body.lastLLMContent,
- lastToolsCalling: body.lastToolsCalling,
- reasoning: body.reasoning,
- stepType: body.stepType ?? ('call_llm' as const),
- thinking: body.thinking ?? false,
- toolsCalling: body.toolsCalling,
- toolsResult: body.toolsResult,
- totalCost: body.totalCost ?? 0,
- totalInputTokens: body.totalInputTokens ?? 0,
- totalOutputTokens: body.totalOutputTokens ?? 0,
- totalSteps: body.totalSteps ?? 0,
- totalTokens: body.totalTokens ?? 0,
- totalToolCalls: body.totalToolCalls,
- });
+ const msgBody = renderStepProgress(
+ {
+ content: body.content,
+ elapsedMs: body.elapsedMs,
+ executionTimeMs: body.executionTimeMs ?? 0,
+ lastContent: body.lastLLMContent,
+ lastToolsCalling: body.lastToolsCalling,
+ reasoning: body.reasoning,
+ stepType: body.stepType ?? ('call_llm' as const),
+ thinking: body.thinking ?? false,
+ toolsCalling: body.toolsCalling,
+ toolsResult: body.toolsResult,
+ totalCost: body.totalCost ?? 0,
+ totalInputTokens: body.totalInputTokens ?? 0,
+ totalOutputTokens: body.totalOutputTokens ?? 0,
+ totalSteps: body.totalSteps ?? 0,
+ totalTokens: body.totalTokens ?? 0,
+ totalToolCalls: body.totalToolCalls,
+ },
+ replyLocale,
+ );
const stats: UsageStats = {
elapsedMs: body.elapsedMs,
@@ -226,6 +237,7 @@ export class BotCallbackService {
messenger: PlatformMessenger,
progressMessageId: string,
client: PlatformClient,
+ replyLocale: BotReplyLocale,
charLimit?: number,
canEdit = true,
): Promise<void> {
@@ -237,7 +249,7 @@ export class BotCallbackService {
operationId,
errorMessage,
);
- const errorText = renderError(operationId);
+ const errorText = renderError(operationId, replyLocale);
try {
if (canEdit && progressMessageId) {
await messenger.editMessage(progressMessageId, errorText);
@@ -251,7 +263,7 @@ export class BotCallbackService {
}
if (reason === 'interrupted') {
- const stoppedText = renderStopped(errorMessage || 'Execution stopped.');
+ const stoppedText = renderStopped(errorMessage, replyLocale);
try {
await messenger.createMessage(stoppedText);
} catch (error) {
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index c1d4ca85e4e..f9bfb7d878a 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -15,13 +15,32 @@ import { AiAgentService } from '@/server/services/aiAgent';
import { AgentBridgeService } from './AgentBridgeService';
import {
type BotPlatformRuntimeContext,
+ type BotReplyLocale,
buildRuntimeKey,
+ type DmSettings,
+ extractDmSettings,
+ extractGroupSettings,
+ extractUserAllowlist,
+ getBotReplyLocale,
+ type GroupSettings,
+ normalizeBotReplyLocale,
type PlatformClient,
type PlatformDefinition,
platformRegistry,
resolveBotProviderConfig,
+ shouldAllowSender,
+ shouldHandleDm,
+ shouldHandleGroup,
+ type UserAllowlist,
} from './platforms';
-import { renderError } from './replyTemplate';
+import {
+ renderCommandReply,
+ renderDmRejected,
+ renderError,
+ renderGroupRejected,
+ renderInlineError,
+ renderSenderRejected,
+} from './replyTemplate';
const log = debug('lobe-server:bot:message-router');
@@ -71,6 +90,11 @@ interface CommandContext {
/** Text after the command name (e.g. "/new foo" → "foo"). */
args: string;
post: (text: string) => Promise<any>;
+ /** Locale to use for any system-generated reply text. Plumbed in by the
+ * caller — text-based commands derive it per-message via the platform's
+ * `extractAuthorLocale`, native slash commands fall back to the platform
+ * default since their event shape doesn't always carry user locale. */
+ replyLocale: BotReplyLocale;
setState: (state: Record<string, any>, opts?: { replace?: boolean }) => Promise<any>;
threadId: string;
}
@@ -396,6 +420,147 @@ export class BotMessageRouter {
const bridge = new AgentBridgeService(serverDB, userId);
const charLimit = (info.settings?.charLimit as number) || undefined;
const displayToolCalls = info.settings?.displayToolCalls !== false;
+ const dmSettings: DmSettings = extractDmSettings(info.settings);
+ const groupSettings: GroupSettings = extractGroupSettings(info.settings);
+ const userAllowlist: UserAllowlist = extractUserAllowlist(info.settings);
+ const fallbackReplyLocale: BotReplyLocale = getBotReplyLocale(platform);
+
+ /**
+ * Resolve the reply locale for a single inbound event. Prefer the
+ * sender's platform-reported locale (e.g. Telegram's
+ * `from.language_code`) so a Brazilian Telegram user sees Portuguese,
+ * even though Telegram's channel-level default is English. Fall back to
+ * the platform default when the platform doesn't expose a locale or the
+ * value is empty.
+ */
+ const detectReplyLocale = (message: { author?: unknown }): BotReplyLocale => {
+ const detected = normalizeBotReplyLocale(client.extractAuthorLocale?.(message as any));
+ return detected ?? fallbackReplyLocale;
+ };
+
+ /**
+ * Global user-level gate. Applied **before** any per-scope policy so a
+ * populated `allowFrom` restricts every inbound surface (DMs, group
+ * @mentions, threads) to listed users. Empty list = no filter.
+ */
+ const passesGlobalAllowlist = (message: { author?: { userId?: string } }): boolean =>
+ shouldAllowSender({
+ authorUserId: message.author?.userId,
+ userAllowlist,
+ });
+
+ /**
+ * Gate inbound events on DM policy. Non-DM threads pass through — their
+ * group-policy / @mention rules apply instead. DM threads are blocked
+ * when disabled, and filtered against the global `allowFrom` user list
+ * when set to `allowlist`.
+ */
+ const passesDmPolicy = (
+ thread: { isDM?: boolean },
+ message: { author?: { userId?: string } },
+ ): boolean =>
+ shouldHandleDm({
+ authorUserId: message.author?.userId,
+ dmSettings,
+ isDM: thread.isDM === true,
+ userAllowlist,
+ });
+
+ /**
+ * Gate inbound events on group policy. DM threads pass through — they
+ * are governed by `passesDmPolicy` instead. Non-DM threads are blocked
+ * when disabled, and filtered against `groupAllowFrom` (channel / group
+ * / chat IDs) when set to `allowlist`.
+ *
+ * Operators paste **raw** platform IDs (what Discord's "Copy Channel
+ * ID" or Telegram's chat-id tools yield), but `thread.channelId` is a
+ * *composite* string carrying the platform prefix
+ * (`discord:guild:channel`, `telegram:chatId`, …). Using it directly
+ * never matches a raw paste. Each PlatformClient already exposes
+ * `extractChatId` returning the most-specific raw ID, so we use that
+ * as the primary candidate.
+ *
+ * Discord-only quirk: a bare `@mention` in a parent channel triggers
+ * an auto-reply thread; `extractChatId` then resolves to the thread,
+ * not the parent operators pasted. `extraGroupAllowlistChannels`
+ * surfaces the parent so either ID lets the message through.
+ */
+ const passesGroupPolicy = (thread: { id: string; isDM?: boolean }): boolean =>
+ shouldHandleGroup({
+ candidateChannelIds: [
+ client.extractChatId(thread.id),
+ ...(client.extraGroupAllowlistChannels?.(thread.id) ?? []),
+ ],
+ groupSettings,
+ isDM: thread.isDM === true,
+ });
+
+ /**
+ * Handle a sender that the global `allowFrom` rejected. Posts the
+ * notice in the same thread the inbound event arrived on, mirroring
+ * `notifyGroupRejected` / `notifyDmRejected` rather than escalating
+ * to ephemeral / out-of-band DM.
+ *
+ * - DM scope: uses the DM-allowlist copy ("you aren't authorized to
+ * send direct messages…") since the sender is on the DM surface.
+ * - Group scope: uses the generic `senderRejected` copy that avoids
+ * "direct messages" — the sender @-mentioned in a group, not in a
+ * DM. On Discord this lands inside the auto-created reply thread,
+ * so it doesn't pollute the parent channel; on Telegram / Slack /
+ * Feishu it's visible to the group, which is consistent with how
+ * `notifyGroupRejected` already handles policy-driven rejections.
+ */
+ const handleSenderRejected = async (
+ thread: { isDM?: boolean; post: (text: string) => Promise<unknown> },
+ replyLocale: BotReplyLocale,
+ ): Promise<void> => {
+ const text =
+ thread.isDM === true
+ ? renderDmRejected('allowlist', replyLocale)
+ : renderSenderRejected(replyLocale);
+ try {
+ await thread.post(text);
+ } catch (error) {
+ log('handleSenderRejected: failed to post rejection notice: %O', error);
+ }
+ };
+
+ /**
+ * Post a one-line system reply telling the sender why their DM was
+ * dropped. Best-effort — a transient platform error must never bubble
+ * back into the handler since the message is informational, not part of
+ * the agent flow.
+ */
+ const notifyDmRejected = async (
+ thread: { post: (text: string) => Promise<unknown> },
+ replyLocale: BotReplyLocale,
+ ): Promise<void> => {
+ // 'open' should never reach here, but guard anyway so we never post the
+ // wrong copy if shouldHandleDm grows another false branch.
+ if (dmSettings.policy === 'open') return;
+ try {
+ await thread.post(renderDmRejected(dmSettings.policy, replyLocale));
+ } catch (error) {
+ log('notifyDmRejected: failed to post rejection notice: %O', error);
+ }
+ };
+
+ /**
+ * Same shape as `notifyDmRejected`, for group / channel rejection. The
+ * @mention is public, so the rejection is too — operators get UX
+ * feedback that their bot is configured to a smaller scope.
+ */
+ const notifyGroupRejected = async (
+ thread: { post: (text: string) => Promise<unknown> },
+ replyLocale: BotReplyLocale,
+ ): Promise<void> => {
+ if (groupSettings.policy === 'open') return;
+ try {
+ await thread.post(renderGroupRejected(groupSettings.policy, replyLocale));
+ } catch (error) {
+ log('notifyGroupRejected: failed to post rejection notice: %O', error);
+ }
+ };
/** Try dispatching a text command. Returns true if handled.
* Strips platform mention artifacts (e.g. Slack's `<@U123>`) before
@@ -407,6 +572,7 @@ export class BotMessageRouter {
setState: (s: Record<string, any>, o?: { replace?: boolean }) => Promise<any>;
},
text: string | undefined,
+ replyLocale: BotReplyLocale,
): Promise<boolean> => {
const sanitized = client.sanitizeUserInput?.(text ?? '') ?? text;
const result = BotMessageRouter.dispatchTextCommand(sanitized, commands);
@@ -414,14 +580,88 @@ export class BotMessageRouter {
await result.command.handler({
args: result.args,
post: (t) => thread.post(t),
+ replyLocale,
setState: (s, o) => thread.setState(s, o),
threadId: thread.id,
});
return true;
};
+ /** Returns true when the inbound passes the standard caller-test
+ * text. Used to short-circuit gate checks for non-command messages in
+ * subscribed group threads that aren't addressed to the bot. */
+ const looksLikeCommand = (text: string | undefined): boolean => {
+ const sanitized = client.sanitizeUserInput?.(text ?? '') ?? text;
+ return BotMessageRouter.dispatchTextCommand(sanitized, commands) !== null;
+ };
+
+ /**
+ * Run all three access gates (global `allowFrom`, group policy, DM policy)
+ * and post the appropriate rejection notice in the thread on failure.
+ * Returns true when the inbound passes every gate.
+ *
+ * Centralised so every entry point — @-mentions, subscribed-message
+ * handler, DM catch-all, **and the slash-command dispatchers** — applies
+ * the same checks. Without this, a /command path could side-effect
+ * (`/stop` cancelling a run, `/new` resetting state) for senders the
+ * normal message path would have rejected.
+ */
+ const passGatesOrNotify = async (
+ thread: { id: string; isDM?: boolean; post: (t: string) => Promise<unknown> },
+ author: { userId?: string; userName?: string },
+ replyLocale: BotReplyLocale,
+ caller: string,
+ ): Promise<boolean> => {
+ if (!passesGlobalAllowlist({ author })) {
+ log(
+ '%s: sender blocked by allowFrom, agent=%s, platform=%s, thread=%s, author=%s',
+ caller,
+ agentId,
+ platform,
+ thread.id,
+ author.userName ?? author.userId,
+ );
+ await handleSenderRejected(thread, replyLocale);
+ return false;
+ }
+ if (!passesGroupPolicy(thread)) {
+ log(
+ '%s: group blocked by policy, agent=%s, platform=%s, thread=%s, policy=%s',
+ caller,
+ agentId,
+ platform,
+ thread.id,
+ groupSettings.policy,
+ );
+ await notifyGroupRejected(thread, replyLocale);
+ return false;
+ }
+ if (!passesDmPolicy(thread, { author })) {
+ log(
+ '%s: DM blocked by policy, agent=%s, platform=%s, thread=%s, author=%s, policy=%s',
+ caller,
+ agentId,
+ platform,
+ thread.id,
+ author.userName ?? author.userId,
+ dmSettings.policy,
+ );
+ await notifyDmRejected(thread, replyLocale);
+ return false;
+ }
+ return true;
+ };
+
bot.onNewMention(async (thread, message, context?: MessageContext) => {
- if (await tryDispatch(thread, message.text)) return;
+ const replyLocale = detectReplyLocale(message);
+
+ // Gate first — must run before tryDispatch so a /command from a
+ // non-allowlisted sender can't slip through and side-effect.
+ if (!(await passGatesOrNotify(thread, message.author, replyLocale, 'onNewMention'))) {
+ return;
+ }
+
+ if (await tryDispatch(thread, message.text, replyLocale)) return;
log(
'onNewMention raw: agent=%s, platform=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
@@ -480,11 +720,12 @@ export class BotMessageRouter {
charLimit,
client,
displayToolCalls,
+ replyLocale,
});
} catch (error) {
log('onNewMention: unhandled error from handleMention: %O', error);
try {
- await thread.post(renderError());
+ await thread.post(renderError(undefined, replyLocale));
} catch {
// best-effort notification
}
@@ -493,7 +734,7 @@ export class BotMessageRouter {
bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {
if (message.author.isBot === true) return;
- if (await tryDispatch(thread, message.text)) return;
+ const replyLocale = detectReplyLocale(message);
// Group / channel / thread policy: only respond when the bot is @-mentioned.
// DMs are 1:1 conversations, so every message is implicitly addressed to the bot.
@@ -501,12 +742,17 @@ export class BotMessageRouter {
// thread — including messages between other users — and hijack the conversation.
// Skipped (debounced) messages are also inspected so a mention queued behind a
// non-mention still triggers a reply.
+ //
+ // Commands are exempt from the @-mention requirement (Telegram/Feishu users
+ // type `/new` directly without mentioning the bot), but they are NOT exempt
+ // from the access gates below.
const isAddressedToBot =
thread.isDM ||
message.isMention === true ||
context?.skipped?.some((m) => m.isMention === true) === true;
+ const isCommand = looksLikeCommand(message.text);
- if (!isAddressedToBot) {
+ if (!isAddressedToBot && !isCommand) {
log(
'onSubscribedMessage: skip non-mention in group thread, agent=%s, platform=%s, author=%s, thread=%s',
agentId,
@@ -517,6 +763,14 @@ export class BotMessageRouter {
return;
}
+ // Gate before tryDispatch so a /command from a non-allowlisted sender
+ // (or in a disabled DM/group scope) cannot side-effect.
+ if (!(await passGatesOrNotify(thread, message.author, replyLocale, 'onSubscribedMessage'))) {
+ return;
+ }
+
+ if (await tryDispatch(thread, message.text, replyLocale)) return;
+
log(
'onSubscribedMessage raw: agent=%s, platform=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
agentId,
@@ -575,29 +829,66 @@ export class BotMessageRouter {
charLimit,
client,
displayToolCalls,
+ replyLocale,
});
} catch (error) {
log('onSubscribedMessage: unhandled error from handleSubscribedMessage: %O', error);
try {
- await thread.post(renderError());
+ await thread.post(renderError(undefined, replyLocale));
} catch {
// best-effort notification
}
}
});
- // Register slash command handlers (native + text-based)
- this.registerCommands(bot, commands, client);
+ // Register slash command handlers (native + text-based). The gate
+ // helper is passed in so command paths share the access checks with
+ // the message handlers — without this, a non-allowlisted sender could
+ // /stop or /new and bypass the rest of the policy stack.
+ this.registerCommands(
+ bot,
+ commands,
+ client,
+ {
+ detectFromMessage: detectReplyLocale,
+ fallback: fallbackReplyLocale,
+ },
+ passGatesOrNotify,
+ );
- // Register onNewMessage handler based on platform config
- const dmEnabled = info.settings?.dm?.enabled ?? false;
- if (dmEnabled) {
+ // DM catch-all: only registered when DM handling is enabled. For mixed
+ // platforms (e.g. Slack/Discord with both DMs and group channels), the
+ // handler itself restricts routing to DM threads that satisfy the policy —
+ // otherwise the `/./` regex would match every group message and hijack
+ // non-mention traffic. Group @-mentions keep going through `onNewMention`.
+ if (dmSettings.policy !== 'disabled') {
bot.onNewMessage(/./, async (thread, message, context?: MessageContext) => {
if (message.author.isBot === true) return;
// Skip text-based slash commands — already handled by registerCommands
+ // (which applies the same gates).
if (BotMessageRouter.dispatchTextCommand(message.text, commands)) return;
+ // The catch-all exists solely to handle DMs on mention-less platforms
+ // (Telegram, WeChat, …) and on mixed platforms where the DM flow should
+ // not require an @-mention. Group / channel traffic is already handled
+ // by onNewMention + onSubscribedMessage; if we let it through here we
+ // would hijack every non-mention message in shared threads.
+ if (thread.isDM !== true) return;
+
+ const replyLocale = detectReplyLocale(message);
+
+ if (
+ !(await passGatesOrNotify(
+ thread,
+ message.author,
+ replyLocale,
+ `onNewMessage (${platform} catch-all)`,
+ ))
+ ) {
+ return;
+ }
+
log(
'onNewMessage raw (%s catch-all): agent=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
platform,
@@ -656,12 +947,13 @@ export class BotMessageRouter {
charLimit,
client,
displayToolCalls,
+ replyLocale,
});
} catch (error) {
log('onNewMessage: unhandled error from handleMention: %O', error);
try {
const errMsg = error instanceof Error ? error.message : String(error);
- await thread.post(`**Error**: ${errMsg}`);
+ await thread.post(renderInlineError(errMsg, replyLocale));
} catch {
// best-effort notification
}
@@ -693,7 +985,7 @@ export class BotMessageRouter {
handler: async (ctx) => {
log('command /new: agent=%s, platform=%s', agentId, platform);
await ctx.setState({ topicId: undefined }, { replace: true });
- await ctx.post('Conversation reset. Your next message will start a new topic.');
+ await ctx.post(renderCommandReply('cmdNewReset', ctx.replyLocale));
},
name: 'new',
},
@@ -703,7 +995,7 @@ export class BotMessageRouter {
log('command /stop: agent=%s, platform=%s', agentId, platform);
const isActive = AgentBridgeService.isThreadActive(ctx.threadId);
if (!isActive) {
- await ctx.post('No active execution to stop.');
+ await ctx.post(renderCommandReply('cmdStopNotActive', ctx.replyLocale));
return;
}
const operationId = AgentBridgeService.getActiveOperationId(ctx.threadId);
@@ -713,21 +1005,21 @@ export class BotMessageRouter {
const result = await aiAgentService.interruptTask({ operationId });
if (!result.success) {
log('command /stop: runtime interrupt rejected for operationId=%s', operationId);
- await ctx.post('Unable to stop the current execution.');
+ await ctx.post(renderCommandReply('cmdStopUnable', ctx.replyLocale));
return;
}
AgentBridgeService.clearActiveThread(ctx.threadId);
log('command /stop: interrupted operationId=%s', operationId);
} catch (error) {
log('command /stop: interruptTask failed: %O', error);
- await ctx.post('Unable to stop the current execution.');
+ await ctx.post(renderCommandReply('cmdStopUnable', ctx.replyLocale));
return;
}
} else {
AgentBridgeService.requestStop(ctx.threadId);
log('command /stop: queued deferred stop for thread=%s', ctx.threadId);
}
- await ctx.post('Stop requested.');
+ await ctx.post(renderCommandReply('cmdStopRequested', ctx.replyLocale));
},
name: 'stop',
},
@@ -759,13 +1051,54 @@ export class BotMessageRouter {
* To add a new command, add an entry to `buildCommands()` — it will be
* automatically registered on all platforms.
*/
- private registerCommands(bot: Chat<any>, commands: BotCommand[], client: PlatformClient): void {
+ private registerCommands(
+ bot: Chat<any>,
+ commands: BotCommand[],
+ client: PlatformClient,
+ locale: {
+ detectFromMessage: (message: { author?: unknown }) => BotReplyLocale;
+ fallback: BotReplyLocale;
+ },
+ /**
+ * Apply the same access stack the message handlers use (allowFrom +
+ * group policy + DM policy) before dispatching a command. Returns true
+ * when the dispatch is allowed; on rejection the helper has already
+ * posted the appropriate notice in the thread.
+ */
+ gate: (
+ thread: { id: string; isDM?: boolean; post: (t: string) => Promise<unknown> },
+ author: { userId?: string; userName?: string },
+ replyLocale: BotReplyLocale,
+ caller: string,
+ ) => Promise<boolean>,
+ ): void {
// --- Native slash commands (Slack, Discord) ---
for (const cmd of commands) {
bot.onSlashCommand(`/${cmd.name}`, async (event) => {
+ // Native slash-command events expose a Channel (Postable, so it has
+ // `id` / `isDM` / `post`) and the invoking user. Project both into
+ // the gate-friendly thread/author shape.
+ const threadLike = {
+ id: event.channel.id,
+ isDM: event.channel.isDM,
+ post: (t: string) => event.channel.post(t),
+ };
+ const authorLike = {
+ userId: event.user?.userId,
+ userName: event.user?.userName,
+ };
+ const replyLocale = locale.fallback;
+ if (!(await gate(threadLike, authorLike, replyLocale, `onSlashCommand /${cmd.name}`))) {
+ return;
+ }
await cmd.handler({
args: event.text,
post: (text) => event.channel.post(text),
+ // Native slash-command events don't carry a Chat SDK Message, so
+ // there's no per-sender locale field to read; use the channel
+ // default. Telegram/Feishu/etc. dispatch via the text-based path
+ // below, which DOES have per-message locale.
+ replyLocale,
setState: (state, opts) => event.channel.setState(state, opts),
threadId: event.channel.id,
});
@@ -785,9 +1118,16 @@ export class BotMessageRouter {
const sanitized = client.sanitizeUserInput?.(message.text ?? '') ?? message.text;
const result = BotMessageRouter.dispatchTextCommand(sanitized, commands);
if (!result) return;
+ const replyLocale = locale.detectFromMessage(message);
+ if (
+ !(await gate(thread, message.author, replyLocale, `onNewMessage /${result.command.name}`))
+ ) {
+ return;
+ }
await result.command.handler({
args: result.args,
post: (text) => thread.post(text),
+ replyLocale,
setState: (state, opts) => thread.setState(state, opts),
threadId: thread.id,
});
diff --git a/src/server/services/bot/__tests__/AgentBridgeService.test.ts b/src/server/services/bot/__tests__/AgentBridgeService.test.ts
index 934ce282aca..548c99513a1 100644
--- a/src/server/services/bot/__tests__/AgentBridgeService.test.ts
+++ b/src/server/services/bot/__tests__/AgentBridgeService.test.ts
@@ -181,6 +181,78 @@ describe('AgentBridgeService', () => {
);
});
+ describe('progress message gating by supportsMessageEdit', () => {
+ // Regression test for the QQ duplicate-reply bug:
+ // QQ doesn't support message edits — the chat-adapter falls `editMessage`
+ // back to `postMessage`. So if we posted an "ack" placeholder and then
+ // tried to edit it on afterStep + onComplete, the user saw the placeholder
+ // PLUS two duplicate copies of the final reply. Edit-incapable platforms
+ // must skip the placeholder entirely so the final reply lands once.
+
+ beforeEach(() => {
+ // Happy-path startup so we only count the placeholder post, not error fallbacks.
+ mockExecAgent.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-1',
+ createdAt: new Date().toISOString(),
+ operationId: 'op-1',
+ success: true,
+ topicId: 'topic-1',
+ });
+ });
+
+ /** Pull the `progressMessageId` the bridge handed to execAgent's webhook hooks. */
+ const progressMessageIdFromHooks = (): unknown => {
+ const call = mockExecAgent.mock.calls.at(-1);
+ const hooks = call?.[0]?.hooks as
+ | Array<{ id?: string; webhook?: { body?: Record<string, unknown> } }>
+ | undefined;
+ return hooks?.find((h) => h.id === 'bot-completion')?.webhook?.body?.progressMessageId;
+ };
+
+ it('posts the ack for an edit-incapable platform but does not track it as progressMessage', async () => {
+ mockGetPlatform.mockReturnValue({
+ id: 'qq',
+ name: 'QQ',
+ supportsMessageEdit: false,
+ });
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread();
+ const message = createMessage();
+ const client = createClient();
+
+ await service.handleMention(thread, message, {
+ agentId: 'agent-1',
+ botContext: { platform: 'qq', platformThreadId: 'qq:c2c:user-1' } as any,
+ client,
+ });
+
+ // User still gets immediate feedback ("处理中…").
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ // But the ack is NOT tracked as `progressMessage`, so the downstream
+ // hooks won't try to edit it (which would surface as a duplicate message
+ // on edit-incapable platforms).
+ expect(progressMessageIdFromHooks()).toBeUndefined();
+ });
+
+ it('posts the ack AND tracks it as progressMessage when the platform supports edit', async () => {
+ // Default mock returns supportsMessageEdit: true (Discord).
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread();
+ const message = createMessage();
+ const client = createClient();
+
+ await service.handleMention(thread, message, {
+ agentId: 'agent-1',
+ botContext: { platform: 'discord', platformThreadId: THREAD_ID } as any,
+ client,
+ });
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ // Tracked → downstream hooks will edit this message in place.
+ expect(progressMessageIdFromHooks()).toBe('progress-msg-1');
+ });
+ });
+
describe('activeThreads cleanup on side-effect failure', () => {
// Regression test for the "already has an active execution" lockup:
// a transient network error from `thread.startTyping()` (or any other
diff --git a/src/server/services/bot/__tests__/BotMessageRouter.test.ts b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
index d21774fcd80..8e45d2afeae 100644
--- a/src/server/services/bot/__tests__/BotMessageRouter.test.ts
+++ b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
@@ -108,7 +108,20 @@ const mockGetPlatform = vi.hoisted(() =>
createClient: vi.fn().mockReturnValue({
applicationId: 'mock-app',
createAdapter: mockCreateAdapter,
- extractChatId: (id: string) => id.split(':')[1],
+ extractAuthorLocale: (msg: any) => msg?.raw?.from?.language_code,
+ // Match the per-platform contract: return the most-specific raw
+ // ID (last segment of the composite). Telegram `telegram:chat-1`
+ // → `chat-1`; Discord `discord:guild:channel:thread` → `thread`.
+ extractChatId: (id: string) => id.split(':').at(-1) ?? '',
+ // Mirrors Discord's `extraGroupAllowlistChannels`: when the
+ // platformThreadId has a thread segment, surface the parent
+ // channel as an extra allowlist candidate. Two-segment IDs
+ // (Telegram-style `telegram:chat-1`) return [], leaving
+ // existing tests unaffected.
+ extraGroupAllowlistChannels: (threadId: string) => {
+ const parts = threadId.split(':');
+ return parts.length === 4 && parts[2] ? [parts[2]] : [];
+ },
getMessenger: () => ({
createMessage: vi.fn(),
editMessage: vi.fn(),
@@ -128,13 +141,114 @@ const mockGetPlatform = vi.hoisted(() =>
}),
);
+// Mirrors the real `parseIdList` in ../platforms/const.ts: accepts the new
+// `[{ id, name? }]` shape plus the legacy string / string[] shapes that
+// existing data on disk may still be in.
+const parseAllowlistMock = vi.hoisted(() => (raw: unknown): string[] => {
+ if (typeof raw === 'string') {
+ return raw
+ .split(/[\s,]+/)
+ .map((id) => id.trim())
+ .filter(Boolean);
+ }
+ if (Array.isArray(raw)) {
+ return raw
+ .map((entry) => {
+ if (typeof entry === 'string') return entry.trim();
+ if (entry && typeof entry === 'object' && 'id' in entry) {
+ const id = (entry as { id?: unknown }).id;
+ return typeof id === 'string' ? id.trim() : '';
+ }
+ return '';
+ })
+ .filter(Boolean);
+ }
+ return [];
+});
+
vi.mock('../platforms', () => ({
buildRuntimeKey: (platform: string, appId: string) => `${platform}:${appId}`,
+ getBotReplyLocale: (platform: string | undefined): string => {
+ if (platform === 'feishu' || platform === 'qq' || platform === 'wechat') return 'zh-CN';
+ return 'en-US';
+ },
+ normalizeBotReplyLocale: (raw: string | undefined | null): string | undefined => {
+ if (!raw) return undefined;
+ const parts = raw.replaceAll('_', '-').split('-');
+ const formatted =
+ parts.length === 1
+ ? parts[0].toLowerCase()
+ : `${parts[0].toLowerCase()}-${parts[1].toUpperCase()}`;
+ // Keep this in sync with the project `normalizeLocale` for the cases we test:
+ // - exact match returns as-is
+ // - 'zh-CN' / 'pt-BR' / 'en-US' are project locales
+ // - unknown → 'en-US'
+ const known = new Set(['en-US', 'zh-CN', 'zh-TW', 'pt-BR', 'ja-JP', 'ko-KR', 'fr-FR']);
+ if (known.has(formatted)) return formatted;
+ return 'en-US';
+ },
+ extractDmSettings: (settings: Record<string, unknown> | null | undefined) => {
+ const rawPolicy = settings?.dmPolicy as string | undefined;
+ const policy =
+ rawPolicy === 'allowlist' || rawPolicy === 'open' || rawPolicy === 'disabled'
+ ? rawPolicy
+ : 'open';
+ return { policy };
+ },
+ extractGroupSettings: (settings: Record<string, unknown> | null | undefined) => {
+ const allowFrom = parseAllowlistMock(settings?.groupAllowFrom);
+ const rawPolicy = settings?.groupPolicy as string | undefined;
+ const policy =
+ rawPolicy === 'allowlist' || rawPolicy === 'open' || rawPolicy === 'disabled'
+ ? rawPolicy
+ : 'open';
+ return { allowFrom, policy };
+ },
+ extractUserAllowlist: (settings: Record<string, unknown> | null | undefined) => {
+ const explicit = parseAllowlistMock(settings?.allowFrom);
+ if (explicit.length === 0) return { ids: [] };
+ const operatorId = (settings?.userId as string | undefined)?.trim();
+ if (!operatorId || explicit.includes(operatorId)) return { ids: explicit };
+ return { ids: [...explicit, operatorId] };
+ },
mergeWithDefaults: mockMergeWithDefaults,
platformRegistry: {
getPlatform: mockGetPlatform,
},
resolveBotProviderConfig: mockResolveBotProviderConfig,
+ shouldAllowSender: (params: {
+ authorUserId: string | undefined;
+ userAllowlist: { ids: string[] };
+ }) => {
+ if (params.userAllowlist.ids.length === 0) return true;
+ if (!params.authorUserId) return false;
+ return params.userAllowlist.ids.includes(params.authorUserId);
+ },
+ shouldHandleDm: (params: {
+ authorUserId: string | undefined;
+ dmSettings: { policy: 'allowlist' | 'disabled' | 'open' };
+ isDM: boolean;
+ userAllowlist: { ids: string[] };
+ }) => {
+ if (!params.isDM) return true;
+ if (params.dmSettings.policy === 'disabled') return false;
+ if (params.dmSettings.policy === 'open') return true;
+ if (!params.authorUserId) return false;
+ if (params.userAllowlist.ids.length === 0) return false;
+ return params.userAllowlist.ids.includes(params.authorUserId);
+ },
+ shouldHandleGroup: (params: {
+ candidateChannelIds: ReadonlyArray<string | undefined>;
+ groupSettings: { allowFrom: string[]; policy: 'allowlist' | 'disabled' | 'open' };
+ isDM: boolean;
+ }) => {
+ if (params.isDM) return true;
+ if (params.groupSettings.policy === 'disabled') return false;
+ if (params.groupSettings.policy === 'open') return true;
+ const ids = params.candidateChannelIds.filter((id): id is string => Boolean(id));
+ if (ids.length === 0) return false;
+ return ids.some((id) => params.groupSettings.allowFrom.includes(id));
+ },
}));
// ==================== Helpers ====================
@@ -270,11 +384,11 @@ describe('BotMessageRouter', () => {
expect(mockOnSubscribedMessage).toHaveBeenCalled();
});
- it('should register onNewMessage when dm.enabled is true', async () => {
+ it('should register onNewMessage when DM policy is not disabled', async () => {
mockFindEnabledByPlatform.mockResolvedValue([
makeProvider({
applicationId: 'tg-123',
- settings: { dm: { enabled: true } },
+ settings: { dmPolicy: 'open' },
}),
]);
@@ -288,8 +402,13 @@ describe('BotMessageRouter', () => {
expect(mockOnNewMessage).toHaveBeenCalledTimes(2);
});
- it('should NOT register DM onNewMessage when dm is not enabled', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'app-123' })]);
+ it('should NOT register DM onNewMessage when DM policy is disabled', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-123',
+ settings: { dmPolicy: 'disabled' },
+ }),
+ ]);
const router = new BotMessageRouter();
const handler = router.getWebhookHandler('telegram', 'app-123');
@@ -308,8 +427,13 @@ describe('BotMessageRouter', () => {
* `onSubscribedMessage` handler that was registered with the Chat SDK
* so tests can invoke it directly with synthetic thread/message objects.
*/
- async function loadSubscribedHandler() {
- mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'app-1' })]);
+ async function loadSubscribedHandler(settings?: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ settings: settings ?? { dmPolicy: 'open' },
+ }),
+ ]);
const router = new BotMessageRouter();
const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
@@ -330,12 +454,15 @@ describe('BotMessageRouter', () => {
};
}
- function makeMessage(overrides: Partial<{ isMention: boolean; text: string }> = {}) {
+ function makeMessage(
+ overrides: Partial<{ isMention: boolean; text: string; userId: string }> = {},
+ ) {
+ const { userId = 'alice-id', ...rest } = overrides;
return {
- author: { isBot: false, userName: 'alice' },
+ author: { isBot: false, userId, userName: 'alice' },
isMention: false,
text: 'hello there',
- ...overrides,
+ ...rest,
};
}
@@ -387,14 +514,985 @@ describe('BotMessageRouter', () => {
const handler = await loadSubscribedHandler();
const thread = makeThread({ isDM: false });
const message = {
- author: { isBot: true, userName: 'other-bot' },
+ author: { isBot: true, userId: 'other-bot-id', userName: 'other-bot' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+
+ it('should block DM follow-ups when DM is disabled and notify the sender', async () => {
+ const handler = await loadSubscribedHandler({ dmPolicy: 'disabled' });
+ const thread = makeThread({ isDM: true });
+ const message = makeMessage({ isMention: false, text: 'hi' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
+ });
+
+ it('should block DM follow-ups for users outside the allowlist and notify the sender', async () => {
+ const handler = await loadSubscribedHandler({
+ allowFrom: 'bob-id, carol-id',
+ dmPolicy: 'allowlist',
+ });
+ const thread = makeThread({ isDM: true });
+ const message = makeMessage({ isMention: false, text: 'hi', userId: 'alice-id' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+
+ it('should pass DM follow-ups for users on the allowlist', async () => {
+ const handler = await loadSubscribedHandler({
+ allowFrom: 'alice-id, bob-id',
+ dmPolicy: 'allowlist',
+ });
+ const thread = makeThread({ isDM: true });
+ const message = makeMessage({ isMention: false, text: 'hi', userId: 'alice-id' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not affect group @-mentions when DM is disabled', async () => {
+ const handler = await loadSubscribedHandler({ dmPolicy: 'disabled' });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: true, text: '@bot hi' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('onNewMention DM policy', () => {
+ async function loadMentionHandler(settings?: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ settings: settings ?? { dmPolicy: 'open' },
+ }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnNewMention.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onNewMention was not registered');
+ return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ it('should allow group @-mentions regardless of DM policy', async () => {
+ const handler = await loadMentionHandler({ dmPolicy: 'disabled' });
+ const thread = {
+ id: 'telegram:group-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('should block @-mentions inside DMs when DM is disabled and notify the sender', async () => {
+ const handler = await loadMentionHandler({ dmPolicy: 'disabled' });
+ const thread = {
+ id: 'discord:@me:channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
+ });
+
+ it('should block DM @-mentions from users outside the allowlist and notify the sender', async () => {
+ const handler = await loadMentionHandler({
+ allowFrom: 'bob-id',
+ dmPolicy: 'allowlist',
+ });
+ const thread = {
+ id: 'discord:@me:channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+ });
+
+ describe('onNewMessage DM catch-all', () => {
+ async function loadDmCatchAllHandler(settings?: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ settings: settings ?? { dmPolicy: 'open' },
+ }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ // The catch-all is the onNewMessage registration with the /./ pattern.
+ // The first onNewMessage registration is for text-based slash commands
+ // with a specific command regex.
+ const catchAllCall = mockOnNewMessage.mock.calls.find((call) => {
+ const pattern = call[0];
+ return pattern instanceof RegExp && pattern.source === '.';
+ });
+ if (!catchAllCall) return null;
+ return catchAllCall[1] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ it('should not register the DM catch-all when DM is disabled', async () => {
+ const handler = await loadDmCatchAllHandler({ dmPolicy: 'disabled' });
+ expect(handler).toBeNull();
+ });
+
+ it('should register the DM catch-all when DM is enabled', async () => {
+ const handler = await loadDmCatchAllHandler({ dmPolicy: 'open' });
+ expect(handler).not.toBeNull();
+ });
+
+ it('should ignore non-DM threads in the catch-all', async () => {
+ const handler = await loadDmCatchAllHandler();
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:group-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'hello from a group',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('should handle DM messages through the catch-all', async () => {
+ const handler = await loadDmCatchAllHandler();
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'hi in a DM',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('should block DM messages blocked by the allowlist and notify the sender', async () => {
+ const handler = await loadDmCatchAllHandler({
+ allowFrom: 'bob-id',
+ dmPolicy: 'allowlist',
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'hi in a DM',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+ });
+
+ describe('group policy', () => {
+ /**
+ * Returns the registered onSubscribedMessage and onNewMention handlers so
+ * group-policy assertions can drive each entry point with the same
+ * fixture.
+ */
+ async function loadHandlers(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const sub = mockOnSubscribedMessage.mock.calls.at(-1);
+ const mention = mockOnNewMention.mock.calls.at(-1);
+ if (!sub || !mention) throw new Error('handlers not registered');
+ return {
+ mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ };
+ }
+
+ function makeGroupThread(channelId: string) {
+ return {
+ channelId,
+ id: `telegram:${channelId}`,
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ }
+
+ function makeMentionMessage() {
+ return {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+ }
+
+ it('blocks @-mentions in groups when group policy is disabled and notifies the sender', async () => {
+ const { subscribed } = await loadHandlers({ groupPolicy: 'disabled' });
+ const thread = makeGroupThread('channel-1');
+
+ await subscribed(thread, makeMentionMessage());
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("doesn't respond in groups or channels");
+ });
+
+ it('blocks @-mentions on the new-mention path when group policy is disabled', async () => {
+ const { mention } = await loadHandlers({ groupPolicy: 'disabled' });
+ const thread = makeGroupThread('channel-1');
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("doesn't respond in groups or channels");
+ });
+
+ it('allows @-mentions in channels listed in groupAllowFrom', async () => {
+ const { subscribed } = await loadHandlers({
+ groupAllowFrom: 'channel-1, channel-2',
+ groupPolicy: 'allowlist',
+ });
+ const thread = makeGroupThread('channel-1');
+
+ await subscribed(thread, makeMentionMessage());
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('blocks @-mentions in channels outside groupAllowFrom and notifies the sender', async () => {
+ const { subscribed } = await loadHandlers({
+ groupAllowFrom: 'channel-1',
+ groupPolicy: 'allowlist',
+ });
+ const thread = makeGroupThread('channel-9');
+
+ await subscribed(thread, makeMentionMessage());
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
+ });
+
+ it('allows Discord @-mentions when the operator allowlisted ONLY the auto-thread ID', async () => {
+ // Operator wants to allow exactly one specific thread (e.g. they
+ // copied the thread ID from Discord directly). The router uses
+ // `extractChatId` (= the most-specific raw ID, here the thread) as
+ // the primary candidate, so an allowlist holding just the thread ID
+ // matches.
+ const { mention } = await loadHandlers({
+ groupAllowFrom: 'auto-thread-id',
+ groupPolicy: 'allowlist',
+ });
+ const thread = {
+ channelId: 'auto-thread-id',
+ id: 'discord:guild-1:parent-channel:auto-thread-id',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('allows Discord @-mentions when the operator allowlisted the PARENT channel', async () => {
+ // Real-world bug: operator pastes the parent channel ID
+ // (`parent-channel`) into groupAllowFrom; Discord auto-creates a
+ // reply thread for the @-mention so `thread.channelId` is the
+ // ephemeral thread ID, not the parent. The router asks the platform
+ // client for extra allowlist candidates and accepts the message
+ // because the parent matches.
+ const { mention } = await loadHandlers({
+ groupAllowFrom: 'parent-channel',
+ groupPolicy: 'allowlist',
+ });
+ const thread = {
+ channelId: 'auto-thread-id',
+ id: 'discord:guild-1:parent-channel:auto-thread-id',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('blocks Discord @-mentions when neither the thread nor parent are allowlisted', async () => {
+ const { mention } = await loadHandlers({
+ groupAllowFrom: 'some-other-channel',
+ groupPolicy: 'allowlist',
+ });
+ const thread = {
+ channelId: 'auto-thread-id',
+ id: 'discord:guild-1:parent-channel:auto-thread-id',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
+ });
+
+ it('does not affect DMs when group policy is disabled', async () => {
+ const { subscribed } = await loadHandlers({ groupPolicy: 'disabled' });
+ const thread = {
+ channelId: 'dm-channel',
+ id: 'telegram:dm',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await subscribed(thread, {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ text: 'hi in DM',
+ });
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('global allowFrom (user-level identity gate)', () => {
+ /**
+ * Real-world bug report: DM Policy=Allowlist, allowFrom=[me], Group
+ * Policy=Open. A non-allowlisted user @-mentioned the bot in a server
+ * channel and the bot still tried to process — because the old
+ * implementation only consumed allowFrom under `dmPolicy='allowlist'`
+ * and isDM=true. Lock in: a populated allowFrom blocks every inbound
+ * surface — DMs and group @mentions alike.
+ */
+ async function loadHandlers(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const sub = mockOnSubscribedMessage.mock.calls.at(-1);
+ const mention = mockOnNewMention.mock.calls.at(-1);
+ if (!sub || !mention) throw new Error('handlers not registered');
+ return {
+ mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ };
+ }
+
+ it('blocks a non-allowlisted sender in a group and posts the generic notice in-thread', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot hello',
+ };
+
+ await mention(thread, message);
+
+ // Bot must not handle the message...
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ // ...but must notify the sender in-thread with the generic
+ // "interact with this bot" copy. On Discord the post lands in the
+ // auto-created reply thread, so it does not pollute the parent
+ // channel; on other platforms it lands in the same group/thread
+ // the @mention came from, mirroring notifyGroupRejected.
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(thread.post.mock.calls[0][0]).toContain('interact with this bot');
+ // The generic copy intentionally avoids "direct messages" — the
+ // sender did not try to DM, they @-mentioned in a group.
+ expect(thread.post.mock.calls[0][0]).not.toContain('direct messages');
+ });
+
+ it('blocks a non-allowlisted sender in a DM (with notification)', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ id: 'telegram:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await mention(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+
+ it('lets allowlisted senders through in a group', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await mention(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('blocks subscribed-thread non-allowlisted senders in groups with the generic notice', async () => {
+ const { subscribed } = await loadHandlers({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await subscribed(thread, {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain('interact with this bot');
+ });
+
+ it('with empty allowFrom acts as no-op, all senders allowed', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: '',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, {
+ author: { isBot: false, userId: 'random-user', userName: 'random' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it("treats settings.userId as implicitly allowed when allowFrom doesn't list them (anti-lockout)", async () => {
+ // The operator filled in `userId` (the AI-tools field) so AI can
+ // push notifications to them, then later set `allowFrom` to scope
+ // the bot to a couple of friends — forgetting to add themselves.
+ // The router must still let the operator interact.
+ const { mention } = await loadHandlers({
+ allowFrom: 'friend-1, friend-2',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ userId: 'operator-id',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, {
+ author: { isBot: false, userId: 'operator-id', userName: 'me' },
isMention: true,
text: '@bot hi',
+ });
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('does not flip the bot to private mode when only userId is set (allowFrom empty)', async () => {
+ // The reverse safety check: a long-standing operator who only ever
+ // configured `userId` for AI push must not suddenly find their bot
+ // restricted to themselves once allowFrom-as-global-gate ships.
+ const { mention } = await loadHandlers({
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ userId: 'operator-id',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, {
+ author: { isBot: false, userId: 'random-user', userName: 'random' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ // Random user gets through because allowFrom is empty → no filter.
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('command access gates (P1: /commands must respect allowFrom + DM/group policy)', () => {
+ /**
+ * Real-world risk: command dispatch (`/new`, `/stop`) historically ran
+ * BEFORE the allowFrom / DM-policy / group-policy checks. A blocked
+ * sender could still side-effect — `/stop` cancelling an active run,
+ * `/new` resetting thread state — even though normal messages were
+ * rejected. Lock in: every command-dispatch path applies the same
+ * access stack as the message handlers.
+ */
+ async function loadAllHandlers(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const sub = mockOnSubscribedMessage.mock.calls.at(-1);
+ const mention = mockOnNewMention.mock.calls.at(-1);
+ // The command-regex onNewMessage is registered LAST (after the DM
+ // catch-all `/./`), so pick it by matching the `/(new|stop)` pattern.
+ const cmdHandlerCall = mockOnNewMessage.mock.calls.find(
+ (call) => call[0] instanceof RegExp && call[0].source.includes('new'),
+ );
+ const slashNewCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/new');
+ const slashStopCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/stop');
+ if (!sub || !mention || !cmdHandlerCall || !slashNewCall || !slashStopCall) {
+ throw new Error('handlers not registered');
+ }
+ return {
+ cmdRegexHandler: cmdHandlerCall[1] as (thread: any, message: any) => Promise<void>,
+ mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ slashNew: slashNewCall[1] as (event: any) => Promise<void>,
+ slashStop: slashStopCall[1] as (event: any) => Promise<void>,
+ subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ };
+ }
+
+ function makeChannel(overrides: Record<string, unknown> = {}) {
+ return {
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ ...overrides,
+ };
+ }
+
+ it('blocks a native /stop slash command from a non-allowlisted sender', async () => {
+ const { slashStop } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const channel = makeChannel();
+ const event = {
+ channel,
+ text: '',
+ user: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ };
+
+ await slashStop(event);
+
+ // Rejection notice posted, but the command handler must not have
+ // called setState or kicked off an interruptTask.
+ expect(channel.post).toHaveBeenCalledTimes(1);
+ expect(channel.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(channel.setState).not.toHaveBeenCalled();
+ });
+
+ it('blocks a native /new slash command in a disabled-DM channel', async () => {
+ const { slashNew } = await loadAllHandlers({
+ dmPolicy: 'disabled',
+ groupPolicy: 'open',
+ });
+ const channel = makeChannel({ isDM: true });
+ const event = {
+ channel,
+ text: '',
+ user: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ };
+
+ await slashNew(event);
+
+ // DM rejection notice (mentions DMs / direct messages), no state reset.
+ expect(channel.post).toHaveBeenCalledTimes(1);
+ expect(channel.post.mock.calls[0][0]).toMatch(/direct message/i);
+ expect(channel.setState).not.toHaveBeenCalled();
+ });
+
+ it('blocks a native slash command in a non-allowlisted group channel', async () => {
+ const { slashNew } = await loadAllHandlers({
+ groupAllowFrom: 'channel-2',
+ groupPolicy: 'allowlist',
+ });
+ const channel = makeChannel({ id: 'telegram:channel-9', isDM: false });
+ const event = {
+ channel,
+ text: '',
+ user: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ };
+
+ await slashNew(event);
+
+ expect(channel.post).toHaveBeenCalledTimes(1);
+ expect(channel.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
+ expect(channel.setState).not.toHaveBeenCalled();
+ });
+
+ it('blocks a text-based /new (Telegram regex path) from a non-allowlisted sender', async () => {
+ const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: false,
+ text: '/new',
+ };
+
+ await cmdRegexHandler(thread, message);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(thread.setState).not.toHaveBeenCalled();
+ });
+
+ it('blocks /stop typed in onNewMention as a command from a non-allowlisted sender', async () => {
+ // Older code dispatched commands BEFORE the allowFrom check; this
+ // test catches a regression where /stop in an @-mention slips through.
+ const { mention } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot /stop',
+ };
+
+ await mention(thread, message);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(thread.setState).not.toHaveBeenCalled();
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('blocks /new typed in onSubscribedMessage from a non-allowlisted sender', async () => {
+ const { subscribed } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: false,
+ text: '/new',
+ };
+
+ await subscribed(thread, message);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(thread.setState).not.toHaveBeenCalled();
+ });
+
+ it('still allows /commands from an allowlisted sender (gate does not break the happy path)', async () => {
+ const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ text: '/new',
+ };
+
+ await cmdRegexHandler(thread, message);
+
+ // /new resets the topic (replace=true) and posts a confirmation.
+ expect(thread.setState).toHaveBeenCalledWith({ topicId: undefined }, { replace: true });
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).not.toContain("aren't authorized");
+ });
+ });
+
+ describe('regression: nested settings.dm.policy is ignored', () => {
+ /**
+ * Original bug: the form persisted `settings.dmPolicy` (flat) but the
+ * router read `settings.dm.policy` (nested), so every saved policy
+ * silently fell back to `'open'` and DMs were never blocked. Lock that
+ * direction in: the *flat* key is authoritative; the legacy nested
+ * shape is dead.
+ */
+ it('a saved dmPolicy=disabled at the flat key blocks DMs end-to-end', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings: { dmPolicy: 'disabled' } }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnNewMention.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onNewMention was not registered');
+ const handler = lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+
+ const thread = {
+ id: 'telegram:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ await handler(thread, {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
+ });
+
+ it('a legacy nested settings.dm.policy=disabled is IGNORED and DMs pass through', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ // Pre-bug-fix shape — nested object the form never actually wrote
+ // to. extractDmSettings doesn't read this; policy falls back to
+ // 'open', so the DM goes through.
+ settings: { dm: { policy: 'disabled' } },
+ }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnNewMention.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onNewMention was not registered');
+ const handler = lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+
+ const thread = {
+ id: 'telegram:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ await handler(thread, {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ // Nested shape is dead → policy resolved as 'open' → DM goes through.
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('per-message reply locale auto-detect', () => {
+ /**
+ * Boot the router so its handler registration runs, then return the
+ * `onSubscribedMessage` handler — the easiest entry point to drive a
+ * locale-detected DM rejection without mocking the bridge call.
+ */
+ async function loadHandler(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnSubscribedMessage.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onSubscribedMessage was not registered');
+ return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ it('passes the sender platform locale into the bridge call', async () => {
+ const handler = await loadHandler({ dmPolicy: 'open' });
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ raw: { from: { language_code: 'pt-br' } },
+ text: 'olá',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ // pt-br → pt-BR via the project normalizeLocale
+ expect(mockHandleSubscribedMessage.mock.calls[0][2].replyLocale).toBe('pt-BR');
+ });
+
+ it('falls back to the platform default locale when the sender locale is missing', async () => {
+ const handler = await loadHandler({ dmPolicy: 'open' });
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ raw: {}, // no language_code → use platform default (en-US for Telegram)
+ text: 'hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ expect(mockHandleSubscribedMessage.mock.calls[0][2].replyLocale).toBe('en-US');
+ });
+
+ it('uses the sender locale for the DM rejection notice copy', async () => {
+ const handler = await loadHandler({ dmPolicy: 'disabled' });
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ // Chinese-speaking user on Telegram (default en-US) — copy should
+ // follow the sender, not the platform default.
+ raw: { from: { language_code: 'zh-cn' } },
+ text: '你好',
};
await handler(thread, message);
expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain('该机器人不接受私信');
});
});
});
diff --git a/src/server/services/bot/__tests__/replyTemplate.test.ts b/src/server/services/bot/__tests__/replyTemplate.test.ts
index cd68f27edf0..5c00c06932a 100644
--- a/src/server/services/bot/__tests__/replyTemplate.test.ts
+++ b/src/server/services/bot/__tests__/replyTemplate.test.ts
@@ -3,11 +3,18 @@ import { describe, expect, it } from 'vitest';
import type { RenderStepParams } from '../replyTemplate';
import {
formatTokens,
+ renderCommandReply,
+ renderDmRejected,
renderError,
+ renderErrorWithDetails,
renderFinalReply,
+ renderGroupRejected,
+ renderInlineError,
renderLLMGenerating,
+ renderSenderRejected,
renderStart,
renderStepProgress,
+ renderStopped,
renderToolExecuting,
splitMessage,
summarizeOutput,
@@ -336,6 +343,158 @@ describe('replyTemplate', () => {
it('should fall back to a generic header when no operation id is provided', () => {
expect(renderError()).toBe('**Agent Execution Failed**');
});
+
+ it('renders Chinese copy when locale is zh-CN', () => {
+ expect(renderError(undefined, 'zh-CN')).toBe('**Agent 执行失败**');
+ expect(renderError('op-1', 'zh-CN')).toContain('Agent 执行失败');
+ expect(renderError('op-1', 'zh-CN')).toContain('op-1');
+ });
+
+ it('falls back to English for locales without a translated dictionary', () => {
+ expect(renderError(undefined, 'ja-JP')).toBe('**Agent Execution Failed**');
+ });
+ });
+
+ // ==================== renderStopped ====================
+
+ describe('renderStopped', () => {
+ it('returns the default English message when no message is supplied', () => {
+ expect(renderStopped()).toBe('Execution stopped.');
+ });
+
+ it('returns the default Chinese message when locale is zh-CN', () => {
+ expect(renderStopped(undefined, 'zh-CN')).toBe('执行已停止。');
+ });
+
+ it('passes through an explicit message regardless of locale', () => {
+ expect(renderStopped('Stopped by user.', 'zh-CN')).toBe('Stopped by user.');
+ });
+ });
+
+ // ==================== renderDmRejected ====================
+
+ describe('renderDmRejected', () => {
+ it('renders disabled and allowlist English copy', () => {
+ expect(renderDmRejected('disabled')).toContain("isn't accepting direct messages");
+ expect(renderDmRejected('allowlist')).toContain("aren't authorized");
+ });
+
+ it('renders disabled and allowlist Chinese copy when locale is zh-CN', () => {
+ expect(renderDmRejected('disabled', 'zh-CN')).toContain('不接受私信');
+ expect(renderDmRejected('allowlist', 'zh-CN')).toContain('没有私信该机器人的权限');
+ });
+ });
+
+ // ==================== renderGroupRejected ====================
+
+ describe('renderGroupRejected', () => {
+ it('renders disabled and allowlist English copy', () => {
+ expect(renderGroupRejected('disabled')).toContain("doesn't respond in groups or channels");
+ expect(renderGroupRejected('allowlist')).toContain("isn't enabled in this channel");
+ });
+
+ it('renders disabled and allowlist Chinese copy when locale is zh-CN', () => {
+ expect(renderGroupRejected('disabled', 'zh-CN')).toContain('不在群组或频道中响应');
+ expect(renderGroupRejected('allowlist', 'zh-CN')).toContain('未在此频道启用');
+ });
+ });
+
+ // ==================== renderSenderRejected ====================
+
+ describe('renderSenderRejected', () => {
+ it("uses generic 'interact with this bot' phrasing — never 'direct messages'", () => {
+ // The notice is shown out-of-band when a user @-mentioned in a
+ // group; saying "you aren't authorized to send direct messages"
+ // would misdescribe what the user actually did.
+ const en = renderSenderRejected();
+ expect(en).toContain("aren't authorized");
+ expect(en).toContain('interact with this bot');
+ expect(en).not.toContain('direct messages');
+ });
+
+ it('renders Chinese copy when locale is zh-CN, also avoiding DM phrasing', () => {
+ const zh = renderSenderRejected('zh-CN');
+ expect(zh).toContain('交互的权限');
+ expect(zh).not.toContain('私信');
+ });
+ });
+
+ // ==================== renderInlineError / renderErrorWithDetails ====================
+
+ describe('renderInlineError', () => {
+ it('formats a compact **Error** line in English by default', () => {
+ expect(renderInlineError('boom')).toBe('**Error**: boom');
+ });
+
+ it('uses Chinese copy when locale is zh-CN', () => {
+ expect(renderInlineError('boom', 'zh-CN')).toBe('**错误**:boom');
+ });
+ });
+
+ describe('renderErrorWithDetails', () => {
+ it('embeds the raw detail block in English by default', () => {
+ const out = renderErrorWithDetails('stack trace');
+ expect(out).toContain('Agent Execution Failed');
+ expect(out).toContain('Details:');
+ expect(out).toContain('stack trace');
+ });
+
+ it('embeds the raw detail block with Chinese label when locale is zh-CN', () => {
+ const out = renderErrorWithDetails('stack trace', 'zh-CN');
+ expect(out).toContain('Agent 执行失败');
+ expect(out).toContain('详细信息');
+ expect(out).toContain('stack trace');
+ });
+ });
+
+ // ==================== renderCommandReply ====================
+
+ describe('renderCommandReply', () => {
+ it('returns the English copy for each command key by default', () => {
+ expect(renderCommandReply('cmdNewReset')).toContain('Conversation reset');
+ expect(renderCommandReply('cmdStopNotActive')).toContain('No active execution');
+ expect(renderCommandReply('cmdStopRequested')).toBe('Stop requested.');
+ expect(renderCommandReply('cmdStopUnable')).toContain('Unable to stop');
+ });
+
+ it('returns the Chinese copy when locale is zh-CN', () => {
+ expect(renderCommandReply('cmdNewReset', 'zh-CN')).toContain('对话已重置');
+ expect(renderCommandReply('cmdStopNotActive', 'zh-CN')).toContain('没有正在执行');
+ expect(renderCommandReply('cmdStopRequested', 'zh-CN')).toBe('已发出停止请求。');
+ expect(renderCommandReply('cmdStopUnable', 'zh-CN')).toContain('无法停止');
+ });
+ });
+
+ // ==================== renderStepProgress locale ====================
+
+ describe('renderStepProgress locale', () => {
+ it('uses Chinese "处理中…" placeholder in zh-CN', () => {
+ const out = renderStepProgress(makeParams({ stepType: 'call_llm' }), 'zh-CN');
+ expect(out).toContain('处理中…');
+ expect(out).not.toContain('Processing...');
+ });
+
+ it('uses Chinese tools-calling header in zh-CN', () => {
+ const out = renderStepProgress(
+ makeParams({
+ stepType: 'call_tool',
+ totalToolCalls: 3,
+ elapsedMs: 1500,
+ }),
+ 'zh-CN',
+ );
+ expect(out).toContain('共 **3** 次工具调用');
+ });
+ });
+
+ // ==================== renderStart locale ====================
+
+ describe('renderStart locale', () => {
+ it('returns a Chinese ack phrase when locale is zh-CN', () => {
+ // The zh fallback list is small and flat — every entry is non-Latin.
+ const phrase = renderStart('hi', { lng: 'zh-CN' });
+ expect(/[\u4E00-\u9FFF]/.test(phrase)).toBe(true);
+ });
});
// ==================== renderStepProgress (dispatcher) ====================
diff --git a/src/server/services/bot/ackPhrases/index.ts b/src/server/services/bot/ackPhrases/index.ts
index 0f9917dbcc7..e13dd42a568 100644
--- a/src/server/services/bot/ackPhrases/index.ts
+++ b/src/server/services/bot/ackPhrases/index.ts
@@ -1,6 +1,29 @@
+import type { BotReplyLocale } from '../platforms';
import type { ContextType, TimeSegment } from './vibeMatrix';
import { VIBE_CORPUS } from './vibeMatrix';
+/**
+ * Per-locale fallback ack phrases for languages without a curated vibe corpus.
+ * Sampled flatly (no time / context awareness) — when the audience justifies
+ * the effort we can lift these into a proper corpus per locale, but a small
+ * set of natural-sounding generic acks already beats English on Chinese
+ * platforms. Keep entries short and conversational.
+ */
+const LOCALE_FALLBACK_ACK_PHRASES: Partial<Record<BotReplyLocale, string[]>> = {
+ 'zh-CN': [
+ '收到,处理中…',
+ '好的,马上来。',
+ '稍等片刻。',
+ '正在看,请稍候。',
+ '已收到,开始处理。',
+ '让我想想。',
+ '马上。',
+ '好嘞。',
+ '在了,等我一会儿。',
+ '处理中…',
+ ],
+};
+
// Simple sample implementation to avoid dependency issues
function sample<T>(arr: T[]): T | undefined {
if (!arr || arr.length === 0) return undefined;
@@ -126,6 +149,13 @@ export interface AckOptions {
* Force a specific time (for testing)
*/
date?: Date;
+ /**
+ * Locale used to pick which corpus to sample from. The English corpus
+ * (`VIBE_CORPUS`) is curated by time-of-day and intent; other locales
+ * sample from a small flat fallback list under `LOCALE_FALLBACK_ACK_PHRASES`.
+ * Omit to keep current behavior (English).
+ */
+ lng?: BotReplyLocale;
/**
* The user's timezone (e.g. 'Asia/Shanghai', 'America/New_York')
* If not provided, defaults to server time
@@ -134,6 +164,11 @@ export interface AckOptions {
}
export function getExtremeAck(content: string = '', options: AckOptions = {}): string {
+ const fallbackList = options.lng && LOCALE_FALLBACK_ACK_PHRASES[options.lng];
+ if (fallbackList) {
+ return sample(fallbackList) ?? fallbackList[0];
+ }
+
const now = options.date || new Date();
// Calculate the hour in the user's local time
diff --git a/src/server/services/bot/platforms/__tests__/const.test.ts b/src/server/services/bot/platforms/__tests__/const.test.ts
index a898af20657..958c4d687dd 100644
--- a/src/server/services/bot/platforms/__tests__/const.test.ts
+++ b/src/server/services/bot/platforms/__tests__/const.test.ts
@@ -1,6 +1,79 @@
import { describe, expect, it } from 'vitest';
-import { getStepReactionEmoji, THINKING_REACTION_EMOJI, WORKING_REACTION_EMOJI } from '../const';
+import {
+ allowFromField,
+ extractDmSettings,
+ extractGroupSettings,
+ extractUserAllowlist,
+ getBotReplyLocale,
+ getStepReactionEmoji,
+ makeDmPolicyField,
+ makeGroupPolicyFields,
+ normalizeBotReplyLocale,
+ shouldAllowSender,
+ shouldHandleDm,
+ shouldHandleGroup,
+ THINKING_REACTION_EMOJI,
+ WORKING_REACTION_EMOJI,
+} from '../const';
+
+describe('normalizeBotReplyLocale', () => {
+ it('returns undefined for empty / nullish input so callers fall back', () => {
+ expect(normalizeBotReplyLocale(undefined)).toBeUndefined();
+ expect(normalizeBotReplyLocale(null)).toBeUndefined();
+ expect(normalizeBotReplyLocale('')).toBeUndefined();
+ });
+
+ it('normalizes Telegram-style lowercase to project Locales', () => {
+ expect(normalizeBotReplyLocale('pt-br')).toBe('pt-BR');
+ expect(normalizeBotReplyLocale('zh-cn')).toBe('zh-CN');
+ expect(normalizeBotReplyLocale('en')).toBe('en-US');
+ });
+
+ it('normalizes Feishu-style underscore to project Locales', () => {
+ expect(normalizeBotReplyLocale('zh_CN')).toBe('zh-CN');
+ expect(normalizeBotReplyLocale('en_US')).toBe('en-US');
+ });
+
+ it('passes through Discord/Slack-style mixed case unchanged', () => {
+ expect(normalizeBotReplyLocale('en-US')).toBe('en-US');
+ expect(normalizeBotReplyLocale('zh-CN')).toBe('zh-CN');
+ });
+
+ it('falls back to en-US when the input is not a project locale', () => {
+ expect(normalizeBotReplyLocale('xx-yy')).toBe('en-US');
+ });
+
+ it('maps Chinese script subtags to the matching regional locale', () => {
+ // Telegram emits these lowercase shapes for Chinese users — without
+ // explicit script handling they fall through to en-US.
+ expect(normalizeBotReplyLocale('zh-hans')).toBe('zh-CN');
+ expect(normalizeBotReplyLocale('zh-hant')).toBe('zh-TW');
+ expect(normalizeBotReplyLocale('zh-Hans-CN')).toBe('zh-CN');
+ expect(normalizeBotReplyLocale('zh-Hant-TW')).toBe('zh-TW');
+ expect(normalizeBotReplyLocale('zh_Hant_HK')).toBe('zh-TW');
+ });
+});
+
+describe('getBotReplyLocale', () => {
+ it('returns zh-CN for Chinese-first platforms', () => {
+ expect(getBotReplyLocale('feishu')).toBe('zh-CN');
+ expect(getBotReplyLocale('qq')).toBe('zh-CN');
+ expect(getBotReplyLocale('wechat')).toBe('zh-CN');
+ });
+
+ it('returns en-US for English-first platforms', () => {
+ expect(getBotReplyLocale('discord')).toBe('en-US');
+ expect(getBotReplyLocale('slack')).toBe('en-US');
+ expect(getBotReplyLocale('telegram')).toBe('en-US');
+ expect(getBotReplyLocale('lark')).toBe('en-US');
+ });
+
+ it('falls back to en-US for unknown or missing platforms', () => {
+ expect(getBotReplyLocale(undefined)).toBe('en-US');
+ expect(getBotReplyLocale('mystery-platform')).toBe('en-US');
+ });
+});
describe('getStepReactionEmoji', () => {
it('returns working emoji after call_llm that queued pending tool calls (tools about to run)', () => {
@@ -21,3 +94,410 @@ describe('getStepReactionEmoji', () => {
expect(getStepReactionEmoji(undefined, undefined)).toBe(THINKING_REACTION_EMOJI);
});
});
+
+describe('makeDmPolicyField', () => {
+ it('produces a flat dmPolicy field with the supplied default policy and three modes', () => {
+ const field = makeDmPolicyField({ policy: 'open' });
+
+ expect(field.key).toBe('dmPolicy');
+ expect(field.type).toBe('string');
+ expect(field.default).toBe('open');
+ expect(field.enum).toEqual(['open', 'allowlist', 'disabled']);
+ });
+
+ it('supports the per-platform default override (e.g. opt-in disabled)', () => {
+ const field = makeDmPolicyField({ policy: 'disabled' });
+ expect(field.default).toBe('disabled');
+ });
+});
+
+describe('allowFromField', () => {
+ it('is an object list (id + optional name) so operators can label entries', () => {
+ expect(allowFromField.key).toBe('allowFrom');
+ expect(allowFromField.type).toBe('array');
+ // Default is an empty array — empty means "no user-level filter".
+ expect(allowFromField.default).toEqual([]);
+ // Always visible — applies globally to DM and group, no visibleWhen gate.
+ expect(allowFromField.visibleWhen).toBeUndefined();
+
+ expect(allowFromField.items?.type).toBe('object');
+ const props = allowFromField.items?.properties ?? [];
+ const keys = props.map((p) => p.key);
+ expect(keys).toEqual(['id', 'name']);
+ // Only `id` is required — `name` is just a reminder for the operator.
+ expect(props.find((p) => p.key === 'id')?.required).toBe(true);
+ expect(props.find((p) => p.key === 'name')?.required).toBeFalsy();
+ });
+});
+
+describe('makeGroupPolicyFields', () => {
+ it('produces a [groupPolicy, groupAllowFrom] pair with the supplied default', () => {
+ const fields = makeGroupPolicyFields({ policy: 'open' });
+ expect(fields).toHaveLength(2);
+
+ const [policy, allowFrom] = fields;
+ expect(policy.key).toBe('groupPolicy');
+ expect(policy.default).toBe('open');
+ expect(policy.enum).toEqual(['open', 'allowlist', 'disabled']);
+
+ expect(allowFrom.key).toBe('groupAllowFrom');
+ expect(allowFrom.type).toBe('array');
+ expect(allowFrom.default).toEqual([]);
+ expect(allowFrom.items?.type).toBe('object');
+ expect((allowFrom.items?.properties ?? []).map((p) => p.key)).toEqual(['id', 'name']);
+ expect(allowFrom.visibleWhen).toEqual({ field: 'groupPolicy', value: 'allowlist' });
+ });
+});
+
+describe('extractDmSettings', () => {
+ it('defaults to open when dmPolicy is missing or invalid', () => {
+ // In production `mergeWithDefaults` always injects `dmPolicy` from the
+ // platform schema, so this branch is only a safety net for malformed
+ // settings — we land on the most permissive valid policy.
+ expect(extractDmSettings(undefined)).toEqual({ policy: 'open' });
+ expect(extractDmSettings({})).toEqual({ policy: 'open' });
+ expect(extractDmSettings({ dmPolicy: 'mystery' })).toEqual({ policy: 'open' });
+ });
+
+ it('reads the flat dmPolicy field (not legacy nested settings.dm.policy)', () => {
+ expect(extractDmSettings({ dmPolicy: 'disabled' })).toEqual({ policy: 'disabled' });
+ expect(extractDmSettings({ dmPolicy: 'allowlist' })).toEqual({ policy: 'allowlist' });
+ // Regression: the original bug stored disabled at `settings.dm.policy` but
+ // never read it back. The new shape is flat; nested `dm.policy` is ignored.
+ expect(extractDmSettings({ dm: { policy: 'disabled' } })).toEqual({ policy: 'open' });
+ });
+});
+
+describe('extractUserAllowlist', () => {
+ it('returns an empty list when allowFrom is missing or empty', () => {
+ expect(extractUserAllowlist(undefined)).toEqual({ ids: [] });
+ expect(extractUserAllowlist({})).toEqual({ ids: [] });
+ expect(extractUserAllowlist({ allowFrom: '' })).toEqual({ ids: [] });
+ expect(extractUserAllowlist({ allowFrom: [] })).toEqual({ ids: [] });
+ });
+
+ it('reads the new object-list shape, dropping name from the runtime view', () => {
+ expect(
+ extractUserAllowlist({
+ allowFrom: [
+ { id: 'alice', name: 'Alice — PM' },
+ { id: 'bob', name: 'Bob' },
+ ],
+ }),
+ ).toEqual({ ids: ['alice', 'bob'] });
+ });
+
+ it('tolerates entries without a name (name is optional)', () => {
+ expect(extractUserAllowlist({ allowFrom: [{ id: 'alice' }, { id: 'bob' }] })).toEqual({
+ ids: ['alice', 'bob'],
+ });
+ });
+
+ it('drops object entries with empty / missing id (require id, fail closed)', () => {
+ expect(
+ extractUserAllowlist({
+ allowFrom: [{ id: ' ' }, { id: 'bob' }, { name: 'no-id' } as { id?: string }],
+ }),
+ ).toEqual({ ids: ['bob'] });
+ });
+
+ it('still parses the legacy comma / whitespace string (back-compat for stored data)', () => {
+ expect(extractUserAllowlist({ allowFrom: ' alice, bob\n carol ' })).toEqual({
+ ids: ['alice', 'bob', 'carol'],
+ });
+ });
+
+ it('still parses the legacy bare string[] form', () => {
+ expect(extractUserAllowlist({ allowFrom: ['alice', ' bob ', ''] })).toEqual({
+ ids: ['alice', 'bob'],
+ });
+ });
+
+ it('handles a mixed legacy/new array (string and object entries together)', () => {
+ expect(
+ extractUserAllowlist({ allowFrom: ['alice', { id: 'bob', name: 'Bob' }, ' '] }),
+ ).toEqual({ ids: ['alice', 'bob'] });
+ });
+
+ it('does NOT inject userId when allowFrom is empty (preserves no-filter semantics)', () => {
+ // Critical: setting only `userId` (the AI-tools field) must not
+ // implicitly turn the bot into a private one. Existing operators who
+ // pre-date allowFrom rely on that.
+ expect(extractUserAllowlist({ userId: 'alice' })).toEqual({ ids: [] });
+ expect(extractUserAllowlist({ allowFrom: [], userId: 'alice' })).toEqual({ ids: [] });
+ });
+
+ it('implicitly merges userId into a populated allowFrom (anti-lockout, object-list shape)', () => {
+ expect(
+ extractUserAllowlist({
+ allowFrom: [
+ { id: 'bob', name: 'Bob' },
+ { id: 'carol', name: 'Carol' },
+ ],
+ userId: 'alice',
+ }),
+ ).toEqual({ ids: ['bob', 'carol', 'alice'] });
+ });
+
+ it('does not duplicate userId when it is already in the object-list allowFrom', () => {
+ expect(
+ extractUserAllowlist({
+ allowFrom: [{ id: 'alice', name: 'me' }, { id: 'bob' }],
+ userId: 'alice',
+ }),
+ ).toEqual({ ids: ['alice', 'bob'] });
+ });
+
+ it('ignores a blank userId string', () => {
+ expect(extractUserAllowlist({ allowFrom: [{ id: 'bob' }], userId: ' ' })).toEqual({
+ ids: ['bob'],
+ });
+ });
+});
+
+describe('extractGroupSettings', () => {
+ it('defaults to open when groupPolicy is missing or invalid', () => {
+ expect(extractGroupSettings(undefined)).toEqual({ allowFrom: [], policy: 'open' });
+ expect(extractGroupSettings({})).toEqual({ allowFrom: [], policy: 'open' });
+ expect(extractGroupSettings({ groupPolicy: 'mystery' })).toEqual({
+ allowFrom: [],
+ policy: 'open',
+ });
+ });
+
+ it('reads the new object-list shape, returning ids only', () => {
+ expect(
+ extractGroupSettings({
+ groupAllowFrom: [
+ { id: 'channel-1', name: '#ops' },
+ { id: 'channel-2', name: '#friends' },
+ ],
+ groupPolicy: 'allowlist',
+ }),
+ ).toEqual({
+ allowFrom: ['channel-1', 'channel-2'],
+ policy: 'allowlist',
+ });
+ });
+
+ it('still parses the legacy comma / whitespace string (back-compat)', () => {
+ expect(
+ extractGroupSettings({
+ groupAllowFrom: 'channel-1, channel-2\n channel-3',
+ groupPolicy: 'allowlist',
+ }),
+ ).toEqual({
+ allowFrom: ['channel-1', 'channel-2', 'channel-3'],
+ policy: 'allowlist',
+ });
+ });
+});
+
+describe('shouldAllowSender (global user allowlist)', () => {
+ const empty = { ids: [] as string[] };
+ const aliceAndBob = { ids: ['alice-id', 'bob-id'] };
+
+ it('passes any sender when the allowlist is empty (no global filter)', () => {
+ expect(shouldAllowSender({ authorUserId: 'anyone', userAllowlist: empty })).toBe(true);
+ expect(shouldAllowSender({ authorUserId: undefined, userAllowlist: empty })).toBe(true);
+ });
+
+ it('passes senders in the populated allowlist', () => {
+ expect(shouldAllowSender({ authorUserId: 'alice-id', userAllowlist: aliceAndBob })).toBe(true);
+ });
+
+ it('blocks senders outside the populated allowlist', () => {
+ expect(shouldAllowSender({ authorUserId: 'carol-id', userAllowlist: aliceAndBob })).toBe(false);
+ });
+
+ it('fails closed for a missing user id when the allowlist is populated', () => {
+ expect(shouldAllowSender({ authorUserId: undefined, userAllowlist: aliceAndBob })).toBe(false);
+ });
+});
+
+describe('shouldHandleDm', () => {
+ const open = { policy: 'open' as const };
+ const disabled = { policy: 'disabled' as const };
+ const allowlist = { policy: 'allowlist' as const };
+ const emptyUserAllowlist = { ids: [] as string[] };
+ const aliceAndBob = { ids: ['alice-id', 'bob-id'] };
+
+ it('lets non-DM threads pass unconditionally', () => {
+ expect(
+ shouldHandleDm({
+ authorUserId: undefined,
+ dmSettings: disabled,
+ isDM: false,
+ userAllowlist: emptyUserAllowlist,
+ }),
+ ).toBe(true);
+ });
+
+ it('blocks DMs when disabled', () => {
+ expect(
+ shouldHandleDm({
+ authorUserId: 'alice-id',
+ dmSettings: disabled,
+ isDM: true,
+ userAllowlist: aliceAndBob,
+ }),
+ ).toBe(false);
+ });
+
+ it('allows DMs under the open policy regardless of allowlist contents', () => {
+ expect(
+ shouldHandleDm({
+ authorUserId: 'anyone',
+ dmSettings: open,
+ isDM: true,
+ userAllowlist: emptyUserAllowlist,
+ }),
+ ).toBe(true);
+ // The global gate (shouldAllowSender) is the runtime filter for `open`;
+ // shouldHandleDm itself does not re-check it.
+ expect(
+ shouldHandleDm({
+ authorUserId: 'anyone',
+ dmSettings: open,
+ isDM: true,
+ userAllowlist: aliceAndBob,
+ }),
+ ).toBe(true);
+ });
+
+ it('allows DMs in allowlist mode when the sender is on the list', () => {
+ expect(
+ shouldHandleDm({
+ authorUserId: 'alice-id',
+ dmSettings: allowlist,
+ isDM: true,
+ userAllowlist: aliceAndBob,
+ }),
+ ).toBe(true);
+ });
+
+ it('rejects DMs in allowlist mode when the sender is NOT on the list', () => {
+ expect(
+ shouldHandleDm({
+ authorUserId: 'carol-id',
+ dmSettings: allowlist,
+ isDM: true,
+ userAllowlist: aliceAndBob,
+ }),
+ ).toBe(false);
+ });
+
+ it('fails closed in allowlist mode when allowFrom is empty (no DMs)', () => {
+ // This is the only behavioural difference from `open`: `open` would
+ // pass anyone here, `allowlist` rejects everyone.
+ expect(
+ shouldHandleDm({
+ authorUserId: 'alice-id',
+ dmSettings: allowlist,
+ isDM: true,
+ userAllowlist: emptyUserAllowlist,
+ }),
+ ).toBe(false);
+ });
+
+ it('fails closed when the allowlisted policy sees a missing user id', () => {
+ expect(
+ shouldHandleDm({
+ authorUserId: undefined,
+ dmSettings: allowlist,
+ isDM: true,
+ userAllowlist: aliceAndBob,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('shouldHandleGroup', () => {
+ const open = { allowFrom: [] as string[], policy: 'open' as const };
+ const disabled = { allowFrom: [] as string[], policy: 'disabled' as const };
+ const allowlist = { allowFrom: ['channel-1', 'channel-2'], policy: 'allowlist' as const };
+
+ it('lets DM threads pass unconditionally', () => {
+ expect(
+ shouldHandleGroup({ candidateChannelIds: [], groupSettings: disabled, isDM: true }),
+ ).toBe(true);
+ });
+
+ it('blocks group traffic when disabled', () => {
+ expect(
+ shouldHandleGroup({
+ candidateChannelIds: ['channel-1'],
+ groupSettings: disabled,
+ isDM: false,
+ }),
+ ).toBe(false);
+ });
+
+ it('allows group traffic under the open policy', () => {
+ expect(
+ shouldHandleGroup({
+ candidateChannelIds: ['any-channel'],
+ groupSettings: open,
+ isDM: false,
+ }),
+ ).toBe(true);
+ });
+
+ it('allows group traffic from channels in the allowlist', () => {
+ expect(
+ shouldHandleGroup({
+ candidateChannelIds: ['channel-1'],
+ groupSettings: allowlist,
+ isDM: false,
+ }),
+ ).toBe(true);
+ });
+
+ it('rejects group traffic from channels outside the allowlist', () => {
+ expect(
+ shouldHandleGroup({
+ candidateChannelIds: ['channel-9'],
+ groupSettings: allowlist,
+ isDM: false,
+ }),
+ ).toBe(false);
+ });
+
+ it('fails closed when the allowlisted policy sees no channel ids', () => {
+ expect(
+ shouldHandleGroup({ candidateChannelIds: [], groupSettings: allowlist, isDM: false }),
+ ).toBe(false);
+ expect(
+ shouldHandleGroup({
+ candidateChannelIds: [undefined, undefined],
+ groupSettings: allowlist,
+ isDM: false,
+ }),
+ ).toBe(false);
+ });
+
+ it('passes when ANY candidate is in the allowlist (Discord auto-thread + parent)', () => {
+ // Real-world scenario: operator pastes the *parent* channel ID
+ // (`channel-1`); Discord routes the inbound mention through an
+ // auto-created reply thread whose ID is `auto-thread-id`. The router
+ // hands both candidates over — only the parent matches, but that is
+ // enough to let the message through.
+ expect(
+ shouldHandleGroup({
+ candidateChannelIds: ['auto-thread-id', 'channel-1'],
+ groupSettings: allowlist,
+ isDM: false,
+ }),
+ ).toBe(true);
+ });
+
+ it('rejects when none of the candidates is in the allowlist', () => {
+ expect(
+ shouldHandleGroup({
+ candidateChannelIds: ['auto-thread-id', 'unrelated-parent'],
+ groupSettings: allowlist,
+ isDM: false,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/src/server/services/bot/platforms/const.ts b/src/server/services/bot/platforms/const.ts
index 11be02863ea..a6daf326827 100644
--- a/src/server/services/bot/platforms/const.ts
+++ b/src/server/services/bot/platforms/const.ts
@@ -1,8 +1,11 @@
+import { DEFAULT_LANG } from '@/const/locale';
+import { type Locales, normalizeLocale } from '@/locales/resources';
+
import type { FieldSchema } from './types';
export const displayToolCallsField: FieldSchema = {
key: 'displayToolCalls',
- default: true,
+ default: false,
description: 'channel.displayToolCallsHint',
label: 'channel.displayToolCalls',
type: 'boolean',
@@ -22,6 +25,408 @@ export const userIdField: FieldSchema = {
type: 'string',
};
+// ---------- Bot reply locale ----------
+
+/**
+ * Locale used for **system-generated** bot reply text (errors, stopped notices,
+ * DM rejection). Aliased to the project-wide `Locales` so adding a new IM
+ * platform language doesn't drift from the rest of the codebase. Agent
+ * conversation content is produced by the LLM and follows the user's language
+ * naturally — this only governs the small set of static strings the bot
+ * itself emits.
+ *
+ * Picked per-platform since each platform has a primary audience: Chinese
+ * platforms (Feishu / QQ / WeChat) ship Chinese strings, the rest ship
+ * English. Languages without an entry in the system-string dictionary
+ * gracefully fall back to `DEFAULT_LANG` ('en-US') at render time.
+ */
+export type BotReplyLocale = Locales;
+
+const PLATFORM_REPLY_LOCALES: Record<string, BotReplyLocale> = {
+ discord: 'en-US',
+ feishu: 'zh-CN',
+ lark: 'en-US',
+ qq: 'zh-CN',
+ slack: 'en-US',
+ telegram: 'en-US',
+ wechat: 'zh-CN',
+};
+
+export function getBotReplyLocale(platform: string | undefined): BotReplyLocale {
+ if (!platform) return DEFAULT_LANG;
+ return PLATFORM_REPLY_LOCALES[platform] ?? DEFAULT_LANG;
+}
+
+/**
+ * Coerce a platform-reported locale string to one of the project `Locales`.
+ *
+ * Different IM platforms emit different shapes for the same tag:
+ * - Telegram: lowercase BCP 47 (`pt-br`, `zh-hans`)
+ * - Discord / Slack: mixed case (`pt-BR`, `zh-CN`)
+ * - Feishu / Lark: underscored (`zh_CN`)
+ *
+ * We re-format to `lang-REGION` and then defer to the project's
+ * `normalizeLocale` so the resulting value sits inside `Locales`. Returns
+ * `undefined` for falsy input so the caller can fall back to a platform
+ * default; non-empty strings always produce a value (English when nothing
+ * else matches).
+ */
+export function normalizeBotReplyLocale(
+ raw: string | undefined | null,
+): BotReplyLocale | undefined {
+ if (!raw) return undefined;
+ const parts = raw.replaceAll('_', '-').split('-');
+ const lang = parts[0].toLowerCase();
+
+ // BCP 47 script subtags for Chinese (Telegram emits `zh-hans` / `zh-hant`,
+ // some web platforms emit `zh-Hans-CN` / `zh-Hant-TW`). `normalizeLocale`
+ // only knows region tags, so a `zh-HANS` shape silently falls back to
+ // en-US — map scripts to the closest regional locale before delegating.
+ if (lang === 'zh' && parts.length >= 2) {
+ const scriptOrRegion = parts[1].toLowerCase();
+ if (scriptOrRegion === 'hans') return 'zh-CN';
+ if (scriptOrRegion === 'hant') return 'zh-TW';
+ }
+
+ const formatted = parts.length === 1 ? lang : `${lang}-${parts[1].toUpperCase()}`;
+ return normalizeLocale(formatted);
+}
+
+// ---------- Access policies (DM + Group) ----------
+
+/**
+ * Two access policies share the runtime: `dmPolicy` gates 1:1 DMs, and
+ * `groupPolicy` gates group / channel / thread traffic. Both live as flat
+ * top-level fields on `settings` because the channel form auto-generated by
+ * `Body.tsx` flattens any `type: 'object'` field's children — nesting at the
+ * schema layer would not survive serialization, and an earlier attempt at
+ * `settings.dm.policy` silently fell through to the `'open'` fallback for
+ * every saved channel.
+ *
+ * Allowlists are split by what they hold:
+ * - `allowFrom` (top level, unprefixed) — **user IDs**. A *global* identity
+ * gate: when populated, **only** these users can interact with the bot
+ * anywhere — DMs, group @mentions, threads — regardless of `dmPolicy` /
+ * `groupPolicy` mode. Empty means "no user-level filter". Setting
+ * `dmPolicy='allowlist'` is an explicit "DMs require this list" signal
+ * that fails closed when the list is empty; otherwise the global gate
+ * already does the work.
+ * - `groupAllowFrom` — **channel / group / thread IDs**. Owned by
+ * `groupPolicy` because the value type is unrelated to user IDs.
+ *
+ * The naming rule: a name without a scope prefix advertises that the value
+ * crosses scopes (`allowFrom` is consulted by every gate); a prefixed name
+ * advertises the field is the property of one specific scope.
+ */
+export type DmPolicy = 'open' | 'allowlist' | 'disabled';
+
+/** User-ID allowlist shared across user-scope policies (DM today). */
+export interface UserAllowlist {
+ /** Parsed, deduplicated platform user IDs. */
+ ids: string[];
+}
+
+export interface DmSettings {
+ policy: DmPolicy;
+}
+
+export type GroupPolicy = 'open' | 'allowlist' | 'disabled';
+
+export interface GroupSettings {
+ /** Parsed channel / group / thread IDs (matched against `thread.channelId`). */
+ allowFrom: string[];
+ policy: GroupPolicy;
+}
+
+const DM_POLICIES: ReadonlySet<DmPolicy> = new Set(['open', 'allowlist', 'disabled']);
+const GROUP_POLICIES: ReadonlySet<GroupPolicy> = new Set(['open', 'allowlist', 'disabled']);
+
+/**
+ * DM Policy: gate inbound 1:1 messages.
+ *
+ * - `open` (default): accept DMs from anyone (subject to the global
+ * `allowFrom` gate when that is populated)
+ * - `allowlist`: DMs require the sender to be in the global `allowFrom`
+ * list. Distinct from `open` only when `allowFrom` is empty: `allowlist`
+ * then **fails closed** (no DMs), while `open` still lets anyone DM.
+ * - `disabled`: ignore all DMs (the sender gets a one-line system reply
+ * pointing them at @mentioning the bot in a shared channel instead)
+ */
+export function makeDmPolicyField(defaults: { policy: DmPolicy }): FieldSchema {
+ return {
+ key: 'dmPolicy',
+ default: defaults.policy,
+ description: 'channel.dmPolicyHint',
+ enum: ['open', 'allowlist', 'disabled'],
+ enumLabels: ['channel.dmPolicyOpen', 'channel.dmPolicyAllowlist', 'channel.dmPolicyDisabled'],
+ label: 'channel.dmPolicy',
+ type: 'string',
+ };
+}
+
+/**
+ * Global user-ID allowlist. Always visible — when populated, the runtime
+ * applies it to **all** inbound traffic (DM and group), independently of
+ * `dmPolicy` and `groupPolicy` mode. Empty means "no user-level filter".
+ *
+ * Tying visibility to `dmPolicy='allowlist'` was tried earlier and rejected
+ * because it forced operators who only wanted to scope group @mentions to
+ * also flip DM mode, which is misleading. Always-visible matches the
+ * field's actual semantics.
+ *
+ * Stored as `Array<{ id, name? }>` so the operator can label each entry
+ * (e.g. `name: '产品同事 Ada'`) and recognise IDs months later. The runtime
+ * only consults `id` — see {@link parseIdList} for the back-compat parser
+ * that still accepts the legacy comma-separated string and bare string[].
+ */
+export const allowFromField: FieldSchema = {
+ key: 'allowFrom',
+ default: [],
+ description: 'channel.allowFromHint',
+ label: 'channel.allowFrom',
+ type: 'array',
+ items: {
+ key: 'item',
+ label: '',
+ type: 'object',
+ properties: [
+ {
+ key: 'id',
+ label: 'channel.allowFromIdLabel',
+ placeholder: 'channel.allowFromIdPlaceholder',
+ required: true,
+ type: 'string',
+ },
+ {
+ key: 'name',
+ label: 'channel.allowFromNameLabel',
+ placeholder: 'channel.allowFromNamePlaceholder',
+ type: 'string',
+ },
+ ],
+ },
+};
+
+/**
+ * Group Policy: gate inbound non-DM traffic.
+ *
+ * - `open` (default): respond to @mentions in any group / channel / thread
+ * - `allowlist`: respond only when `thread.channelId` is in
+ * `groupAllowFrom` — what users copy via Discord "Copy Channel ID",
+ * Telegram chat ID, Slack channel ID, etc.
+ * - `disabled`: ignore all non-DM traffic
+ */
+export function makeGroupPolicyFields(defaults: { policy: GroupPolicy }): FieldSchema[] {
+ return [
+ {
+ key: 'groupPolicy',
+ default: defaults.policy,
+ description: 'channel.groupPolicyHint',
+ enum: ['open', 'allowlist', 'disabled'],
+ enumLabels: [
+ 'channel.groupPolicyOpen',
+ 'channel.groupPolicyAllowlist',
+ 'channel.groupPolicyDisabled',
+ ],
+ label: 'channel.groupPolicy',
+ type: 'string',
+ },
+ {
+ key: 'groupAllowFrom',
+ default: [],
+ description: 'channel.groupAllowFromHint',
+ label: 'channel.groupAllowFrom',
+ type: 'array',
+ items: {
+ key: 'item',
+ label: '',
+ type: 'object',
+ properties: [
+ {
+ key: 'id',
+ label: 'channel.groupAllowFromIdLabel',
+ placeholder: 'channel.groupAllowFromIdPlaceholder',
+ required: true,
+ type: 'string',
+ },
+ {
+ key: 'name',
+ label: 'channel.groupAllowFromNameLabel',
+ placeholder: 'channel.groupAllowFromNamePlaceholder',
+ type: 'string',
+ },
+ ],
+ },
+ visibleWhen: { field: 'groupPolicy', value: 'allowlist' },
+ },
+ ];
+}
+
+/**
+ * Pull the platform IDs out of an allowlist value, regardless of which
+ * historical shape it has on disk. Three shapes are all valid input:
+ *
+ * 1. `Array<{ id, name? }>` — current shape produced by the channel form,
+ * where `name` is an operator-facing label and `id` is what the runtime
+ * matches against. Only `id` is returned.
+ * 2. `string[]` — legacy shape used briefly during the dm/group policy
+ * rollout, before names existed.
+ * 3. `string` — original shape: comma / newline / whitespace-separated IDs
+ * pasted into a single text field.
+ *
+ * Empty / missing IDs are dropped. The caller (gating in `BotMessageRouter`)
+ * never sees the names — those exist purely so the operator can recognise
+ * each entry on the settings page.
+ */
+function parseIdList(raw: unknown): string[] {
+ if (typeof raw === 'string') {
+ return raw
+ .split(/[\s,]+/)
+ .map((id) => id.trim())
+ .filter(Boolean);
+ }
+ if (Array.isArray(raw)) {
+ return raw
+ .map((entry) => {
+ if (typeof entry === 'string') return entry.trim();
+ if (entry && typeof entry === 'object' && 'id' in entry) {
+ const id = (entry as { id?: unknown }).id;
+ return typeof id === 'string' ? id.trim() : '';
+ }
+ return '';
+ })
+ .filter(Boolean);
+ }
+ return [];
+}
+
+/** Read `settings.dmPolicy`. `mergeWithDefaults` injects the schema default
+ * in production; `'open'` is the safety net for malformed input. */
+export function extractDmSettings(
+ settings: Record<string, unknown> | null | undefined,
+): DmSettings {
+ const rawPolicy = settings?.dmPolicy as string | undefined;
+ const policy: DmPolicy = DM_POLICIES.has(rawPolicy as DmPolicy)
+ ? (rawPolicy as DmPolicy)
+ : 'open';
+ return { policy };
+}
+
+/**
+ * Read the global user-ID allowlist from `settings.allowFrom`.
+ *
+ * When `allowFrom` is non-empty and `settings.userId` (the operator's own
+ * platform ID, used by AI tools to push notifications back to them) is
+ * also set, that operator ID is implicitly merged in so the operator
+ * cannot accidentally lock themselves out by listing only their friends.
+ *
+ * Empty `allowFrom` short-circuits to "no filter" — populating only
+ * `userId` does **not** flip the bot into private mode, which preserves
+ * the original purpose of `userId` (AI-to-operator push) for everyone
+ * who set it before `allowFrom` existed.
+ */
+export function extractUserAllowlist(
+ settings: Record<string, unknown> | null | undefined,
+): UserAllowlist {
+ const explicit = parseIdList(settings?.allowFrom);
+ if (explicit.length === 0) return { ids: [] };
+ const operatorId = (settings?.userId as string | undefined)?.trim();
+ if (!operatorId || explicit.includes(operatorId)) return { ids: explicit };
+ return { ids: [...explicit, operatorId] };
+}
+
+/** Read `settings.groupPolicy` + `settings.groupAllowFrom`. */
+export function extractGroupSettings(
+ settings: Record<string, unknown> | null | undefined,
+): GroupSettings {
+ const rawPolicy = settings?.groupPolicy as string | undefined;
+ const policy: GroupPolicy = GROUP_POLICIES.has(rawPolicy as GroupPolicy)
+ ? (rawPolicy as GroupPolicy)
+ : 'open';
+ return { allowFrom: parseIdList(settings?.groupAllowFrom), policy };
+}
+
+/**
+ * Global user-level gate. The router applies this **before** every per-scope
+ * policy check, so a populated `allowFrom` restricts who can interact with
+ * the bot anywhere — DMs, group @mentions, threads.
+ *
+ * - Empty `allowFrom` → no filter, anyone passes.
+ * - Populated `allowFrom` → sender's user ID must be in the list. A missing
+ * `authorUserId` fails closed.
+ */
+export function shouldAllowSender(params: {
+ authorUserId: string | undefined;
+ userAllowlist: UserAllowlist;
+}): boolean {
+ const { authorUserId, userAllowlist } = params;
+ if (userAllowlist.ids.length === 0) return true;
+ if (!authorUserId) return false;
+ return userAllowlist.ids.includes(authorUserId);
+}
+
+/**
+ * Gate inbound DM handling. Non-DM threads pass through unconditionally —
+ * those are governed by `shouldHandleGroup` instead.
+ *
+ * Callers are expected to apply {@link shouldAllowSender} first, so this
+ * function only encodes the per-scope semantics:
+ *
+ * - `policy='disabled'` → block all DMs.
+ * - `policy='open'` → allow any sender (the global `allowFrom` filter, if
+ * populated, is enforced earlier by the caller).
+ * - `policy='allowlist'` → require the sender to be in the global
+ * `userAllowlist`, **and fail closed when the list is empty** (this is
+ * the only behavioural difference from `open`; `open` lets anyone DM
+ * when `allowFrom` is empty, `allowlist` does not).
+ */
+export function shouldHandleDm(params: {
+ authorUserId: string | undefined;
+ dmSettings: DmSettings;
+ isDM: boolean;
+ userAllowlist: UserAllowlist;
+}): boolean {
+ const { authorUserId, dmSettings, isDM, userAllowlist } = params;
+ if (!isDM) return true;
+ if (dmSettings.policy === 'disabled') return false;
+ if (dmSettings.policy === 'open') return true;
+ // allowlist: require non-empty list AND user in it (fail closed otherwise)
+ if (!authorUserId) return false;
+ if (userAllowlist.ids.length === 0) return false;
+ return userAllowlist.ids.includes(authorUserId);
+}
+
+/**
+ * Gate inbound group/channel handling. DM threads pass through
+ * unconditionally — those are governed by `shouldHandleDm` instead.
+ *
+ * - `policy='disabled'` → ignore everything outside DMs.
+ * - `policy='open'` → respond as before (existing @mention rules apply).
+ * - `policy='allowlist'` → match if **any** candidate channel ID is in
+ * the configured list. The list of candidates exists because some
+ * platforms surface multiple IDs for one logical surface — Discord
+ * auto-creates a reply thread for each @-mention, so the inbound
+ * `thread.channelId` is the thread, but operators paste the *parent*
+ * channel ID into the allowlist. The router asks the PlatformClient
+ * to expand the candidate list (see `extraGroupAllowlistChannels`)
+ * and we accept any match. An empty/all-falsy candidate set fails
+ * closed.
+ */
+export function shouldHandleGroup(params: {
+ candidateChannelIds: ReadonlyArray<string | undefined>;
+ groupSettings: GroupSettings;
+ isDM: boolean;
+}): boolean {
+ const { candidateChannelIds, groupSettings, isDM } = params;
+ if (isDM) return true;
+ if (groupSettings.policy === 'disabled') return false;
+ if (groupSettings.policy === 'open') return true;
+ // allowlist
+ const candidates = candidateChannelIds.filter((id): id is string => Boolean(id));
+ if (candidates.length === 0) return false;
+ return candidates.some((id) => groupSettings.allowFrom.includes(id));
+}
+
// ---------- Step-aware reactions ----------
/**
diff --git a/src/server/services/bot/platforms/discord/client.test.ts b/src/server/services/bot/platforms/discord/client.test.ts
index 57435cfe37f..acb0c28fb1f 100644
--- a/src/server/services/bot/platforms/discord/client.test.ts
+++ b/src/server/services/bot/platforms/discord/client.test.ts
@@ -34,6 +34,32 @@ describe('DiscordGatewayClient', () => {
});
});
+ describe('extraGroupAllowlistChannels', () => {
+ // Operators paste the parent channel ID (Discord "Copy Channel ID")
+ // into groupAllowFrom; @-mentions arrive routed through an auto-created
+ // reply thread, so `thread.channelId` is the thread, not the parent.
+ // This hook surfaces the parent so the allowlist still matches.
+ it('returns the parent channel ID when the thread segment is present', () => {
+ const client = createClient();
+
+ expect(
+ client.extraGroupAllowlistChannels?.('discord:guild-1:channel-1:auto-thread-id'),
+ ).toEqual(['channel-1']);
+ });
+
+ it('returns an empty list for top-level channels (parent already supplied)', () => {
+ const client = createClient();
+
+ expect(client.extraGroupAllowlistChannels?.('discord:guild-1:channel-1')).toEqual([]);
+ });
+
+ it('returns an empty list for DMs (no parent concept)', () => {
+ const client = createClient();
+
+ expect(client.extraGroupAllowlistChannels?.('discord:@me:dm-channel-1')).toEqual([]);
+ });
+ });
+
describe('extractFiles', () => {
// Discord is the easy case: attachments come with public CDN URLs that
// require no auth and survive `Message.toJSON` unchanged. extractFiles
@@ -178,4 +204,41 @@ describe('DiscordGatewayClient', () => {
expect(result).toBeUndefined();
});
});
+
+ describe('extractAuthorLocale', () => {
+ const makeMessage = (overrides: Record<string, unknown>) =>
+ ({
+ attachments: [],
+ id: 'msg-1',
+ text: '',
+ ...overrides,
+ }) as any;
+
+ it('returns the user locale from an INTERACTION_CREATE payload', () => {
+ const client = createClient();
+ expect(
+ client.extractAuthorLocale!(
+ makeMessage({ raw: { locale: 'pt-BR', guild_locale: 'en-US' } }),
+ ),
+ ).toBe('pt-BR');
+ });
+
+ it('falls back to guild_locale when the user-level field is missing', () => {
+ const client = createClient();
+ expect(client.extractAuthorLocale!(makeMessage({ raw: { guild_locale: 'zh-CN' } }))).toBe(
+ 'zh-CN',
+ );
+ });
+
+ it('returns undefined for plain MESSAGE_CREATE payloads (Discord does not expose user locale there)', () => {
+ const client = createClient();
+ expect(
+ client.extractAuthorLocale!(
+ makeMessage({ raw: { author: { id: '123', username: 'alice' } } }),
+ ),
+ ).toBeUndefined();
+ expect(client.extractAuthorLocale!(makeMessage({ raw: {} }))).toBeUndefined();
+ expect(client.extractAuthorLocale!(makeMessage({}))).toBeUndefined();
+ });
+ });
});
diff --git a/src/server/services/bot/platforms/discord/client.ts b/src/server/services/bot/platforms/discord/client.ts
index 8222b8cd481..a5c90eb903b 100644
--- a/src/server/services/bot/platforms/discord/client.ts
+++ b/src/server/services/bot/platforms/discord/client.ts
@@ -302,6 +302,40 @@ class DiscordGatewayClient implements PlatformClient {
return extractChannelId(platformThreadId);
}
+ /**
+ * Resolve the message sender's preferred Discord locale.
+ *
+ * Discord intentionally does **not** include `User.locale` in MESSAGE_CREATE
+ * Gateway events: the field is only populated by `GET /users/@me` for the
+ * authenticated user and is gated behind the `identify` OAuth2 scope. There
+ * is no member-, presence-, or guild-membership event that surfaces another
+ * user's preferred language either. So for DMs and group `@mentions` we
+ * cannot detect locale at all — the router will fall back to the channel's
+ * platform default.
+ *
+ * The two fields we *can* read both live on `INTERACTION_CREATE` payloads
+ * (slash commands, message components):
+ * - `raw.locale` — the invoking user's client locale (`pt-BR`, `zh-CN`, …)
+ * - `raw.guild_locale` — the guild's `preferred_locale`; used as a soft
+ * fallback for community guilds when the user-level field is missing
+ *
+ * Returns `undefined` outside those interaction paths so the router can
+ * apply the platform default.
+ */
+ extractAuthorLocale(message: Message): string | undefined {
+ const raw = (message as any).raw as Record<string, any> | undefined;
+ if (!raw) return undefined;
+ const interactionLocale = raw.locale;
+ if (typeof interactionLocale === 'string' && interactionLocale.length > 0) {
+ return interactionLocale;
+ }
+ const guildLocale = raw.guild_locale;
+ if (typeof guildLocale === 'string' && guildLocale.length > 0) {
+ return guildLocale;
+ }
+ return undefined;
+ }
+
formatReply(body: string, stats?: UsageStats): string {
if (!stats || !this.config.settings?.showUsageStats) return body;
return `${body}\n\n-# ${formatUsageStats(stats)}`;
@@ -325,6 +359,24 @@ class DiscordGatewayClient implements PlatformClient {
return threadId;
}
+ /**
+ * Surface the parent channel for the group allowlist. When the bot is
+ * @-mentioned in a parent channel, Discord spawns an auto-reply thread
+ * and `thread.channelId` resolves to the **thread** (segment 3 of the
+ * composite). Operators, however, paste the *parent* channel ID
+ * (segment 2 — what Discord's "Copy Channel ID" returns). Returning the
+ * parent here lets `shouldHandleGroup` accept either form.
+ */
+ extraGroupAllowlistChannels(platformThreadId: string): string[] {
+ const parts = platformThreadId.split(':');
+ // Format: discord:guildId:channelId[:discordThreadId]
+ // Only when there's a thread segment is the parent distinct from
+ // `thread.channelId` (which already maps to the thread). For
+ // top-level channels the router already supplies `parts[2]`.
+ if (parts.length === 4 && parts[2]) return [parts[2]];
+ return [];
+ }
+
sanitizeUserInput(text: string): string {
return text.replaceAll(new RegExp(`<@!?${this.applicationId}>\\s*`, 'g'), '').trim();
}
diff --git a/src/server/services/bot/platforms/discord/schema.ts b/src/server/services/bot/platforms/discord/schema.ts
index 04c85a27206..d6cf661c845 100644
--- a/src/server/services/bot/platforms/discord/schema.ts
+++ b/src/server/services/bot/platforms/discord/schema.ts
@@ -5,7 +5,14 @@ import {
MIN_BOT_HISTORY_LIMIT,
} from '@lobechat/const';
-import { displayToolCallsField, serverIdField, userIdField } from '../const';
+import {
+ allowFromField,
+ displayToolCallsField,
+ makeDmPolicyField,
+ makeGroupPolicyFields,
+ serverIdField,
+ userIdField,
+} from '../const';
import type { FieldSchema } from '../types';
import { MAX_DISCORD_HISTORY_LIMIT } from './const';
@@ -89,35 +96,9 @@ export const schema: FieldSchema[] = [
},
serverIdField,
userIdField,
- // TODO: DM schema - not implemented yet
- // {
- // key: 'dm',
- // label: 'channel.dm',
- // properties: [
- // {
- // key: 'enabled',
- // default: false,
- // description: 'channel.dmEnabledHint',
- // label: 'channel.dmEnabled',
- // type: 'boolean',
- // },
- // {
- // key: 'policy',
- // default: 'disabled',
- // enum: ['open', 'allowlist', 'disabled'],
- // enumLabels: [
- // 'channel.dmPolicyOpen',
- // 'channel.dmPolicyAllowlist',
- // 'channel.dmPolicyDisabled',
- // ],
- // description: 'channel.dmPolicyHint',
- // label: 'channel.dmPolicy',
- // type: 'string',
- // visibleWhen: { field: 'enabled', value: true },
- // },
- // ],
- // type: 'object',
- // },
+ makeDmPolicyField({ policy: 'open' }),
+ ...makeGroupPolicyFields({ policy: 'open' }),
+ allowFromField,
],
type: 'object',
},
diff --git a/src/server/services/bot/platforms/feishu/definitions/schema.ts b/src/server/services/bot/platforms/feishu/definitions/schema.ts
index 7cec9950094..218c9735ace 100644
--- a/src/server/services/bot/platforms/feishu/definitions/schema.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/schema.ts
@@ -5,7 +5,13 @@ import {
MIN_BOT_HISTORY_LIMIT,
} from '@lobechat/const';
-import { displayToolCallsField, userIdField } from '../../const';
+import {
+ allowFromField,
+ displayToolCallsField,
+ makeDmPolicyField,
+ makeGroupPolicyFields,
+ userIdField,
+} from '../../const';
import type { FieldSchema } from '../../types';
import { DEFAULT_FEISHU_CONNECTION_MODE, MAX_FEISHU_HISTORY_LIMIT } from '../const';
@@ -104,35 +110,9 @@ export const sharedSchema: FieldSchema[] = [
type: 'number',
},
userIdField,
- // TODO: DM schema - not implemented yet
- // {
- // key: 'dm',
- // label: 'channel.dm',
- // properties: [
- // {
- // key: 'enabled',
- // default: true,
- // description: 'channel.dmEnabledHint',
- // label: 'channel.dmEnabled',
- // type: 'boolean',
- // },
- // {
- // key: 'policy',
- // default: 'open',
- // enum: ['open', 'allowlist', 'disabled'],
- // enumLabels: [
- // 'channel.dmPolicyOpen',
- // 'channel.dmPolicyAllowlist',
- // 'channel.dmPolicyDisabled',
- // ],
- // description: 'channel.dmPolicyHint',
- // label: 'channel.dmPolicy',
- // type: 'string',
- // visibleWhen: { field: 'enabled', value: true },
- // },
- // ],
- // type: 'object',
- // },
+ makeDmPolicyField({ policy: 'open' }),
+ ...makeGroupPolicyFields({ policy: 'open' }),
+ allowFromField,
],
type: 'object',
},
diff --git a/src/server/services/bot/platforms/index.ts b/src/server/services/bot/platforms/index.ts
index d07f7f40709..57fa0cb519b 100644
--- a/src/server/services/bot/platforms/index.ts
+++ b/src/server/services/bot/platforms/index.ts
@@ -10,11 +10,28 @@ import { telegram } from './telegram/definition';
import { wechat } from './wechat/definition';
export {
+ allowFromField,
+ type BotReplyLocale,
displayToolCallsField,
+ type DmPolicy,
+ type DmSettings,
+ extractDmSettings,
+ extractGroupSettings,
+ extractUserAllowlist,
+ getBotReplyLocale,
getStepReactionEmoji,
+ type GroupPolicy,
+ type GroupSettings,
+ makeDmPolicyField,
+ makeGroupPolicyFields,
+ normalizeBotReplyLocale,
RECEIVED_REACTION_EMOJI,
serverIdField,
+ shouldAllowSender,
+ shouldHandleDm,
+ shouldHandleGroup,
THINKING_REACTION_EMOJI,
+ type UserAllowlist,
userIdField,
WORKING_REACTION_EMOJI,
} from './const';
diff --git a/src/server/services/bot/platforms/qq/schema.ts b/src/server/services/bot/platforms/qq/schema.ts
index aa55a9b315c..fe3e6cdcf73 100644
--- a/src/server/services/bot/platforms/qq/schema.ts
+++ b/src/server/services/bot/platforms/qq/schema.ts
@@ -1,6 +1,12 @@
import { MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';
-import { displayToolCallsField, userIdField } from '../const';
+import {
+ allowFromField,
+ displayToolCallsField,
+ makeDmPolicyField,
+ makeGroupPolicyFields,
+ userIdField,
+} from '../const';
import type { FieldSchema } from '../types';
import { DEFAULT_QQ_CONNECTION_MODE } from './const';
@@ -76,35 +82,9 @@ export const schema: FieldSchema[] = [
},
displayToolCallsField,
userIdField,
- // TODO: DM schema - not implemented yet
- // {
- // key: 'dm',
- // label: 'channel.dm',
- // properties: [
- // {
- // key: 'enabled',
- // default: true,
- // description: 'channel.dmEnabledHint',
- // label: 'channel.dmEnabled',
- // type: 'boolean',
- // },
- // {
- // key: 'policy',
- // default: 'open',
- // enum: ['open', 'allowlist', 'disabled'],
- // enumLabels: [
- // 'channel.dmPolicyOpen',
- // 'channel.dmPolicyAllowlist',
- // 'channel.dmPolicyDisabled',
- // ],
- // description: 'channel.dmPolicyHint',
- // label: 'channel.dmPolicy',
- // type: 'string',
- // visibleWhen: { field: 'enabled', value: true },
- // },
- // ],
- // type: 'object',
- // },
+ makeDmPolicyField({ policy: 'open' }),
+ ...makeGroupPolicyFields({ policy: 'open' }),
+ allowFromField,
],
type: 'object',
},
diff --git a/src/server/services/bot/platforms/slack/schema.ts b/src/server/services/bot/platforms/slack/schema.ts
index 786d45f3688..b2b2553c3d7 100644
--- a/src/server/services/bot/platforms/slack/schema.ts
+++ b/src/server/services/bot/platforms/slack/schema.ts
@@ -5,7 +5,14 @@ import {
MIN_BOT_HISTORY_LIMIT,
} from '@lobechat/const';
-import { displayToolCallsField, serverIdField, userIdField } from '../const';
+import {
+ allowFromField,
+ displayToolCallsField,
+ makeDmPolicyField,
+ makeGroupPolicyFields,
+ serverIdField,
+ userIdField,
+} from '../const';
import type { FieldSchema } from '../types';
import { DEFAULT_SLACK_CONNECTION_MODE, MAX_SLACK_HISTORY_LIMIT } from './const';
@@ -105,35 +112,9 @@ export const schema: FieldSchema[] = [
},
serverIdField,
userIdField,
- // TODO: DM schema - not implemented yet
- // {
- // key: 'dm',
- // label: 'channel.dm',
- // properties: [
- // {
- // key: 'enabled',
- // default: true,
- // description: 'channel.dmEnabledHint',
- // label: 'channel.dmEnabled',
- // type: 'boolean',
- // },
- // {
- // key: 'policy',
- // default: 'open',
- // enum: ['open', 'allowlist', 'disabled'],
- // enumLabels: [
- // 'channel.dmPolicyOpen',
- // 'channel.dmPolicyAllowlist',
- // 'channel.dmPolicyDisabled',
- // ],
- // description: 'channel.dmPolicyHint',
- // label: 'channel.dmPolicy',
- // type: 'string',
- // visibleWhen: { field: 'enabled', value: true },
- // },
- // ],
- // type: 'object',
- // },
+ makeDmPolicyField({ policy: 'open' }),
+ ...makeGroupPolicyFields({ policy: 'open' }),
+ allowFromField,
],
type: 'object',
},
diff --git a/src/server/services/bot/platforms/telegram/client.test.ts b/src/server/services/bot/platforms/telegram/client.test.ts
index d3a402950c6..28a84e4bfbe 100644
--- a/src/server/services/bot/platforms/telegram/client.test.ts
+++ b/src/server/services/bot/platforms/telegram/client.test.ts
@@ -352,3 +352,21 @@ describe('TelegramWebhookClient.extractFiles', () => {
expect(result).toBeUndefined();
});
});
+
+describe('TelegramWebhookClient.extractAuthorLocale', () => {
+ it('returns the language_code from raw.from when present', () => {
+ const client = createClient();
+ expect(
+ client.extractAuthorLocale!(makeMessage({ raw: { from: { language_code: 'pt-br' } } })),
+ ).toBe('pt-br');
+ });
+
+ it('returns undefined when raw.from is missing or has no language_code', () => {
+ const client = createClient();
+ expect(client.extractAuthorLocale!(makeMessage({ raw: {} }))).toBeUndefined();
+ expect(client.extractAuthorLocale!(makeMessage({ raw: { from: {} } }))).toBeUndefined();
+ expect(
+ client.extractAuthorLocale!(makeMessage({ raw: { from: { language_code: '' } } })),
+ ).toBeUndefined();
+ });
+});
diff --git a/src/server/services/bot/platforms/telegram/client.ts b/src/server/services/bot/platforms/telegram/client.ts
index b97edfb0b53..08a728731d2 100644
--- a/src/server/services/bot/platforms/telegram/client.ts
+++ b/src/server/services/bot/platforms/telegram/client.ts
@@ -195,6 +195,19 @@ class TelegramWebhookClient implements PlatformClient {
return extractChatId(platformThreadId);
}
+ /**
+ * Telegram exposes the sender's preferred UI language on every inbound
+ * message via `from.language_code`. Values are IETF-ish (`en`, `zh-hans`,
+ * `pt-br`, …) so the caller normalizes them against the project locale set.
+ * Returns `undefined` for service messages or anonymous senders that omit
+ * the field.
+ */
+ extractAuthorLocale(message: Message): string | undefined {
+ const raw = (message as any).raw as Record<string, any> | undefined;
+ const code = raw?.from?.language_code;
+ return typeof code === 'string' && code.length > 0 ? code : undefined;
+ }
+
async registerBotCommands(
commands: Array<{ command: string; description: string }>,
): Promise<void> {
diff --git a/src/server/services/bot/platforms/telegram/schema.ts b/src/server/services/bot/platforms/telegram/schema.ts
index c5af9446190..7b786df661a 100644
--- a/src/server/services/bot/platforms/telegram/schema.ts
+++ b/src/server/services/bot/platforms/telegram/schema.ts
@@ -1,6 +1,12 @@
import { DEFAULT_BOT_DEBOUNCE_MS, MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';
-import { displayToolCallsField, userIdField } from '../const';
+import {
+ allowFromField,
+ displayToolCallsField,
+ makeDmPolicyField,
+ makeGroupPolicyFields,
+ userIdField,
+} from '../const';
import type { FieldSchema } from '../types';
export const schema: FieldSchema[] = [
@@ -74,35 +80,9 @@ export const schema: FieldSchema[] = [
},
displayToolCallsField,
userIdField,
- // TODO: DM schema - not implemented yet
- // {
- // key: 'dm',
- // label: 'channel.dm',
- // properties: [
- // {
- // key: 'enabled',
- // default: true,
- // description: 'channel.dmEnabledHint',
- // label: 'channel.dmEnabled',
- // type: 'boolean',
- // },
- // {
- // key: 'policy',
- // default: 'open',
- // enum: ['open', 'allowlist', 'disabled'],
- // enumLabels: [
- // 'channel.dmPolicyOpen',
- // 'channel.dmPolicyAllowlist',
- // 'channel.dmPolicyDisabled',
- // ],
- // description: 'channel.dmPolicyHint',
- // label: 'channel.dmPolicy',
- // type: 'string',
- // visibleWhen: { field: 'enabled', value: true },
- // },
- // ],
- // type: 'object',
- // },
+ makeDmPolicyField({ policy: 'open' }),
+ ...makeGroupPolicyFields({ policy: 'open' }),
+ allowFromField,
],
type: 'object',
},
diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.ts
index 2a5bbbf52e4..17f31aa50fc 100644
--- a/src/server/services/bot/platforms/types.ts
+++ b/src/server/services/bot/platforms/types.ts
@@ -142,6 +142,19 @@ export interface PlatformClient {
/** Create a Chat SDK adapter config for inbound message handling. */
createAdapter: () => Record<string, any>;
+ /**
+ * Read the inbound message author's preferred language from the platform
+ * payload (e.g. Telegram's `from.language_code`, Discord's `user.locale`).
+ * Returns the raw platform string — caller is responsible for normalizing
+ * it against the project `Locales` set. Return `undefined` when the
+ * platform doesn't expose locale or the field is empty so the caller can
+ * fall back to the platform default.
+ *
+ * Optional — platforms that don't expose user locale (QQ / WeChat) omit
+ * this method.
+ */
+ extractAuthorLocale?: (message: Message) => string | undefined;
+
/** Extract the chat/channel ID from a composite platformThreadId. */
extractChatId: (platformThreadId: string) => string;
@@ -158,6 +171,23 @@ export interface PlatformClient {
*/
extractFiles?: (message: Message) => Promise<AttachmentSource[] | ExtractFilesResult | undefined>;
+ /**
+ * Surface additional channel IDs the group allowlist (`groupAllowFrom`)
+ * should match against, beyond the inbound `thread.channelId` the router
+ * already supplies.
+ *
+ * Discord auto-creates a per-mention reply thread when the bot is
+ * @-mentioned in a parent channel; the thread's ID becomes
+ * `thread.channelId`, but operators copy the **parent** channel ID into
+ * the allowlist. Without this hook the allowlist would never match for
+ * @-mentions. The hook returns the parent so either ID lets the message
+ * through.
+ *
+ * Other platforms (Telegram chat IDs, Slack channel IDs, Feishu chat IDs)
+ * have a 1:1 mapping with what the user pastes and can omit this method.
+ */
+ extraGroupAllowlistChannels?: (platformThreadId: string) => string[];
+
/**
* Transform outbound Markdown content into a format the platform can render.
* Called before `formatReply` and `splitMessage`.
diff --git a/src/server/services/bot/replyTemplate.ts b/src/server/services/bot/replyTemplate.ts
index 7a860064c54..7f14b573a69 100644
--- a/src/server/services/bot/replyTemplate.ts
+++ b/src/server/services/bot/replyTemplate.ts
@@ -1,6 +1,6 @@
import type { StepPresentationData } from '../agentRuntime/types';
import { getExtremeAck } from './ackPhrases';
-import { formatDuration } from './platforms';
+import { type BotReplyLocale, formatDuration } from './platforms';
// Use raw Unicode emoji instead of Chat SDK emoji placeholders,
// because bot-callback webhooks send via DiscordPlatformClient directly
@@ -108,12 +108,15 @@ function formatCompletedTools(
export { formatDuration, formatTokens } from './platforms';
-function renderProgressHeader(params: { elapsedMs?: number; totalToolCalls?: number }): string {
+function renderProgressHeader(
+ params: { elapsedMs?: number; totalToolCalls?: number },
+ lng?: BotReplyLocale,
+): string {
const { elapsedMs, totalToolCalls } = params;
if (!totalToolCalls || totalToolCalls <= 0) return '';
const time = elapsedMs && elapsedMs > 0 ? ` · ${formatDuration(elapsedMs)}` : '';
- return `> total **${totalToolCalls}** tools calling ${time}\n\n`;
+ return getSystemStrings(lng).toolsCallingHeader(totalToolCalls, time);
}
// ==================== 1. Start ====================
@@ -126,10 +129,10 @@ export const renderStart = getExtremeAck;
* LLM step just finished. Returns the message body (no usage stats).
* Stats are handled separately via `PlatformClient.formatReply`.
*/
-export function renderLLMGenerating(params: RenderStepParams): string {
+export function renderLLMGenerating(params: RenderStepParams, lng?: BotReplyLocale): string {
const { content, elapsedMs, lastContent, reasoning, toolsCalling, totalToolCalls } = params;
const displayContent = (content || lastContent)?.trim();
- const header = renderProgressHeader({ elapsedMs, totalToolCalls });
+ const header = renderProgressHeader({ elapsedMs, totalToolCalls }, lng);
// Sub-state: LLM decided to call tools → show content + pending tool calls (○)
if (toolsCalling && toolsCalling.length > 0) {
@@ -149,7 +152,7 @@ export function renderLLMGenerating(params: RenderStepParams): string {
return `${header}${displayContent}`;
}
- return `${header}${EMOJI_THINKING} Processing...`;
+ return `${header}${EMOJI_THINKING} ${getSystemStrings(lng).processing}`;
}
// ==================== 3. Tool Executing ====================
@@ -158,9 +161,10 @@ export function renderLLMGenerating(params: RenderStepParams): string {
* Tool step just finished, LLM is next.
* Returns the message body (no usage stats).
*/
-export function renderToolExecuting(params: RenderStepParams): string {
+export function renderToolExecuting(params: RenderStepParams, lng?: BotReplyLocale): string {
const { elapsedMs, lastContent, lastToolsCalling, toolsResult, totalToolCalls } = params;
- const header = renderProgressHeader({ elapsedMs, totalToolCalls });
+ const header = renderProgressHeader({ elapsedMs, totalToolCalls }, lng);
+ const processing = `${EMOJI_THINKING} ${getSystemStrings(lng).processing}`;
const parts: string[] = [];
@@ -170,9 +174,9 @@ export function renderToolExecuting(params: RenderStepParams): string {
if (lastToolsCalling && lastToolsCalling.length > 0) {
parts.push(formatCompletedTools(lastToolsCalling, toolsResult));
- parts.push(`${EMOJI_THINKING} Processing...`);
+ parts.push(processing);
} else {
- parts.push(`${EMOJI_THINKING} Processing...`);
+ parts.push(processing);
}
return parts.join('\n\n');
@@ -188,15 +192,165 @@ export function renderFinalReply(content: string): string {
return content.trimEnd();
}
-export function renderError(operationId?: string): string {
- if (operationId) {
- return `**Agent Execution Failed**\nOperation ID: \`${operationId}\``;
- }
- return `**Agent Execution Failed**`;
+// ==================== System message strings ====================
+
+/**
+ * Static strings emitted by the bot itself (errors, stopped notices, DM
+ * rejection). Keyed by IETF locale so it lines up with the project-wide
+ * `Locales` set; new platform languages can be added by dropping in another
+ * entry without touching the type. A missing locale falls back to `en-US`
+ * at lookup time, so we never silently render `undefined`.
+ *
+ * Agent conversation content is produced by the LLM and is not routed
+ * through this map.
+ */
+type SystemStrings = {
+ cmdNewReset: string;
+ cmdStopNotActive: string;
+ cmdStopRequested: string;
+ cmdStopUnable: string;
+ dmRejectedAllowlist: string;
+ dmRejectedDisabled: string;
+ error: string;
+ errorWithDetails: (details: string) => string;
+ errorWithId: (operationId: string) => string;
+ groupRejectedAllowlist: string;
+ groupRejectedDisabled: string;
+ inlineError: (message: string) => string;
+ processing: string;
+ /**
+ * Generic "user is not on the allowlist" copy used when the global
+ * `allowFrom` gate rejects an inbound non-DM event. Delivered via
+ * ephemeral (Slack) or as an out-of-band DM (Discord/Telegram fallback),
+ * so the wording avoids "direct messages" — the sender did not try to DM.
+ */
+ senderRejected: string;
+ stoppedDefault: string;
+ toolsCallingHeader: (count: number, time: string) => string;
+};
+
+const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {
+ 'en-US': {
+ cmdNewReset: 'Conversation reset. Your next message will start a new topic.',
+ cmdStopNotActive: 'No active execution to stop.',
+ cmdStopRequested: 'Stop requested.',
+ cmdStopUnable: 'Unable to stop the current execution.',
+ dmRejectedAllowlist:
+ "Sorry, you aren't authorized to send direct messages to this bot. Please contact the bot's owner if you need access.",
+ dmRejectedDisabled:
+ "This bot isn't accepting direct messages. Please reach out by mentioning it in a shared channel or group instead.",
+ error: '**Agent Execution Failed**',
+ errorWithDetails: (details) =>
+ `**Agent Execution Failed**. Details:\n\`\`\`\n${details}\n\`\`\``,
+ errorWithId: (operationId) => `**Agent Execution Failed**\nOperation ID: \`${operationId}\``,
+ groupRejectedAllowlist:
+ "This bot isn't enabled in this channel. Please contact the bot's owner if you need access.",
+ groupRejectedDisabled:
+ "This bot doesn't respond in groups or channels. Please reach out via direct message instead.",
+ inlineError: (message) => `**Error**: ${message}`,
+ processing: 'Processing...',
+ senderRejected:
+ "Sorry, you aren't authorized to interact with this bot. Please contact the bot's owner if you need access.",
+ stoppedDefault: 'Execution stopped.',
+ toolsCallingHeader: (count, time) => `> total **${count}** tools calling ${time}\n\n`,
+ },
+ 'zh-CN': {
+ cmdNewReset: '对话已重置,下一条消息会开启新话题。',
+ cmdStopNotActive: '当前没有正在执行的任务可以停止。',
+ cmdStopRequested: '已发出停止请求。',
+ cmdStopUnable: '无法停止当前执行。',
+ dmRejectedAllowlist: '抱歉,您没有私信该机器人的权限。如需访问请联系机器人管理员。',
+ dmRejectedDisabled: '该机器人不接受私信。请在共享频道或群组里 @它来联系。',
+ error: '**Agent 执行失败**',
+ errorWithDetails: (details) => `**Agent 执行失败**,详细信息:\n\`\`\`\n${details}\n\`\`\``,
+ errorWithId: (operationId) => `**Agent 执行失败**\nOperation ID: \`${operationId}\``,
+ groupRejectedAllowlist: '该机器人未在此频道启用。如需访问请联系机器人管理员。',
+ groupRejectedDisabled: '该机器人不在群组或频道中响应。请通过私信联系。',
+ inlineError: (message) => `**错误**:${message}`,
+ processing: '处理中…',
+ senderRejected: '抱歉,您没有与该机器人交互的权限。如需访问请联系机器人管理员。',
+ stoppedDefault: '执行已停止。',
+ toolsCallingHeader: (count, time) => `> 共 **${count}** 次工具调用 ${time}\n\n`,
+ },
+};
+
+const DEFAULT_REPLY_LOCALE: BotReplyLocale = 'en-US';
+
+const getSystemStrings = (lng: BotReplyLocale = DEFAULT_REPLY_LOCALE): SystemStrings =>
+ SYSTEM_STRINGS[lng] ?? SYSTEM_STRINGS[DEFAULT_REPLY_LOCALE]!;
+
+export function renderError(operationId?: string, lng?: BotReplyLocale): string {
+ const strings = getSystemStrings(lng);
+ return operationId ? strings.errorWithId(operationId) : strings.error;
+}
+
+export function renderStopped(message?: string, lng?: BotReplyLocale): string {
+ return message ?? getSystemStrings(lng).stoppedDefault;
+}
+
+/**
+ * Verbose error template used when we want to surface the underlying error
+ * message verbatim (typically for stale-topic or FK violations where the raw
+ * detail helps the operator diagnose the failure).
+ */
+export function renderErrorWithDetails(details: string, lng?: BotReplyLocale): string {
+ return getSystemStrings(lng).errorWithDetails(details);
+}
+
+/**
+ * Compact `**Error**: …` line used as a last-resort handler-level fallback
+ * when an unexpected exception escapes the bridge / catch-all path.
+ */
+export function renderInlineError(message: string, lng?: BotReplyLocale): string {
+ return getSystemStrings(lng).inlineError(message);
}
-export function renderStopped(message = 'Execution stopped.'): string {
- return message;
+export type CommandReplyKey =
+ | 'cmdNewReset'
+ | 'cmdStopNotActive'
+ | 'cmdStopRequested'
+ | 'cmdStopUnable';
+
+/**
+ * Render a slash-command response (e.g. `/new`, `/stop`). Centralized so the
+ * command handlers don't each carry their own English literal.
+ */
+export function renderCommandReply(key: CommandReplyKey, lng?: BotReplyLocale): string {
+ return getSystemStrings(lng)[key];
+}
+
+/**
+ * Render the system message shown to a sender whose DM was blocked by the
+ * channel's DM Policy. We split disabled vs allowlist so the user can act on
+ * the answer (e.g. ping in a channel instead, or ask the owner for access).
+ */
+export function renderDmRejected(reason: 'disabled' | 'allowlist', lng?: BotReplyLocale): string {
+ const strings = getSystemStrings(lng);
+ return reason === 'disabled' ? strings.dmRejectedDisabled : strings.dmRejectedAllowlist;
+}
+
+/**
+ * Render the system message shown when an inbound non-DM event was blocked
+ * by Group Policy. Same disabled-vs-allowlist split as
+ * {@link renderDmRejected} so the sender can pivot (try DM, ask the owner).
+ */
+export function renderGroupRejected(
+ reason: 'disabled' | 'allowlist',
+ lng?: BotReplyLocale,
+): string {
+ const strings = getSystemStrings(lng);
+ return reason === 'disabled' ? strings.groupRejectedDisabled : strings.groupRejectedAllowlist;
+}
+
+/**
+ * Render the system message shown when the **global `allowFrom`** gate
+ * rejected the sender of a non-DM event (group / channel / thread). The
+ * notice is delivered out-of-band — ephemerally on Slack, via DM fallback
+ * on Discord/Telegram — so the copy intentionally avoids "direct messages"
+ * (the sender did not try to DM, they @-mentioned in a group).
+ */
+export function renderSenderRejected(lng?: BotReplyLocale): string {
+ return getSystemStrings(lng).senderRejected;
}
// ==================== Dispatcher ====================
@@ -205,9 +359,9 @@ export function renderStopped(message = 'Execution stopped.'): string {
* Dispatch to the correct template based on step state.
* Returns message body only — caller handles stats via platform.
*/
-export function renderStepProgress(params: RenderStepParams): string {
+export function renderStepProgress(params: RenderStepParams, lng?: BotReplyLocale): string {
if (params.stepType === 'call_llm') {
- return renderLLMGenerating(params);
+ return renderLLMGenerating(params, lng);
}
- return renderToolExecuting(params);
+ return renderToolExecuting(params, lng);
}