Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(webui): improve setup flows across chat channels (NAN-112) (#5356)
chengyongrue8a29a00870c
diff --git a/nanobot/channels/contracts.py b/nanobot/channels/contracts.pyindex 75bb4a0db..0b9319a56 100644--- a/nanobot/channels/contracts.py+++ b/nanobot/channels/contracts.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonfrom collections.abc import Iterablefrom copy import deepcopyfrom dataclasses import dataclass@@ -11,7 +12,7 @@ from typing import TYPE_CHECKING, Any, Callable, Literal, TypeGuard, castif TYPE_CHECKING:from nanobot.channels.plugin import ChannelPlugin-FieldKind = Literal["string", "secret", "list", "bool", "int", "enum"]+FieldKind = Literal["string", "secret", "list", "bool", "int", "float", "json", "enum"]RouteFieldType = str | tuple[str, set[str]]@@ -162,6 +163,7 @@ class ChannelSetupSpec:required: tuple[SetupRequirement, ...] = ()official_url: str | None = Nonevalidator: SetupValidator | None = None+ verifies_connection: bool = False@propertydef secrets(self) -> frozenset[str]:@@ -211,9 +213,20 @@ class ChannelSetupSpec:fields.append(public_field)payload: dict[str, Any] = {"fields": fields,+ "requirements": [+ {+ "alternatives": [+ [f"channels.{channel_name}.{name}" for name in alternative]+ for alternative in requirement.alternatives+ ]+ }+ for requirement in self.required+ ],}if self.official_url:payload["official_url"] = self.official_url+ if self.verifies_connection:+ payload["verifies_connection"] = Truereturn payload@@ -572,6 +585,8 @@ def stringify_channel_value(value: Any) -> str:return "true" if value else "false"if isinstance(value, list):return ", ".join(str(item) for item in cast(list[Any], value))+ if isinstance(value, dict):+ return json.dumps(value, ensure_ascii=False, indent=2)return str(value)diff --git a/nanobot/channels/dingtalk/manifest.py b/nanobot/channels/dingtalk/manifest.pyindex 767d5497d..21faf504d 100644--- a/nanobot/channels/dingtalk/manifest.py+++ b/nanobot/channels/dingtalk/manifest.py@@ -9,6 +9,10 @@ SETUP_SPEC = ChannelSetupSpec("clientId": field(),"clientSecret": field("secret"),"allowFrom": field("list"),+ "allowRemoteMediaRedirects": field("bool", default=False),+ "remoteMediaRedirectAllowedHosts": field("list"),+ "groupUserIsolation": field("bool", default=False),+ "disablePrivateChat": field("bool", default=False),},required=required_fields("clientId", "clientSecret"),official_url="https://open.dingtalk.com/",diff --git a/nanobot/channels/dingtalk/webui/index.ts b/nanobot/channels/dingtalk/webui/index.tsindex ab352ee94..26a02e23d 100644--- a/nanobot/channels/dingtalk/webui/index.ts+++ b/nanobot/channels/dingtalk/webui/index.ts@@ -3,18 +3,17 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://img.alicdn.com/imgextra/i3/O1CN01WMvMRG1ks3Ixc9x1v_!!6000000004738-55-tps-32-32.svg",displayName: "DingTalk",initials: "DT",color: "#1677FF",- logoUrl:- "https://img.alicdn.com/imgextra/i3/O1CN01WMvMRG1ks3Ixc9x1v_!!6000000004738-55-tps-32-32.svg",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("dingtalk"),fields: [- { key: "channels.dingtalk.clientId" },- { key: "channels.dingtalk.clientSecret" },- { key: "channels.dingtalk.allowFrom" },+ { key: "channels.dingtalk.clientId", section: "credentials" },+ { key: "channels.dingtalk.clientSecret", section: "credentials" },+ { key: "channels.dingtalk.allowFrom", section: "access" },],},},diff --git a/nanobot/channels/dingtalk/webui/locales/en.json b/nanobot/channels/dingtalk/webui/locales/en.jsonindex 9dcfd66da..82405ab39 100644--- a/nanobot/channels/dingtalk/webui/locales/en.json+++ b/nanobot/channels/dingtalk/webui/locales/en.json@@ -1,30 +1,43 @@{- "description": "Use nanobot from DingTalk groups.",- "requirements": "DingTalk app credentials and gateway","setup": {"docsLabel": "Open DingTalk setup","officialLabel": "Open DingTalk console",- "tryIt": "Send a test message from the DingTalk group where the app is installed.",- "summary": "DingTalk needs app credentials from Stream mode.",- "steps": [- "Create or choose a DingTalk app with Stream mode enabled.",- "Add Client ID and Client Secret.",- "Save and enable DingTalk, then send a test message."- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "DingTalk client ID",- "help": "Copy it from DingTalk app credentials."+ "placeholder": "DingTalk client ID"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "Copy it from the same DingTalk app credentials page."+ "placeholder": "••••••"},"allowFrom": {"label": "Allowed users","placeholder": "User IDs, comma separated"+ },+ "allowRemoteMediaRedirects": {+ "label": "Allow media redirects",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "Media redirect hosts"+ },+ "groupUserIsolation": {+ "label": "Separate group sessions",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "disablePrivateChat": {+ "label": "Disable direct messages",+ "choices": {+ "true": "On",+ "false": "Off"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/es.json b/nanobot/channels/dingtalk/webui/locales/es.jsonindex 7d411699c..edcc0eb85 100644--- a/nanobot/channels/dingtalk/webui/locales/es.json+++ b/nanobot/channels/dingtalk/webui/locales/es.json@@ -1,30 +1,43 @@{- "description": "Usa nanobot desde grupos de DingTalk.",- "requirements": "Credenciales de la app de DingTalk y pasarela","setup": {"docsLabel": "Abrir guía de DingTalk","officialLabel": "Abrir consola de DingTalk",- "tryIt": "Envía un mensaje de prueba desde el grupo de DingTalk donde está instalada la app.",- "summary": "DingTalk necesita credenciales de una app en modo Stream.",- "steps": [- "Crea o elige una app de DingTalk con el modo Stream activado.",- "Añade el Client ID y el Client Secret.",- "Guarda y activa DingTalk; después envía un mensaje de prueba."- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "Client ID de DingTalk",- "help": "Cópialo de las credenciales de la app de DingTalk."+ "placeholder": "Client ID de DingTalk"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "Cópialo de la misma página de credenciales."+ "placeholder": "••••••"},"allowFrom": {"label": "Usuarios permitidos","placeholder": "ID de usuario separados por comas"+ },+ "allowRemoteMediaRedirects": {+ "label": "Permitir redirecciones de medios",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "Hosts de redireccionamiento de medios"+ },+ "groupUserIsolation": {+ "label": "Sesiones grupales separadas",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "disablePrivateChat": {+ "label": "Desactivar mensajes directos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/fr.json b/nanobot/channels/dingtalk/webui/locales/fr.jsonindex d0eb8fa51..ec5b162d2 100644--- a/nanobot/channels/dingtalk/webui/locales/fr.json+++ b/nanobot/channels/dingtalk/webui/locales/fr.json@@ -1,30 +1,43 @@{- "description": "Utilisez nanobot depuis les groupes DingTalk.",- "requirements": "Identifiants d’application DingTalk et passerelle","setup": {"docsLabel": "Ouvrir le guide DingTalk","officialLabel": "Ouvrir la console DingTalk",- "tryIt": "Envoyez un message test dans le groupe DingTalk où l’application est installée.",- "summary": "DingTalk nécessite les identifiants d’une application en mode Stream.",- "steps": [- "Créez ou choisissez une application DingTalk avec le mode Stream activé.",- "Ajoutez le Client ID et le Client Secret.",- "Enregistrez et activez DingTalk, puis envoyez un message test."- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "Client ID DingTalk",- "help": "Copiez-le depuis les identifiants de l’application DingTalk."+ "placeholder": "Client ID DingTalk"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "Copiez-le depuis la même page d’identifiants DingTalk."+ "placeholder": "••••••"},"allowFrom": {"label": "Utilisateurs autorisés","placeholder": "ID utilisateur séparés par des virgules"+ },+ "allowRemoteMediaRedirects": {+ "label": "Autoriser les redirections multimédias",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "Hôtes de redirection multimédia"+ },+ "groupUserIsolation": {+ "label": "Séances de groupe séparées",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "disablePrivateChat": {+ "label": "Désactiver les messages directs",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/id.json b/nanobot/channels/dingtalk/webui/locales/id.jsonindex c4728d003..38bb612e2 100644--- a/nanobot/channels/dingtalk/webui/locales/id.json+++ b/nanobot/channels/dingtalk/webui/locales/id.json@@ -1,30 +1,43 @@{- "description": "Gunakan nanobot dari grup DingTalk.",- "requirements": "Kredensial aplikasi DingTalk dan gateway","setup": {"docsLabel": "Buka panduan DingTalk","officialLabel": "Buka konsol DingTalk",- "tryIt": "Kirim pesan uji dari grup DingTalk tempat aplikasi dipasang.",- "summary": "DingTalk memerlukan kredensial aplikasi dari mode Stream.",- "steps": [- "Buat atau pilih aplikasi DingTalk dengan mode Stream aktif.",- "Tambahkan Client ID dan Client Secret.",- "Simpan dan aktifkan DingTalk, lalu kirim pesan uji."- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "Client ID DingTalk",- "help": "Salin dari kredensial aplikasi DingTalk."+ "placeholder": "Client ID DingTalk"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "Salin dari halaman kredensial yang sama."+ "placeholder": "••••••"},"allowFrom": {"label": "Pengguna yang diizinkan","placeholder": "ID pengguna, dipisahkan koma"+ },+ "allowRemoteMediaRedirects": {+ "label": "Izinkan pengalihan media",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "Host pengalihan media"+ },+ "groupUserIsolation": {+ "label": "Sesi kelompok terpisah",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "disablePrivateChat": {+ "label": "Nonaktifkan pesan langsung",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/ja.json b/nanobot/channels/dingtalk/webui/locales/ja.jsonindex 3ffbd5d1c..8bf27f0d0 100644--- a/nanobot/channels/dingtalk/webui/locales/ja.json+++ b/nanobot/channels/dingtalk/webui/locales/ja.json@@ -1,30 +1,43 @@{- "description": "DingTalk グループから nanobot を利用します。",- "requirements": "DingTalk アプリの認証情報とゲートウェイ","setup": {"docsLabel": "DingTalk 設定ガイドを開く","officialLabel": "DingTalk コンソールを開く",- "tryIt": "アプリをインストールした DingTalk グループからテストメッセージを送信します。",- "summary": "DingTalk には Stream モードのアプリ認証情報が必要です。",- "steps": [- "Stream モードを有効にした DingTalk アプリを作成または選択します。",- "Client ID と Client Secret を追加します。",- "保存して DingTalk を有効にし、テストメッセージを送信します。"- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "DingTalk Client ID",- "help": "DingTalk アプリの認証情報からコピーします。"+ "placeholder": "DingTalk Client ID"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "同じ認証情報ページからコピーします。"+ "placeholder": "••••••"},"allowFrom": {"label": "許可するユーザー","placeholder": "ユーザー ID(カンマ区切り)"+ },+ "allowRemoteMediaRedirects": {+ "label": "メディアのリダイレクトを許可する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "メディアリダイレクトホスト"+ },+ "groupUserIsolation": {+ "label": "個別のグループセッション",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "disablePrivateChat": {+ "label": "ダイレクトメッセージを無効にする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/ko.json b/nanobot/channels/dingtalk/webui/locales/ko.jsonindex ccc7eb5a5..e754728d6 100644--- a/nanobot/channels/dingtalk/webui/locales/ko.json+++ b/nanobot/channels/dingtalk/webui/locales/ko.json@@ -1,30 +1,43 @@{- "description": "DingTalk 그룹에서 nanobot을 사용합니다.",- "requirements": "DingTalk 앱 인증 정보 및 게이트웨이","setup": {"docsLabel": "DingTalk 설정 가이드 열기","officialLabel": "DingTalk 콘솔 열기",- "tryIt": "앱이 설치된 DingTalk 그룹에서 테스트 메시지를 보내세요.",- "summary": "DingTalk에는 Stream 모드 앱 인증 정보이 필요합니다.",- "steps": [- "Stream 모드가 활성화된 DingTalk 앱을 만들거나 선택하세요.",- "Client ID와 Client Secret을 추가하세요.",- "저장하고 DingTalk을 활성화한 다음 테스트 메시지를 보내세요."- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "DingTalk Client ID",- "help": "DingTalk 앱 인증 정보에서 복사하세요."+ "placeholder": "DingTalk Client ID"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "같은 인증 정보 페이지에서 복사하세요."+ "placeholder": "••••••"},"allowFrom": {"label": "허용된 사용자","placeholder": "사용자 ID, 쉼표로 구분"+ },+ "allowRemoteMediaRedirects": {+ "label": "미디어 리디렉션 허용",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "미디어 리디렉션 호스트"+ },+ "groupUserIsolation": {+ "label": "별도의 그룹 세션",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "disablePrivateChat": {+ "label": "다이렉트 메시지 비활성화",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/pt-BR.json b/nanobot/channels/dingtalk/webui/locales/pt-BR.jsonindex 9dbca3735..545ee3eaf 100644--- a/nanobot/channels/dingtalk/webui/locales/pt-BR.json+++ b/nanobot/channels/dingtalk/webui/locales/pt-BR.json@@ -1,30 +1,43 @@{- "description": "Use o nanobot em grupos do DingTalk.",- "requirements": "Credenciais do app DingTalk e gateway","setup": {"docsLabel": "Abrir guia do DingTalk","officialLabel": "Abrir console do DingTalk",- "tryIt": "Envie uma mensagem de teste no grupo do DingTalk onde o app está instalado.",- "summary": "O DingTalk precisa das credenciais de um app no modo Stream.",- "steps": [- "Crie ou escolha um app do DingTalk com o modo Stream ativado.",- "Adicione o Client ID e o Client Secret.",- "Salve e ative o DingTalk; depois, envie uma mensagem de teste."- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "Client ID do DingTalk",- "help": "Copie das credenciais do app DingTalk."+ "placeholder": "Client ID do DingTalk"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "Copie da mesma página de credenciais."+ "placeholder": "••••••"},"allowFrom": {"label": "Usuários permitidos","placeholder": "IDs de usuário separados por vírgulas"+ },+ "allowRemoteMediaRedirects": {+ "label": "Permitir redirecionamentos de mídia",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "Hosts de redirecionamento de mídia"+ },+ "groupUserIsolation": {+ "label": "Sessões de grupo separadas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "disablePrivateChat": {+ "label": "Desativar mensagens diretas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/vi.json b/nanobot/channels/dingtalk/webui/locales/vi.jsonindex d0616d0a7..b71da5533 100644--- a/nanobot/channels/dingtalk/webui/locales/vi.json+++ b/nanobot/channels/dingtalk/webui/locales/vi.json@@ -1,30 +1,43 @@{- "description": "Sử dụng nanobot trong các nhóm DingTalk.",- "requirements": "Thông tin xác thực ứng dụng DingTalk và gateway","setup": {"docsLabel": "Mở hướng dẫn DingTalk","officialLabel": "Mở bảng điều khiển DingTalk",- "tryIt": "Gửi tin nhắn thử từ nhóm DingTalk đã cài ứng dụng.",- "summary": "DingTalk cần thông tin xác thực ứng dụng ở chế độ Stream.",- "steps": [- "Tạo hoặc chọn ứng dụng DingTalk đã bật chế độ Stream.",- "Thêm Client ID và Client Secret.",- "Lưu và bật DingTalk, sau đó gửi tin nhắn thử."- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "Client ID DingTalk",- "help": "Sao chép từ thông tin xác thực ứng dụng DingTalk."+ "placeholder": "Client ID DingTalk"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "Sao chép từ cùng trang thông tin xác thực."+ "placeholder": "••••••"},"allowFrom": {"label": "Người dùng được phép","placeholder": "ID người dùng, phân tách bằng dấu phẩy"+ },+ "allowRemoteMediaRedirects": {+ "label": "Cho phép chuyển hướng phương tiện",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "Máy chủ chuyển hướng phương tiện"+ },+ "groupUserIsolation": {+ "label": "Các buổi nhóm riêng biệt",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "disablePrivateChat": {+ "label": "Tắt tin nhắn trực tiếp",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/zh-CN.json b/nanobot/channels/dingtalk/webui/locales/zh-CN.jsonindex b80ad7b86..04c0cfcbf 100644--- a/nanobot/channels/dingtalk/webui/locales/zh-CN.json+++ b/nanobot/channels/dingtalk/webui/locales/zh-CN.json@@ -1,31 +1,44 @@{"displayName": "钉钉",- "description": "在钉钉群中使用 nanobot。",- "requirements": "钉钉应用凭据和网关","setup": {"docsLabel": "打开钉钉配置指南","officialLabel": "打开钉钉开发者后台",- "tryIt": "在已安装应用的钉钉群中发送一条测试消息。",- "summary": "钉钉需要 Stream 模式的应用凭据。",- "steps": [- "创建或选择一个已启用 Stream 模式的钉钉应用。",- "填写 Client ID 和 Client Secret。",- "保存并启用钉钉,然后发送一条测试消息。"- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "钉钉 Client ID",- "help": "从钉钉应用凭据页面复制。"+ "placeholder": "钉钉 Client ID"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "从同一个钉钉应用凭据页面复制。"+ "placeholder": "••••••"},"allowFrom": {"label": "允许的用户","placeholder": "用户 ID,用逗号分隔"+ },+ "allowRemoteMediaRedirects": {+ "label": "允许媒体重定向",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "允许重定向的媒体主机"+ },+ "groupUserIsolation": {+ "label": "按群成员隔离会话",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "disablePrivateChat": {+ "label": "禁用私聊",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }}}}diff --git a/nanobot/channels/dingtalk/webui/locales/zh-TW.json b/nanobot/channels/dingtalk/webui/locales/zh-TW.jsonindex 2ce8a1c6e..df60ca07d 100644--- a/nanobot/channels/dingtalk/webui/locales/zh-TW.json+++ b/nanobot/channels/dingtalk/webui/locales/zh-TW.json@@ -1,31 +1,44 @@{"displayName": "釘釘",- "description": "在釘釘群組中使用 nanobot。",- "requirements": "釘釘應用程式憑證和閘道","setup": {"docsLabel": "開啟釘釘設定指南","officialLabel": "開啟釘釘開發者後台",- "tryIt": "在已安裝應用程式的釘釘群組中傳送一則測試訊息。",- "summary": "釘釘需要 Stream 模式的應用程式憑證。",- "steps": [- "建立或選擇一個已啟用 Stream 模式的釘釘應用程式。",- "填入 Client ID 和 Client Secret。",- "儲存並啟用釘釘,然後傳送一則測試訊息。"- ],"fields": {"clientId": {"label": "Client ID",- "placeholder": "釘釘 Client ID",- "help": "從釘釘應用程式憑證頁面複製。"+ "placeholder": "釘釘 Client ID"},"clientSecret": {"label": "Client Secret",- "placeholder": "••••••",- "help": "從同一個釘釘應用程式憑證頁面複製。"+ "placeholder": "••••••"},"allowFrom": {"label": "允許的使用者","placeholder": "使用者 ID,以逗號分隔"+ },+ "allowRemoteMediaRedirects": {+ "label": "允許媒體重定向",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "remoteMediaRedirectAllowedHosts": {+ "label": "允許重定向的媒體主機"+ },+ "groupUserIsolation": {+ "label": "按群組成員隔離會話",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "disablePrivateChat": {+ "label": "停用私聊",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }}}}diff --git a/nanobot/channels/discord/manifest.py b/nanobot/channels/discord/manifest.pyindex 8c6a1ab3e..f398ffe10 100644--- a/nanobot/channels/discord/manifest.py+++ b/nanobot/channels/discord/manifest.py@@ -8,13 +8,22 @@ from nanobot.channels.plugin import ChannelPluginSETUP_SPEC = ChannelSetupSpec(fields={"token": field("secret"),+ "proxy": field(),+ "proxyUsername": field(),+ "proxyPassword": field("secret"),"allowFrom": field("list", snapshot=False),"allowChannels": field("list"),"groupPolicy": field("enum", choices=DIRECT_GROUP_POLICIES, default="mention"),+ "intents": field("int", default=37377),+ "readReceiptEmoji": field(default="👀"),+ "workingEmoji": field(default="🔧"),+ "workingEmojiDelay": field("float", default=2.0),+ "streaming": field("bool", default=True),},required=(required("token"),),official_url="https://discord.com/developers/applications",validator=validate,+ verifies_connection=True,)PLUGIN = ChannelPlugin(diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.pyindex 38dcce695..71083d62f 100644--- a/nanobot/channels/discord/runtime.py+++ b/nanobot/channels/discord/runtime.py@@ -464,10 +464,13 @@ class DiscordChannel(BaseChannel):"proxy_password must be set; ignoring partial credentials",)+ proxy = self.config.proxy+ if proxy and "://" not in proxy:+ proxy = f"http://{proxy}"self._client = DiscordBotClient(self,intents=intents,- proxy=self.config.proxy,+ proxy=proxy,proxy_auth=proxy_auth,)except Exception:diff --git a/nanobot/channels/discord/validation.py b/nanobot/channels/discord/validation.pyindex 6b24e8936..6fb1025ee 100644--- a/nanobot/channels/discord/validation.py+++ b/nanobot/channels/discord/validation.py@@ -18,11 +18,13 @@ from nanobot.channels.validation import (def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:checks, missing = required_checks("discord", values)token = string_value(values.get("token"))+ proxy = string_value(values.get("proxy"))if token:try:data = http_get("https://discord.com/api/v10/users/@me",headers={"Authorization": f"Bot {token}"},+ proxy=proxy or None,)bot_id = str(data.get("id") or "")checks.append(check("bot_token", "Bot token", "pass", "Discord accepted the bot token."))diff --git a/nanobot/channels/discord/webui/index.ts b/nanobot/channels/discord/webui/index.tsindex b6e58715e..f59324dee 100644--- a/nanobot/channels/discord/webui/index.ts+++ b/nanobot/channels/discord/webui/index.ts@@ -3,17 +3,21 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://discord.com/favicon.ico",displayName: "Discord",initials: "DC",color: "#5865F2",- logoUrl: "https://discord.com/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("discord"),fields: [- { key: "channels.discord.token" },- { key: "channels.discord.allowChannels" },- { key: "channels.discord.groupPolicy" },+ { key: "channels.discord.token", section: "credentials" },+ { key: "channels.discord.proxy", section: "connection" },+ { key: "channels.discord.proxyUsername", section: "connection" },+ { key: "channels.discord.proxyPassword", section: "connection" },+ { key: "channels.discord.allowFrom", section: "access" },+ { key: "channels.discord.allowChannels", section: "access" },+ { key: "channels.discord.groupPolicy", section: "behavior" },],},},diff --git a/nanobot/channels/discord/webui/locales/en.json b/nanobot/channels/discord/webui/locales/en.jsonindex e3ab140a1..a72a33564 100644--- a/nanobot/channels/discord/webui/locales/en.json+++ b/nanobot/channels/discord/webui/locales/en.json@@ -1,26 +1,15 @@{- "description": "Use nanobot from Discord servers and DMs.",- "requirements": "Discord bot token, permissions, gateway","setup": {"docsLabel": "Open Discord setup","officialLabel": "Open Discord portal",- "tryIt": "Mention the bot in a server or send it a direct message.",- "summary": "Connecting Discord requires a bot token and the appropriate server permissions.",- "steps": [- "Create a bot in Discord Developer Portal and copy its token.",- "Invite the bot to your server with message read/send and slash command permissions.",- "Save and enable Discord, then mention the bot or send a direct message."- ],"fields": {"token": {"label": "Bot token",- "placeholder": "Discord bot token",- "help": "Create it from the Bot page in Discord Developer Portal."+ "placeholder": "Discord bot token"},"allowChannels": {"label": "Allowed channels",- "placeholder": "Channel IDs, comma separated",- "help": "Leave empty to allow any channel the bot can read."+ "placeholder": "Channel IDs, comma separated"},"groupPolicy": {"label": "Group behavior",@@ -33,6 +22,34 @@"allowFrom": {"label": "Allowed users","placeholder": "User IDs, comma separated"+ },+ "proxy": {+ "label": "Network proxy"+ },+ "proxyUsername": {+ "label": "Proxy username"+ },+ "proxyPassword": {+ "label": "Proxy password"+ },+ "intents": {+ "label": "Gateway intents"+ },+ "readReceiptEmoji": {+ "label": "Read emoji"+ },+ "workingEmoji": {+ "label": "Working emoji"+ },+ "workingEmojiDelay": {+ "label": "Working emoji delay"+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "On",+ "false": "Off"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/es.json b/nanobot/channels/discord/webui/locales/es.jsonindex c22ee5ae3..d59e479de 100644--- a/nanobot/channels/discord/webui/locales/es.json+++ b/nanobot/channels/discord/webui/locales/es.json@@ -1,26 +1,15 @@{- "description": "Usa nanobot en servidores y mensajes directos de Discord.",- "requirements": "Token del bot de Discord, permisos y pasarela","setup": {"docsLabel": "Abrir guía de Discord","officialLabel": "Abrir portal de Discord",- "tryIt": "Menciona al bot en un servidor o envíale un mensaje directo.",- "summary": "Para conectar Discord necesitas un token de bot y los permisos adecuados en el servidor.",- "steps": [- "Crea un bot en Discord Developer Portal y copia su token.",- "Invítalo al servidor con permisos para leer/enviar mensajes y usar comandos slash.",- "Guarda y activa Discord; después menciona al bot o envíale un mensaje directo."- ],"fields": {"token": {"label": "Token del bot",- "placeholder": "Token del bot de Discord",- "help": "Créalo desde la página Bot de Discord Developer Portal."+ "placeholder": "Token del bot de Discord"},"allowChannels": {"label": "Canales permitidos",- "placeholder": "ID de canal separados por comas",- "help": "Déjalo vacío para permitir cualquier canal que el bot pueda leer."+ "placeholder": "ID de canal separados por comas"},"groupPolicy": {"label": "Comportamiento en grupos",@@ -33,6 +22,34 @@"allowFrom": {"label": "Usuarios permitidos","placeholder": "ID de usuario separados por comas"+ },+ "proxy": {+ "label": "proxy de red"+ },+ "proxyUsername": {+ "label": "Nombre de usuario proxy"+ },+ "proxyPassword": {+ "label": "Contraseña de proxy"+ },+ "intents": {+ "label": "Intentos de puerta de enlace"+ },+ "readReceiptEmoji": {+ "label": "Leer emojis"+ },+ "workingEmoji": {+ "label": "Emoji de trabajo"+ },+ "workingEmojiDelay": {+ "label": "Retraso de emoji de trabajo"+ },+ "streaming": {+ "label": "Transmisión",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/fr.json b/nanobot/channels/discord/webui/locales/fr.jsonindex b0462580a..0cc69e573 100644--- a/nanobot/channels/discord/webui/locales/fr.json+++ b/nanobot/channels/discord/webui/locales/fr.json@@ -1,26 +1,15 @@{- "description": "Utilisez nanobot sur les serveurs Discord et en messages privés.",- "requirements": "Jeton du bot Discord, permissions et passerelle","setup": {"docsLabel": "Ouvrir le guide Discord","officialLabel": "Ouvrir le portail Discord",- "tryIt": "Mentionnez le bot sur un serveur ou envoyez-lui un message privé.",- "summary": "La connexion à Discord nécessite un jeton de bot et les permissions appropriées sur le serveur.",- "steps": [- "Créez un bot dans le portail développeur Discord et copiez son jeton.",- "Invitez-le sur votre serveur avec les permissions de lecture, d’envoi et de commandes slash.",- "Enregistrez et activez Discord, puis mentionnez le bot ou envoyez-lui un message privé."- ],"fields": {"token": {"label": "Jeton du bot",- "placeholder": "Jeton du bot Discord",- "help": "Créez-le depuis la page Bot du portail développeur Discord."+ "placeholder": "Jeton du bot Discord"},"allowChannels": {"label": "Salons autorisés",- "placeholder": "ID de salon séparés par des virgules",- "help": "Laissez vide pour autoriser tous les salons lisibles par le bot."+ "placeholder": "ID de salon séparés par des virgules"},"groupPolicy": {"label": "Comportement en groupe",@@ -33,6 +22,34 @@"allowFrom": {"label": "Utilisateurs autorisés","placeholder": "ID utilisateur séparés par des virgules"+ },+ "proxy": {+ "label": "Mandataire réseau"+ },+ "proxyUsername": {+ "label": "Nom d'utilisateur du proxy"+ },+ "proxyPassword": {+ "label": "Mot de passe proxy"+ },+ "intents": {+ "label": "Intentions de passerelle"+ },+ "readReceiptEmoji": {+ "label": "Lire les emoji"+ },+ "workingEmoji": {+ "label": "Emoji fonctionnel"+ },+ "workingEmojiDelay": {+ "label": "Retard d'emoji fonctionnel"+ },+ "streaming": {+ "label": "Diffusion en continu",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/id.json b/nanobot/channels/discord/webui/locales/id.jsonindex 91c194526..a251732a5 100644--- a/nanobot/channels/discord/webui/locales/id.json+++ b/nanobot/channels/discord/webui/locales/id.json@@ -1,26 +1,15 @@{- "description": "Gunakan nanobot dari server dan DM Discord.",- "requirements": "Token bot Discord, izin, dan gateway","setup": {"docsLabel": "Buka panduan Discord","officialLabel": "Buka portal Discord",- "tryIt": "Sebut bot di server atau kirim pesan langsung.",- "summary": "Untuk menghubungkan Discord, Anda memerlukan token bot dan izin yang sesuai di server.",- "steps": [- "Buat bot di Discord Developer Portal dan salin tokennya.",- "Undang bot ke server dengan izin baca/kirim pesan dan perintah slash.",- "Simpan dan aktifkan Discord, lalu sebut bot atau kirim DM."- ],"fields": {"token": {"label": "Token bot",- "placeholder": "Token bot Discord",- "help": "Buat dari halaman Bot di Discord Developer Portal."+ "placeholder": "Token bot Discord"},"allowChannels": {"label": "Kanal yang diizinkan",- "placeholder": "ID kanal, dipisahkan koma",- "help": "Kosongkan untuk mengizinkan semua kanal yang dapat dibaca bot."+ "placeholder": "ID kanal, dipisahkan koma"},"groupPolicy": {"label": "Perilaku grup",@@ -33,6 +22,34 @@"allowFrom": {"label": "Pengguna yang diizinkan","placeholder": "ID pengguna, dipisahkan koma"+ },+ "proxy": {+ "label": "Proksi jaringan"+ },+ "proxyUsername": {+ "label": "Nama pengguna proksi"+ },+ "proxyPassword": {+ "label": "Kata sandi proksi"+ },+ "intents": {+ "label": "Maksud gerbang"+ },+ "readReceiptEmoji": {+ "label": "Baca emoji"+ },+ "workingEmoji": {+ "label": "Emoji yang berfungsi"+ },+ "workingEmojiDelay": {+ "label": "Penundaan emoji yang berfungsi"+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/ja.json b/nanobot/channels/discord/webui/locales/ja.jsonindex 75a550bcb..5d7b7e903 100644--- a/nanobot/channels/discord/webui/locales/ja.json+++ b/nanobot/channels/discord/webui/locales/ja.json@@ -1,26 +1,15 @@{- "description": "Discord サーバーと DM から nanobot を利用します。",- "requirements": "Discord ボットトークン、権限、ゲートウェイ","setup": {"docsLabel": "Discord 設定ガイドを開く","officialLabel": "Discord ポータルを開く",- "tryIt": "サーバーでボットをメンションするか、DM を送信します。",- "summary": "Discord への接続には、ボットトークンとサーバー上の適切な権限が必要です。",- "steps": [- "Discord Developer Portal でボットを作成し、トークンをコピーします。",- "メッセージの読み書きとスラッシュコマンド権限を付けてサーバーに招待します。",- "保存して Discord を有効にし、メンションまたは DM を送信します。"- ],"fields": {"token": {"label": "ボットトークン",- "placeholder": "Discord ボットトークン",- "help": "Discord Developer Portal の Bot ページで作成します。"+ "placeholder": "Discord ボットトークン"},"allowChannels": {"label": "許可するチャンネル",- "placeholder": "チャンネル ID(カンマ区切り)",- "help": "空欄の場合、ボットが読めるすべてのチャンネルを許可します。"+ "placeholder": "チャンネル ID(カンマ区切り)"},"groupPolicy": {"label": "グループでの動作",@@ -33,6 +22,34 @@"allowFrom": {"label": "許可するユーザー","placeholder": "ユーザー ID(カンマ区切り)"+ },+ "proxy": {+ "label": "ネットワークプロキシ"+ },+ "proxyUsername": {+ "label": "プロキシのユーザー名"+ },+ "proxyPassword": {+ "label": "プロキシパスワード"+ },+ "intents": {+ "label": "ゲートウェイの意図"+ },+ "readReceiptEmoji": {+ "label": "絵文字を読む"+ },+ "workingEmoji": {+ "label": "働く絵文字"+ },+ "workingEmojiDelay": {+ "label": "絵文字の動作遅延"+ },+ "streaming": {+ "label": "ストリーミング",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/ko.json b/nanobot/channels/discord/webui/locales/ko.jsonindex c27ba75ad..19084d271 100644--- a/nanobot/channels/discord/webui/locales/ko.json+++ b/nanobot/channels/discord/webui/locales/ko.json@@ -1,26 +1,15 @@{- "description": "Discord 서버와 DM에서 nanobot을 사용합니다.",- "requirements": "Discord 봇 토큰, 권한 및 게이트웨이","setup": {"docsLabel": "Discord 설정 가이드 열기","officialLabel": "Discord 포털 열기",- "tryIt": "서버에서 봇을 멘션하거나 DM을 보내세요.",- "summary": "Discord에 연결하려면 봇 토큰과 서버 내 접근 권한이 필요합니다.",- "steps": [- "Discord Developer Portal에서 봇을 만들고 토큰을 복사하세요.",- "메시지 읽기/보내기 및 슬래시 명령 권한으로 서버에 초대하세요.",- "저장하고 Discord를 활성화한 다음 봇을 멘션하거나 DM을 보내세요."- ],"fields": {"token": {"label": "봇 토큰",- "placeholder": "Discord 봇 토큰",- "help": "Discord Developer Portal의 Bot 페이지에서 생성하세요."+ "placeholder": "Discord 봇 토큰"},"allowChannels": {"label": "허용된 채널",- "placeholder": "채널 ID, 쉼표로 구분",- "help": "비워 두면 봇이 읽을 수 있는 모든 채널을 허용합니다."+ "placeholder": "채널 ID, 쉼표로 구분"},"groupPolicy": {"label": "그룹 동작",@@ -33,6 +22,34 @@"allowFrom": {"label": "허용된 사용자","placeholder": "사용자 ID, 쉼표로 구분"+ },+ "proxy": {+ "label": "네트워크 프록시"+ },+ "proxyUsername": {+ "label": "프록시 사용자 이름"+ },+ "proxyPassword": {+ "label": "프록시 비밀번호"+ },+ "intents": {+ "label": "게이트웨이 인텐트"+ },+ "readReceiptEmoji": {+ "label": "이모티콘 읽기"+ },+ "workingEmoji": {+ "label": "일하는 이모티콘"+ },+ "workingEmojiDelay": {+ "label": "작동하는 이모티콘 지연"+ },+ "streaming": {+ "label": "스트리밍",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/pt-BR.json b/nanobot/channels/discord/webui/locales/pt-BR.jsonindex 970f646a9..00f815f97 100644--- a/nanobot/channels/discord/webui/locales/pt-BR.json+++ b/nanobot/channels/discord/webui/locales/pt-BR.json@@ -1,26 +1,15 @@{- "description": "Use o nanobot em servidores e DMs do Discord.",- "requirements": "Token do bot Discord, permissões e gateway","setup": {"docsLabel": "Abrir guia do Discord","officialLabel": "Abrir portal do Discord",- "tryIt": "Mencione o bot em um servidor ou envie uma mensagem direta.",- "summary": "Para conectar o Discord, você precisa de um token de bot e das permissões adequadas no servidor.",- "steps": [- "Crie um bot no Discord Developer Portal e copie o token.",- "Convide-o para o servidor com permissões de leitura/envio e comandos slash.",- "Salve e ative o Discord; depois, mencione o bot ou envie uma DM."- ],"fields": {"token": {"label": "Token do bot",- "placeholder": "Token do bot Discord",- "help": "Crie-o na página Bot do Discord Developer Portal."+ "placeholder": "Token do bot Discord"},"allowChannels": {"label": "Canais permitidos",- "placeholder": "IDs de canal separados por vírgulas",- "help": "Deixe vazio para permitir qualquer canal que o bot consiga ler."+ "placeholder": "IDs de canal separados por vírgulas"},"groupPolicy": {"label": "Comportamento em grupos",@@ -33,6 +22,34 @@"allowFrom": {"label": "Usuários permitidos","placeholder": "IDs de usuário separados por vírgulas"+ },+ "proxy": {+ "label": "Proxy de rede"+ },+ "proxyUsername": {+ "label": "Nome de usuário proxy"+ },+ "proxyPassword": {+ "label": "Senha proxy"+ },+ "intents": {+ "label": "Intenções de gateway"+ },+ "readReceiptEmoji": {+ "label": "Ler emoticons"+ },+ "workingEmoji": {+ "label": "Emoji de trabalho"+ },+ "workingEmojiDelay": {+ "label": "Atraso de emoji funcionando"+ },+ "streaming": {+ "label": "Transmissão",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/vi.json b/nanobot/channels/discord/webui/locales/vi.jsonindex 2f830d06f..99b5a89a1 100644--- a/nanobot/channels/discord/webui/locales/vi.json+++ b/nanobot/channels/discord/webui/locales/vi.json@@ -1,26 +1,15 @@{- "description": "Sử dụng nanobot trong máy chủ và tin nhắn riêng Discord.",- "requirements": "Token bot Discord, quyền và gateway","setup": {"docsLabel": "Mở hướng dẫn Discord","officialLabel": "Mở cổng nhà phát triển Discord",- "tryIt": "Nhắc bot trong máy chủ hoặc gửi tin nhắn riêng.",- "summary": "Để kết nối Discord, bạn cần token bot và các quyền phù hợp trên máy chủ.",- "steps": [- "Tạo bot trong Discord Developer Portal và sao chép token.",- "Mời bot vào máy chủ với quyền đọc/gửi tin nhắn và lệnh slash.",- "Lưu và bật Discord, sau đó nhắc bot hoặc gửi tin nhắn riêng."- ],"fields": {"token": {"label": "Token bot",- "placeholder": "Token bot Discord",- "help": "Tạo từ trang Bot trong Discord Developer Portal."+ "placeholder": "Token bot Discord"},"allowChannels": {"label": "Kênh được phép",- "placeholder": "ID kênh, phân tách bằng dấu phẩy",- "help": "Để trống để cho phép mọi kênh bot có thể đọc."+ "placeholder": "ID kênh, phân tách bằng dấu phẩy"},"groupPolicy": {"label": "Hành vi trong nhóm",@@ -33,6 +22,34 @@"allowFrom": {"label": "Người dùng được phép","placeholder": "ID người dùng, phân tách bằng dấu phẩy"+ },+ "proxy": {+ "label": "Proxy mạng"+ },+ "proxyUsername": {+ "label": "Tên người dùng proxy"+ },+ "proxyPassword": {+ "label": "Mật khẩu proxy"+ },+ "intents": {+ "label": "Ý định của cổng"+ },+ "readReceiptEmoji": {+ "label": "Đọc biểu tượng cảm xúc"+ },+ "workingEmoji": {+ "label": "Biểu tượng cảm xúc đang hoạt động"+ },+ "workingEmojiDelay": {+ "label": "Độ trễ biểu tượng cảm xúc đang hoạt động"+ },+ "streaming": {+ "label": "Truyền phát",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/zh-CN.json b/nanobot/channels/discord/webui/locales/zh-CN.jsonindex ae614d08f..9f78658bd 100644--- a/nanobot/channels/discord/webui/locales/zh-CN.json+++ b/nanobot/channels/discord/webui/locales/zh-CN.json@@ -1,26 +1,15 @@{- "description": "在 Discord 服务器和私信中使用 nanobot。",- "requirements": "Discord 机器人令牌、权限和网关","setup": {"docsLabel": "打开 Discord 配置指南","officialLabel": "打开 Discord 开发者后台",- "tryIt": "在服务器中提及机器人,或向它发送私信。",- "summary": "连接 Discord 需要机器人令牌,以及机器人在服务器中的相应权限。",- "steps": [- "在 Discord Developer Portal 中创建机器人并复制令牌。",- "将机器人邀请到服务器,并授予读取/发送消息及斜杠命令权限。",- "保存并启用 Discord,然后提及机器人或发送私信。"- ],"fields": {"token": {"label": "机器人令牌",- "placeholder": "Discord 机器人令牌",- "help": "从 Discord Developer Portal 的 Bot 页面创建。"+ "placeholder": "Discord 机器人令牌"},"allowChannels": {"label": "允许的频道",- "placeholder": "频道 ID,用逗号分隔",- "help": "留空则允许机器人可读取的所有频道。"+ "placeholder": "频道 ID,用逗号分隔"},"groupPolicy": {"label": "群组行为",@@ -33,6 +22,34 @@"allowFrom": {"label": "允许的用户","placeholder": "用户 ID,用逗号分隔"+ },+ "proxy": {+ "label": "网络代理"+ },+ "proxyUsername": {+ "label": "代理用户名"+ },+ "proxyPassword": {+ "label": "代理密码"+ },+ "intents": {+ "label": "Gateway Intents"+ },+ "readReceiptEmoji": {+ "label": "已读表情"+ },+ "workingEmoji": {+ "label": "处理中表情"+ },+ "workingEmojiDelay": {+ "label": "处理中表情延迟"+ },+ "streaming": {+ "label": "流式输出",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/zh-TW.json b/nanobot/channels/discord/webui/locales/zh-TW.jsonindex 9d173bd67..215fa4402 100644--- a/nanobot/channels/discord/webui/locales/zh-TW.json+++ b/nanobot/channels/discord/webui/locales/zh-TW.json@@ -1,26 +1,15 @@{- "description": "在 Discord 伺服器和私訊中使用 nanobot。",- "requirements": "Discord 機器人權杖、權限和閘道","setup": {"docsLabel": "開啟 Discord 設定指南","officialLabel": "開啟 Discord 開發者後台",- "tryIt": "在伺服器中提及機器人,或向它傳送私訊。",- "summary": "連接 Discord 需要機器人權杖,以及機器人在伺服器中的適當權限。",- "steps": [- "在 Discord Developer Portal 中建立機器人並複製權杖。",- "將機器人邀請到伺服器,並授予讀取/傳送訊息及斜線指令權限。",- "儲存並啟用 Discord,然後提及機器人或傳送私訊。"- ],"fields": {"token": {"label": "機器人權杖",- "placeholder": "Discord 機器人權杖",- "help": "從 Discord Developer Portal 的 Bot 頁面建立。"+ "placeholder": "Discord 機器人權杖"},"allowChannels": {"label": "允許的頻道",- "placeholder": "頻道 ID,以逗號分隔",- "help": "留空則允許機器人可讀取的所有頻道。"+ "placeholder": "頻道 ID,以逗號分隔"},"groupPolicy": {"label": "群組行為",@@ -33,6 +22,34 @@"allowFrom": {"label": "允許的使用者","placeholder": "使用者 ID,以逗號分隔"+ },+ "proxy": {+ "label": "網路代理"+ },+ "proxyUsername": {+ "label": "代理用戶名"+ },+ "proxyPassword": {+ "label": "代理密碼"+ },+ "intents": {+ "label": "Gateway Intents"+ },+ "readReceiptEmoji": {+ "label": "已讀表情"+ },+ "workingEmoji": {+ "label": "處理中表情"+ },+ "workingEmojiDelay": {+ "label": "處理中表情延遲"+ },+ "streaming": {+ "label": "串流輸出",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }}}}diff --git a/nanobot/channels/email/manifest.py b/nanobot/channels/email/manifest.pyindex ba046d714..e8a1fa6a0 100644--- a/nanobot/channels/email/manifest.py+++ b/nanobot/channels/email/manifest.py@@ -21,6 +21,21 @@ SETUP_SPEC = ChannelSetupSpec("allowFrom": field("list"),"verifyDkim": field("bool", default=True),"verifySpf": field("bool", default=True),+ "imapMailbox": field(default="INBOX"),+ "imapUseSsl": field("bool", default=True),+ "smtpUseTls": field("bool", default=True),+ "smtpUseSsl": field("bool", default=False),+ "autoReplyEnabled": field("bool", default=True),+ "markSeen": field("bool", default=True),+ "postAction": field("enum", choices={"delete", "move"}),+ "postActionMoveMailbox": field(),+ "postActionExpunge": field("bool", default=False),+ "postActionIgnoreSkipped": field("bool", default=True),+ "maxBodyChars": field("int", default=12000),+ "subjectPrefix": field(default="Re: "),+ "allowedAttachmentTypes": field("list"),+ "maxAttachmentSize": field("int", default=2_000_000),+ "maxAttachmentsPerEmail": field("int", default=5),},required=required_fields("consentGranted",@@ -33,6 +48,7 @@ SETUP_SPEC = ChannelSetupSpec(),official_url="https://support.google.com/accounts/answer/185833",validator=validate,+ verifies_connection=True,)PLUGIN = ChannelPlugin(diff --git a/nanobot/channels/email/tests/test_validation.py b/nanobot/channels/email/tests/test_validation.pyindex 01e3da8be..0de376f54 100644--- a/nanobot/channels/email/tests/test_validation.py+++ b/nanobot/channels/email/tests/test_validation.py@@ -1,13 +1,20 @@from __future__ import annotations+import imaplib+import pytestfrom nanobot.channels.email import validation as email_validation+from nanobot.channels.email.manifest import SETUP_SPECfrom nanobot.channels.validation import validate_channel_configfrom nanobot.config.loader import save_configfrom nanobot.config.schema import Config+def test_email_exposes_connection_checks_to_setup_clients() -> None:+ assert SETUP_SPEC.verifies_connection is True++def test_validate_email_presets_are_checked_without_saving(tmp_path,monkeypatch: pytest.MonkeyPatch,@@ -17,6 +24,17 @@ def test_validate_email_presets_are_checked_without_saving(original_config = config_path.read_bytes()monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)monkeypatch.setattr(email_validation, "probe_tcp", lambda *_args, **_kwargs: None)+ login_calls: list[tuple[str, tuple[object, ...], dict[str, object]]] = []+ monkeypatch.setattr(+ email_validation,+ "_imap_login",+ lambda *args, **kwargs: login_calls.append(("imap", args, kwargs)),+ )+ monkeypatch.setattr(+ email_validation,+ "_smtp_login",+ lambda *args, **kwargs: login_calls.append(("smtp", args, kwargs)),+ )result = validate_channel_config("email",@@ -33,9 +51,64 @@ def test_validate_email_presets_are_checked_without_saving(assert result["status"] == "connected"assert result["can_enable"] is True+ assert [check["id"] for check in result["checks"]][-2:] == [+ "smtp_reachability",+ "smtp_account",+ ]+ assert login_calls == [+ (+ "imap",+ ("imap.gmail.com", 993, "[email protected]", "imap-secret"),+ {"mailbox": "INBOX", "use_ssl": True},+ ),+ (+ "smtp",+ ("smtp.gmail.com", 587, "[email protected]", "smtp-secret"),+ {"use_ssl": False, "use_tls": True},+ ),+ ]assert config_path.read_bytes() == original_config+def test_validate_email_rejects_invalid_account_credentials(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ config_path = tmp_path / "config.json"+ save_config(Config(), config_path)+ monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)+ monkeypatch.setattr(email_validation, "probe_tcp", lambda *_args, **_kwargs: None)++ def reject_imap_login(*_args, **_kwargs) -> None:+ raise imaplib.IMAP4.error("AUTH failed")++ monkeypatch.setattr(email_validation, "_imap_login", reject_imap_login)+ monkeypatch.setattr(email_validation, "_smtp_login", lambda *_args, **_kwargs: None)++ result = validate_channel_config(+ "email",+ {+ "channels.email.consentGranted": "true",+ "channels.email.imapHost": "imap.example.com",+ "channels.email.imapUsername": "[email protected]",+ "channels.email.imapPassword": "wrong-secret",+ "channels.email.smtpHost": "smtp.example.com",+ "channels.email.smtpUsername": "[email protected]",+ "channels.email.smtpPassword": "smtp-secret",+ },+ )++ assert result["status"] == "invalid"+ assert result["can_enable"] is False+ assert {+ check["id"]: (check["status"], check.get("message"))+ for check in result["checks"]+ }["imap_account"] == (+ "fail",+ "IMAP rejected the username or password.",+ )++def test_validate_email_blocks_private_targets_when_local_access_is_disabled(tmp_path,monkeypatch: pytest.MonkeyPatch,diff --git a/nanobot/channels/email/validation.py b/nanobot/channels/email/validation.pyindex ebcd410f0..ccedcd4b5 100644--- a/nanobot/channels/email/validation.py+++ b/nanobot/channels/email/validation.py@@ -1,5 +1,9 @@"""Email setup validation owned by the channel package."""+import imaplib+import smtplib+import ssl+from contextlib import suppressfrom typing import Anyfrom nanobot.channels.contracts import ChannelValidationContext@@ -13,6 +17,84 @@ from nanobot.channels.validation import (truthy,)+_TIMEOUT_SECONDS = 4.0+++class _MailboxSelectionError(Exception):+ pass+++def _resolved_string(values: dict[str, Any], field: str) -> str:+ from nanobot.config.loader import resolve_env_refs++ return string_value(resolve_env_refs(string_value(values.get(field))))+++def _bool_value(values: dict[str, Any], field: str, *, default: bool) -> bool:+ value = values.get(field)+ return default if value in (None, "") else truthy(value)+++def _imap_login(+ host: str,+ port: int,+ username: str,+ password: str,+ *,+ mailbox: str,+ use_ssl: bool,+) -> None:+ client: Any = (+ imaplib.IMAP4_SSL(host, port, timeout=_TIMEOUT_SECONDS)+ if use_ssl+ else imaplib.IMAP4(host, port, timeout=_TIMEOUT_SECONDS)+ )+ try:+ client.login(username, password)+ try:+ status, _ = client.select(mailbox, readonly=True)+ except imaplib.IMAP4.error as exc:+ raise _MailboxSelectionError from exc+ if status != "OK":+ raise _MailboxSelectionError+ finally:+ with suppress(Exception):+ client.logout()+++def _smtp_login(+ host: str,+ port: int,+ username: str,+ password: str,+ *,+ use_ssl: bool,+ use_tls: bool,+) -> None:+ client = (+ smtplib.SMTP_SSL(host, port, timeout=_TIMEOUT_SECONDS)+ if use_ssl+ else smtplib.SMTP(host, port, timeout=_TIMEOUT_SECONDS)+ )+ with client:+ if use_tls and not use_ssl:+ client.starttls(context=ssl.create_default_context())+ client.login(username, password)+++def _connection_error_message(prefix: str, exc: Exception) -> tuple[str, str]:+ if isinstance(exc, _MailboxSelectionError):+ return "fail", "IMAP connected, but the selected mailbox could not be opened."+ if isinstance(exc, (imaplib.IMAP4.error, smtplib.SMTPAuthenticationError)):+ return "fail", f"{prefix} rejected the username or password."+ if isinstance(exc, (ssl.SSLError, smtplib.SMTPNotSupportedError)):+ return "fail", f"{prefix} security settings are not accepted by the server."+ if isinstance(exc, smtplib.SMTPResponseException):+ return "fail", f"{prefix} rejected the connection settings."+ if isinstance(exc, (TimeoutError, OSError)):+ return "warn", f"Could not reach {prefix} now. Try again later."+ return "warn", f"Could not verify {prefix} now. Try again later."+def validate(values: dict[str, Any],@@ -32,15 +114,33 @@ def validate()for prefix, default_port in (("imap", 993), ("smtp", 587)):- host = string_value(values.get(f"{prefix}Host"))- port = int_value(values.get(f"{prefix}Port")) or default_port+ label = prefix.upper()+ host = _resolved_string(values, f"{prefix}Host")+ username = _resolved_string(values, f"{prefix}Username")+ password = _resolved_string(values, f"{prefix}Password")+ unresolved = any(+ string_value(values.get(field)) and not _resolved_string(values, field)+ for field in (f"{prefix}Host", f"{prefix}Username", f"{prefix}Password")+ )+ if unresolved:+ checks.append(+ check(+ f"{prefix}_environment",+ f"{label} account",+ "fail",+ f"Set every environment variable referenced by the {label} settings.",+ )+ )+ continue+ raw_port = values.get(f"{prefix}Port")+ port = default_port if raw_port in (None, "") else int_value(raw_port)if not host:continue- if port <= 0 or port > 65535:+ if port is None or port <= 0 or port > 65535:checks.append(check(f"{prefix}_port",- f"{prefix.upper()} port",+ f"{label} port","fail","Port must be between 1 and 65535.",)@@ -49,7 +149,7 @@ def validate(checks.append(check(f"{prefix}_settings",- f"{prefix.upper()} settings",+ f"{label} settings","pass",f"{host}:{port} is set.",)@@ -63,7 +163,7 @@ def validate(checks.append(check(f"{prefix}_reachability",- f"{prefix.upper()} reachability",+ f"{label} reachability","pass","The server accepted a TCP connection.",)@@ -72,17 +172,51 @@ def validate(checks.append(check(f"{prefix}_reachability",- f"{prefix.upper()} reachability",+ f"{label} reachability","warn",f"Could not verify network reachability now: {exc}",))+ continue++ if not username or not password:+ continue+ try:+ if prefix == "imap":+ _imap_login(+ host,+ port,+ username,+ password,+ mailbox=_resolved_string(values, "imapMailbox") or "INBOX",+ use_ssl=_bool_value(values, "imapUseSsl", default=True),+ )+ else:+ _smtp_login(+ host,+ port,+ username,+ password,+ use_ssl=_bool_value(values, "smtpUseSsl", default=False),+ use_tls=_bool_value(values, "smtpUseTls", default=True),+ )+ checks.append(+ check(+ f"{prefix}_account",+ f"{label} account",+ "pass",+ f"{label} accepted the account credentials.",+ )+ )+ except Exception as exc:+ status, message = _connection_error_message(label, exc)+ checks.append(check(f"{prefix}_account", f"{label} account", status, message))identity = {- "account": string_value(- values.get("fromAddress")- or values.get("imapUsername")- or values.get("smtpUsername")+ "account": (+ _resolved_string(values, "fromAddress")+ or _resolved_string(values, "imapUsername")+ or _resolved_string(values, "smtpUsername"))}return status_from_checks("email", checks, missing, identity=identity)diff --git a/nanobot/channels/email/webui/index.ts b/nanobot/channels/email/webui/index.tsindex cea01cdaa..e069edda6 100644--- a/nanobot/channels/email/webui/index.ts+++ b/nanobot/channels/email/webui/index.ts@@ -32,34 +32,33 @@ const EMAIL_PROVIDER_PRESETS: ChannelProviderPresetDefinition[] = ["channels.email.smtpPort": "587",},},- { id: "custom", values: {} },];export default {presentation: {+ logoUrl: "https://gmail.com/favicon.ico",displayName: "Email",initials: "EM",color: "#64748B",- logoUrl: "https://gmail.com/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("email"),presets: EMAIL_PROVIDER_PRESETS,fields: [- { key: "channels.email.consentGranted" },- { key: "channels.email.imapHost" },- { key: "channels.email.imapUsername" },- { key: "channels.email.imapPassword" },- { key: "channels.email.smtpHost" },- { key: "channels.email.smtpUsername" },- { key: "channels.email.smtpPassword" },- { key: "channels.email.imapPort" },- { key: "channels.email.smtpPort" },- { key: "channels.email.fromAddress" },- { key: "channels.email.pollIntervalSeconds" },- { key: "channels.email.allowFrom" },- { key: "channels.email.verifyDkim" },- { key: "channels.email.verifySpf" },+ { key: "channels.email.consentGranted", section: "account" },+ { key: "channels.email.imapHost", section: "receiving" },+ { key: "channels.email.imapUsername", section: "receiving" },+ { key: "channels.email.imapPassword", section: "receiving" },+ { key: "channels.email.imapPort", section: "receiving" },+ { key: "channels.email.smtpHost", section: "sending" },+ { key: "channels.email.smtpUsername", section: "sending" },+ { key: "channels.email.smtpPassword", section: "sending" },+ { key: "channels.email.smtpPort", section: "sending" },+ { key: "channels.email.fromAddress", section: "sending" },+ { key: "channels.email.pollIntervalSeconds", section: "behavior" },+ { key: "channels.email.allowFrom", section: "access" },+ { key: "channels.email.verifyDkim", section: "security" },+ { key: "channels.email.verifySpf", section: "security" },],},},diff --git a/nanobot/channels/email/webui/locales/en.json b/nanobot/channels/email/webui/locales/en.jsonindex 2391edd6c..d3bf43894 100644--- a/nanobot/channels/email/webui/locales/en.json+++ b/nanobot/channels/email/webui/locales/en.json@@ -1,26 +1,20 @@{- "description": "Let nanobot receive and answer email messages.",- "requirements": "IMAP inbox, SMTP sender, app password, explicit consent","setup": {"docsLabel": "Open Email setup","officialLabel": "Open app password guide",- "tryIt": "Send a test email to the connected mailbox.",- "summary": "Email reads messages over IMAP and replies over SMTP. Use a dedicated mailbox and grant consent before enabling it.",- "steps": [- "Create a dedicated mailbox and, when required, an app password.",- "Choose a provider preset or enter the IMAP and SMTP settings manually.",- "Grant consent, save and enable Email, then send a test message to the mailbox."- ],+ "presetLabel": "Quick fill",+ "sections": {+ "receiving": "Receiving mail",+ "sending": "Sending mail"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "Custom"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "Allow nanobot to read and send email",- "help": "Turn on to give nanobot access to this mailbox. Make sure this is the dedicated mailbox you want the bot to use.","choices": {"true": "Granted","false": "Not granted"@@ -36,8 +30,7 @@},"imapPassword": {"label": "IMAP password",- "placeholder": "App password",- "help": "Use an app password when your mail provider requires one."+ "placeholder": "App password"},"smtpHost": {"label": "SMTP host",@@ -49,8 +42,7 @@},"smtpPassword": {"label": "SMTP password",- "placeholder": "App password",- "help": "Usually the same app password used for IMAP."+ "placeholder": "App password"},"imapPort": {"label": "IMAP port",@@ -70,8 +62,7 @@},"allowFrom": {"label": "Allowed senders",- "placeholder": "Email addresses, comma separated",- "help": "Leave empty to require pairing before a sender can use email."+ "placeholder": "Email addresses, comma separated"},"verifyDkim": {"label": "Verify DKIM",@@ -86,6 +77,83 @@"true": "On","false": "Off"}+ },+ "imapMailbox": {+ "label": "IMAP mailbox"+ },+ "imapUseSsl": {+ "label": "IMAP SSL",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "smtpUseTls": {+ "label": "SMTP TLS",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "smtpUseSsl": {+ "label": "SMTP SSL",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "autoReplyEnabled": {+ "label": "Automatic replies",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "markSeen": {+ "label": "Mark as read",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "postAction": {+ "label": "After processing",+ "choices": {+ "delete": "Delete",+ "move": "Move"+ }+ },+ "postActionMoveMailbox": {+ "label": "Move to mailbox"+ },+ "postActionExpunge": {+ "label": "Permanently apply action",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "Ignore skipped messages",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "maxBodyChars": {+ "label": "Maximum body length"+ },+ "subjectPrefix": {+ "label": "Reply subject prefix"+ },+ "allowedAttachmentTypes": {+ "label": "Allowed attachment types"+ },+ "maxAttachmentSize": {+ "label": "Maximum attachment size"+ },+ "maxAttachmentsPerEmail": {+ "label": "Maximum attachments"}}}diff --git a/nanobot/channels/email/webui/locales/es.json b/nanobot/channels/email/webui/locales/es.jsonindex 692679c2e..ca4df63fd 100644--- a/nanobot/channels/email/webui/locales/es.json+++ b/nanobot/channels/email/webui/locales/es.json@@ -1,27 +1,21 @@{"displayName": "Correo electrónico",- "description": "Permite que nanobot reciba y responda correos.",- "requirements": "Bandeja IMAP, envío SMTP, contraseña de app y consentimiento explícito","setup": {"docsLabel": "Abrir guía de Email","officialLabel": "Abrir guía de contraseñas de app",- "tryIt": "Envía un correo de prueba al buzón conectado.",- "summary": "Email lee mensajes por IMAP y responde por SMTP. Usa un buzón dedicado y da tu consentimiento antes de activarlo.",- "steps": [- "Crea un buzón dedicado y, si hace falta, una contraseña de app.",- "Elige un proveedor o introduce manualmente IMAP y SMTP.",- "Da tu consentimiento, guarda y activa Email; después envía un mensaje de prueba."- ],+ "presetLabel": "Relleno rápido",+ "sections": {+ "receiving": "Recepción de correo",+ "sending": "Envío de correo"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "Personalizado"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "Permitir que nanobot lea y envíe correos",- "help": "Activa esta opción para permitir el acceso al buzón. Comprueba que sea el buzón dedicado al bot.","choices": {"true": "Concedido","false": "No concedido"@@ -37,8 +31,7 @@},"imapPassword": {"label": "Contraseña IMAP",- "placeholder": "Contraseña de app",- "help": "Usa una contraseña de app si el proveedor la exige."+ "placeholder": "Contraseña de app"},"smtpHost": {"label": "Host SMTP",@@ -50,8 +43,7 @@},"smtpPassword": {"label": "Contraseña SMTP",- "placeholder": "Contraseña de app",- "help": "Normalmente es la misma que para IMAP."+ "placeholder": "Contraseña de app"},"imapPort": {"label": "Puerto IMAP",@@ -71,8 +63,7 @@},"allowFrom": {"label": "Remitentes permitidos",- "placeholder": "Correos separados por comas",- "help": "Déjalo vacío para exigir vinculación previa."+ "placeholder": "Correos separados por comas"},"verifyDkim": {"label": "Verificar DKIM",@@ -87,6 +78,83 @@"true": "Activado","false": "Desactivado"}+ },+ "imapMailbox": {+ "label": "buzón IMAP"+ },+ "imapUseSsl": {+ "label": "SSL IMAP",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "smtpUseTls": {+ "label": "TLS SMTP",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "smtpUseSsl": {+ "label": "SSL SMTP",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "autoReplyEnabled": {+ "label": "Respuestas automáticas",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "markSeen": {+ "label": "Marcar como leído",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "postAction": {+ "label": "Después del procesamiento",+ "choices": {+ "delete": "Eliminar",+ "move": "Mover"+ }+ },+ "postActionMoveMailbox": {+ "label": "Mover al buzón"+ },+ "postActionExpunge": {+ "label": "Aplicar permanentemente la acción",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "Ignorar mensajes omitidos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "maxBodyChars": {+ "label": "Longitud máxima del cuerpo"+ },+ "subjectPrefix": {+ "label": "Prefijo del asunto de respuesta"+ },+ "allowedAttachmentTypes": {+ "label": "Tipos de archivos adjuntos permitidos"+ },+ "maxAttachmentSize": {+ "label": "Tamaño máximo de archivo adjunto"+ },+ "maxAttachmentsPerEmail": {+ "label": "Archivos adjuntos máximos"}}}diff --git a/nanobot/channels/email/webui/locales/fr.json b/nanobot/channels/email/webui/locales/fr.jsonindex 078a76693..1b62dab3b 100644--- a/nanobot/channels/email/webui/locales/fr.json+++ b/nanobot/channels/email/webui/locales/fr.json@@ -1,27 +1,21 @@{"displayName": "E-mail",- "description": "Permettez à nanobot de recevoir des e-mails et d’y répondre.",- "requirements": "Boîte IMAP, envoi SMTP, mot de passe d’application et consentement explicite","setup": {"docsLabel": "Ouvrir le guide Email","officialLabel": "Ouvrir le guide des mots de passe d’application",- "tryIt": "Envoyez un e-mail test à la boîte connectée.",- "summary": "nanobot lit les messages via IMAP et répond via SMTP. Utilisez une boîte dédiée et autorisez l’accès avant d’activer le canal.",- "steps": [- "Créez une boîte dédiée et, si nécessaire, un mot de passe d’application.",- "Choisissez un fournisseur ou saisissez les paramètres IMAP et SMTP.",- "Accordez le consentement, enregistrez et activez Email, puis envoyez un message test."- ],+ "presetLabel": "Remplissage rapide",+ "sections": {+ "receiving": "Réception des e-mails",+ "sending": "Envoi des e-mails"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "Personnalisé"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "Autoriser nanobot à lire et envoyer des e-mails",- "help": "Activez cette option pour autoriser l’accès à cette boîte. Vérifiez qu’il s’agit bien de la boîte dédiée au bot.","choices": {"true": "Accordé","false": "Non accordé"@@ -37,8 +31,7 @@},"imapPassword": {"label": "Mot de passe IMAP",- "placeholder": "Mot de passe d’application",- "help": "Utilisez un mot de passe d’application si le fournisseur l’exige."+ "placeholder": "Mot de passe d’application"},"smtpHost": {"label": "Hôte SMTP",@@ -50,8 +43,7 @@},"smtpPassword": {"label": "Mot de passe SMTP",- "placeholder": "Mot de passe d’application",- "help": "Généralement identique à celui d’IMAP."+ "placeholder": "Mot de passe d’application"},"imapPort": {"label": "Port IMAP",@@ -71,8 +63,7 @@},"allowFrom": {"label": "Expéditeurs autorisés",- "placeholder": "Adresses séparées par des virgules",- "help": "Laissez vide pour que les expéditeurs doivent d’abord s’associer au bot."+ "placeholder": "Adresses séparées par des virgules"},"verifyDkim": {"label": "Vérifier DKIM",@@ -87,6 +78,83 @@"true": "Activé","false": "Désactivé"}+ },+ "imapMailbox": {+ "label": "Boîte aux lettres IMAP"+ },+ "imapUseSsl": {+ "label": "SSL IMAP",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "smtpUseTls": {+ "label": "SMTP-TLS",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "smtpUseSsl": {+ "label": "SMTP-SSL",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "autoReplyEnabled": {+ "label": "Réponses automatiques",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "markSeen": {+ "label": "Marquer comme lu",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "postAction": {+ "label": "Après traitement",+ "choices": {+ "delete": "Supprimer",+ "move": "Déplacer"+ }+ },+ "postActionMoveMailbox": {+ "label": "Déplacer vers la boîte aux lettres"+ },+ "postActionExpunge": {+ "label": "Appliquer l'action de manière permanente",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "Ignorer les messages ignorés",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "maxBodyChars": {+ "label": "Longueur maximale du corps"+ },+ "subjectPrefix": {+ "label": "Préfixe du sujet de la réponse"+ },+ "allowedAttachmentTypes": {+ "label": "Types de pièces jointes autorisés"+ },+ "maxAttachmentSize": {+ "label": "Taille maximale des pièces jointes"+ },+ "maxAttachmentsPerEmail": {+ "label": "Nombre maximal de pièces jointes"}}}diff --git a/nanobot/channels/email/webui/locales/id.json b/nanobot/channels/email/webui/locales/id.jsonindex a99b59b5f..da98c16d6 100644--- a/nanobot/channels/email/webui/locales/id.json+++ b/nanobot/channels/email/webui/locales/id.json@@ -1,27 +1,21 @@{"displayName": "Email",- "description": "Izinkan nanobot menerima dan membalas email.",- "requirements": "Kotak masuk IMAP, pengirim SMTP, kata sandi aplikasi, dan persetujuan eksplisit","setup": {"docsLabel": "Buka panduan Email","officialLabel": "Buka panduan kata sandi aplikasi",- "tryIt": "Kirim email uji ke kotak surat yang terhubung.",- "summary": "Email membaca pesan melalui IMAP dan membalas melalui SMTP. Gunakan kotak surat khusus dan berikan persetujuan sebelum mengaktifkan.",- "steps": [- "Buat kotak surat khusus dan kata sandi aplikasi bila diperlukan.",- "Pilih prasetel penyedia atau masukkan pengaturan IMAP dan SMTP secara manual.",- "Berikan persetujuan, simpan dan aktifkan Email, lalu kirim pesan uji."- ],+ "presetLabel": "Isi cepat",+ "sections": {+ "receiving": "Penerimaan email",+ "sending": "Pengiriman email"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "Kustom"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "Izinkan nanobot membaca dan mengirim email",- "help": "Aktifkan untuk memberi nanobot akses ke kotak surat ini. Pastikan kotak surat tersebut memang dikhususkan untuk bot.","choices": {"true": "Diberikan","false": "Belum diberikan"@@ -37,8 +31,7 @@},"imapPassword": {"label": "Kata sandi IMAP",- "placeholder": "Kata sandi aplikasi",- "help": "Gunakan kata sandi aplikasi jika diwajibkan penyedia."+ "placeholder": "Kata sandi aplikasi"},"smtpHost": {"label": "Host SMTP",@@ -50,8 +43,7 @@},"smtpPassword": {"label": "Kata sandi SMTP",- "placeholder": "Kata sandi aplikasi",- "help": "Biasanya sama dengan kata sandi aplikasi IMAP."+ "placeholder": "Kata sandi aplikasi"},"imapPort": {"label": "Port IMAP",@@ -71,8 +63,7 @@},"allowFrom": {"label": "Pengirim yang diizinkan",- "placeholder": "Alamat email, dipisahkan koma",- "help": "Kosongkan untuk mewajibkan pairing terlebih dahulu."+ "placeholder": "Alamat email, dipisahkan koma"},"verifyDkim": {"label": "Verifikasi DKIM",@@ -87,6 +78,83 @@"true": "Aktif","false": "Nonaktif"}+ },+ "imapMailbox": {+ "label": "kotak surat IMAP"+ },+ "imapUseSsl": {+ "label": "SSL IMAP",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "smtpUseTls": {+ "label": "TLS SMTP",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "smtpUseSsl": {+ "label": "SSL SMTP",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "autoReplyEnabled": {+ "label": "Balasan otomatis",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "markSeen": {+ "label": "Tandai sebagai telah dibaca",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "postAction": {+ "label": "Setelah diproses",+ "choices": {+ "delete": "Hapus",+ "move": "Pindah"+ }+ },+ "postActionMoveMailbox": {+ "label": "Pindah ke kotak surat"+ },+ "postActionExpunge": {+ "label": "Terapkan tindakan secara permanen",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "Abaikan pesan yang dilewati",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "maxBodyChars": {+ "label": "Panjang tubuh maksimal"+ },+ "subjectPrefix": {+ "label": "Awalan subjek balasan"+ },+ "allowedAttachmentTypes": {+ "label": "Jenis lampiran yang diizinkan"+ },+ "maxAttachmentSize": {+ "label": "Ukuran lampiran maksimum"+ },+ "maxAttachmentsPerEmail": {+ "label": "Lampiran maksimum"}}}diff --git a/nanobot/channels/email/webui/locales/ja.json b/nanobot/channels/email/webui/locales/ja.jsonindex 4469c13b7..16f786b68 100644--- a/nanobot/channels/email/webui/locales/ja.json+++ b/nanobot/channels/email/webui/locales/ja.json@@ -1,27 +1,21 @@{"displayName": "メール",- "description": "nanobot でメールを受信し、返信します。",- "requirements": "IMAP 受信箱、SMTP 送信、アプリパスワード、明示的な同意","setup": {"docsLabel": "メール設定ガイドを開く","officialLabel": "アプリパスワードガイドを開く",- "tryIt": "接続したメールボックスにテストメールを送信します。",- "summary": "メールは IMAP で受信し SMTP で返信します。専用メールボックスを使い、有効化前に同意してください。",- "steps": [- "専用メールボックスを作成し、必要ならアプリパスワードを発行します。",- "プロバイダープリセットを選ぶか、IMAP と SMTP を手動入力します。",- "同意して保存し、メールを有効にしてテストメールを送信します。"- ],+ "presetLabel": "クイック入力",+ "sections": {+ "receiving": "メール受信",+ "sending": "メール送信"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "カスタム"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "nanobot にメールの読み取りと送信を許可",- "help": "オンにすると nanobot がこのメールボックスにアクセスできます。ボット用の専用メールボックスであることを確認してください。","choices": {"true": "同意済み","false": "未同意"@@ -37,8 +31,7 @@},"imapPassword": {"label": "IMAP パスワード",- "placeholder": "アプリパスワード",- "help": "プロバイダーが求める場合はアプリパスワードを使います。"+ "placeholder": "アプリパスワード"},"smtpHost": {"label": "SMTP ホスト",@@ -50,8 +43,7 @@},"smtpPassword": {"label": "SMTP パスワード",- "placeholder": "アプリパスワード",- "help": "通常は IMAP と同じアプリパスワードです。"+ "placeholder": "アプリパスワード"},"imapPort": {"label": "IMAP ポート",@@ -71,8 +63,7 @@},"allowFrom": {"label": "許可する送信者",- "placeholder": "メールアドレス(カンマ区切り)",- "help": "空欄の場合、送信者は先にペアリングが必要です。"+ "placeholder": "メールアドレス(カンマ区切り)"},"verifyDkim": {"label": "DKIM を検証",@@ -87,6 +78,83 @@"true": "オン","false": "オフ"}+ },+ "imapMailbox": {+ "label": "IMAPメールボックス"+ },+ "imapUseSsl": {+ "label": "IMAP SSL",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "smtpUseTls": {+ "label": "SMTP TLS",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "smtpUseSsl": {+ "label": "SMTP SSL",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "autoReplyEnabled": {+ "label": "自動応答",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "markSeen": {+ "label": "既読としてマークする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "postAction": {+ "label": "加工後",+ "choices": {+ "delete": "削除",+ "move": "移動"+ }+ },+ "postActionMoveMailbox": {+ "label": "メールボックスに移動"+ },+ "postActionExpunge": {+ "label": "アクションを永続的に適用する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "スキップされたメッセージを無視する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "maxBodyChars": {+ "label": "最大体長"+ },+ "subjectPrefix": {+ "label": "返信件名の接頭辞"+ },+ "allowedAttachmentTypes": {+ "label": "許可される添付ファイルの種類"+ },+ "maxAttachmentSize": {+ "label": "添付ファイルの最大サイズ"+ },+ "maxAttachmentsPerEmail": {+ "label": "最大添付ファイル数"}}}diff --git a/nanobot/channels/email/webui/locales/ko.json b/nanobot/channels/email/webui/locales/ko.jsonindex ab9e2049c..a768e67bb 100644--- a/nanobot/channels/email/webui/locales/ko.json+++ b/nanobot/channels/email/webui/locales/ko.json@@ -1,27 +1,21 @@{"displayName": "이메일",- "description": "nanobot이 이메일을 받고 답장하도록 합니다.",- "requirements": "IMAP 받은편지함, SMTP 발신, 앱 비밀번호 및 명시적 동의","setup": {"docsLabel": "이메일 설정 가이드 열기","officialLabel": "앱 비밀번호 가이드 열기",- "tryIt": "연결된 사서함으로 테스트 이메일을 보내세요.",- "summary": "이메일은 IMAP으로 읽고 SMTP로 답장합니다. 전용 사서함을 사용하고 활성화 전에 동의하세요.",- "steps": [- "전용 사서함을 만들고 필요하면 앱 비밀번호를 생성하세요.",- "제공업체 프리셋을 선택하거나 IMAP 및 SMTP 설정을 직접 입력하세요.",- "동의하고 저장한 뒤 이메일을 활성화하고 테스트 메시지를 보내세요."- ],+ "presetLabel": "빠른 입력",+ "sections": {+ "receiving": "메일 수신",+ "sending": "메일 발신"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "사용자 지정"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "nanobot의 이메일 읽기 및 보내기 허용",- "help": "켜면 nanobot이 이 사서함에 접근할 수 있습니다. 봇 전용 사서함이 맞는지 확인하세요.","choices": {"true": "동의함","false": "동의하지 않음"@@ -37,8 +31,7 @@},"imapPassword": {"label": "IMAP 비밀번호",- "placeholder": "앱 비밀번호",- "help": "메일 제공업체가 요구하면 앱 비밀번호를 사용하세요."+ "placeholder": "앱 비밀번호"},"smtpHost": {"label": "SMTP 호스트",@@ -50,8 +43,7 @@},"smtpPassword": {"label": "SMTP 비밀번호",- "placeholder": "앱 비밀번호",- "help": "보통 IMAP과 같은 앱 비밀번호를 사용합니다."+ "placeholder": "앱 비밀번호"},"imapPort": {"label": "IMAP 포트",@@ -71,8 +63,7 @@},"allowFrom": {"label": "허용된 발신자",- "placeholder": "이메일 주소, 쉼표로 구분",- "help": "비워 두면 발신자가 먼저 페어링해야 합니다."+ "placeholder": "이메일 주소, 쉼표로 구분"},"verifyDkim": {"label": "DKIM 확인",@@ -87,6 +78,83 @@"true": "켜짐","false": "꺼짐"}+ },+ "imapMailbox": {+ "label": "IMAP 사서함"+ },+ "imapUseSsl": {+ "label": "IMAP SSL",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "smtpUseTls": {+ "label": "SMTP TLS",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "smtpUseSsl": {+ "label": "SMTP SSL",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "autoReplyEnabled": {+ "label": "자동 답장",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "markSeen": {+ "label": "읽음으로 표시",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "postAction": {+ "label": "처리 후",+ "choices": {+ "delete": "삭제",+ "move": "이동"+ }+ },+ "postActionMoveMailbox": {+ "label": "사서함으로 이동"+ },+ "postActionExpunge": {+ "label": "영구적으로 작업 적용",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "건너뛴 메시지 무시",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "maxBodyChars": {+ "label": "최대 몸체 길이"+ },+ "subjectPrefix": {+ "label": "답장 제목 접두어"+ },+ "allowedAttachmentTypes": {+ "label": "허용되는 첨부 파일 유형"+ },+ "maxAttachmentSize": {+ "label": "최대 첨부 파일 크기"+ },+ "maxAttachmentsPerEmail": {+ "label": "최대 첨부 파일"}}}diff --git a/nanobot/channels/email/webui/locales/pt-BR.json b/nanobot/channels/email/webui/locales/pt-BR.jsonindex 57fd4faef..4e4d865bd 100644--- a/nanobot/channels/email/webui/locales/pt-BR.json+++ b/nanobot/channels/email/webui/locales/pt-BR.json@@ -1,27 +1,21 @@{"displayName": "E-mail",- "description": "Permita que o nanobot receba e responda e-mails.",- "requirements": "Caixa IMAP, envio SMTP, senha de app e consentimento explícito","setup": {"docsLabel": "Abrir guia de e-mail","officialLabel": "Abrir guia de senhas de app",- "tryIt": "Envie um e-mail de teste para a caixa conectada.",- "summary": "O nanobot lê e-mails por IMAP e responde por SMTP. Use uma caixa dedicada e autorize o acesso antes de ativar o canal.",- "steps": [- "Crie uma caixa dedicada e, quando necessário, uma senha de app.",- "Escolha um provedor ou informe IMAP e SMTP manualmente.",- "Autorize o acesso, salve e ative o canal de e-mail. Depois, envie uma mensagem de teste."- ],+ "presetLabel": "Preenchimento rápido",+ "sections": {+ "receiving": "Recebimento de e-mail",+ "sending": "Envio de e-mail"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "Personalizado"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "Permitir que o nanobot leia e envie e-mails",- "help": "Ative para permitir o acesso a esta caixa de e-mail. Confirme que ela é dedicada ao bot.","choices": {"true": "Concedido","false": "Não concedido"@@ -37,8 +31,7 @@},"imapPassword": {"label": "Senha IMAP",- "placeholder": "Senha de app",- "help": "Use uma senha de app quando o provedor exigir."+ "placeholder": "Senha de app"},"smtpHost": {"label": "Host SMTP",@@ -50,8 +43,7 @@},"smtpPassword": {"label": "Senha SMTP",- "placeholder": "Senha de app",- "help": "Normalmente é a mesma senha usada no IMAP."+ "placeholder": "Senha de app"},"imapPort": {"label": "Porta IMAP",@@ -71,8 +63,7 @@},"allowFrom": {"label": "Remetentes permitidos",- "placeholder": "E-mails separados por vírgulas",- "help": "Deixe vazio para exigir pareamento prévio."+ "placeholder": "E-mails separados por vírgulas"},"verifyDkim": {"label": "Verificar DKIM",@@ -87,6 +78,83 @@"true": "Ativado","false": "Desativado"}+ },+ "imapMailbox": {+ "label": "Caixa de correio IMAP"+ },+ "imapUseSsl": {+ "label": "SSL IMAP",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "smtpUseTls": {+ "label": "TLS SMTP",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "smtpUseSsl": {+ "label": "SSL SMTP",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "autoReplyEnabled": {+ "label": "Respostas automáticas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "markSeen": {+ "label": "Marcar como lido",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "postAction": {+ "label": "Após o processamento",+ "choices": {+ "delete": "Excluir",+ "move": "Mover"+ }+ },+ "postActionMoveMailbox": {+ "label": "Mover para caixa de correio"+ },+ "postActionExpunge": {+ "label": "Aplicar ação permanentemente",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "Ignorar mensagens ignoradas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "maxBodyChars": {+ "label": "Comprimento máximo do corpo"+ },+ "subjectPrefix": {+ "label": "Prefixo do assunto da resposta"+ },+ "allowedAttachmentTypes": {+ "label": "Tipos de anexos permitidos"+ },+ "maxAttachmentSize": {+ "label": "Tamanho máximo do anexo"+ },+ "maxAttachmentsPerEmail": {+ "label": "Máximo de anexos"}}}diff --git a/nanobot/channels/email/webui/locales/vi.json b/nanobot/channels/email/webui/locales/vi.jsonindex 24ce00fce..c476a3cde 100644--- a/nanobot/channels/email/webui/locales/vi.json+++ b/nanobot/channels/email/webui/locales/vi.json@@ -1,27 +1,21 @@{"displayName": "Email",- "description": "Cho phép nanobot nhận và trả lời email.",- "requirements": "Hộp thư IMAP, gửi SMTP, mật khẩu ứng dụng và sự đồng ý rõ ràng","setup": {"docsLabel": "Mở hướng dẫn Email","officialLabel": "Mở hướng dẫn mật khẩu ứng dụng",- "tryIt": "Gửi email thử đến hộp thư đã kết nối.",- "summary": "Email đọc thư qua IMAP và trả lời qua SMTP. Dùng hộp thư riêng và cấp quyền trước khi bật.",- "steps": [- "Tạo hộp thư riêng và mật khẩu ứng dụng nếu cần.",- "Chọn nhà cung cấp hoặc nhập thủ công cài đặt IMAP và SMTP.",- "Cấp quyền, lưu và bật Email, sau đó gửi tin nhắn thử."- ],+ "presetLabel": "Điền nhanh",+ "sections": {+ "receiving": "Nhận thư",+ "sending": "Gửi thư"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "Tùy chỉnh"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "Cho phép nanobot đọc và gửi email",- "help": "Bật để cho phép nanobot truy cập hộp thư này. Hãy kiểm tra đây là hộp thư dành riêng cho bot.","choices": {"true": "Đã đồng ý","false": "Chưa đồng ý"@@ -37,8 +31,7 @@},"imapPassword": {"label": "Mật khẩu IMAP",- "placeholder": "Mật khẩu ứng dụng",- "help": "Dùng mật khẩu ứng dụng khi nhà cung cấp yêu cầu."+ "placeholder": "Mật khẩu ứng dụng"},"smtpHost": {"label": "Máy chủ SMTP",@@ -50,8 +43,7 @@},"smtpPassword": {"label": "Mật khẩu SMTP",- "placeholder": "Mật khẩu ứng dụng",- "help": "Thường giống mật khẩu ứng dụng dùng cho IMAP."+ "placeholder": "Mật khẩu ứng dụng"},"imapPort": {"label": "Cổng IMAP",@@ -71,8 +63,7 @@},"allowFrom": {"label": "Người gửi được phép",- "placeholder": "Địa chỉ email, phân tách bằng dấu phẩy",- "help": "Để trống để yêu cầu ghép nối trước."+ "placeholder": "Địa chỉ email, phân tách bằng dấu phẩy"},"verifyDkim": {"label": "Xác minh DKIM",@@ -87,6 +78,83 @@"true": "Bật","false": "Tắt"}+ },+ "imapMailbox": {+ "label": "Hộp thư IMAP"+ },+ "imapUseSsl": {+ "label": "SSL IMAP",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "smtpUseTls": {+ "label": "TLS SMTP",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "smtpUseSsl": {+ "label": "SSL SMTP",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "autoReplyEnabled": {+ "label": "Trả lời tự động",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "markSeen": {+ "label": "Đánh dấu là đã đọc",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "postAction": {+ "label": "Sau khi xử lý",+ "choices": {+ "delete": "Xóa",+ "move": "Di chuyển"+ }+ },+ "postActionMoveMailbox": {+ "label": "Di chuyển tới hộp thư"+ },+ "postActionExpunge": {+ "label": "Áp dụng hành động vĩnh viễn",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "Bỏ qua tin nhắn bị bỏ qua",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "maxBodyChars": {+ "label": "Chiều dài cơ thể tối đa"+ },+ "subjectPrefix": {+ "label": "Trả lời tiền tố chủ đề"+ },+ "allowedAttachmentTypes": {+ "label": "Các loại tệp đính kèm được phép"+ },+ "maxAttachmentSize": {+ "label": "Kích thước tệp đính kèm tối đa"+ },+ "maxAttachmentsPerEmail": {+ "label": "Tệp đính kèm tối đa"}}}diff --git a/nanobot/channels/email/webui/locales/zh-CN.json b/nanobot/channels/email/webui/locales/zh-CN.jsonindex 961422b47..b664ad8f8 100644--- a/nanobot/channels/email/webui/locales/zh-CN.json+++ b/nanobot/channels/email/webui/locales/zh-CN.json@@ -1,26 +1,20 @@{- "description": "让 nanobot 接收并回复电子邮件。",- "requirements": "IMAP 收件箱、SMTP 发件服务、应用专用密码和明确授权","setup": {"docsLabel": "打开邮件配置指南","officialLabel": "打开应用专用密码指南",- "tryIt": "向已连接的邮箱发送一封测试邮件。",- "summary": "邮件渠道通过 IMAP 读取邮件并通过 SMTP 回复。请使用专用邮箱,并在启用前明确授权。",- "steps": [- "创建专用邮箱,并在服务商要求时创建应用专用密码。",- "选择服务商预设,或手动填写 IMAP 和 SMTP 设置。",- "授予授权,保存并启用邮件渠道,然后向邮箱发送一封测试邮件。"- ],+ "presetLabel": "快速填充",+ "sections": {+ "receiving": "接收邮件",+ "sending": "发送邮件"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "自定义"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "允许 nanobot 读取和发送邮件",- "help": "开启即表示同意 nanobot 访问此邮箱。请确认这是你要连接的机器人专用邮箱。","choices": {"true": "已授权","false": "未授权"@@ -36,8 +30,7 @@},"imapPassword": {"label": "IMAP 密码",- "placeholder": "应用专用密码",- "help": "如果邮件服务商要求,请使用应用专用密码。"+ "placeholder": "应用专用密码"},"smtpHost": {"label": "SMTP 主机",@@ -49,8 +42,7 @@},"smtpPassword": {"label": "SMTP 密码",- "placeholder": "应用专用密码",- "help": "通常与 IMAP 使用同一个应用专用密码。"+ "placeholder": "应用专用密码"},"imapPort": {"label": "IMAP 端口",@@ -70,8 +62,7 @@},"allowFrom": {"label": "允许的发件人",- "placeholder": "邮箱地址,用逗号分隔",- "help": "留空则要求发件人先完成配对。"+ "placeholder": "邮箱地址,用逗号分隔"},"verifyDkim": {"label": "验证 DKIM",@@ -86,6 +77,83 @@"true": "开启","false": "关闭"}+ },+ "imapMailbox": {+ "label": "IMAP 邮箱"+ },+ "imapUseSsl": {+ "label": "IMAP SSL",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "smtpUseTls": {+ "label": "SMTP TLS",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "smtpUseSsl": {+ "label": "SMTP SSL",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "autoReplyEnabled": {+ "label": "自动回复",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "markSeen": {+ "label": "标为已读",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "postAction": {+ "label": "处理后",+ "choices": {+ "delete": "删除",+ "move": "移动"+ }+ },+ "postActionMoveMailbox": {+ "label": "移至邮箱"+ },+ "postActionExpunge": {+ "label": "永久执行操作",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "忽略未处理邮件",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "maxBodyChars": {+ "label": "正文长度上限"+ },+ "subjectPrefix": {+ "label": "回复主题前缀"+ },+ "allowedAttachmentTypes": {+ "label": "允许的附件类型"+ },+ "maxAttachmentSize": {+ "label": "附件大小上限"+ },+ "maxAttachmentsPerEmail": {+ "label": "附件数量上限"}}},diff --git a/nanobot/channels/email/webui/locales/zh-TW.json b/nanobot/channels/email/webui/locales/zh-TW.jsonindex fbce0a910..27d5b4166 100644--- a/nanobot/channels/email/webui/locales/zh-TW.json+++ b/nanobot/channels/email/webui/locales/zh-TW.json@@ -1,27 +1,21 @@{"displayName": "電子郵件",- "description": "讓 nanobot 接收並回覆電子郵件。",- "requirements": "IMAP 收件匣、SMTP 寄件服務、應用程式密碼和明確授權","setup": {"docsLabel": "開啟郵件設定指南","officialLabel": "開啟應用程式密碼指南",- "tryIt": "向已連接的信箱傳送一封測試郵件。",- "summary": "郵件管道透過 IMAP 讀取郵件並透過 SMTP 回覆。請使用專用信箱,並在啟用前明確授權。",- "steps": [- "建立專用信箱,並在服務商要求時建立應用程式密碼。",- "選擇服務商預設,或手動填入 IMAP 和 SMTP 設定。",- "授予權限,儲存並啟用郵件管道,然後向信箱傳送一封測試郵件。"- ],+ "presetLabel": "快速填入",+ "sections": {+ "receiving": "接收郵件",+ "sending": "傳送郵件"+ },"presets": {"gmail": "Gmail","outlook": "Outlook",- "icloud": "iCloud",- "custom": "自訂"+ "icloud": "iCloud"},"fields": {"consentGranted": {"label": "允許 nanobot 讀取及傳送電子郵件",- "help": "開啟即表示同意 nanobot 存取此信箱。請確認這是要提供給機器人使用的專用信箱。","choices": {"true": "已授權","false": "未授權"@@ -37,8 +31,7 @@},"imapPassword": {"label": "IMAP 密碼",- "placeholder": "應用程式密碼",- "help": "若郵件服務商要求,請使用應用程式密碼。"+ "placeholder": "應用程式密碼"},"smtpHost": {"label": "SMTP 主機",@@ -50,8 +43,7 @@},"smtpPassword": {"label": "SMTP 密碼",- "placeholder": "應用程式密碼",- "help": "通常與 IMAP 使用同一個應用程式密碼。"+ "placeholder": "應用程式密碼"},"imapPort": {"label": "IMAP 連接埠",@@ -71,8 +63,7 @@},"allowFrom": {"label": "允許的寄件者",- "placeholder": "電子郵件地址,以逗號分隔",- "help": "留空則要求寄件者先完成配對。"+ "placeholder": "電子郵件地址,以逗號分隔"},"verifyDkim": {"label": "驗證 DKIM",@@ -87,6 +78,83 @@"true": "開啟","false": "關閉"}+ },+ "imapMailbox": {+ "label": "IMAP 信箱"+ },+ "imapUseSsl": {+ "label": "IMAP SSL",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "smtpUseTls": {+ "label": "SMTP TLS",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "smtpUseSsl": {+ "label": "SMTP SSL",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "autoReplyEnabled": {+ "label": "自動回覆",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "markSeen": {+ "label": "標為已讀",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "postAction": {+ "label": "處理後",+ "choices": {+ "delete": "刪除",+ "move": "移動"+ }+ },+ "postActionMoveMailbox": {+ "label": "移至信箱"+ },+ "postActionExpunge": {+ "label": "永久執行操作",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "postActionIgnoreSkipped": {+ "label": "忽略未處理郵件",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "maxBodyChars": {+ "label": "正文長度上限"+ },+ "subjectPrefix": {+ "label": "回覆主題前綴"+ },+ "allowedAttachmentTypes": {+ "label": "允許的附件類型"+ },+ "maxAttachmentSize": {+ "label": "附件大小上限"+ },+ "maxAttachmentsPerEmail": {+ "label": "附件數量上限"}}}diff --git a/nanobot/channels/feishu/manifest.py b/nanobot/channels/feishu/manifest.pyindex ee6c00f4a..2b248f7a1 100644--- a/nanobot/channels/feishu/manifest.py+++ b/nanobot/channels/feishu/manifest.py@@ -24,6 +24,16 @@ SETUP_SPEC = ChannelSetupSpec(),"allowFrom": field("list", snapshot=False),"topicIsolation": field("bool", default=True, snapshot=False),+ "name": field(default="nanobot", snapshot=False),+ "encryptKey": field("secret", snapshot=False),+ "verificationToken": field("secret", snapshot=False),+ "reactEmoji": field(default="THUMBSUP", snapshot=False),+ "doneEmoji": field(snapshot=False),+ "toolHintPrefix": field(default="🔧", snapshot=False),+ "replyToMessage": field("bool", default=False, snapshot=False),+ "streaming": field("bool", default=True, snapshot=False),+ "instanceId": field(writable=False, snapshot=False),+ "identityKey": field(writable=False, snapshot=False),},required=required_fields("appId", "appSecret"),official_url="https://open.feishu.cn/app",diff --git a/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx b/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsxindex f9536903a..012638544 100644--- a/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx+++ b/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx@@ -1,29 +1,20 @@-import { useState } from "react";-import { Loader2, RotateCcw } from "lucide-react";import { useTranslation } from "react-i18next";import {channelTranslator,- type ChannelTranslator,} from "@/channel-plugins/i18n";import type { ChannelPluginPanelProps } from "@/channel-plugins/types";import { ChannelInstancesPanel } from "@/components/settings/channels/ChannelInstancesPanel";-import { Button } from "@/components/ui/button";-import { enableNanobotFeature } from "@/lib/api";import type {NanobotChannelInstanceInfo,NanobotFeatureInfo,- NanobotFeaturesPayload,} from "@/lib/types";-import { useClient } from "@/providers/ClientProvider";-import { FeishuConnectFlow } from "./FeishuConnectFlow";export function FeishuAssistantsPanel({token,feature,showBrandLogos,- chatAppsDocsUrl,onFeaturesUpdate,}: ChannelPluginPanelProps) {const { t } = useTranslation();@@ -36,122 +27,30 @@ export function FeishuAssistantsPanel({<ChannelInstancesPanelfeature={feature}showBrandLogos={showBrandLogos}- chatAppsDocsUrl={chatAppsDocsUrl}instances={instances}onFeaturesUpdate={onFeaturesUpdate}customization={{- countLabel: (count) => feishuAssistantCountLabel(count, tx),toggleAriaLabel: (instance) => tx("custom.toggleAssistant", "{{name}} assistant", {name: instanceDisplayName(instance),}),configuredLabel: tx("custom.configured", "Connected"),needsSetupLabel: tx("custom.needsSetup", "Needs authorization"),- renderInstanceSummary: (instance) => (- maskFeishuAppId(instance.config_values?.["channels.feishu.appId"])- || tx("custom.noAppId", "No App ID")- ),- renderInstanceAction: (instance) => (- <FeishuInstanceAction+ renderInstanceSummary: () => null,+ renderInstanceAction: (instance) => instance.configured ? null : (+ <FeishuConnectFlowkey={instance.id}token={token}- instance={instance}+ instanceId={instance.id}+ mode="replace"+ idleLabel={t("settings.channels.connect", { defaultValue: "Connect" })}onFeaturesUpdate={onFeaturesUpdate}/>),- footer: (- <div className="mt-4 overflow-hidden rounded-floating border border-border/70 bg-background px-4 py-4">- <div className="text-[13px] font-semibold text-foreground">- {tx("custom.createAnother", "Create another assistant")}- </div>- <p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">- {tx(- "custom.createHint",- "Create a separate Feishu bot for another team, space, or workflow.",- )}- </p>- <FeishuConnectFlow- token={token}- instanceId="default"- mode="create"- idleLabel={tx("custom.createAssistant", "Create assistant")}- onFeaturesUpdate={onFeaturesUpdate}- />- </div>- ),}}/>);}-function FeishuInstanceAction({- token,- instance,- onFeaturesUpdate,-}: {- token: string;- instance: NanobotChannelInstanceInfo;- onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;-}) {- const { client } = useClient();- const { t } = useTranslation();- const tx = channelTranslator(t, "feishu");- const [busy, setBusy] = useState(false);- const [error, setError] = useState<string | null>(null);-- if (!instance.configured) {- return (- <FeishuConnectFlow- token={token}- instanceId={instance.id}- mode="replace"- idleLabel={t("settings.channels.connect", { defaultValue: "Connect" })}- onFeaturesUpdate={onFeaturesUpdate}- />- );- }-- const reconnect = async () => {- setBusy(true);- setError(null);- try {- onFeaturesUpdate(- await enableNanobotFeature(client, "feishu", { instanceId: instance.id }),- );- } catch (err) {- setError((err as Error).message);- } finally {- setBusy(false);- }- };-- return (- <>- <div className="mt-3 flex justify-end">- <Button- type="button"- size="sm"- variant="outline"- className="h-8 rounded-full border-border/65 bg-background/80 px-3 text-[12px] font-semibold hover:bg-muted/70"- onClick={() => void reconnect()}- disabled={busy || !instance.enabled}- >- {busy ? (- <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />- ) : (- <RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />- )}- {tx("custom.reconnect", "Reconnect")}- </Button>- </div>- {error ? (- <div className="mt-3 rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">- {error}- </div>- ) : null}- </>- );-}-function defaultFeishuInstance(feature: NanobotFeatureInfo): NanobotChannelInstanceInfo {return {id: "default",@@ -163,21 +62,6 @@ function defaultFeishuInstance(feature: NanobotFeatureInfo): NanobotChannelInsta};}-function feishuAssistantCountLabel(- count: number,- tx: ChannelTranslator,-): string {- if (count === 0) return tx("custom.countNone", "No assistant connected");- if (count === 1) return tx("custom.countOne", "1 assistant connected");- return tx("custom.countMany", "{{count}} assistants connected", { count });-}-function instanceDisplayName(instance: NanobotChannelInstanceInfo): string {return instance.display_name?.trim() || instance.name.trim() || instance.id;}--function maskFeishuAppId(appId: string | undefined): string {- if (!appId) return "";- if (appId.length <= 10) return appId;- return `${appId.slice(0, 7)}...${appId.slice(-4)}`;-}diff --git a/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx b/nanobot/channels/feishu/webui/FeishuConnectFlow.tsxindex 7142ebe54..471a57bc0 100644--- a/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx+++ b/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx@@ -25,7 +25,7 @@ export function FeishuConnectFlow({<ChannelQrConnectFlowtoken={token}channelName="feishu"- startOptions={{ domain: "feishu", instanceId, mode }}+ startParams={{ domain: "feishu", instance_id: instanceId, mode }}idleLabel={idleLabel}connectRequestId={connectRequestId}onFeaturesUpdate={onFeaturesUpdate}diff --git a/nanobot/channels/feishu/webui/index.tsx b/nanobot/channels/feishu/webui/index.tsxindex 5e32a56b5..13ec8153d 100644--- a/nanobot/channels/feishu/webui/index.tsx+++ b/nanobot/channels/feishu/webui/index.tsx@@ -15,14 +15,13 @@ export default {lark: {displayName: "Lark",initials: "LK",- logoUrl: "https://www.larksuite.com/favicon.ico",},},presentation: {+ logoUrl: "https://www.larksuite.com/favicon.ico",displayName: "Feishu",initials: "FS",color: "#3370FF",- logoUrl: "https://www.feishu.cn/favicon.ico",setup: {mode: "connect",command: "nanobot channels login feishu",diff --git a/nanobot/channels/feishu/webui/locales/en.json b/nanobot/channels/feishu/webui/locales/en.jsonindex 8075ea02e..06040d21a 100644--- a/nanobot/channels/feishu/webui/locales/en.json+++ b/nanobot/channels/feishu/webui/locales/en.json@@ -1,17 +1,8 @@{- "description": "Use nanobot from Feishu chats and groups.",- "requirements": "Feishu app credentials, event subscription, gateway","setup": {"primaryAction": "Connect with Feishu","docsLabel": "Open Feishu setup","officialLabel": "Open Feishu console",- "tryIt": "Send a DM or mention the Feishu assistant in a group.",- "summary": "Connect creates or links a Feishu app by QR code, then saves the app credentials for nanobot.",- "steps": [- "Click Connect and scan the QR code with Feishu or Lark on your phone.",- "Approve the app connection. nanobot saves the App ID and Secret automatically.",- "Send the bot a direct message or mention it in a Feishu group to test it."- ],"fields": {"appId": {"label": "App ID",@@ -19,8 +10,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "Leave blank to keep current secret",- "help": "Paste a new App Secret only when rotating credentials."+ "placeholder": "Leave blank to keep current secret"},"domain": {"label": "Region",@@ -47,6 +37,38 @@"true": "Separate session for each topic","false": "One shared session for the group"}+ },+ "name": {+ "label": "Account name"+ },+ "encryptKey": {+ "label": "Encryption key"+ },+ "verificationToken": {+ "label": "Verification token"+ },+ "reactEmoji": {+ "label": "Read emoji"+ },+ "doneEmoji": {+ "label": "Done emoji"+ },+ "toolHintPrefix": {+ "label": "Tool hint prefix"+ },+ "replyToMessage": {+ "label": "Reply to message",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "On",+ "false": "Off"+ }}}},@@ -54,14 +76,6 @@"toggleAssistant": "{{name}} assistant","configured": "Connected","needsSetup": "Needs authorization",- "noAppId": "No App ID",- "createAnother": "Create another assistant",- "createHint": "Create a separate Feishu bot for another team, space, or workflow.",- "createAssistant": "Create assistant",- "reconnect": "Reconnect",- "countNone": "No assistant connected",- "countOne": "1 assistant connected",- "countMany": "{{count}} assistants connected","qrAlt": "Feishu connection QR code","scanTitle": "Scan with Feishu","scanDescription": "Use Feishu or Lark on your phone to scan this code. nanobot will finish setup automatically after authorization.",diff --git a/nanobot/channels/feishu/webui/locales/es.json b/nanobot/channels/feishu/webui/locales/es.jsonindex a21fe1348..76add6601 100644--- a/nanobot/channels/feishu/webui/locales/es.json+++ b/nanobot/channels/feishu/webui/locales/es.json@@ -1,17 +1,8 @@{- "description": "Usa nanobot en chats y grupos de Feishu.",- "requirements": "Credenciales de Feishu, suscripción a eventos y pasarela","setup": {"primaryAction": "Conectar Feishu","docsLabel": "Abrir guía de Feishu","officialLabel": "Abrir consola de Feishu",- "tryIt": "Envía un DM o menciona al asistente en un grupo.",- "summary": "La conexión crea o vincula una app de Feishu por QR y guarda sus credenciales.",- "steps": [- "Haz clic en Conectar y escanea el QR con Feishu o Lark.",- "Aprueba la conexión. nanobot guarda el App ID y el Secret automáticamente.",- "Envía un DM al bot o menciónalo en un grupo de Feishu."- ],"fields": {"appId": {"label": "App ID",@@ -19,8 +10,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "Déjalo vacío para conservar el secreto",- "help": "Pega un nuevo secreto solo si quieres sustituir el que está guardado."+ "placeholder": "Déjalo vacío para conservar el secreto"},"domain": {"label": "Región",@@ -47,6 +37,38 @@"true": "Una sesión separada por tema","false": "Una sesión compartida para el grupo"}+ },+ "name": {+ "label": "Nombre de cuenta"+ },+ "encryptKey": {+ "label": "Clave de cifrado"+ },+ "verificationToken": {+ "label": "Token de verificación"+ },+ "reactEmoji": {+ "label": "Leer emojis"+ },+ "doneEmoji": {+ "label": "emoji hecho"+ },+ "toolHintPrefix": {+ "label": "Prefijo de sugerencia de herramienta"+ },+ "replyToMessage": {+ "label": "Responder al mensaje",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "streaming": {+ "label": "Transmisión",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }}}},@@ -54,14 +76,6 @@"toggleAssistant": "Activar el asistente {{name}}","configured": "Conectado","needsSetup": "Necesita autorización",- "noAppId": "Sin App ID",- "createAnother": "Crear otro asistente",- "createHint": "Crea un bot de Feishu independiente para otro equipo, espacio o flujo de trabajo.",- "createAssistant": "Crear asistente",- "reconnect": "Reconectar",- "countNone": "Ningún asistente conectado",- "countOne": "1 asistente conectado",- "countMany": "{{count}} asistentes conectados","qrAlt": "Código QR de conexión de Feishu","scanTitle": "Escanea con Feishu","scanDescription": "Escanea con Feishu o Lark en tu teléfono. nanobot completará la configuración tras la autorización.",diff --git a/nanobot/channels/feishu/webui/locales/fr.json b/nanobot/channels/feishu/webui/locales/fr.jsonindex 395e28d17..87288bf64 100644--- a/nanobot/channels/feishu/webui/locales/fr.json+++ b/nanobot/channels/feishu/webui/locales/fr.json@@ -1,17 +1,8 @@{- "description": "Utilisez nanobot dans les conversations et groupes Feishu.",- "requirements": "Identifiants Feishu, abonnement aux événements et passerelle","setup": {"primaryAction": "Connecter Feishu","docsLabel": "Ouvrir le guide Feishu","officialLabel": "Ouvrir la console Feishu",- "tryIt": "Envoyez un message privé ou mentionnez l’assistant dans un groupe.",- "summary": "La connexion crée ou associe une application Feishu par QR code et enregistre ses identifiants.",- "steps": [- "Cliquez sur Connecter et scannez le QR code avec Feishu ou Lark.",- "Approuvez la connexion. nanobot enregistre automatiquement l’App ID et le Secret.",- "Envoyez un message privé au bot ou mentionnez-le dans un groupe Feishu."- ],"fields": {"appId": {"label": "App ID",@@ -19,8 +10,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "Laisser vide pour conserver le secret",- "help": "Collez un nouveau secret uniquement pour remplacer celui qui est enregistré."+ "placeholder": "Laisser vide pour conserver le secret"},"domain": {"label": "Région",@@ -47,6 +37,38 @@"true": "Une session séparée par sujet","false": "Une session partagée pour le groupe"}+ },+ "name": {+ "label": "Nom du compte"+ },+ "encryptKey": {+ "label": "Clé de chiffrement"+ },+ "verificationToken": {+ "label": "Jeton de vérification"+ },+ "reactEmoji": {+ "label": "Lire les emoji"+ },+ "doneEmoji": {+ "label": "Terminé emoji"+ },+ "toolHintPrefix": {+ "label": "Préfixe d'indice d'outil"+ },+ "replyToMessage": {+ "label": "Répondre au message",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "streaming": {+ "label": "Diffusion en continu",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }}}},@@ -54,14 +76,6 @@"toggleAssistant": "Activer l’assistant {{name}}","configured": "Connecté","needsSetup": "Autorisation requise",- "noAppId": "Aucun App ID",- "createAnother": "Créer un autre assistant",- "createHint": "Créez un bot Feishu distinct pour une autre équipe, un autre espace ou un autre usage.",- "createAssistant": "Créer l’assistant",- "reconnect": "Reconnecter",- "countNone": "Aucun assistant connecté",- "countOne": "1 assistant connecté",- "countMany": "{{count}} assistants connectés","qrAlt": "QR code de connexion Feishu","scanTitle": "Scanner avec Feishu","scanDescription": "Utilisez Feishu ou Lark sur votre téléphone pour scanner ce code. nanobot terminera la configuration après autorisation.",diff --git a/nanobot/channels/feishu/webui/locales/id.json b/nanobot/channels/feishu/webui/locales/id.jsonindex 957baf50f..c84e72128 100644--- a/nanobot/channels/feishu/webui/locales/id.json+++ b/nanobot/channels/feishu/webui/locales/id.json@@ -1,17 +1,8 @@{- "description": "Gunakan nanobot dari chat dan grup Feishu.",- "requirements": "Kredensial Feishu, langganan event, dan gateway","setup": {"primaryAction": "Hubungkan Feishu","docsLabel": "Buka panduan Feishu","officialLabel": "Buka konsol Feishu",- "tryIt": "Kirim DM atau sebut asisten di grup.",- "summary": "Koneksi membuat atau menautkan aplikasi Feishu lewat QR dan menyimpan kredensialnya.",- "steps": [- "Klik Hubungkan dan pindai QR dengan Feishu atau Lark.",- "Setujui koneksi. nanobot menyimpan App ID dan Secret otomatis.",- "Kirim DM ke bot atau sebut di grup Feishu."- ],"fields": {"appId": {"label": "App ID",@@ -19,8 +10,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "Kosongkan untuk mempertahankan secret",- "help": "Masukkan App Secret baru hanya untuk mengganti nilai yang tersimpan."+ "placeholder": "Kosongkan untuk mempertahankan secret"},"domain": {"label": "Wilayah",@@ -47,6 +37,38 @@"true": "Sesi terpisah untuk setiap topik","false": "Satu sesi bersama untuk grup"}+ },+ "name": {+ "label": "Nama akun"+ },+ "encryptKey": {+ "label": "Kunci enkripsi"+ },+ "verificationToken": {+ "label": "Token verifikasi"+ },+ "reactEmoji": {+ "label": "Baca emoji"+ },+ "doneEmoji": {+ "label": "Selesai emoji"+ },+ "toolHintPrefix": {+ "label": "Awalan petunjuk alat"+ },+ "replyToMessage": {+ "label": "Membalas pesan",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }}}},@@ -54,14 +76,6 @@"toggleAssistant": "Aktifkan asisten {{name}}","configured": "Terhubung","needsSetup": "Perlu otorisasi",- "noAppId": "Tidak ada App ID",- "createAnother": "Buat asisten lain",- "createHint": "Buat bot Feishu terpisah untuk tim atau alur kerja lain.",- "createAssistant": "Buat asisten",- "reconnect": "Hubungkan ulang",- "countNone": "Belum ada asisten terhubung",- "countOne": "1 asisten terhubung",- "countMany": "{{count}} asisten terhubung","qrAlt": "Kode QR koneksi Feishu","scanTitle": "Pindai dengan Feishu","scanDescription": "Pindai kode ini dengan Feishu atau Lark di ponsel. nanobot akan menyelesaikan penyiapan setelah Anda menyetujui akses.",diff --git a/nanobot/channels/feishu/webui/locales/ja.json b/nanobot/channels/feishu/webui/locales/ja.jsonindex f4532c35f..7ffafcc8b 100644--- a/nanobot/channels/feishu/webui/locales/ja.json+++ b/nanobot/channels/feishu/webui/locales/ja.json@@ -1,17 +1,8 @@{- "description": "Feishu のチャットとグループから nanobot を利用します。",- "requirements": "Feishu アプリ認証情報、イベント購読、ゲートウェイ","setup": {"primaryAction": "Feishu に接続","docsLabel": "Feishu 設定ガイドを開く","officialLabel": "Feishu コンソールを開く",- "tryIt": "DM を送るか、グループで Feishu アシスタントをメンションします。",- "summary": "QR コードで Feishu アプリを作成または連携し、認証情報を自動保存します。",- "steps": [- "接続をクリックし、スマートフォンの Feishu または Lark で QR コードを読み取ります。",- "アプリ接続を承認すると、nanobot が App ID と Secret を保存します。",- "ボットに DM を送るか Feishu グループでメンションします。"- ],"fields": {"appId": {"label": "App ID",@@ -19,8 +10,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "現在のシークレットを保持するには空欄",- "help": "認証情報を更新するときだけ新しい App Secret を貼り付けます。"+ "placeholder": "現在のシークレットを保持するには空欄"},"domain": {"label": "地域",@@ -47,6 +37,38 @@"true": "トピックごとにセッションを分離","false": "グループでセッションを共有"}+ },+ "name": {+ "label": "アカウント名"+ },+ "encryptKey": {+ "label": "暗号化キー"+ },+ "verificationToken": {+ "label": "検証トークン"+ },+ "reactEmoji": {+ "label": "絵文字を読む"+ },+ "doneEmoji": {+ "label": "完了絵文字"+ },+ "toolHintPrefix": {+ "label": "ツールヒントの接頭辞"+ },+ "replyToMessage": {+ "label": "メッセージに返信する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "streaming": {+ "label": "ストリーミング",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }}}},@@ -54,14 +76,6 @@"toggleAssistant": "アシスタント {{name}} を有効にする","configured": "接続済み","needsSetup": "認可が必要",- "noAppId": "App ID なし",- "createAnother": "別のアシスタントを作成",- "createHint": "別のチームやワークフロー用に独立した Feishu ボットを作成します。",- "createAssistant": "アシスタントを作成",- "reconnect": "再接続",- "countNone": "接続済みアシスタントなし",- "countOne": "接続済みアシスタント:1 件",- "countMany": "接続済みアシスタント:{{count}} 件","qrAlt": "Feishu 接続 QR コード","scanTitle": "Feishu でスキャン","scanDescription": "スマートフォンの Feishu または Lark でスキャンしてください。認可後に nanobot が設定を完了します。",diff --git a/nanobot/channels/feishu/webui/locales/ko.json b/nanobot/channels/feishu/webui/locales/ko.jsonindex 03b632a47..8dd21c805 100644--- a/nanobot/channels/feishu/webui/locales/ko.json+++ b/nanobot/channels/feishu/webui/locales/ko.json@@ -1,17 +1,8 @@{- "description": "Feishu 채팅과 그룹에서 nanobot을 사용합니다.",- "requirements": "Feishu 앱 인증 정보, 이벤트 구독 및 게이트웨이","setup": {"primaryAction": "Feishu 연결","docsLabel": "Feishu 설정 가이드 열기","officialLabel": "Feishu 콘솔 열기",- "tryIt": "DM을 보내거나 그룹에서 Feishu 어시스턴트를 멘션하세요.",- "summary": "QR 코드로 Feishu 앱을 만들거나 연결하고 인증 정보을 자동 저장합니다.",- "steps": [- "연결을 클릭하고 휴대폰의 Feishu 또는 Lark로 QR 코드를 스캔하세요.",- "앱 연결을 승인하면 nanobot이 App ID와 Secret을 자동 저장합니다.",- "봇에 DM을 보내거나 Feishu 그룹에서 멘션하세요."- ],"fields": {"appId": {"label": "App ID",@@ -19,8 +10,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "현재 Secret을 유지하려면 비워 두세요",- "help": "인증 정보을 교체할 때만 새 App Secret을 붙여 넣으세요."+ "placeholder": "현재 Secret을 유지하려면 비워 두세요"},"domain": {"label": "지역",@@ -47,6 +37,38 @@"true": "주제별로 세션 분리","false": "그룹에서 하나의 세션 공유"}+ },+ "name": {+ "label": "계정 이름"+ },+ "encryptKey": {+ "label": "암호화 키"+ },+ "verificationToken": {+ "label": "인증 토큰"+ },+ "reactEmoji": {+ "label": "이모티콘 읽기"+ },+ "doneEmoji": {+ "label": "이모티콘 완료"+ },+ "toolHintPrefix": {+ "label": "도구 힌트 접두사"+ },+ "replyToMessage": {+ "label": "메시지에 답장하기",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "streaming": {+ "label": "스트리밍",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }}}},@@ -54,14 +76,6 @@"toggleAssistant": "{{name}} 어시스턴트 활성화","configured": "연결됨","needsSetup": "인증 필요",- "noAppId": "App ID 없음",- "createAnother": "다른 어시스턴트 만들기",- "createHint": "다른 팀이나 워크플로를 위한 별도 Feishu 봇을 만드세요.",- "createAssistant": "어시스턴트 만들기",- "reconnect": "다시 연결",- "countNone": "연결된 어시스턴트 없음",- "countOne": "어시스턴트 1개 연결됨",- "countMany": "어시스턴트 {{count}}개 연결됨","qrAlt": "Feishu 연결 QR 코드","scanTitle": "Feishu로 스캔","scanDescription": "휴대폰의 Feishu 또는 Lark로 스캔하세요. 승인 후 nanobot이 설정을 완료합니다.",diff --git a/nanobot/channels/feishu/webui/locales/pt-BR.json b/nanobot/channels/feishu/webui/locales/pt-BR.jsonindex 21f0d1ba3..b8d442239 100644--- a/nanobot/channels/feishu/webui/locales/pt-BR.json+++ b/nanobot/channels/feishu/webui/locales/pt-BR.json@@ -1,17 +1,8 @@{- "description": "Use o nanobot em conversas e grupos do Feishu.",- "requirements": "Credenciais do Feishu, assinatura de eventos e gateway","setup": {"primaryAction": "Conectar Feishu","docsLabel": "Abrir guia do Feishu","officialLabel": "Abrir console do Feishu",- "tryIt": "Envie uma DM ou mencione o assistente em um grupo.",- "summary": "A conexão cria ou vincula um app Feishu por QR e salva as credenciais.",- "steps": [- "Clique em Conectar e escaneie o QR com Feishu ou Lark.",- "Aprove a conexão. O nanobot salva App ID e Secret automaticamente.",- "Envie uma DM ao bot ou mencione-o em um grupo Feishu."- ],"fields": {"appId": {"label": "App ID",@@ -19,8 +10,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "Deixe vazio para manter o segredo",- "help": "Cole um novo apenas ao trocar credenciais."+ "placeholder": "Deixe vazio para manter o segredo"},"domain": {"label": "Região",@@ -47,6 +37,38 @@"true": "Uma sessão separada por tópico","false": "Uma sessão compartilhada para o grupo"}+ },+ "name": {+ "label": "Nome da conta"+ },+ "encryptKey": {+ "label": "Chave de criptografia"+ },+ "verificationToken": {+ "label": "Token de verificação"+ },+ "reactEmoji": {+ "label": "Ler emoticons"+ },+ "doneEmoji": {+ "label": "Emoji pronto"+ },+ "toolHintPrefix": {+ "label": "Prefixo de dica de ferramenta"+ },+ "replyToMessage": {+ "label": "Responder à mensagem",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "streaming": {+ "label": "Transmissão",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }}}},@@ -54,14 +76,6 @@"toggleAssistant": "Ativar assistente {{name}}","configured": "Conectado","needsSetup": "Precisa de autorização",- "noAppId": "Sem App ID",- "createAnother": "Criar outro assistente",- "createHint": "Crie um bot Feishu separado para outra equipe, espaço ou fluxo de trabalho.",- "createAssistant": "Criar assistente",- "reconnect": "Reconectar",- "countNone": "Nenhum assistente conectado",- "countOne": "1 assistente conectado",- "countMany": "{{count}} assistentes conectados","qrAlt": "QR code de conexão do Feishu","scanTitle": "Escaneie com o Feishu","scanDescription": "Escaneie com Feishu ou Lark no celular. O nanobot concluirá a configuração após a autorização.",diff --git a/nanobot/channels/feishu/webui/locales/vi.json b/nanobot/channels/feishu/webui/locales/vi.jsonindex 7fdaf3a6b..ecf607fdd 100644--- a/nanobot/channels/feishu/webui/locales/vi.json+++ b/nanobot/channels/feishu/webui/locales/vi.json@@ -1,17 +1,8 @@{- "description": "Sử dụng nanobot trong cuộc trò chuyện và nhóm Feishu.",- "requirements": "Thông tin xác thực Feishu, đăng ký sự kiện và gateway","setup": {"primaryAction": "Kết nối Feishu","docsLabel": "Mở hướng dẫn Feishu","officialLabel": "Mở bảng điều khiển Feishu",- "tryIt": "Gửi tin nhắn riêng hoặc nhắc trợ lý trong nhóm.",- "summary": "Kết nối tạo hoặc liên kết ứng dụng Feishu bằng QR và lưu thông tin xác thực.",- "steps": [- "Nhấn Kết nối và quét QR bằng Feishu hoặc Lark.",- "Phê duyệt kết nối. nanobot tự lưu App ID và Secret.",- "Gửi tin nhắn riêng cho bot hoặc nhắc bot trong nhóm Feishu."- ],"fields": {"appId": {"label": "App ID",@@ -19,8 +10,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "Để trống để giữ khóa hiện tại",- "help": "Chỉ nhập App Secret mới khi muốn thay thế giá trị đã lưu."+ "placeholder": "Để trống để giữ khóa hiện tại"},"domain": {"label": "Khu vực",@@ -47,6 +37,38 @@"true": "Phiên riêng cho từng chủ đề","false": "Dùng chung một phiên cho nhóm"}+ },+ "name": {+ "label": "Tên tài khoản"+ },+ "encryptKey": {+ "label": "Khóa mã hóa"+ },+ "verificationToken": {+ "label": "Mã thông báo xác minh"+ },+ "reactEmoji": {+ "label": "Đọc biểu tượng cảm xúc"+ },+ "doneEmoji": {+ "label": "biểu tượng cảm xúc xong"+ },+ "toolHintPrefix": {+ "label": "Tiền tố gợi ý công cụ"+ },+ "replyToMessage": {+ "label": "Trả lời tin nhắn",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "streaming": {+ "label": "Truyền phát",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }}}},@@ -54,14 +76,6 @@"toggleAssistant": "Bật trợ lý {{name}}","configured": "Đã kết nối","needsSetup": "Cần cấp quyền",- "noAppId": "Không có App ID",- "createAnother": "Tạo trợ lý khác",- "createHint": "Tạo bot Feishu riêng cho nhóm hoặc quy trình khác.",- "createAssistant": "Tạo trợ lý",- "reconnect": "Kết nối lại",- "countNone": "Chưa kết nối trợ lý",- "countOne": "Đã kết nối 1 trợ lý",- "countMany": "Đã kết nối {{count}} trợ lý","qrAlt": "Mã QR kết nối Feishu","scanTitle": "Quét bằng Feishu","scanDescription": "Quét bằng Feishu hoặc Lark trên điện thoại. nanobot sẽ hoàn tất cấu hình sau khi cấp quyền.",diff --git a/nanobot/channels/feishu/webui/locales/zh-CN.json b/nanobot/channels/feishu/webui/locales/zh-CN.jsonindex 9f6bda391..3a7a154de 100644--- a/nanobot/channels/feishu/webui/locales/zh-CN.json+++ b/nanobot/channels/feishu/webui/locales/zh-CN.json@@ -1,18 +1,9 @@{"displayName": "飞书",- "description": "在飞书会话和群组中使用 nanobot。",- "requirements": "飞书应用凭据、事件订阅和网关","setup": {"primaryAction": "连接飞书","docsLabel": "打开飞书配置指南","officialLabel": "打开飞书开发者后台",- "tryIt": "向飞书助手发送私信,或在群组中提及它。",- "summary": "连接流程会通过二维码创建或关联飞书应用,并自动为 nanobot 保存应用凭据。",- "steps": [- "点击连接,用手机飞书或 Lark 扫描二维码。",- "批准应用连接,nanobot 会自动保存 App ID 和 Secret。",- "向机器人发送私信,或在飞书群中提及它以完成测试。"- ],"fields": {"appId": {"label": "App ID",@@ -20,8 +11,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "留空以保留现有密钥",- "help": "仅在轮换凭据时粘贴新的 App Secret。"+ "placeholder": "留空以保留现有密钥"},"domain": {"label": "区域",@@ -48,6 +38,38 @@"true": "每个话题使用独立会话","false": "群聊共用一个会话"}+ },+ "name": {+ "label": "账户名称"+ },+ "encryptKey": {+ "label": "加密密钥"+ },+ "verificationToken": {+ "label": "验证令牌"+ },+ "reactEmoji": {+ "label": "已读表情"+ },+ "doneEmoji": {+ "label": "完成表情"+ },+ "toolHintPrefix": {+ "label": "工具提示前缀"+ },+ "replyToMessage": {+ "label": "引用回复",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "streaming": {+ "label": "流式输出",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }}}},@@ -55,14 +77,6 @@"toggleAssistant": "{{name}} 助手","configured": "已连接","needsSetup": "需要授权",- "noAppId": "没有 App ID",- "createAnother": "创建另一个助手",- "createHint": "为其他团队、空间或工作流创建独立的飞书机器人。",- "createAssistant": "创建助手",- "reconnect": "重新连接",- "countNone": "尚未连接助手",- "countOne": "已连接 1 个助手",- "countMany": "已连接 {{count}} 个助手","qrAlt": "飞书连接二维码","scanTitle": "使用飞书扫码","scanDescription": "用手机上的飞书或 Lark 扫描二维码。授权完成后,nanobot 会自动完成配置。",diff --git a/nanobot/channels/feishu/webui/locales/zh-TW.json b/nanobot/channels/feishu/webui/locales/zh-TW.jsonindex e5ecad1c5..83f985ecd 100644--- a/nanobot/channels/feishu/webui/locales/zh-TW.json+++ b/nanobot/channels/feishu/webui/locales/zh-TW.json@@ -1,18 +1,9 @@{"displayName": "飛書",- "description": "在飛書對話和群組中使用 nanobot。",- "requirements": "飛書應用程式憑證、事件訂閱和閘道","setup": {"primaryAction": "連接飛書","docsLabel": "開啟飛書設定指南","officialLabel": "開啟飛書開發者後台",- "tryIt": "向飛書助手傳送私訊,或在群組中提及它。",- "summary": "連接流程會透過QR Code建立或關聯飛書應用程式,並自動為 nanobot 儲存應用程式憑證。",- "steps": [- "點選連接,用手機飛書或 Lark 掃描QR Code。",- "核准應用程式連接,nanobot 會自動儲存 App ID 和 Secret。",- "向機器人傳送私訊,或在飛書群組中提及它以完成測試。"- ],"fields": {"appId": {"label": "App ID",@@ -20,8 +11,7 @@},"appSecret": {"label": "App Secret",- "placeholder": "留空以保留現有金鑰",- "help": "僅在輪換憑證時貼上新的 App Secret。"+ "placeholder": "留空以保留現有金鑰"},"domain": {"label": "區域",@@ -48,6 +38,38 @@"true": "每個主題使用獨立工作階段","false": "群組共用一個工作階段"}+ },+ "name": {+ "label": "帳戶名稱"+ },+ "encryptKey": {+ "label": "加密金鑰"+ },+ "verificationToken": {+ "label": "驗證令牌"+ },+ "reactEmoji": {+ "label": "已讀表情"+ },+ "doneEmoji": {+ "label": "完成表情"+ },+ "toolHintPrefix": {+ "label": "工具提示前綴"+ },+ "replyToMessage": {+ "label": "引用回覆",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "streaming": {+ "label": "串流輸出",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }}}},@@ -55,14 +77,6 @@"toggleAssistant": "{{name}} 助手","configured": "已連接","needsSetup": "需要授權",- "noAppId": "沒有 App ID",- "createAnother": "建立另一個助手",- "createHint": "為其他團隊、空間或工作流程建立獨立的飛書機器人。",- "createAssistant": "建立助手",- "reconnect": "重新連線",- "countNone": "尚未連接助手",- "countOne": "已連接 1 個助手",- "countMany": "已連接 {{count}} 個助手","qrAlt": "飛書連線 QR Code","scanTitle": "使用飛書掃描","scanDescription": "請使用手機上的飛書或 Lark 掃描此 QR Code。完成授權後,nanobot 會自動完成設定。",diff --git a/nanobot/channels/matrix/manifest.py b/nanobot/channels/matrix/manifest.pyindex d669b2164..d6096b6f1 100644--- a/nanobot/channels/matrix/manifest.py+++ b/nanobot/channels/matrix/manifest.py@@ -13,7 +13,16 @@ SETUP_SPEC = ChannelSetupSpec("accessToken": field("secret"),"deviceId": field(),"groupPolicy": field("enum", choices=GROUP_POLICIES, default="open"),- "allowFrom": field("list", writable=False),+ "allowFrom": field("list"),+ "e2eeEnabled": field("bool", default=False),+ "sasVerification": field("bool", default=False),+ "syncStopGraceSeconds": field("int", default=2),+ "maxMediaBytes": field("int", default=20 * 1024 * 1024),+ "maxConcurrentMediaDownloads": field("int", default=2),+ "groupAllowFrom": field("list"),+ "allowRoomMentions": field("bool", default=False),+ "streaming": field("bool", default=False),+ "proxy": field(),},required=(*required_fields("homeserver", "userId"),diff --git a/nanobot/channels/matrix/runtime.py b/nanobot/channels/matrix/runtime.pyindex 47cad8b69..bbcf246fd 100644--- a/nanobot/channels/matrix/runtime.py+++ b/nanobot/channels/matrix/runtime.py@@ -301,6 +301,7 @@ class MatrixConfig(Base):group_allow_from: list[str] = Field(default_factory=list)allow_room_mentions: bool = Falsestreaming: bool = False+ proxy: str | None = Noneclass MatrixChannel(BaseChannel):@@ -356,10 +357,14 @@ class MatrixChannel(BaseChannel):# Replace ':' with '_' to produce a Windows-safe filenamesafe_store_name = self.config.user_id.replace(":", "_") + f"_{self.config.device_id}.db"+ proxy = self.config.proxy.strip() if self.config.proxy else ""+ if proxy and "://" not in proxy:+ proxy = f"http://{proxy}"self.client = AsyncClient(homeserver=self.config.homeserver,user=self.config.user_id,store_path=str(self.store_path),+ proxy=proxy or None,config=AsyncClientConfig(store_sync_tokens=True,encryption_enabled=self.config.e2ee_enabled,diff --git a/nanobot/channels/matrix/tests/test_matrix_channel.py b/nanobot/channels/matrix/tests/test_matrix_channel.pyindex e2950df15..c9e961ae5 100644--- a/nanobot/channels/matrix/tests/test_matrix_channel.py+++ b/nanobot/channels/matrix/tests/test_matrix_channel.py@@ -48,11 +48,12 @@ class _DummyTask:class _FakeAsyncClient:- def __init__(self, homeserver, user, store_path, config) -> None:+ def __init__(self, homeserver, user, store_path, config, proxy=None) -> None:self.homeserver = homeserverself.user = userself.store_path = store_pathself.config = config+ self.proxy = proxyself.user_id: str | None = Noneself.access_token: str | None = Noneself.device_id: str | None = None@@ -326,11 +327,15 @@ async def test_start_skips_load_store_when_device_id_missing("nanobot.channels.matrix.runtime.asyncio.create_task", _fake_create_task)- channel = MatrixChannel(_make_config(device_id="", e2ee_enabled=True), MessageBus())+ channel = MatrixChannel(+ _make_config(device_id="", e2ee_enabled=True, proxy="127.0.0.1:7890"),+ MessageBus(),+ )await channel.start()assert len(clients) == 1assert clients[0].config.encryption_enabled is True+ assert clients[0].proxy == "http://127.0.0.1:7890"assert clients[0].load_store_called is Falseassert len(clients[0].callbacks) == 3assert clients[0].to_device_callbacks == []diff --git a/nanobot/channels/matrix/tests/test_validation.py b/nanobot/channels/matrix/tests/test_validation.pyindex 6cd621a7c..36d02a499 100644--- a/nanobot/channels/matrix/tests/test_validation.py+++ b/nanobot/channels/matrix/tests/test_validation.py@@ -10,7 +10,7 @@ from nanobot.config.schema import Config@pytest.mark.parametrize(("credentials", "expected_status", "expected_missing"),[- ({}, "needs_setup", "password_or_accessToken"),+ ({}, "needs_setup", "password"),({"channels.matrix.accessToken": "token"}, "needs_setup", "deviceId"),({"channels.matrix.password": "secret"}, "configured", None),(@@ -49,3 +49,35 @@ def test_validate_matrix_requires_a_complete_login_method(assert result["missing_fields"] == []else:assert expected_missing in result["missing_fields"]+++def test_validate_matrix_can_replace_a_saved_password_with_a_token(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ config_path = tmp_path / "config.json"+ save_config(+ Config.model_validate({+ "channels": {+ "matrix": {+ "homeserver": "https://matrix.example",+ "userId": "@nanobot:matrix.example",+ "password": "saved-password",+ },+ },+ }),+ config_path,+ )+ monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)++ result = validate_channel_config(+ "matrix",+ {+ "channels.matrix.password": None,+ "channels.matrix.accessToken": "replacement-token",+ "channels.matrix.deviceId": "DEVICE",+ },+ )++ assert result["status"] == "configured"+ assert result["missing_fields"] == []diff --git a/nanobot/channels/matrix/validation.py b/nanobot/channels/matrix/validation.pyindex 19b9a8c82..cfe443661 100644--- a/nanobot/channels/matrix/validation.py+++ b/nanobot/channels/matrix/validation.py@@ -25,7 +25,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict)else:if not password and not access_token:- missing.append("password_or_accessToken")+ missing.append("password")message = "Add a password, or an access token with its device ID."else:missing.append("deviceId")diff --git a/nanobot/channels/matrix/webui/index.ts b/nanobot/channels/matrix/webui/index.tsindex 1d9a00487..8a45162a3 100644--- a/nanobot/channels/matrix/webui/index.ts+++ b/nanobot/channels/matrix/webui/index.ts@@ -3,20 +3,20 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://matrix.org/favicon.ico",displayName: "Matrix",initials: "MX",color: "#0DBD8B",- logoUrl: "https://matrix.org/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("matrix"),fields: [- { key: "channels.matrix.homeserver" },- { key: "channels.matrix.userId" },- { key: "channels.matrix.password" },- { key: "channels.matrix.accessToken" },- { key: "channels.matrix.deviceId" },- { key: "channels.matrix.groupPolicy" },+ { key: "channels.matrix.homeserver", section: "connection" },+ { key: "channels.matrix.userId", section: "account" },+ { key: "channels.matrix.password", section: "credentials" },+ { key: "channels.matrix.accessToken", section: "credentials" },+ { key: "channels.matrix.deviceId", section: "credentials" },+ { key: "channels.matrix.groupPolicy", section: "behavior" },],},},diff --git a/nanobot/channels/matrix/webui/locales/en.json b/nanobot/channels/matrix/webui/locales/en.jsonindex 6c0de5fd9..9d3f97646 100644--- a/nanobot/channels/matrix/webui/locales/en.json+++ b/nanobot/channels/matrix/webui/locales/en.json@@ -1,16 +1,7 @@{- "description": "Use nanobot from Matrix rooms.",- "requirements": "Homeserver, account token, room access","setup": {"docsLabel": "Open Matrix setup","officialLabel": "Open Matrix clients",- "tryIt": "Invite the Matrix account into a room and send a test message.",- "summary": "Enter your Matrix homeserver and sign in with a password or access token.",- "steps": [- "Create or choose a Matrix account for nanobot.",- "Enter the homeserver, user ID, and either password or access-token credentials.",- "Save and enable Matrix, invite the account to a room, and send a test message."- ],"fields": {"homeserver": {"label": "Homeserver",@@ -22,18 +13,15 @@},"password": {"label": "Password",- "placeholder": "••••••",- "help": "Use either password login or access token login."+ "placeholder": "••••••"},"accessToken": {"label": "Access token",- "placeholder": "Enter an access token",- "help": "Preferred when your Matrix client exposes an access token."+ "placeholder": "Enter an access token"},"deviceId": {"label": "Device ID",- "placeholder": "Required with an access token",- "help": "Copy the device ID associated with the access token. Password login does not need it."+ "placeholder": "Required with an access token"},"groupPolicy": {"label": "Group behavior",@@ -42,6 +30,53 @@"open": "All messages","allowlist": "Allowlist"}+ },+ "allowFrom": {+ "label": "Allowed users"+ },+ "e2eeEnabled": {+ "label": "End-to-end encryption",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "sasVerification": {+ "label": "SAS verification",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "syncStopGraceSeconds": {+ "label": "Sync stop grace period"+ },+ "maxMediaBytes": {+ "label": "Maximum media size"+ },+ "maxConcurrentMediaDownloads": {+ "label": "Concurrent media downloads"+ },+ "groupAllowFrom": {+ "label": "Allowed groups"+ },+ "allowRoomMentions": {+ "label": "Allow room mentions",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "proxy": {+ "label": "Network proxy",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/es.json b/nanobot/channels/matrix/webui/locales/es.jsonindex 3e5b405ca..f7c08b3b0 100644--- a/nanobot/channels/matrix/webui/locales/es.json+++ b/nanobot/channels/matrix/webui/locales/es.json@@ -1,16 +1,7 @@{- "description": "Usa nanobot desde salas de Matrix.",- "requirements": "Servidor de la cuenta, credenciales de acceso y permisos para las salas","setup": {"docsLabel": "Abrir guía de Matrix","officialLabel": "Abrir lista de clientes Matrix",- "tryIt": "Invita la cuenta de Matrix a una sala y envía un mensaje de prueba.",- "summary": "Introduce el servidor de tu cuenta de Matrix e inicia sesión con una contraseña o un token de acceso.",- "steps": [- "Crea o elige una cuenta de Matrix para nanobot.",- "Introduce el servidor de tu cuenta, el ID de usuario y la contraseña o el token de acceso.",- "Guarda y activa Matrix, invita la cuenta a una sala y envía un mensaje de prueba."- ],"fields": {"homeserver": {"label": "Servidor de la cuenta",@@ -22,18 +13,15 @@},"password": {"label": "Contraseña",- "placeholder": "••••••",- "help": "Usa contraseña o token de acceso."+ "placeholder": "••••••"},"accessToken": {"label": "Token de acceso",- "placeholder": "Introduce un token de acceso",- "help": "Preferible si tu cliente Matrix muestra un token de acceso."+ "placeholder": "Introduce un token de acceso"},"deviceId": {"label": "ID del dispositivo",- "placeholder": "Obligatorio con token",- "help": "Copia el ID asociado al token. No se necesita con contraseña."+ "placeholder": "Obligatorio con token"},"groupPolicy": {"label": "Comportamiento en grupos",@@ -42,6 +30,53 @@"open": "Todos los mensajes","allowlist": "Lista de permitidos"}+ },+ "allowFrom": {+ "label": "Usuarios permitidos"+ },+ "e2eeEnabled": {+ "label": "Cifrado de extremo a extremo",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "sasVerification": {+ "label": "verificación SAS",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "syncStopGraceSeconds": {+ "label": "Período de gracia para detener la sincronización"+ },+ "maxMediaBytes": {+ "label": "Tamaño máximo de medios"+ },+ "maxConcurrentMediaDownloads": {+ "label": "Descargas multimedia simultáneas"+ },+ "groupAllowFrom": {+ "label": "Grupos permitidos"+ },+ "allowRoomMentions": {+ "label": "Permitir menciones de sala",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "streaming": {+ "label": "Transmisión",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "proxy": {+ "label": "Proxy de red",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/fr.json b/nanobot/channels/matrix/webui/locales/fr.jsonindex 319ad92c4..9e7843ac0 100644--- a/nanobot/channels/matrix/webui/locales/fr.json+++ b/nanobot/channels/matrix/webui/locales/fr.json@@ -1,16 +1,7 @@{- "description": "Utilisez nanobot depuis les salons Matrix.",- "requirements": "Serveur d’accueil, jeton de compte et accès aux salons","setup": {"docsLabel": "Ouvrir le guide Matrix","officialLabel": "Ouvrir la liste des clients Matrix",- "tryIt": "Invitez le compte Matrix dans un salon et envoyez un message test.",- "summary": "Saisissez le serveur de votre compte Matrix et connectez-vous avec un mot de passe ou un jeton d’accès.",- "steps": [- "Créez ou choisissez un compte Matrix pour nanobot.",- "Saisissez le serveur, l’ID utilisateur et le mot de passe ou le jeton d’accès.",- "Enregistrez et activez Matrix, invitez le compte dans un salon et envoyez un message test."- ],"fields": {"homeserver": {"label": "Serveur d’accueil",@@ -22,18 +13,15 @@},"password": {"label": "Mot de passe",- "placeholder": "••••••",- "help": "Utilisez le mot de passe ou le jeton d’accès."+ "placeholder": "••••••"},"accessToken": {"label": "Jeton d’accès",- "placeholder": "Saisir un jeton d’accès",- "help": "À privilégier si votre client Matrix expose un jeton d’accès."+ "placeholder": "Saisir un jeton d’accès"},"deviceId": {"label": "ID de l’appareil",- "placeholder": "Requis avec un jeton d’accès",- "help": "Copiez l’ID d’appareil associé au jeton. Il n’est pas nécessaire avec un mot de passe."+ "placeholder": "Requis avec un jeton d’accès"},"groupPolicy": {"label": "Comportement en groupe",@@ -42,6 +30,53 @@"open": "Tous les messages","allowlist": "Liste d’autorisation"}+ },+ "allowFrom": {+ "label": "Utilisateurs autorisés"+ },+ "e2eeEnabled": {+ "label": "Chiffrement de bout en bout",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "sasVerification": {+ "label": "Vérification SAS",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "syncStopGraceSeconds": {+ "label": "Délai de grâce pour l'arrêt de la synchronisation"+ },+ "maxMediaBytes": {+ "label": "Taille maximale du support"+ },+ "maxConcurrentMediaDownloads": {+ "label": "Téléchargements multimédias simultanés"+ },+ "groupAllowFrom": {+ "label": "Groupes autorisés"+ },+ "allowRoomMentions": {+ "label": "Autoriser les mentions de salles",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "streaming": {+ "label": "Diffusion en continu",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "proxy": {+ "label": "Proxy réseau",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/id.json b/nanobot/channels/matrix/webui/locales/id.jsonindex 28edefe1c..1753c9b2e 100644--- a/nanobot/channels/matrix/webui/locales/id.json+++ b/nanobot/channels/matrix/webui/locales/id.json@@ -1,16 +1,7 @@{- "description": "Gunakan nanobot dari ruang Matrix.",- "requirements": "Server akun, kredensial, dan akses ruang","setup": {"docsLabel": "Buka panduan Matrix","officialLabel": "Buka daftar klien Matrix",- "tryIt": "Undang akun Matrix ke ruang dan kirim pesan uji.",- "summary": "Masukkan server akun Matrix, lalu masuk dengan kata sandi atau token akses.",- "steps": [- "Buat atau pilih akun Matrix untuk nanobot.",- "Masukkan server akun, ID pengguna, serta kata sandi atau token akses.",- "Simpan dan aktifkan Matrix, undang akun ke ruang, lalu kirim pesan uji."- ],"fields": {"homeserver": {"label": "Server akun",@@ -22,18 +13,15 @@},"password": {"label": "Kata sandi",- "placeholder": "••••••",- "help": "Gunakan kata sandi atau token akses."+ "placeholder": "••••••"},"accessToken": {"label": "Token akses",- "placeholder": "Masukkan token akses",- "help": "Disarankan jika klien Matrix menyediakan token akses."+ "placeholder": "Masukkan token akses"},"deviceId": {"label": "ID perangkat",- "placeholder": "Wajib dengan token akses",- "help": "Salin ID perangkat yang terkait token. Login kata sandi tidak memerlukannya."+ "placeholder": "Wajib dengan token akses"},"groupPolicy": {"label": "Perilaku grup",@@ -42,6 +30,53 @@"open": "Semua pesan","allowlist": "Daftar izin"}+ },+ "allowFrom": {+ "label": "Pengguna yang diizinkan"+ },+ "e2eeEnabled": {+ "label": "Enkripsi ujung ke ujung",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "sasVerification": {+ "label": "verifikasi SAS",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "syncStopGraceSeconds": {+ "label": "Sinkronisasi menghentikan masa tenggang"+ },+ "maxMediaBytes": {+ "label": "Ukuran media maksimum"+ },+ "maxConcurrentMediaDownloads": {+ "label": "Pengunduhan media secara bersamaan"+ },+ "groupAllowFrom": {+ "label": "Grup yang diizinkan"+ },+ "allowRoomMentions": {+ "label": "Izinkan penyebutan ruangan",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "proxy": {+ "label": "Proxy jaringan",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/ja.json b/nanobot/channels/matrix/webui/locales/ja.jsonindex 9c0769d43..cc587fef2 100644--- a/nanobot/channels/matrix/webui/locales/ja.json+++ b/nanobot/channels/matrix/webui/locales/ja.json@@ -1,16 +1,7 @@{- "description": "Matrix ルームから nanobot を利用します。",- "requirements": "ホームサーバー、アカウントトークン、ルームへのアクセス","setup": {"docsLabel": "Matrix 設定ガイドを開く","officialLabel": "Matrix クライアント一覧を開く",- "tryIt": "Matrix アカウントをルームに招待し、テストメッセージを送信します。",- "summary": "Matrix アカウントのホームサーバーを入力し、パスワードまたはアクセストークンでログインします。",- "steps": [- "nanobot 用の Matrix アカウントを作成または選択します。",- "ホームサーバー、ユーザー ID、パスワードまたはアクセストークンを入力します。",- "保存して Matrix を有効にし、アカウントをルームに招待してテストメッセージを送信します。"- ],"fields": {"homeserver": {"label": "ホームサーバー",@@ -22,18 +13,15 @@},"password": {"label": "パスワード",- "placeholder": "••••••",- "help": "パスワードまたはアクセストークンのどちらかを使います。"+ "placeholder": "••••••"},"accessToken": {"label": "アクセストークン",- "placeholder": "アクセストークンを入力",- "help": "Matrix クライアントでアクセストークンを取得できる場合に推奨します。"+ "placeholder": "アクセストークンを入力"},"deviceId": {"label": "デバイス ID",- "placeholder": "アクセストークン使用時に必須",- "help": "トークンに関連付けられたデバイス ID をコピーします。パスワードログインでは不要です。"+ "placeholder": "アクセストークン使用時に必須"},"groupPolicy": {"label": "グループでの動作",@@ -42,6 +30,53 @@"open": "すべてのメッセージ","allowlist": "許可リスト"}+ },+ "allowFrom": {+ "label": "許可されたユーザー"+ },+ "e2eeEnabled": {+ "label": "エンドツーエンドの暗号化",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "sasVerification": {+ "label": "SAS 検証",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "syncStopGraceSeconds": {+ "label": "同期停止猶予期間"+ },+ "maxMediaBytes": {+ "label": "最大メディアサイズ"+ },+ "maxConcurrentMediaDownloads": {+ "label": "メディアの同時ダウンロード"+ },+ "groupAllowFrom": {+ "label": "許可されたグループ"+ },+ "allowRoomMentions": {+ "label": "部屋のメンションを許可する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "streaming": {+ "label": "ストリーミング",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "proxy": {+ "label": "ネットワークプロキシ",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/ko.json b/nanobot/channels/matrix/webui/locales/ko.jsonindex 99b4692b7..391c32324 100644--- a/nanobot/channels/matrix/webui/locales/ko.json+++ b/nanobot/channels/matrix/webui/locales/ko.json@@ -1,16 +1,7 @@{- "description": "Matrix 룸에서 nanobot을 사용합니다.",- "requirements": "홈서버, 계정 토큰 및 룸 접근 권한","setup": {"docsLabel": "Matrix 설정 가이드 열기","officialLabel": "Matrix 클라이언트 목록 열기",- "tryIt": "Matrix 계정을 룸에 초대하고 테스트 메시지를 보내세요.",- "summary": "Matrix 계정의 홈서버를 입력하고 비밀번호 또는 액세스 토큰으로 로그인하세요.",- "steps": [- "nanobot용 Matrix 계정을 만들거나 선택하세요.",- "홈서버, 사용자 ID, 비밀번호 또는 액세스 토큰을 입력하세요.",- "저장하고 Matrix를 활성화한 다음 계정을 룸에 초대하고 테스트 메시지를 보내세요."- ],"fields": {"homeserver": {"label": "홈서버",@@ -22,18 +13,15 @@},"password": {"label": "비밀번호",- "placeholder": "••••••",- "help": "비밀번호 또는 액세스 토큰 중 하나를 사용하세요."+ "placeholder": "••••••"},"accessToken": {"label": "액세스 토큰",- "placeholder": "액세스 토큰 입력",- "help": "Matrix 클라이언트에서 토큰을 확인할 수 있다면 권장합니다."+ "placeholder": "액세스 토큰 입력"},"deviceId": {"label": "장치 ID",- "placeholder": "액세스 토큰 사용 시 필수",- "help": "토큰과 연결된 장치 ID를 복사하세요. 비밀번호 로그인에는 필요하지 않습니다."+ "placeholder": "액세스 토큰 사용 시 필수"},"groupPolicy": {"label": "그룹 동작",@@ -42,6 +30,53 @@"open": "모든 메시지","allowlist": "허용 목록"}+ },+ "allowFrom": {+ "label": "허용된 사용자"+ },+ "e2eeEnabled": {+ "label": "엔드투엔드 암호화",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "sasVerification": {+ "label": "SAS 검증",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "syncStopGraceSeconds": {+ "label": "동기화 중지 유예 기간"+ },+ "maxMediaBytes": {+ "label": "최대 미디어 크기"+ },+ "maxConcurrentMediaDownloads": {+ "label": "동시 미디어 다운로드"+ },+ "groupAllowFrom": {+ "label": "허용된 그룹"+ },+ "allowRoomMentions": {+ "label": "회의실 언급 허용",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "streaming": {+ "label": "스트리밍",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "proxy": {+ "label": "네트워크 프록시",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/pt-BR.json b/nanobot/channels/matrix/webui/locales/pt-BR.jsonindex 20c8f8d5a..759b49b2a 100644--- a/nanobot/channels/matrix/webui/locales/pt-BR.json+++ b/nanobot/channels/matrix/webui/locales/pt-BR.json@@ -1,16 +1,7 @@{- "description": "Use o nanobot em salas do Matrix.",- "requirements": "Servidor da conta, credenciais e acesso às salas","setup": {"docsLabel": "Abrir guia do Matrix","officialLabel": "Abrir lista de clientes Matrix",- "tryIt": "Convide a conta Matrix para uma sala e envie uma mensagem de teste.",- "summary": "Informe o servidor da sua conta Matrix e entre com uma senha ou um token de acesso.",- "steps": [- "Crie ou escolha uma conta Matrix para o nanobot.",- "Informe o servidor da conta, o ID de usuário e a senha ou o token de acesso.",- "Salve e ative o Matrix, convide a conta para uma sala e envie uma mensagem de teste."- ],"fields": {"homeserver": {"label": "Servidor da conta",@@ -22,18 +13,15 @@},"password": {"label": "Senha",- "placeholder": "••••••",- "help": "Use senha ou token de acesso."+ "placeholder": "••••••"},"accessToken": {"label": "Token de acesso",- "placeholder": "Informe um token de acesso",- "help": "Preferível quando o cliente Matrix fornece um token."+ "placeholder": "Informe um token de acesso"},"deviceId": {"label": "ID do dispositivo",- "placeholder": "Obrigatório com token",- "help": "Copie o ID associado ao token. O login por senha não precisa dele."+ "placeholder": "Obrigatório com token"},"groupPolicy": {"label": "Comportamento em grupos",@@ -42,6 +30,53 @@"open": "Todas as mensagens","allowlist": "Lista de permissão"}+ },+ "allowFrom": {+ "label": "Usuários permitidos"+ },+ "e2eeEnabled": {+ "label": "Criptografia ponta a ponta",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "sasVerification": {+ "label": "Verificação SAS",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "syncStopGraceSeconds": {+ "label": "Período de carência para interrupção da sincronização"+ },+ "maxMediaBytes": {+ "label": "Tamanho máximo da mídia"+ },+ "maxConcurrentMediaDownloads": {+ "label": "Downloads simultâneos de mídia"+ },+ "groupAllowFrom": {+ "label": "Grupos permitidos"+ },+ "allowRoomMentions": {+ "label": "Permitir menções à sala",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "streaming": {+ "label": "Transmissão",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "proxy": {+ "label": "Proxy de rede",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/vi.json b/nanobot/channels/matrix/webui/locales/vi.jsonindex a09dd040f..a34bae5d1 100644--- a/nanobot/channels/matrix/webui/locales/vi.json+++ b/nanobot/channels/matrix/webui/locales/vi.json@@ -1,16 +1,7 @@{- "description": "Sử dụng nanobot từ các phòng Matrix.",- "requirements": "Máy chủ tài khoản, thông tin đăng nhập và quyền truy cập phòng","setup": {"docsLabel": "Mở hướng dẫn Matrix","officialLabel": "Mở danh sách ứng dụng Matrix",- "tryIt": "Mời tài khoản Matrix vào phòng và gửi tin nhắn thử.",- "summary": "Nhập máy chủ của tài khoản Matrix rồi đăng nhập bằng mật khẩu hoặc token truy cập.",- "steps": [- "Tạo hoặc chọn tài khoản Matrix cho nanobot.",- "Nhập máy chủ tài khoản, ID người dùng và mật khẩu hoặc token truy cập.",- "Lưu và bật Matrix, mời tài khoản vào phòng rồi gửi tin nhắn thử."- ],"fields": {"homeserver": {"label": "Máy chủ tài khoản",@@ -22,18 +13,15 @@},"password": {"label": "Mật khẩu",- "placeholder": "••••••",- "help": "Dùng mật khẩu hoặc token truy cập."+ "placeholder": "••••••"},"accessToken": {"label": "Token truy cập",- "placeholder": "Nhập token truy cập",- "help": "Nên dùng khi ứng dụng Matrix cung cấp token truy cập."+ "placeholder": "Nhập token truy cập"},"deviceId": {"label": "ID thiết bị",- "placeholder": "Bắt buộc khi dùng token",- "help": "Sao chép ID thiết bị gắn với token. Đăng nhập mật khẩu không cần."+ "placeholder": "Bắt buộc khi dùng token"},"groupPolicy": {"label": "Hành vi trong nhóm",@@ -42,6 +30,53 @@"open": "Mọi tin nhắn","allowlist": "Danh sách cho phép"}+ },+ "allowFrom": {+ "label": "Người dùng được phép"+ },+ "e2eeEnabled": {+ "label": "Mã hóa đầu cuối",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "sasVerification": {+ "label": "Xác minh SAS",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "syncStopGraceSeconds": {+ "label": "Thời gian gia hạn dừng đồng bộ hóa"+ },+ "maxMediaBytes": {+ "label": "Kích thước phương tiện tối đa"+ },+ "maxConcurrentMediaDownloads": {+ "label": "Tải xuống phương tiện đồng thời"+ },+ "groupAllowFrom": {+ "label": "Nhóm được phép"+ },+ "allowRoomMentions": {+ "label": "Cho phép đề cập đến phòng",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "streaming": {+ "label": "Truyền phát",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "proxy": {+ "label": "Proxy mạng",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/zh-CN.json b/nanobot/channels/matrix/webui/locales/zh-CN.jsonindex 1c43b9e68..b34e7a768 100644--- a/nanobot/channels/matrix/webui/locales/zh-CN.json+++ b/nanobot/channels/matrix/webui/locales/zh-CN.json@@ -1,16 +1,7 @@{- "description": "在 Matrix 房间中使用 nanobot。",- "requirements": "主服务器、账户令牌和房间访问权限","setup": {"docsLabel": "打开 Matrix 配置指南","officialLabel": "打开 Matrix 客户端列表",- "tryIt": "将 Matrix 账户邀请进房间并发送一条测试消息。",- "summary": "填写 Matrix 账户所在的服务器,并使用密码或访问令牌登录。",- "steps": [- "为 nanobot 创建或选择一个 Matrix 账户。",- "填写主服务器、用户 ID,以及密码或访问令牌凭据。",- "保存并启用 Matrix,将账户邀请进房间,然后发送一条测试消息。"- ],"fields": {"homeserver": {"label": "账户服务器",@@ -22,18 +13,15 @@},"password": {"label": "密码",- "placeholder": "••••••",- "help": "密码登录和访问令牌登录任选其一。"+ "placeholder": "••••••"},"accessToken": {"label": "访问令牌",- "placeholder": "输入访问令牌",- "help": "如果 Matrix 客户端可以显示访问令牌,建议使用该方式。"+ "placeholder": "输入访问令牌"},"deviceId": {"label": "设备 ID",- "placeholder": "使用访问令牌时必填",- "help": "复制与访问令牌关联的设备 ID;密码登录不需要。"+ "placeholder": "使用访问令牌时必填"},"groupPolicy": {"label": "群组行为",@@ -42,6 +30,53 @@"open": "所有消息","allowlist": "白名单"}+ },+ "allowFrom": {+ "label": "允许的用户"+ },+ "e2eeEnabled": {+ "label": "端到端加密",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "sasVerification": {+ "label": "SAS 验证",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "syncStopGraceSeconds": {+ "label": "同步停止等待时间"+ },+ "maxMediaBytes": {+ "label": "媒体大小上限"+ },+ "maxConcurrentMediaDownloads": {+ "label": "并发媒体下载数"+ },+ "groupAllowFrom": {+ "label": "允许的群组"+ },+ "allowRoomMentions": {+ "label": "响应房间提及",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "streaming": {+ "label": "流式输出",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "proxy": {+ "label": "网络代理",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/matrix/webui/locales/zh-TW.json b/nanobot/channels/matrix/webui/locales/zh-TW.jsonindex fb61c19d2..5c5b1c545 100644--- a/nanobot/channels/matrix/webui/locales/zh-TW.json+++ b/nanobot/channels/matrix/webui/locales/zh-TW.json@@ -1,16 +1,7 @@{- "description": "在 Matrix 房間中使用 nanobot。",- "requirements": "主伺服器、帳戶權杖和房間存取權限","setup": {"docsLabel": "開啟 Matrix 設定指南","officialLabel": "開啟 Matrix 用戶端列表",- "tryIt": "將 Matrix 帳戶邀請進房間並傳送一則測試訊息。",- "summary": "填入 Matrix 帳戶所在的伺服器,並使用密碼或存取權杖登入。",- "steps": [- "為 nanobot 建立或選擇一個 Matrix 帳戶。",- "填入主伺服器、使用者 ID,以及密碼或存取權杖憑證。",- "儲存並啟用 Matrix,將帳戶邀請進房間,然後傳送一則測試訊息。"- ],"fields": {"homeserver": {"label": "帳戶伺服器",@@ -22,18 +13,15 @@},"password": {"label": "密碼",- "placeholder": "••••••",- "help": "密碼登入和存取權杖登入任選其一。"+ "placeholder": "••••••"},"accessToken": {"label": "存取權杖",- "placeholder": "輸入存取權杖",- "help": "若 Matrix 用戶端可顯示存取權杖,建議使用此方式。"+ "placeholder": "輸入存取權杖"},"deviceId": {"label": "裝置 ID",- "placeholder": "使用存取權杖時必填",- "help": "複製與存取權杖關聯的裝置 ID;密碼登入不需要。"+ "placeholder": "使用存取權杖時必填"},"groupPolicy": {"label": "群組行為",@@ -42,6 +30,53 @@"open": "所有訊息","allowlist": "允許清單"}+ },+ "allowFrom": {+ "label": "允許的用戶"+ },+ "e2eeEnabled": {+ "label": "端對端加密",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "sasVerification": {+ "label": "SAS 驗證",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "syncStopGraceSeconds": {+ "label": "同步停止等待時間"+ },+ "maxMediaBytes": {+ "label": "媒體大小上限"+ },+ "maxConcurrentMediaDownloads": {+ "label": "並發媒體下載數"+ },+ "groupAllowFrom": {+ "label": "允許的群組"+ },+ "allowRoomMentions": {+ "label": "響應房間提及",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "streaming": {+ "label": "串流輸出",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "proxy": {+ "label": "網路代理",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/mattermost/manifest.py b/nanobot/channels/mattermost/manifest.pyindex 4061a3513..61c162215 100644--- a/nanobot/channels/mattermost/manifest.py+++ b/nanobot/channels/mattermost/manifest.py@@ -12,6 +12,21 @@ SETUP_SPEC = ChannelSetupSpec("groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"),"groupPolicyInThread": field("enum", choices=GROUP_POLICIES, default="mention"),"allowFrom": field("list"),+ "allowFromMatchMode": field(+ "enum", choices={"id", "username", "email"}, default="id"+ ),+ "groupAllowFrom": field("list"),+ "replyInThread": field("bool", default=True),+ "includeThreadContext": field("bool", default=True),+ "threadContextLimit": field("int", default=20),+ "streaming": field("bool", default=True),+ "reactEmoji": field(default="eyes"),+ "doneEmoji": field(default="white_check_mark"),+ "sendProgress": field("bool", default=True),+ "sendToolHints": field("bool", default=True),+ "dm.enabled": field("bool", default=True),+ "dm.policy": field("enum", choices={"open", "allowlist"}, default="open"),+ "dm.allowFrom": field("list"),},required=required_fields("serverUrl", "token"),official_url="https://developers.mattermost.com/integrate/reference/bot-accounts/",diff --git a/nanobot/channels/mattermost/webui/index.ts b/nanobot/channels/mattermost/webui/index.tsindex a6206cde0..d18eb84b5 100644--- a/nanobot/channels/mattermost/webui/index.ts+++ b/nanobot/channels/mattermost/webui/index.ts@@ -3,19 +3,20 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://mattermost.com/favicon.ico",displayName: "Mattermost",initials: "MM",color: "#1C58D9",- logoUrl: "https://mattermost.com/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("mattermost"),fields: [- { key: "channels.mattermost.serverUrl" },- { key: "channels.mattermost.token" },- { key: "channels.mattermost.teamId" },- { key: "channels.mattermost.groupPolicy" },- { key: "channels.mattermost.groupPolicyInThread" },+ { key: "channels.mattermost.serverUrl", section: "connection" },+ { key: "channels.mattermost.teamId", section: "account" },+ { key: "channels.mattermost.token", section: "credentials" },+ { key: "channels.mattermost.allowFrom", section: "access" },+ { key: "channels.mattermost.groupPolicy", section: "behavior" },+ { key: "channels.mattermost.groupPolicyInThread", section: "behavior" },],},},diff --git a/nanobot/channels/mattermost/webui/locales/en.json b/nanobot/channels/mattermost/webui/locales/en.jsonindex 5c2945211..c8e7ec50d 100644--- a/nanobot/channels/mattermost/webui/locales/en.json+++ b/nanobot/channels/mattermost/webui/locales/en.json@@ -1,26 +1,15 @@{- "description": "Use nanobot from Mattermost channels and DMs.",- "requirements": "Mattermost server URL, bot token, channel access","setup": {"docsLabel": "Open Mattermost setup","officialLabel": "Open Mattermost bot guide",- "tryIt": "Mention the bot in a Mattermost channel or send it a direct message.",- "summary": "Mattermost connects through a bot account on your server and listens for channel and direct messages.",- "steps": [- "Create a Mattermost bot account and copy its access token.",- "Enter the server URL and grant the bot access to the target team and channels.",- "Save and enable Mattermost, then mention the bot or send a direct message."- ],"fields": {"serverUrl": {"label": "Server URL",- "placeholder": "https://mattermost.example.com",- "help": "Use the base URL of your Mattermost workspace."+ "placeholder": "https://mattermost.example.com"},"token": {"label": "Bot token",- "placeholder": "Mattermost bot token",- "help": "Create this from a Mattermost bot account."+ "placeholder": "Mattermost bot token"},"teamId": {"label": "Team ID",@@ -45,6 +34,78 @@"allowFrom": {"label": "Allowed users","placeholder": "User IDs, comma separated"+ },+ "allowFromMatchMode": {+ "label": "User matching",+ "choices": {+ "email": "Email",+ "id": "User ID",+ "username": "Username"+ }+ },+ "groupAllowFrom": {+ "label": "Allowed channels"+ },+ "replyInThread": {+ "label": "Reply in thread",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "includeThreadContext": {+ "label": "Include thread context",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "threadContextLimit": {+ "label": "Thread context limit"+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "reactEmoji": {+ "label": "Read emoji"+ },+ "doneEmoji": {+ "label": "Done emoji"+ },+ "sendProgress": {+ "label": "Send progress",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "sendToolHints": {+ "label": "Send tool hints",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "dm_enabled": {+ "label": "Enable direct messages",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "dm_policy": {+ "label": "Direct message access",+ "choices": {+ "allowlist": "Allowlist",+ "open": "Open"+ }+ },+ "dm_allowFrom": {+ "label": "Allowed direct-message users"}}}diff --git a/nanobot/channels/mattermost/webui/locales/es.json b/nanobot/channels/mattermost/webui/locales/es.jsonindex 6d4456614..bfaed53fe 100644--- a/nanobot/channels/mattermost/webui/locales/es.json+++ b/nanobot/channels/mattermost/webui/locales/es.json@@ -1,26 +1,15 @@{- "description": "Usa nanobot en canales y mensajes directos de Mattermost.",- "requirements": "URL del servidor Mattermost, token del bot y acceso a canales","setup": {"docsLabel": "Abrir guía de Mattermost","officialLabel": "Abrir guía de bots de Mattermost",- "tryIt": "Menciona al bot en un canal de Mattermost o envíale un mensaje directo.",- "summary": "Mattermost se conecta mediante una cuenta bot en tu servidor y escucha canales y mensajes directos.",- "steps": [- "Crea una cuenta bot de Mattermost y copia su token de acceso.",- "Introduce la URL del servidor y permite acceso al equipo y canales de destino.",- "Guarda y activa Mattermost; después menciona al bot o envíale un mensaje directo."- ],"fields": {"serverUrl": {"label": "URL del servidor",- "placeholder": "https://mattermost.example.com",- "help": "Usa la URL base de tu espacio Mattermost."+ "placeholder": "https://mattermost.example.com"},"token": {"label": "Token del bot",- "placeholder": "Token del bot Mattermost",- "help": "Créalo desde una cuenta bot de Mattermost."+ "placeholder": "Token del bot Mattermost"},"teamId": {"label": "ID del equipo",@@ -45,6 +34,78 @@"allowFrom": {"label": "Usuarios permitidos","placeholder": "ID de usuario separados por comas"+ },+ "allowFromMatchMode": {+ "label": "Coincidencia de usuarios",+ "choices": {+ "email": "Correo electrónico",+ "id": "ID de usuario",+ "username": "Nombre de usuario"+ }+ },+ "groupAllowFrom": {+ "label": "Canales permitidos"+ },+ "replyInThread": {+ "label": "Responder en el hilo",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "includeThreadContext": {+ "label": "Incluir contexto de hilo",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "threadContextLimit": {+ "label": "Límite de contexto del hilo"+ },+ "streaming": {+ "label": "Transmisión",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "reactEmoji": {+ "label": "Leer emojis"+ },+ "doneEmoji": {+ "label": "emoji hecho"+ },+ "sendProgress": {+ "label": "Enviar progreso",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "sendToolHints": {+ "label": "Enviar sugerencias de herramientas",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "dm_enabled": {+ "label": "Habilitar mensajes directos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "dm_policy": {+ "label": "Acceso a mensajes directos",+ "choices": {+ "allowlist": "Lista de permitidos",+ "open": "Abierto"+ }+ },+ "dm_allowFrom": {+ "label": "Usuarios permitidos de mensajes directos"}}}diff --git a/nanobot/channels/mattermost/webui/locales/fr.json b/nanobot/channels/mattermost/webui/locales/fr.jsonindex c0063b2b2..70fe37ee1 100644--- a/nanobot/channels/mattermost/webui/locales/fr.json+++ b/nanobot/channels/mattermost/webui/locales/fr.json@@ -1,26 +1,15 @@{- "description": "Utilisez nanobot dans les canaux et messages privés Mattermost.",- "requirements": "URL du serveur Mattermost, jeton du bot et accès aux canaux","setup": {"docsLabel": "Ouvrir le guide Mattermost","officialLabel": "Ouvrir le guide des bots Mattermost",- "tryIt": "Mentionnez le bot dans un canal Mattermost ou envoyez-lui un message privé.",- "summary": "Mattermost se connecte via un compte bot sur votre serveur et écoute les canaux et messages privés.",- "steps": [- "Créez un compte bot Mattermost et copiez son jeton d’accès.",- "Saisissez l’URL du serveur et accordez l’accès à l’équipe et aux canaux cibles.",- "Enregistrez et activez Mattermost, puis mentionnez le bot ou envoyez-lui un message privé."- ],"fields": {"serverUrl": {"label": "URL du serveur",- "placeholder": "https://mattermost.example.com",- "help": "Utilisez l’URL de base de votre espace Mattermost."+ "placeholder": "https://mattermost.example.com"},"token": {"label": "Jeton du bot",- "placeholder": "Jeton du bot Mattermost",- "help": "Créez-le depuis un compte bot Mattermost."+ "placeholder": "Jeton du bot Mattermost"},"teamId": {"label": "ID de l’équipe",@@ -45,6 +34,78 @@"allowFrom": {"label": "Utilisateurs autorisés","placeholder": "ID utilisateur séparés par des virgules"+ },+ "allowFromMatchMode": {+ "label": "Correspondance des utilisateurs",+ "choices": {+ "email": "Courriel",+ "id": "Identifiant utilisateur",+ "username": "Nom d'utilisateur"+ }+ },+ "groupAllowFrom": {+ "label": "Chaînes autorisées"+ },+ "replyInThread": {+ "label": "Répondre dans le fil de discussion",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "includeThreadContext": {+ "label": "Inclure le contexte du fil de discussion",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "threadContextLimit": {+ "label": "Limite du contexte du fil de discussion"+ },+ "streaming": {+ "label": "Diffusion en continu",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "reactEmoji": {+ "label": "Lire les emoji"+ },+ "doneEmoji": {+ "label": "Terminé emoji"+ },+ "sendProgress": {+ "label": "Envoyer la progression",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "sendToolHints": {+ "label": "Envoyer des conseils sur les outils",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "dm_enabled": {+ "label": "Activer les messages directs",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "dm_policy": {+ "label": "Accès aux messages directs",+ "choices": {+ "allowlist": "Liste verte",+ "open": "Ouvert"+ }+ },+ "dm_allowFrom": {+ "label": "Utilisateurs de messagerie directe autorisés"}}}diff --git a/nanobot/channels/mattermost/webui/locales/id.json b/nanobot/channels/mattermost/webui/locales/id.jsonindex d57870eeb..c0966f2f2 100644--- a/nanobot/channels/mattermost/webui/locales/id.json+++ b/nanobot/channels/mattermost/webui/locales/id.json@@ -1,26 +1,15 @@{- "description": "Gunakan nanobot dari kanal dan DM Mattermost.",- "requirements": "URL server Mattermost, token bot, dan akses kanal","setup": {"docsLabel": "Buka panduan Mattermost","officialLabel": "Buka panduan bot Mattermost",- "tryIt": "Sebut bot di kanal Mattermost atau kirim pesan langsung.",- "summary": "Mattermost terhubung melalui akun bot di server dan menerima pesan kanal serta pesan langsung.",- "steps": [- "Buat akun bot Mattermost dan salin token aksesnya.",- "Masukkan URL server dan berikan akses ke tim serta kanal tujuan.",- "Simpan dan aktifkan Mattermost, lalu sebut bot atau kirim DM."- ],"fields": {"serverUrl": {"label": "URL server",- "placeholder": "https://mattermost.example.com",- "help": "Gunakan URL dasar ruang kerja Mattermost."+ "placeholder": "https://mattermost.example.com"},"token": {"label": "Token bot",- "placeholder": "Token bot Mattermost",- "help": "Buat dari akun bot Mattermost."+ "placeholder": "Token bot Mattermost"},"teamId": {"label": "ID tim",@@ -45,6 +34,78 @@"allowFrom": {"label": "Pengguna yang diizinkan","placeholder": "ID pengguna, dipisahkan koma"+ },+ "allowFromMatchMode": {+ "label": "Pencocokan pengguna",+ "choices": {+ "email": "Surel",+ "id": "ID Pengguna",+ "username": "Nama pengguna"+ }+ },+ "groupAllowFrom": {+ "label": "Saluran yang diizinkan"+ },+ "replyInThread": {+ "label": "Balas di thread",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "includeThreadContext": {+ "label": "Sertakan konteks thread",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "threadContextLimit": {+ "label": "Batas konteks thread"+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "reactEmoji": {+ "label": "Baca emoji"+ },+ "doneEmoji": {+ "label": "Selesai emoji"+ },+ "sendProgress": {+ "label": "Kirim kemajuan",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "sendToolHints": {+ "label": "Kirim petunjuk alat",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "dm_enabled": {+ "label": "Aktifkan pesan langsung",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "dm_policy": {+ "label": "Akses pesan langsung",+ "choices": {+ "allowlist": "Daftar yang diizinkan",+ "open": "Buka"+ }+ },+ "dm_allowFrom": {+ "label": "Mengizinkan pengguna pesan langsung"}}}diff --git a/nanobot/channels/mattermost/webui/locales/ja.json b/nanobot/channels/mattermost/webui/locales/ja.jsonindex 33b42d25f..34ef2cffb 100644--- a/nanobot/channels/mattermost/webui/locales/ja.json+++ b/nanobot/channels/mattermost/webui/locales/ja.json@@ -1,26 +1,15 @@{- "description": "Mattermost のチャンネルと DM から nanobot を利用します。",- "requirements": "Mattermost サーバー URL、ボットトークン、チャンネルアクセス","setup": {"docsLabel": "Mattermost 設定ガイドを開く","officialLabel": "Mattermost ボットガイドを開く",- "tryIt": "Mattermost チャンネルでボットをメンションするか、DM を送信します。",- "summary": "Mattermost はサーバー上のボットアカウントで接続し、チャンネルと DM を受信します。",- "steps": [- "Mattermost ボットアカウントを作成し、アクセストークンをコピーします。",- "サーバー URL を入力し、対象チームとチャンネルへのアクセスを許可します。",- "保存して Mattermost を有効にし、メンションまたは DM を送信します。"- ],"fields": {"serverUrl": {"label": "サーバー URL",- "placeholder": "https://mattermost.example.com",- "help": "Mattermost ワークスペースのベース URL を使います。"+ "placeholder": "https://mattermost.example.com"},"token": {"label": "ボットトークン",- "placeholder": "Mattermost ボットトークン",- "help": "Mattermost ボットアカウントから作成します。"+ "placeholder": "Mattermost ボットトークン"},"teamId": {"label": "チーム ID",@@ -45,6 +34,78 @@"allowFrom": {"label": "許可するユーザー","placeholder": "ユーザー ID(カンマ区切り)"+ },+ "allowFromMatchMode": {+ "label": "ユーザーマッチング",+ "choices": {+ "email": "電子メール",+ "id": "ユーザーID",+ "username": "ユーザー名"+ }+ },+ "groupAllowFrom": {+ "label": "許可されたチャネル"+ },+ "replyInThread": {+ "label": "スレッド内で返信する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "includeThreadContext": {+ "label": "スレッドコンテキストを含める",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "threadContextLimit": {+ "label": "スレッドコンテキストの制限"+ },+ "streaming": {+ "label": "ストリーミング",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "reactEmoji": {+ "label": "絵文字を読む"+ },+ "doneEmoji": {+ "label": "完了絵文字"+ },+ "sendProgress": {+ "label": "進捗状況の送信",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "sendToolHints": {+ "label": "ツールヒントを送信する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "dm_enabled": {+ "label": "ダイレクトメッセージを有効にする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "dm_policy": {+ "label": "ダイレクトメッセージへのアクセス",+ "choices": {+ "allowlist": "ホワイトリスト",+ "open": "開く"+ }+ },+ "dm_allowFrom": {+ "label": "許可されたダイレクトメッセージユーザー"}}}diff --git a/nanobot/channels/mattermost/webui/locales/ko.json b/nanobot/channels/mattermost/webui/locales/ko.jsonindex 28257647e..4f8e3682e 100644--- a/nanobot/channels/mattermost/webui/locales/ko.json+++ b/nanobot/channels/mattermost/webui/locales/ko.json@@ -1,26 +1,15 @@{- "description": "Mattermost 채널과 DM에서 nanobot을 사용합니다.",- "requirements": "Mattermost 서버 URL, 봇 토큰 및 채널 접근 권한","setup": {"docsLabel": "Mattermost 설정 가이드 열기","officialLabel": "Mattermost 봇 가이드 열기",- "tryIt": "Mattermost 채널에서 봇을 멘션하거나 DM을 보내세요.",- "summary": "Mattermost는 서버의 봇 계정으로 연결해 채널과 DM을 수신합니다.",- "steps": [- "Mattermost 봇 계정을 만들고 액세스 토큰을 복사하세요.",- "서버 URL을 입력하고 대상 팀과 채널 접근 권한을 부여하세요.",- "저장하고 Mattermost를 활성화한 다음 봇을 멘션하거나 DM을 보내세요."- ],"fields": {"serverUrl": {"label": "서버 URL",- "placeholder": "https://mattermost.example.com",- "help": "Mattermost 작업 공간 기본 URL을 사용하세요."+ "placeholder": "https://mattermost.example.com"},"token": {"label": "봇 토큰",- "placeholder": "Mattermost 봇 토큰",- "help": "Mattermost 봇 계정에서 생성하세요."+ "placeholder": "Mattermost 봇 토큰"},"teamId": {"label": "팀 ID",@@ -45,6 +34,78 @@"allowFrom": {"label": "허용된 사용자","placeholder": "사용자 ID, 쉼표로 구분"+ },+ "allowFromMatchMode": {+ "label": "사용자 매칭",+ "choices": {+ "email": "이메일",+ "id": "사용자 ID",+ "username": "사용자 이름"+ }+ },+ "groupAllowFrom": {+ "label": "허용된 채널"+ },+ "replyInThread": {+ "label": "스레드로 답장하기",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "includeThreadContext": {+ "label": "스레드 컨텍스트 포함",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "threadContextLimit": {+ "label": "스레드 컨텍스트 제한"+ },+ "streaming": {+ "label": "스트리밍",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "reactEmoji": {+ "label": "이모티콘 읽기"+ },+ "doneEmoji": {+ "label": "이모티콘 완료"+ },+ "sendProgress": {+ "label": "진행 상황 보내기",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "sendToolHints": {+ "label": "도구 힌트 보내기",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "dm_enabled": {+ "label": "다이렉트 메시지 활성화",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "dm_policy": {+ "label": "다이렉트 메시지 액세스",+ "choices": {+ "allowlist": "허용 목록",+ "open": "열기"+ }+ },+ "dm_allowFrom": {+ "label": "허용된 직접 메시지 사용자"}}}diff --git a/nanobot/channels/mattermost/webui/locales/pt-BR.json b/nanobot/channels/mattermost/webui/locales/pt-BR.jsonindex e8794f2f0..eacddaa85 100644--- a/nanobot/channels/mattermost/webui/locales/pt-BR.json+++ b/nanobot/channels/mattermost/webui/locales/pt-BR.json@@ -1,26 +1,15 @@{- "description": "Use o nanobot em canais e DMs do Mattermost.",- "requirements": "URL do servidor Mattermost, token do bot e acesso aos canais","setup": {"docsLabel": "Abrir guia do Mattermost","officialLabel": "Abrir guia de bots do Mattermost",- "tryIt": "Mencione o bot em um canal Mattermost ou envie uma mensagem direta.",- "summary": "O nanobot se conecta ao servidor Mattermost com uma conta de bot para receber mensagens de canais e mensagens diretas.",- "steps": [- "Crie uma conta de bot Mattermost e copie o token de acesso.",- "Informe a URL do servidor e conceda acesso à equipe e aos canais desejados.",- "Salve e ative o Mattermost; depois, mencione o bot ou envie uma DM."- ],"fields": {"serverUrl": {"label": "URL do servidor",- "placeholder": "https://mattermost.example.com",- "help": "Use a URL base do seu espaço de trabalho Mattermost."+ "placeholder": "https://mattermost.example.com"},"token": {"label": "Token do bot",- "placeholder": "Token do bot Mattermost",- "help": "Crie-o em uma conta de bot Mattermost."+ "placeholder": "Token do bot Mattermost"},"teamId": {"label": "ID da equipe",@@ -45,6 +34,78 @@"allowFrom": {"label": "Usuários permitidos","placeholder": "IDs de usuário separados por vírgulas"+ },+ "allowFromMatchMode": {+ "label": "Correspondência de usuário",+ "choices": {+ "email": "E-mail",+ "id": "ID do usuário",+ "username": "Nome de usuário"+ }+ },+ "groupAllowFrom": {+ "label": "Canais permitidos"+ },+ "replyInThread": {+ "label": "Responder no tópico",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "includeThreadContext": {+ "label": "Incluir contexto do thread",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "threadContextLimit": {+ "label": "Limite de contexto do thread"+ },+ "streaming": {+ "label": "Transmissão",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "reactEmoji": {+ "label": "Ler emoticons"+ },+ "doneEmoji": {+ "label": "Emoji pronto"+ },+ "sendProgress": {+ "label": "Enviar progresso",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "sendToolHints": {+ "label": "Envie dicas de ferramentas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "dm_enabled": {+ "label": "Habilitar mensagens diretas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "dm_policy": {+ "label": "Acesso direto a mensagens",+ "choices": {+ "allowlist": "Lista de permissões",+ "open": "Abrir"+ }+ },+ "dm_allowFrom": {+ "label": "Usuários de mensagens diretas permitidos"}}}diff --git a/nanobot/channels/mattermost/webui/locales/vi.json b/nanobot/channels/mattermost/webui/locales/vi.jsonindex c68e3b2bb..7071e9ae4 100644--- a/nanobot/channels/mattermost/webui/locales/vi.json+++ b/nanobot/channels/mattermost/webui/locales/vi.json@@ -1,26 +1,15 @@{- "description": "Sử dụng nanobot trong kênh và tin nhắn riêng Mattermost.",- "requirements": "URL máy chủ Mattermost, token bot và quyền truy cập kênh","setup": {"docsLabel": "Mở hướng dẫn Mattermost","officialLabel": "Mở hướng dẫn bot Mattermost",- "tryIt": "Nhắc bot trong kênh Mattermost hoặc gửi tin nhắn riêng.",- "summary": "Mattermost kết nối qua tài khoản bot trên máy chủ và nhận tin nhắn kênh cùng tin nhắn riêng.",- "steps": [- "Tạo tài khoản bot Mattermost và sao chép token truy cập.",- "Nhập URL máy chủ và cấp quyền vào nhóm cùng các kênh đích.",- "Lưu và bật Mattermost, sau đó nhắc bot hoặc gửi tin nhắn riêng."- ],"fields": {"serverUrl": {"label": "URL máy chủ",- "placeholder": "https://mattermost.example.com",- "help": "Dùng URL gốc của không gian Mattermost."+ "placeholder": "https://mattermost.example.com"},"token": {"label": "Token bot",- "placeholder": "Token bot Mattermost",- "help": "Tạo từ tài khoản bot Mattermost."+ "placeholder": "Token bot Mattermost"},"teamId": {"label": "ID nhóm",@@ -45,6 +34,78 @@"allowFrom": {"label": "Người dùng được phép","placeholder": "ID người dùng, phân tách bằng dấu phẩy"+ },+ "allowFromMatchMode": {+ "label": "So khớp người dùng",+ "choices": {+ "email": "Email",+ "id": "ID người dùng",+ "username": "Tên người dùng"+ }+ },+ "groupAllowFrom": {+ "label": "Các kênh được phép"+ },+ "replyInThread": {+ "label": "Trả lời trong chủ đề",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "includeThreadContext": {+ "label": "Bao gồm bối cảnh chủ đề",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "threadContextLimit": {+ "label": "Giới hạn bối cảnh của chủ đề"+ },+ "streaming": {+ "label": "Truyền phát",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "reactEmoji": {+ "label": "Đọc biểu tượng cảm xúc"+ },+ "doneEmoji": {+ "label": "biểu tượng cảm xúc xong"+ },+ "sendProgress": {+ "label": "Gửi tiến trình",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "sendToolHints": {+ "label": "Gửi gợi ý công cụ",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "dm_enabled": {+ "label": "Bật tin nhắn trực tiếp",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "dm_policy": {+ "label": "Truy cập tin nhắn trực tiếp",+ "choices": {+ "allowlist": "Danh sách cho phép",+ "open": "Mở"+ }+ },+ "dm_allowFrom": {+ "label": "Cho phép người dùng nhắn tin trực tiếp"}}}diff --git a/nanobot/channels/mattermost/webui/locales/zh-CN.json b/nanobot/channels/mattermost/webui/locales/zh-CN.jsonindex 521a5c06d..072d98965 100644--- a/nanobot/channels/mattermost/webui/locales/zh-CN.json+++ b/nanobot/channels/mattermost/webui/locales/zh-CN.json@@ -1,26 +1,15 @@{- "description": "在 Mattermost 频道和私信中使用 nanobot。",- "requirements": "Mattermost 服务器地址、机器人令牌和频道权限","setup": {"docsLabel": "打开 Mattermost 配置指南","officialLabel": "打开 Mattermost 机器人指南",- "tryIt": "在 Mattermost 频道中提及机器人,或向它发送私信。",- "summary": "Mattermost 通过服务器中的机器人账户连接,并监听频道和私信。",- "steps": [- "创建 Mattermost 机器人账户并复制访问令牌。",- "填写服务器地址,并授予机器人访问目标团队和频道的权限。",- "保存并启用 Mattermost,然后提及机器人或发送私信。"- ],"fields": {"serverUrl": {"label": "服务器地址",- "placeholder": "https://mattermost.example.com",- "help": "填写 Mattermost 工作区的基础地址。"+ "placeholder": "https://mattermost.example.com"},"token": {"label": "机器人令牌",- "placeholder": "Mattermost 机器人令牌",- "help": "从 Mattermost 机器人账户创建。"+ "placeholder": "Mattermost 机器人令牌"},"teamId": {"label": "团队 ID",@@ -45,6 +34,78 @@"allowFrom": {"label": "允许的用户","placeholder": "用户 ID,用逗号分隔"+ },+ "allowFromMatchMode": {+ "label": "用户匹配方式",+ "choices": {+ "email": "邮箱",+ "id": "用户 ID",+ "username": "用户名"+ }+ },+ "groupAllowFrom": {+ "label": "允许的频道"+ },+ "replyInThread": {+ "label": "在话题中回复",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "includeThreadContext": {+ "label": "包含话题上下文",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "threadContextLimit": {+ "label": "话题上下文上限"+ },+ "streaming": {+ "label": "流式输出",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "reactEmoji": {+ "label": "已读表情"+ },+ "doneEmoji": {+ "label": "完成表情"+ },+ "sendProgress": {+ "label": "发送进度消息",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "sendToolHints": {+ "label": "发送工具提示",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "dm_enabled": {+ "label": "启用私聊",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "dm_policy": {+ "label": "私聊权限",+ "choices": {+ "allowlist": "白名单",+ "open": "全部"+ }+ },+ "dm_allowFrom": {+ "label": "允许私聊的用户"}}}diff --git a/nanobot/channels/mattermost/webui/locales/zh-TW.json b/nanobot/channels/mattermost/webui/locales/zh-TW.jsonindex af3e390c7..69f142c4f 100644--- a/nanobot/channels/mattermost/webui/locales/zh-TW.json+++ b/nanobot/channels/mattermost/webui/locales/zh-TW.json@@ -1,26 +1,15 @@{- "description": "在 Mattermost 頻道和私訊中使用 nanobot。",- "requirements": "Mattermost 伺服器網址、機器人權杖和頻道權限","setup": {"docsLabel": "開啟 Mattermost 設定指南","officialLabel": "開啟 Mattermost 機器人指南",- "tryIt": "在 Mattermost 頻道中提及機器人,或向它傳送私訊。",- "summary": "Mattermost 透過伺服器中的機器人帳戶連線,並監聽頻道和私訊。",- "steps": [- "建立 Mattermost 機器人帳戶並複製存取權杖。",- "填入伺服器網址,並授予機器人存取目標團隊和頻道的權限。",- "儲存並啟用 Mattermost,然後提及機器人或傳送私訊。"- ],"fields": {"serverUrl": {"label": "伺服器網址",- "placeholder": "https://mattermost.example.com",- "help": "填入 Mattermost 工作區的基礎網址。"+ "placeholder": "https://mattermost.example.com"},"token": {"label": "機器人權杖",- "placeholder": "Mattermost 機器人權杖",- "help": "從 Mattermost 機器人帳戶建立。"+ "placeholder": "Mattermost 機器人權杖"},"teamId": {"label": "團隊 ID",@@ -45,6 +34,78 @@"allowFrom": {"label": "允許的使用者","placeholder": "使用者 ID,以逗號分隔"+ },+ "allowFromMatchMode": {+ "label": "用戶匹配方式",+ "choices": {+ "email": "信箱",+ "id": "使用者 ID",+ "username": "使用者名稱"+ }+ },+ "groupAllowFrom": {+ "label": "允許的頻道"+ },+ "replyInThread": {+ "label": "在話題中回复",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "includeThreadContext": {+ "label": "包含話題上下文",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "threadContextLimit": {+ "label": "話題上下文上限"+ },+ "streaming": {+ "label": "串流輸出",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "reactEmoji": {+ "label": "已讀表情"+ },+ "doneEmoji": {+ "label": "完成表情"+ },+ "sendProgress": {+ "label": "發送進度訊息",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "sendToolHints": {+ "label": "發送工具提示",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "dm_enabled": {+ "label": "啟用私聊",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "dm_policy": {+ "label": "私聊權限",+ "choices": {+ "allowlist": "白名單",+ "open": "全部"+ }+ },+ "dm_allowFrom": {+ "label": "允許私聊的用戶"}}}diff --git a/nanobot/channels/mochat/manifest.py b/nanobot/channels/mochat/manifest.pyindex 6318e45a9..df0e750af 100644--- a/nanobot/channels/mochat/manifest.py+++ b/nanobot/channels/mochat/manifest.py@@ -12,6 +12,21 @@ SETUP_SPEC = ChannelSetupSpec("sessions": field("list"),"panels": field("list"),"allowFrom": field("list"),+ "socketUrl": field(),+ "socketPath": field(default="/socket.io"),+ "socketDisableMsgpack": field("bool", default=False),+ "socketReconnectDelayMs": field("int", default=1000),+ "socketMaxReconnectDelayMs": field("int", default=10000),+ "socketConnectTimeoutMs": field("int", default=10000),+ "refreshIntervalMs": field("int", default=30000),+ "watchTimeoutMs": field("int", default=25000),+ "watchLimit": field("int", default=100),+ "retryDelayMs": field("int", default=500),+ "maxRetryAttempts": field("int", default=0),+ "mention.requireInGroups": field("bool", default=False),+ "groups": field("json", default={}),+ "replyDelayMode": field(default="non-mention"),+ "replyDelayMs": field("int", default=120000),},required=(required("clawToken"),),official_url="https://mochat.io/",@@ -26,5 +41,5 @@ PLUGIN = ChannelPlugin("python-socketio>=5.16.0,<6.0.0","msgpack>=1.1.0,<2.0.0",),- settings_visible=False,+ webui="webui/index.ts",)diff --git a/nanobot/channels/mochat/webui/index.ts b/nanobot/channels/mochat/webui/index.tsnew file mode 100644index 000000000..c37358589--- /dev/null+++ b/nanobot/channels/mochat/webui/index.ts@@ -0,0 +1,23 @@+import type { ChannelUiContribution } from "@/channel-plugins/types";+import { chatAppGuideUrl } from "@/components/settings/channels/catalog";++export default {+ presentation: {+ logoUrl: "https://mochat.io/favicon.ico",+ displayName: "MoChat",+ initials: "MC",+ color: "#111827",+ setup: {+ mode: "credentials",+ docsUrl: chatAppGuideUrl("mochat"),+ fields: [+ { key: "channels.mochat.clawToken", section: "credentials" },+ { key: "channels.mochat.baseUrl", section: "connection" },+ { key: "channels.mochat.agentUserId", section: "account" },+ { key: "channels.mochat.sessions", section: "access" },+ { key: "channels.mochat.panels", section: "access" },+ { key: "channels.mochat.allowFrom", section: "access" },+ ],+ },+ },+} satisfies ChannelUiContribution;diff --git a/nanobot/channels/mochat/webui/locales/en.json b/nanobot/channels/mochat/webui/locales/en.jsonnew file mode 100644index 000000000..02a7e047c--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/en.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "Open MoChat setup guide",+ "officialLabel": "Open MoChat",+ "fields": {+ "clawToken": {+ "label": "Claw token",+ "placeholder": "MoChat Claw token"+ },+ "baseUrl": {+ "label": "Server URL",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "Agent user ID",+ "placeholder": "Optional agent user ID"+ },+ "sessions": {+ "label": "Sessions",+ "placeholder": "Session IDs, comma separated"+ },+ "panels": {+ "label": "Panels",+ "placeholder": "Panel IDs, comma separated"+ },+ "allowFrom": {+ "label": "Allowed users",+ "placeholder": "User IDs, comma separated"+ },+ "socketUrl": {+ "label": "Socket URL"+ },+ "socketPath": {+ "label": "Socket path"+ },+ "socketDisableMsgpack": {+ "label": "Disable MessagePack",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "socketReconnectDelayMs": {+ "label": "Reconnect delay"+ },+ "socketMaxReconnectDelayMs": {+ "label": "Maximum reconnect delay"+ },+ "socketConnectTimeoutMs": {+ "label": "Connection timeout"+ },+ "refreshIntervalMs": {+ "label": "Refresh interval"+ },+ "watchTimeoutMs": {+ "label": "Watch timeout"+ },+ "watchLimit": {+ "label": "Watch batch size"+ },+ "retryDelayMs": {+ "label": "Retry delay"+ },+ "maxRetryAttempts": {+ "label": "Maximum retries"+ },+ "mention_requireInGroups": {+ "label": "Require mentions in groups",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "groups": {+ "label": "Group rules (JSON)"+ },+ "replyDelayMode": {+ "label": "Reply delay mode"+ },+ "replyDelayMs": {+ "label": "Reply delay"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/es.json b/nanobot/channels/mochat/webui/locales/es.jsonnew file mode 100644index 000000000..8f5f90a6a--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/es.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "Abrir la guía de configuración de MoChat",+ "officialLabel": "Abrir MoChat",+ "fields": {+ "clawToken": {+ "label": "Token de Claw",+ "placeholder": "Token de Claw de MoChat"+ },+ "baseUrl": {+ "label": "URL del servidor",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "ID de usuario del agente",+ "placeholder": "ID de usuario del agente opcional"+ },+ "sessions": {+ "label": "Sesiones",+ "placeholder": "IDs de sesión, separados por comas"+ },+ "panels": {+ "label": "Paneles",+ "placeholder": "IDs de panel, separados por comas"+ },+ "allowFrom": {+ "label": "Usuarios permitidos",+ "placeholder": "IDs de usuario, separados por comas"+ },+ "socketUrl": {+ "label": "URL del conector"+ },+ "socketPath": {+ "label": "Ruta del zócalo"+ },+ "socketDisableMsgpack": {+ "label": "Deshabilitar paquete de mensajes",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "socketReconnectDelayMs": {+ "label": "Retardo de reconexión"+ },+ "socketMaxReconnectDelayMs": {+ "label": "Retardo máximo de reconexión"+ },+ "socketConnectTimeoutMs": {+ "label": "Tiempo de espera de conexión"+ },+ "refreshIntervalMs": {+ "label": "Intervalo de actualización"+ },+ "watchTimeoutMs": {+ "label": "Ver tiempo de espera"+ },+ "watchLimit": {+ "label": "Ver tamaño del lote"+ },+ "retryDelayMs": {+ "label": "Retraso de reintento"+ },+ "maxRetryAttempts": {+ "label": "Reintentos máximos"+ },+ "mention_requireInGroups": {+ "label": "Requerir menciones en grupos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "groups": {+ "label": "Reglas de grupo (JSON)"+ },+ "replyDelayMode": {+ "label": "Modo de retardo de respuesta"+ },+ "replyDelayMs": {+ "label": "Retraso en la respuesta"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/fr.json b/nanobot/channels/mochat/webui/locales/fr.jsonnew file mode 100644index 000000000..86bf05270--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/fr.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "Ouvrir le guide de configuration MoChat",+ "officialLabel": "Ouvrir MoChat",+ "fields": {+ "clawToken": {+ "label": "Jeton Claw",+ "placeholder": "Jeton Claw MoChat"+ },+ "baseUrl": {+ "label": "URL du serveur",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "Identifiant utilisateur de l’agent",+ "placeholder": "Identifiant utilisateur facultatif"+ },+ "sessions": {+ "label": "Sessions",+ "placeholder": "Identifiants de session, séparés par des virgules"+ },+ "panels": {+ "label": "Panneaux",+ "placeholder": "Identifiants de panneau, séparés par des virgules"+ },+ "allowFrom": {+ "label": "Utilisateurs autorisés",+ "placeholder": "Identifiants utilisateur, séparés par des virgules"+ },+ "socketUrl": {+ "label": "URL de socket"+ },+ "socketPath": {+ "label": "Chemin de prise"+ },+ "socketDisableMsgpack": {+ "label": "Désactiver MessagePack",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "socketReconnectDelayMs": {+ "label": "Délai de reconnexion"+ },+ "socketMaxReconnectDelayMs": {+ "label": "Délai de reconnexion maximum"+ },+ "socketConnectTimeoutMs": {+ "label": "Délai de connexion"+ },+ "refreshIntervalMs": {+ "label": "Intervalle d'actualisation"+ },+ "watchTimeoutMs": {+ "label": "Expiration du délai de visionnage"+ },+ "watchLimit": {+ "label": "Surveiller la taille du lot"+ },+ "retryDelayMs": {+ "label": "Délai de nouvelle tentative"+ },+ "maxRetryAttempts": {+ "label": "Nombre maximal de tentatives"+ },+ "mention_requireInGroups": {+ "label": "Exiger des mentions dans les groupes",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "groups": {+ "label": "Règles de groupe (JSON)"+ },+ "replyDelayMode": {+ "label": "Mode de délai de réponse"+ },+ "replyDelayMs": {+ "label": "Délai de réponse"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/id.json b/nanobot/channels/mochat/webui/locales/id.jsonnew file mode 100644index 000000000..b40e3d973--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/id.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "Buka panduan penyiapan MoChat",+ "officialLabel": "Buka MoChat",+ "fields": {+ "clawToken": {+ "label": "Token Claw",+ "placeholder": "Token Claw MoChat"+ },+ "baseUrl": {+ "label": "URL server",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "ID pengguna agen",+ "placeholder": "ID pengguna agen opsional"+ },+ "sessions": {+ "label": "Sesi",+ "placeholder": "ID sesi, pisahkan dengan koma"+ },+ "panels": {+ "label": "Panel",+ "placeholder": "ID panel, pisahkan dengan koma"+ },+ "allowFrom": {+ "label": "Pengguna yang diizinkan",+ "placeholder": "ID pengguna, pisahkan dengan koma"+ },+ "socketUrl": {+ "label": "URL soket"+ },+ "socketPath": {+ "label": "Jalur soket"+ },+ "socketDisableMsgpack": {+ "label": "Nonaktifkan MessagePack",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "socketReconnectDelayMs": {+ "label": "Sambungkan kembali penundaan"+ },+ "socketMaxReconnectDelayMs": {+ "label": "Penundaan penyambungan kembali maksimum"+ },+ "socketConnectTimeoutMs": {+ "label": "Batas waktu koneksi habis"+ },+ "refreshIntervalMs": {+ "label": "Interval penyegaran"+ },+ "watchTimeoutMs": {+ "label": "Waktu tunggu tonton habis"+ },+ "watchLimit": {+ "label": "Perhatikan ukuran batch"+ },+ "retryDelayMs": {+ "label": "Coba lagi penundaan"+ },+ "maxRetryAttempts": {+ "label": "Percobaan ulang maksimum"+ },+ "mention_requireInGroups": {+ "label": "Memerlukan penyebutan dalam kelompok",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "groups": {+ "label": "Aturan grup (JSON)"+ },+ "replyDelayMode": {+ "label": "Mode penundaan balasan"+ },+ "replyDelayMs": {+ "label": "Keterlambatan balasan"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/ja.json b/nanobot/channels/mochat/webui/locales/ja.jsonnew file mode 100644index 000000000..3b2a3ba96--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/ja.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "MoChat 設定ガイドを開く",+ "officialLabel": "MoChat を開く",+ "fields": {+ "clawToken": {+ "label": "Claw トークン",+ "placeholder": "MoChat Claw トークン"+ },+ "baseUrl": {+ "label": "サーバー URL",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "エージェントのユーザー ID",+ "placeholder": "任意のエージェントユーザー ID"+ },+ "sessions": {+ "label": "セッション",+ "placeholder": "セッション ID(カンマ区切り)"+ },+ "panels": {+ "label": "パネル",+ "placeholder": "パネル ID(カンマ区切り)"+ },+ "allowFrom": {+ "label": "許可するユーザー",+ "placeholder": "ユーザー ID(カンマ区切り)"+ },+ "socketUrl": {+ "label": "ソケットURL"+ },+ "socketPath": {+ "label": "ソケットパス"+ },+ "socketDisableMsgpack": {+ "label": "メッセージパックを無効にする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "socketReconnectDelayMs": {+ "label": "再接続の遅延"+ },+ "socketMaxReconnectDelayMs": {+ "label": "最大再接続遅延"+ },+ "socketConnectTimeoutMs": {+ "label": "接続タイムアウト"+ },+ "refreshIntervalMs": {+ "label": "リフレッシュ間隔"+ },+ "watchTimeoutMs": {+ "label": "ウォッチタイムアウト"+ },+ "watchLimit": {+ "label": "バッチサイズを監視する"+ },+ "retryDelayMs": {+ "label": "再試行の遅延"+ },+ "maxRetryAttempts": {+ "label": "最大再試行回数"+ },+ "mention_requireInGroups": {+ "label": "グループでのメンションを必須にする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "groups": {+ "label": "グループルール(JSON)"+ },+ "replyDelayMode": {+ "label": "返信遅延モード"+ },+ "replyDelayMs": {+ "label": "返信遅延"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/ko.json b/nanobot/channels/mochat/webui/locales/ko.jsonnew file mode 100644index 000000000..93eac51c5--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/ko.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "MoChat 설정 가이드 열기",+ "officialLabel": "MoChat 열기",+ "fields": {+ "clawToken": {+ "label": "Claw 토큰",+ "placeholder": "MoChat Claw 토큰"+ },+ "baseUrl": {+ "label": "서버 URL",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "에이전트 사용자 ID",+ "placeholder": "선택 사항인 에이전트 사용자 ID"+ },+ "sessions": {+ "label": "세션",+ "placeholder": "세션 ID, 쉼표로 구분"+ },+ "panels": {+ "label": "패널",+ "placeholder": "패널 ID, 쉼표로 구분"+ },+ "allowFrom": {+ "label": "허용된 사용자",+ "placeholder": "사용자 ID, 쉼표로 구분"+ },+ "socketUrl": {+ "label": "소켓 URL"+ },+ "socketPath": {+ "label": "소켓 경로"+ },+ "socketDisableMsgpack": {+ "label": "MessagePack 비활성화",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "socketReconnectDelayMs": {+ "label": "재연결 지연"+ },+ "socketMaxReconnectDelayMs": {+ "label": "최대 재연결 지연"+ },+ "socketConnectTimeoutMs": {+ "label": "연결 시간 초과"+ },+ "refreshIntervalMs": {+ "label": "새로 고침 간격"+ },+ "watchTimeoutMs": {+ "label": "시청 시간 초과"+ },+ "watchLimit": {+ "label": "시계 배치 크기"+ },+ "retryDelayMs": {+ "label": "재시도 지연"+ },+ "maxRetryAttempts": {+ "label": "최대 재시도"+ },+ "mention_requireInGroups": {+ "label": "그룹에서 멘션 필요",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "groups": {+ "label": "그룹 규칙(JSON)"+ },+ "replyDelayMode": {+ "label": "응답 지연 모드"+ },+ "replyDelayMs": {+ "label": "답변 지연"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/pt-BR.json b/nanobot/channels/mochat/webui/locales/pt-BR.jsonnew file mode 100644index 000000000..0f7be278a--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/pt-BR.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "Abrir o guia de configuração do MoChat",+ "officialLabel": "Abrir o MoChat",+ "fields": {+ "clawToken": {+ "label": "Token Claw",+ "placeholder": "Token Claw do MoChat"+ },+ "baseUrl": {+ "label": "URL do servidor",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "ID de usuário do agente",+ "placeholder": "ID de usuário opcional do agente"+ },+ "sessions": {+ "label": "Sessões",+ "placeholder": "IDs de sessão, separados por vírgulas"+ },+ "panels": {+ "label": "Painéis",+ "placeholder": "IDs de painel, separados por vírgulas"+ },+ "allowFrom": {+ "label": "Usuários permitidos",+ "placeholder": "IDs de usuário, separados por vírgulas"+ },+ "socketUrl": {+ "label": "URL do soquete"+ },+ "socketPath": {+ "label": "Caminho do soquete"+ },+ "socketDisableMsgpack": {+ "label": "Desativar MessagePack",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "socketReconnectDelayMs": {+ "label": "Atraso na reconexão"+ },+ "socketMaxReconnectDelayMs": {+ "label": "Atraso máximo de reconexão"+ },+ "socketConnectTimeoutMs": {+ "label": "Tempo limite de conexão"+ },+ "refreshIntervalMs": {+ "label": "Intervalo de atualização"+ },+ "watchTimeoutMs": {+ "label": "Tempo limite de exibição"+ },+ "watchLimit": {+ "label": "Observe o tamanho do lote"+ },+ "retryDelayMs": {+ "label": "Atraso na nova tentativa"+ },+ "maxRetryAttempts": {+ "label": "Máximo de tentativas"+ },+ "mention_requireInGroups": {+ "label": "Exigir menções em grupos",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "groups": {+ "label": "Regras de grupo (JSON)"+ },+ "replyDelayMode": {+ "label": "Modo de atraso de resposta"+ },+ "replyDelayMs": {+ "label": "Atraso na resposta"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/vi.json b/nanobot/channels/mochat/webui/locales/vi.jsonnew file mode 100644index 000000000..ab067c1d9--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/vi.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "Mở hướng dẫn thiết lập MoChat",+ "officialLabel": "Mở MoChat",+ "fields": {+ "clawToken": {+ "label": "Mã Claw",+ "placeholder": "Mã Claw của MoChat"+ },+ "baseUrl": {+ "label": "URL máy chủ",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "ID người dùng của agent",+ "placeholder": "ID người dùng agent không bắt buộc"+ },+ "sessions": {+ "label": "Phiên",+ "placeholder": "ID phiên, phân tách bằng dấu phẩy"+ },+ "panels": {+ "label": "Bảng",+ "placeholder": "ID bảng, phân tách bằng dấu phẩy"+ },+ "allowFrom": {+ "label": "Người dùng được phép",+ "placeholder": "ID người dùng, phân tách bằng dấu phẩy"+ },+ "socketUrl": {+ "label": "URL ổ cắm"+ },+ "socketPath": {+ "label": "Đường dẫn ổ cắm"+ },+ "socketDisableMsgpack": {+ "label": "Tắt MessagePack",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "socketReconnectDelayMs": {+ "label": "Độ trễ kết nối lại"+ },+ "socketMaxReconnectDelayMs": {+ "label": "Độ trễ kết nối lại tối đa"+ },+ "socketConnectTimeoutMs": {+ "label": "Hết thời gian kết nối"+ },+ "refreshIntervalMs": {+ "label": "Khoảng thời gian làm mới"+ },+ "watchTimeoutMs": {+ "label": "Hết thời gian xem"+ },+ "watchLimit": {+ "label": "Kích thước lô đồng hồ"+ },+ "retryDelayMs": {+ "label": "Trì hoãn thử lại"+ },+ "maxRetryAttempts": {+ "label": "Số lần thử lại tối đa"+ },+ "mention_requireInGroups": {+ "label": "Yêu cầu đề cập trong nhóm",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "groups": {+ "label": "Quy tắc nhóm (JSON)"+ },+ "replyDelayMode": {+ "label": "Chế độ trì hoãn trả lời"+ },+ "replyDelayMs": {+ "label": "Trả lời chậm trễ"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/zh-CN.json b/nanobot/channels/mochat/webui/locales/zh-CN.jsonnew file mode 100644index 000000000..b71a1b0b3--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/zh-CN.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "打开 MoChat 配置指南",+ "officialLabel": "打开 MoChat",+ "fields": {+ "clawToken": {+ "label": "Claw 令牌",+ "placeholder": "MoChat Claw 令牌"+ },+ "baseUrl": {+ "label": "服务地址",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "Agent 用户 ID",+ "placeholder": "可选的 Agent 用户 ID"+ },+ "sessions": {+ "label": "会话",+ "placeholder": "会话 ID,用逗号分隔"+ },+ "panels": {+ "label": "面板",+ "placeholder": "面板 ID,用逗号分隔"+ },+ "allowFrom": {+ "label": "允许的用户",+ "placeholder": "用户 ID,用逗号分隔"+ },+ "socketUrl": {+ "label": "Socket 地址"+ },+ "socketPath": {+ "label": "Socket 路径"+ },+ "socketDisableMsgpack": {+ "label": "禁用 MessagePack",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "socketReconnectDelayMs": {+ "label": "重连延迟"+ },+ "socketMaxReconnectDelayMs": {+ "label": "最大重连延迟"+ },+ "socketConnectTimeoutMs": {+ "label": "连接超时"+ },+ "refreshIntervalMs": {+ "label": "刷新间隔"+ },+ "watchTimeoutMs": {+ "label": "拉取超时"+ },+ "watchLimit": {+ "label": "单次拉取数量"+ },+ "retryDelayMs": {+ "label": "重试延迟"+ },+ "maxRetryAttempts": {+ "label": "最大重试次数"+ },+ "mention_requireInGroups": {+ "label": "群组中需要提及",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "groups": {+ "label": "群组规则(JSON)"+ },+ "replyDelayMode": {+ "label": "回复延迟方式"+ },+ "replyDelayMs": {+ "label": "回复延迟"+ }+ }+ }+}diff --git a/nanobot/channels/mochat/webui/locales/zh-TW.json b/nanobot/channels/mochat/webui/locales/zh-TW.jsonnew file mode 100644index 000000000..1136c7bbb--- /dev/null+++ b/nanobot/channels/mochat/webui/locales/zh-TW.json@@ -0,0 +1,85 @@+{+ "setup": {+ "docsLabel": "開啟 MoChat 設定指南",+ "officialLabel": "開啟 MoChat",+ "fields": {+ "clawToken": {+ "label": "Claw 權杖",+ "placeholder": "MoChat Claw 權杖"+ },+ "baseUrl": {+ "label": "服務位址",+ "placeholder": "https://mochat.io"+ },+ "agentUserId": {+ "label": "Agent 使用者 ID",+ "placeholder": "選填的 Agent 使用者 ID"+ },+ "sessions": {+ "label": "工作階段",+ "placeholder": "工作階段 ID,以逗號分隔"+ },+ "panels": {+ "label": "面板",+ "placeholder": "面板 ID,以逗號分隔"+ },+ "allowFrom": {+ "label": "允許的使用者",+ "placeholder": "使用者 ID,以逗號分隔"+ },+ "socketUrl": {+ "label": "Socket 位址"+ },+ "socketPath": {+ "label": "Socket 路徑"+ },+ "socketDisableMsgpack": {+ "label": "禁用 MessagePack",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "socketReconnectDelayMs": {+ "label": "重連延遲"+ },+ "socketMaxReconnectDelayMs": {+ "label": "最大重連延遲"+ },+ "socketConnectTimeoutMs": {+ "label": "連線逾時"+ },+ "refreshIntervalMs": {+ "label": "刷新間隔"+ },+ "watchTimeoutMs": {+ "label": "拉取超時"+ },+ "watchLimit": {+ "label": "單次拉取數量"+ },+ "retryDelayMs": {+ "label": "重試延遲"+ },+ "maxRetryAttempts": {+ "label": "最大重試次數"+ },+ "mention_requireInGroups": {+ "label": "群組需要提及",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "groups": {+ "label": "群組規則(JSON)"+ },+ "replyDelayMode": {+ "label": "回覆延遲方式"+ },+ "replyDelayMs": {+ "label": "回覆延遲"+ }+ }+ }+}diff --git a/nanobot/channels/msteams/manifest.py b/nanobot/channels/msteams/manifest.pyindex 5b298e4a7..fd074542a 100644--- a/nanobot/channels/msteams/manifest.py+++ b/nanobot/channels/msteams/manifest.py@@ -11,6 +11,16 @@ SETUP_SPEC = ChannelSetupSpec("tenantId": field(),"path": field(default="/api/messages"),"allowFrom": field("list"),+ "host": field(default="0.0.0.0"),+ "port": field("int", default=3978),+ "replyInThread": field("bool", default=True),+ "mentionOnlyResponse": field(default="Hi — what can I help with?"),+ "validateInboundAuth": field("bool", default=True),+ "refTtlDays": field("int", default=30),+ "pruneWebChatRefs": field("bool", default=True),+ "pruneNonPersonalRefs": field("bool", default=True),+ "refTouchIntervalS": field("int", default=300),+ "trustedServiceUrlHosts": field("list"),},required=required_fields("appId", "appPassword"),official_url="https://dev.teams.microsoft.com/apps",diff --git a/nanobot/channels/msteams/webui/index.ts b/nanobot/channels/msteams/webui/index.tsindex 7360fd0d8..378a5619f 100644--- a/nanobot/channels/msteams/webui/index.ts+++ b/nanobot/channels/msteams/webui/index.ts@@ -3,19 +3,19 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://teams.public.onecdn.static.microsoft/evergreen-assets/icons/microsoft_teams_logo_refresh_v2025.ico",displayName: "Microsoft Teams",initials: "MS",color: "#6264A7",- logoUrl: "https://www.microsoft.com/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("msteams"),fields: [- { key: "channels.msteams.appId" },- { key: "channels.msteams.appPassword" },- { key: "channels.msteams.tenantId" },- { key: "channels.msteams.path" },- { key: "channels.msteams.allowFrom" },+ { key: "channels.msteams.appId", section: "credentials" },+ { key: "channels.msteams.appPassword", section: "credentials" },+ { key: "channels.msteams.tenantId", section: "account" },+ { key: "channels.msteams.path", section: "connection" },+ { key: "channels.msteams.allowFrom", section: "access" },],},},diff --git a/nanobot/channels/msteams/webui/locales/en.json b/nanobot/channels/msteams/webui/locales/en.jsonindex 9f41278f2..cde8c51b6 100644--- a/nanobot/channels/msteams/webui/locales/en.json+++ b/nanobot/channels/msteams/webui/locales/en.json@@ -1,26 +1,15 @@{- "description": "Use nanobot from Microsoft Teams chats.",- "requirements": "Azure bot app credentials, public callback endpoint","setup": {"docsLabel": "Open Teams setup","officialLabel": "Open Teams developer portal",- "tryIt": "Install the Teams app and send a test message.",- "summary": "Teams receives messages through the Bot Framework callback URL. It needs a reachable HTTPS endpoint in production.",- "steps": [- "Create an Azure Bot or Teams app and copy its App ID and client secret.",- "Expose the callback path over HTTPS and add it as the bot messaging endpoint.",- "Save and enable Teams, then install the app and send a test message."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "Copy it from the Azure Bot or Teams app registration."+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "Client secret",- "placeholder": "••••••",- "help": "Create a client secret for the Microsoft app."+ "placeholder": "••••••"},"tenantId": {"label": "Tenant ID",@@ -33,6 +22,52 @@"allowFrom": {"label": "Allowed users","placeholder": "Teams user IDs, comma separated"+ },+ "host": {+ "label": "Listen host"+ },+ "port": {+ "label": "Listen port"+ },+ "replyInThread": {+ "label": "Reply in thread",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "mentionOnlyResponse": {+ "label": "Mention-only reply"+ },+ "validateInboundAuth": {+ "label": "Validate incoming requests",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "refTtlDays": {+ "label": "Conversation lifetime"+ },+ "pruneWebChatRefs": {+ "label": "Remove Web Chat conversations",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "Remove non-personal conversations",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "refTouchIntervalS": {+ "label": "Conversation refresh interval"+ },+ "trustedServiceUrlHosts": {+ "label": "Trusted service hosts"}}}diff --git a/nanobot/channels/msteams/webui/locales/es.json b/nanobot/channels/msteams/webui/locales/es.jsonindex d7eadcabf..7468b1291 100644--- a/nanobot/channels/msteams/webui/locales/es.json+++ b/nanobot/channels/msteams/webui/locales/es.json@@ -1,26 +1,15 @@{- "description": "Usa nanobot desde chats de Microsoft Teams.",- "requirements": "Credenciales de la app bot de Azure y endpoint público de callback","setup": {"docsLabel": "Abrir guía de Teams","officialLabel": "Abrir portal de desarrolladores de Teams",- "tryIt": "Instala la app de Teams y envía un mensaje de prueba.",- "summary": "Teams recibe mensajes mediante la URL de callback de Bot Framework. En producción necesita un endpoint HTTPS accesible.",- "steps": [- "Crea un Azure Bot o una app de Teams y copia el App ID y el secreto de cliente.",- "Expón la ruta de callback por HTTPS y añádela como endpoint de mensajería.",- "Guarda y activa Teams; después instala la app y envía un mensaje de prueba."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "Cópialo del registro de Azure Bot o la app de Teams."+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "Secreto de cliente",- "placeholder": "••••••",- "help": "Crea un secreto de cliente para la app de Microsoft."+ "placeholder": "••••••"},"tenantId": {"label": "ID del tenant",@@ -33,6 +22,52 @@"allowFrom": {"label": "Usuarios permitidos","placeholder": "ID de usuario de Teams separados por comas"+ },+ "host": {+ "label": "Escuchar anfitrión"+ },+ "port": {+ "label": "Puerto de escucha"+ },+ "replyInThread": {+ "label": "Responder en el hilo",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "mentionOnlyResponse": {+ "label": "Respuesta de solo mención"+ },+ "validateInboundAuth": {+ "label": "Validar solicitudes entrantes",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "refTtlDays": {+ "label": "Duración de la conversación"+ },+ "pruneWebChatRefs": {+ "label": "Eliminar conversaciones de chat web",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "Eliminar conversaciones no personales",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "refTouchIntervalS": {+ "label": "Intervalo de actualización de la conversación"+ },+ "trustedServiceUrlHosts": {+ "label": "Anfitriones de servicios confiables"}}}diff --git a/nanobot/channels/msteams/webui/locales/fr.json b/nanobot/channels/msteams/webui/locales/fr.jsonindex 0b8756399..e8cbc21bd 100644--- a/nanobot/channels/msteams/webui/locales/fr.json+++ b/nanobot/channels/msteams/webui/locales/fr.json@@ -1,26 +1,15 @@{- "description": "Utilisez nanobot depuis les conversations Microsoft Teams.",- "requirements": "Identifiants de l’application bot Azure et endpoint de rappel public","setup": {"docsLabel": "Ouvrir le guide Teams","officialLabel": "Ouvrir le portail développeur Teams",- "tryIt": "Installez l’application Teams et envoyez un message test.",- "summary": "Teams reçoit les messages via l’URL de rappel Bot Framework. Un endpoint HTTPS accessible est nécessaire en production.",- "steps": [- "Créez un bot Azure ou une application Teams et copiez l’App ID et le secret client.",- "Exposez le chemin de rappel en HTTPS et définissez-le comme endpoint de messagerie.",- "Enregistrez et activez Teams, puis installez l’application et envoyez un message test."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "Copiez-le depuis l’inscription du bot Azure ou de l’application Teams."+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "Secret client",- "placeholder": "••••••",- "help": "Créez un secret client pour l’application Microsoft."+ "placeholder": "••••••"},"tenantId": {"label": "ID du locataire",@@ -33,6 +22,52 @@"allowFrom": {"label": "Utilisateurs autorisés","placeholder": "ID utilisateur Teams séparés par des virgules"+ },+ "host": {+ "label": "Écouter l'hôte"+ },+ "port": {+ "label": "Port d'écoute"+ },+ "replyInThread": {+ "label": "Répondre dans le fil de discussion",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "mentionOnlyResponse": {+ "label": "Réponse avec mention uniquement"+ },+ "validateInboundAuth": {+ "label": "Valider les demandes entrantes",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "refTtlDays": {+ "label": "Durée de vie des conversations"+ },+ "pruneWebChatRefs": {+ "label": "Supprimer les conversations de chat Web",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "Supprimer les conversations non personnelles",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "refTouchIntervalS": {+ "label": "Intervalle d'actualisation des conversations"+ },+ "trustedServiceUrlHosts": {+ "label": "Hôtes de services de confiance"}}}diff --git a/nanobot/channels/msteams/webui/locales/id.json b/nanobot/channels/msteams/webui/locales/id.jsonindex fb7e15bd2..d305d9e31 100644--- a/nanobot/channels/msteams/webui/locales/id.json+++ b/nanobot/channels/msteams/webui/locales/id.json@@ -1,26 +1,15 @@{- "description": "Gunakan nanobot dari chat Microsoft Teams.",- "requirements": "Kredensial aplikasi bot Azure dan endpoint callback publik","setup": {"docsLabel": "Buka panduan Teams","officialLabel": "Buka portal pengembang Teams",- "tryIt": "Pasang aplikasi Teams dan kirim pesan uji.",- "summary": "Teams menerima pesan melalui URL callback Bot Framework. Untuk penggunaan di lingkungan produksi, alamat HTTPS harus dapat diakses dari luar.",- "steps": [- "Buat Azure Bot atau aplikasi Teams dan salin App ID serta client secret.",- "Paparkan jalur callback melalui HTTPS dan jadikan endpoint pesan bot.",- "Simpan dan aktifkan Teams, lalu pasang aplikasi dan kirim pesan uji."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "Salin dari pendaftaran Azure Bot atau aplikasi Teams."+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "Client secret",- "placeholder": "••••••",- "help": "Buat client secret untuk aplikasi Microsoft."+ "placeholder": "••••••"},"tenantId": {"label": "Tenant ID",@@ -33,6 +22,52 @@"allowFrom": {"label": "Pengguna yang diizinkan","placeholder": "ID pengguna Teams, dipisahkan koma"+ },+ "host": {+ "label": "Dengarkan tuan rumah"+ },+ "port": {+ "label": "Dengarkan pelabuhan"+ },+ "replyInThread": {+ "label": "Balas di thread",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "mentionOnlyResponse": {+ "label": "Balasan yang hanya disebutkan saja"+ },+ "validateInboundAuth": {+ "label": "Validasi permintaan masuk",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "refTtlDays": {+ "label": "Percakapan seumur hidup"+ },+ "pruneWebChatRefs": {+ "label": "Hapus percakapan Obrolan Web",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "Hapus percakapan non-pribadi",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "refTouchIntervalS": {+ "label": "Interval penyegaran percakapan"+ },+ "trustedServiceUrlHosts": {+ "label": "Host layanan tepercaya"}}}diff --git a/nanobot/channels/msteams/webui/locales/ja.json b/nanobot/channels/msteams/webui/locales/ja.jsonindex 905e54372..1809cc356 100644--- a/nanobot/channels/msteams/webui/locales/ja.json+++ b/nanobot/channels/msteams/webui/locales/ja.json@@ -1,26 +1,15 @@{- "description": "Microsoft Teams のチャットから nanobot を利用します。",- "requirements": "Azure ボットアプリの認証情報と公開コールバックエンドポイント","setup": {"docsLabel": "Teams 設定ガイドを開く","officialLabel": "Teams 開発者ポータルを開く",- "tryIt": "Teams アプリをインストールし、テストメッセージを送信します。",- "summary": "Teams は Bot Framework のコールバック URL でメッセージを受信します。本番環境では到達可能な HTTPS エンドポイントが必要です。",- "steps": [- "Azure Bot または Teams アプリを作成し、App ID とクライアントシークレットをコピーします。",- "コールバックパスを HTTPS で公開し、ボットのメッセージングエンドポイントに設定します。",- "保存して Teams を有効にし、アプリをインストールしてテストメッセージを送信します。"- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "Azure Bot または Teams アプリ登録からコピーします。"+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "クライアントシークレット",- "placeholder": "••••••",- "help": "Microsoft アプリ用のクライアントシークレットを作成します。"+ "placeholder": "••••••"},"tenantId": {"label": "テナント ID",@@ -33,6 +22,52 @@"allowFrom": {"label": "許可するユーザー","placeholder": "Teams ユーザー ID(カンマ区切り)"+ },+ "host": {+ "label": "リッスンホスト"+ },+ "port": {+ "label": "リッスンポート"+ },+ "replyInThread": {+ "label": "スレッド内で返信する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "mentionOnlyResponse": {+ "label": "メンションのみの返信"+ },+ "validateInboundAuth": {+ "label": "受信リクエストを検証する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "refTtlDays": {+ "label": "会話の存続期間"+ },+ "pruneWebChatRefs": {+ "label": "Web チャットの会話を削除する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "個人的ではない会話を削除する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "refTouchIntervalS": {+ "label": "会話の更新間隔"+ },+ "trustedServiceUrlHosts": {+ "label": "信頼できるサービスホスト"}}}diff --git a/nanobot/channels/msteams/webui/locales/ko.json b/nanobot/channels/msteams/webui/locales/ko.jsonindex 739ad045a..b2c44abd5 100644--- a/nanobot/channels/msteams/webui/locales/ko.json+++ b/nanobot/channels/msteams/webui/locales/ko.json@@ -1,26 +1,15 @@{- "description": "Microsoft Teams 채팅에서 nanobot을 사용합니다.",- "requirements": "Azure 봇 앱 인증 정보 및 공개 콜백 엔드포인트","setup": {"docsLabel": "Teams 설정 가이드 열기","officialLabel": "Teams 개발자 포털 열기",- "tryIt": "Teams 앱을 설치하고 테스트 메시지를 보내세요.",- "summary": "Teams는 Bot Framework 콜백 URL로 메시지를 받습니다. 운영 환경에는 접근 가능한 HTTPS 엔드포인트가 필요합니다.",- "steps": [- "Azure Bot 또는 Teams 앱을 만들고 App ID와 클라이언트 암호을 복사하세요.",- "콜백 경로를 HTTPS로 공개하고 봇 메시징 엔드포인트로 설정하세요.",- "저장하고 Teams를 활성화한 다음 앱을 설치하고 테스트 메시지를 보내세요."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "Azure Bot 또는 Teams 앱 등록에서 복사하세요."+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "클라이언트 암호",- "placeholder": "••••••",- "help": "Microsoft 앱의 클라이언트 암호를 생성하세요."+ "placeholder": "••••••"},"tenantId": {"label": "테넌트 ID",@@ -33,6 +22,52 @@"allowFrom": {"label": "허용된 사용자","placeholder": "Teams 사용자 ID, 쉼표로 구분"+ },+ "host": {+ "label": "호스트 듣기"+ },+ "port": {+ "label": "청취 포트"+ },+ "replyInThread": {+ "label": "스레드로 답장하기",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "mentionOnlyResponse": {+ "label": "언급 전용 답변"+ },+ "validateInboundAuth": {+ "label": "들어오는 요청의 유효성을 검사합니다.",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "refTtlDays": {+ "label": "대화 수명"+ },+ "pruneWebChatRefs": {+ "label": "웹 채팅 대화 제거",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "개인 대화가 아닌 대화 삭제",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "refTouchIntervalS": {+ "label": "대화 새로 고침 간격"+ },+ "trustedServiceUrlHosts": {+ "label": "신뢰할 수 있는 서비스 호스트"}}}diff --git a/nanobot/channels/msteams/webui/locales/pt-BR.json b/nanobot/channels/msteams/webui/locales/pt-BR.jsonindex 1b7850a39..a26c6eb25 100644--- a/nanobot/channels/msteams/webui/locales/pt-BR.json+++ b/nanobot/channels/msteams/webui/locales/pt-BR.json@@ -1,26 +1,15 @@{- "description": "Use o nanobot em conversas do Microsoft Teams.",- "requirements": "Credenciais do app bot Azure e endpoint público de callback","setup": {"docsLabel": "Abrir guia do Teams","officialLabel": "Abrir portal de desenvolvedores do Teams",- "tryIt": "Instale o app do Teams e envie uma mensagem de teste.",- "summary": "O Teams recebe mensagens pela URL de callback do Bot Framework. Em produção, precisa de um endpoint HTTPS acessível.",- "steps": [- "Crie um Azure Bot ou app Teams e copie o App ID e o segredo do cliente.",- "Exponha o caminho de callback por HTTPS e defina-o como endpoint de mensagens.",- "Salve e ative o Teams; depois, instale o app e envie uma mensagem de teste."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "Copie do registro do Azure Bot ou do app Teams."+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "Segredo do cliente",- "placeholder": "••••••",- "help": "Crie um segredo do cliente para o app Microsoft."+ "placeholder": "••••••"},"tenantId": {"label": "ID do locatário",@@ -33,6 +22,52 @@"allowFrom": {"label": "Usuários permitidos","placeholder": "IDs de usuário do Teams separados por vírgulas"+ },+ "host": {+ "label": "Ouça o apresentador"+ },+ "port": {+ "label": "Porta de escuta"+ },+ "replyInThread": {+ "label": "Responder no tópico",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "mentionOnlyResponse": {+ "label": "Resposta apenas com menção"+ },+ "validateInboundAuth": {+ "label": "Validar solicitações recebidas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "refTtlDays": {+ "label": "Vida útil da conversa"+ },+ "pruneWebChatRefs": {+ "label": "Remover conversas do Web Chat",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "Remover conversas não pessoais",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "refTouchIntervalS": {+ "label": "Intervalo de atualização da conversa"+ },+ "trustedServiceUrlHosts": {+ "label": "Hosts de serviço confiáveis"}}}diff --git a/nanobot/channels/msteams/webui/locales/vi.json b/nanobot/channels/msteams/webui/locales/vi.jsonindex 5c3be71c7..29b938d63 100644--- a/nanobot/channels/msteams/webui/locales/vi.json+++ b/nanobot/channels/msteams/webui/locales/vi.json@@ -1,26 +1,15 @@{- "description": "Sử dụng nanobot từ các cuộc trò chuyện Microsoft Teams.",- "requirements": "Thông tin xác thực bot Azure và endpoint callback công khai","setup": {"docsLabel": "Mở hướng dẫn Teams","officialLabel": "Mở cổng nhà phát triển Teams",- "tryIt": "Cài ứng dụng Teams và gửi tin nhắn thử.",- "summary": "Teams nhận tin nhắn qua URL callback của Bot Framework. Khi triển khai chính thức, cần một địa chỉ HTTPS có thể truy cập từ bên ngoài.",- "steps": [- "Tạo Azure Bot hoặc ứng dụng Teams và sao chép App ID cùng client secret.",- "Công khai đường dẫn callback qua HTTPS và đặt làm endpoint nhắn tin của bot.",- "Lưu và bật Teams, sau đó cài ứng dụng và gửi tin nhắn thử."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "Sao chép từ đăng ký Azure Bot hoặc ứng dụng Teams."+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "Client secret",- "placeholder": "••••••",- "help": "Tạo client secret cho ứng dụng Microsoft."+ "placeholder": "••••••"},"tenantId": {"label": "Tenant ID",@@ -33,6 +22,52 @@"allowFrom": {"label": "Người dùng được phép","placeholder": "ID người dùng Teams, phân tách bằng dấu phẩy"+ },+ "host": {+ "label": "Nghe máy chủ"+ },+ "port": {+ "label": "Cổng nghe"+ },+ "replyInThread": {+ "label": "Trả lời trong chủ đề",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "mentionOnlyResponse": {+ "label": "Trả lời chỉ đề cập"+ },+ "validateInboundAuth": {+ "label": "Xác thực các yêu cầu đến",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "refTtlDays": {+ "label": "Cuộc trò chuyện trọn đời"+ },+ "pruneWebChatRefs": {+ "label": "Xóa cuộc hội thoại Trò chuyện trên web",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "Xóa các cuộc trò chuyện không mang tính cá nhân",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "refTouchIntervalS": {+ "label": "Khoảng thời gian làm mới cuộc hội thoại"+ },+ "trustedServiceUrlHosts": {+ "label": "Máy chủ dịch vụ đáng tin cậy"}}}diff --git a/nanobot/channels/msteams/webui/locales/zh-CN.json b/nanobot/channels/msteams/webui/locales/zh-CN.jsonindex 9b8f46ace..14df1de3b 100644--- a/nanobot/channels/msteams/webui/locales/zh-CN.json+++ b/nanobot/channels/msteams/webui/locales/zh-CN.json@@ -1,26 +1,15 @@{- "description": "在 Microsoft Teams 会话中使用 nanobot。",- "requirements": "Azure 机器人应用凭据和公网回调地址","setup": {"docsLabel": "打开 Teams 配置指南","officialLabel": "打开 Teams 开发者后台",- "tryIt": "安装 Teams 应用并发送一条测试消息。",- "summary": "Teams 通过 Bot Framework 回调地址接收消息;生产环境需要可访问的 HTTPS 端点。",- "steps": [- "创建 Azure Bot 或 Teams 应用,并复制 App ID 和客户端密钥。",- "通过 HTTPS 暴露回调路径,并将其设为机器人的消息端点。",- "保存并启用 Teams,然后安装应用并发送一条测试消息。"- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "从 Azure Bot 或 Teams 应用注册页面复制。"+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "客户端密钥",- "placeholder": "••••••",- "help": "为 Microsoft 应用创建客户端密钥。"+ "placeholder": "••••••"},"tenantId": {"label": "租户 ID",@@ -33,6 +22,52 @@"allowFrom": {"label": "允许的用户","placeholder": "Teams 用户 ID,用逗号分隔"+ },+ "host": {+ "label": "监听地址"+ },+ "port": {+ "label": "监听端口"+ },+ "replyInThread": {+ "label": "在话题中回复",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "mentionOnlyResponse": {+ "label": "仅被提及时的回复"+ },+ "validateInboundAuth": {+ "label": "验证入站请求",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "refTtlDays": {+ "label": "会话保留天数"+ },+ "pruneWebChatRefs": {+ "label": "清理 Web Chat 会话",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "清理非个人会话",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "refTouchIntervalS": {+ "label": "会话刷新间隔"+ },+ "trustedServiceUrlHosts": {+ "label": "可信服务主机"}}}diff --git a/nanobot/channels/msteams/webui/locales/zh-TW.json b/nanobot/channels/msteams/webui/locales/zh-TW.jsonindex 4f91f1f88..0a786e721 100644--- a/nanobot/channels/msteams/webui/locales/zh-TW.json+++ b/nanobot/channels/msteams/webui/locales/zh-TW.json@@ -1,26 +1,15 @@{- "description": "在 Microsoft Teams 對話中使用 nanobot。",- "requirements": "Azure 機器人應用程式憑證和公開回呼端點","setup": {"docsLabel": "開啟 Teams 設定指南","officialLabel": "開啟 Teams 開發者後台",- "tryIt": "安裝 Teams 應用程式並傳送一則測試訊息。",- "summary": "Teams 透過 Bot Framework 回呼網址接收訊息;正式環境需要可存取的 HTTPS 端點。",- "steps": [- "建立 Azure Bot 或 Teams 應用程式,並複製 App ID 和用戶端金鑰。",- "透過 HTTPS 公開回呼路徑,並將其設為機器人的訊息端點。",- "儲存並啟用 Teams,然後安裝應用程式並傳送一則測試訊息。"- ],"fields": {"appId": {"label": "App ID",- "placeholder": "Microsoft App ID",- "help": "從 Azure Bot 或 Teams 應用程式註冊頁面複製。"+ "placeholder": "Microsoft App ID"},"appPassword": {"label": "用戶端金鑰",- "placeholder": "••••••",- "help": "為 Microsoft 應用程式建立用戶端金鑰。"+ "placeholder": "••••••"},"tenantId": {"label": "租用戶 ID",@@ -33,6 +22,52 @@"allowFrom": {"label": "允許的使用者","placeholder": "Teams 使用者 ID,以逗號分隔"+ },+ "host": {+ "label": "監聽地址"+ },+ "port": {+ "label": "監聽埠"+ },+ "replyInThread": {+ "label": "在話題中回复",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "mentionOnlyResponse": {+ "label": "僅被提及時的回复"+ },+ "validateInboundAuth": {+ "label": "驗證入站請求",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "refTtlDays": {+ "label": "會話保留天數"+ },+ "pruneWebChatRefs": {+ "label": "清理 Web Chat 會話",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "pruneNonPersonalRefs": {+ "label": "清理非個人會話",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "refTouchIntervalS": {+ "label": "會話刷新間隔"+ },+ "trustedServiceUrlHosts": {+ "label": "可信任服務主機"}}}diff --git a/nanobot/channels/napcat/manifest.py b/nanobot/channels/napcat/manifest.pyindex c4923d42f..19f87e9cd 100644--- a/nanobot/channels/napcat/manifest.py+++ b/nanobot/channels/napcat/manifest.py@@ -10,6 +10,9 @@ SETUP_SPEC = ChannelSetupSpec("accessToken": field("secret"),"allowFrom": field("list"),"groupPolicy": field("enum", choices=DIRECT_GROUP_POLICIES, default="mention"),+ "groupPolicyOverrides": field("json", default={}),+ "welcomeNewMembers": field("bool", default=True),+ "maxImageBytes": field("int", default=20 * 1024 * 1024),},required=(required("wsUrl"),),official_url="https://napneko.github.io/",diff --git a/nanobot/channels/napcat/webui/index.ts b/nanobot/channels/napcat/webui/index.tsindex 11bfbc21a..22a16202e 100644--- a/nanobot/channels/napcat/webui/index.ts+++ b/nanobot/channels/napcat/webui/index.ts@@ -3,18 +3,18 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://napneko.github.io/assets/newnewlogo.png",displayName: "NapCat",initials: "NC",color: "#F97316",- logoUrl: "https://napneko.github.io/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("napcat"),fields: [- { key: "channels.napcat.wsUrl" },- { key: "channels.napcat.accessToken" },- { key: "channels.napcat.groupPolicy" },- { key: "channels.napcat.allowFrom" },+ { key: "channels.napcat.wsUrl", section: "connection" },+ { key: "channels.napcat.accessToken", section: "credentials" },+ { key: "channels.napcat.groupPolicy", section: "behavior" },+ { key: "channels.napcat.allowFrom", section: "access" },],},},diff --git a/nanobot/channels/napcat/webui/locales/en.json b/nanobot/channels/napcat/webui/locales/en.jsonindex 891ca8056..ab719ffae 100644--- a/nanobot/channels/napcat/webui/locales/en.json+++ b/nanobot/channels/napcat/webui/locales/en.json@@ -1,21 +1,11 @@{- "description": "Connect nanobot through a NapCat gateway.",- "requirements": "NapCat WebSocket endpoint, optional access token","setup": {"docsLabel": "Open NapCat setup","officialLabel": "Open NapCat docs",- "tryIt": "Send a QQ test message through NapCat.",- "summary": "NapCat connects nanobot to QQ through a local or remote OneBot WebSocket endpoint.",- "steps": [- "Start NapCat and enable a Forward WebSocket service.",- "Copy the WebSocket URL and optional access token into nanobot.",- "Save and enable NapCat, then send a QQ test message."- ],"fields": {"wsUrl": {"label": "WebSocket URL",- "placeholder": "ws://127.0.0.1:3001",- "help": "Use the Forward WebSocket URL from NapCat."+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "Access token",@@ -32,6 +22,19 @@"allowFrom": {"label": "Allowed users","placeholder": "QQ IDs, comma separated"+ },+ "groupPolicyOverrides": {+ "label": "Group behavior overrides (JSON)"+ },+ "welcomeNewMembers": {+ "label": "Welcome new members",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "maxImageBytes": {+ "label": "Maximum image size"}}}diff --git a/nanobot/channels/napcat/webui/locales/es.json b/nanobot/channels/napcat/webui/locales/es.jsonindex 81b524db2..e27277ab0 100644--- a/nanobot/channels/napcat/webui/locales/es.json+++ b/nanobot/channels/napcat/webui/locales/es.json@@ -1,21 +1,11 @@{- "description": "Conecta nanobot mediante una pasarela NapCat.",- "requirements": "Endpoint WebSocket de NapCat y token de acceso opcional","setup": {"docsLabel": "Abrir guía de NapCat","officialLabel": "Abrir documentación de NapCat",- "tryIt": "Envía un mensaje de prueba de QQ mediante NapCat.",- "summary": "NapCat conecta nanobot con QQ mediante un endpoint WebSocket OneBot local o remoto.",- "steps": [- "Inicia NapCat y activa un servicio Forward WebSocket.",- "Copia la URL WebSocket y el token opcional en nanobot.",- "Guarda y activa NapCat; después envía un mensaje de prueba de QQ."- ],"fields": {"wsUrl": {"label": "URL WebSocket",- "placeholder": "ws://127.0.0.1:3001",- "help": "Usa la URL Forward WebSocket de NapCat."+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "Token de acceso",@@ -32,6 +22,19 @@"allowFrom": {"label": "Usuarios permitidos","placeholder": "ID de QQ separados por comas"+ },+ "groupPolicyOverrides": {+ "label": "Anulaciones de comportamiento de grupo (JSON)"+ },+ "welcomeNewMembers": {+ "label": "Bienvenidos nuevos miembros",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "maxImageBytes": {+ "label": "Tamaño máximo de imagen"}}}diff --git a/nanobot/channels/napcat/webui/locales/fr.json b/nanobot/channels/napcat/webui/locales/fr.jsonindex 48cf18149..fff3055b1 100644--- a/nanobot/channels/napcat/webui/locales/fr.json+++ b/nanobot/channels/napcat/webui/locales/fr.json@@ -1,21 +1,11 @@{- "description": "Connectez nanobot via une passerelle NapCat.",- "requirements": "Endpoint WebSocket NapCat et jeton d’accès facultatif","setup": {"docsLabel": "Ouvrir le guide NapCat","officialLabel": "Ouvrir la documentation NapCat",- "tryIt": "Envoyez un message test QQ via NapCat.",- "summary": "NapCat relie nanobot à QQ via un endpoint WebSocket OneBot local ou distant.",- "steps": [- "Démarrez NapCat et activez un service Forward WebSocket.",- "Copiez l’URL WebSocket et le jeton facultatif dans nanobot.",- "Enregistrez et activez NapCat, puis envoyez un message test QQ."- ],"fields": {"wsUrl": {"label": "URL WebSocket",- "placeholder": "ws://127.0.0.1:3001",- "help": "Utilisez l’URL Forward WebSocket de NapCat."+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "Jeton d’accès",@@ -32,6 +22,19 @@"allowFrom": {"label": "Utilisateurs autorisés","placeholder": "ID QQ séparés par des virgules"+ },+ "groupPolicyOverrides": {+ "label": "Remplacements de comportement de groupe (JSON)"+ },+ "welcomeNewMembers": {+ "label": "Bienvenue aux nouveaux membres",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "maxImageBytes": {+ "label": "Taille maximale de l'image"}}}diff --git a/nanobot/channels/napcat/webui/locales/id.json b/nanobot/channels/napcat/webui/locales/id.jsonindex 94ab438b1..40fafb91b 100644--- a/nanobot/channels/napcat/webui/locales/id.json+++ b/nanobot/channels/napcat/webui/locales/id.json@@ -1,21 +1,11 @@{- "description": "Hubungkan nanobot melalui gateway NapCat.",- "requirements": "Endpoint WebSocket NapCat dan token akses opsional","setup": {"docsLabel": "Buka panduan NapCat","officialLabel": "Buka dokumentasi NapCat",- "tryIt": "Kirim pesan uji QQ melalui NapCat.",- "summary": "NapCat menghubungkan nanobot ke QQ melalui endpoint OneBot WebSocket lokal atau jarak jauh.",- "steps": [- "Mulai NapCat dan aktifkan layanan Forward WebSocket.",- "Salin URL WebSocket dan token opsional ke nanobot.",- "Simpan dan aktifkan NapCat, lalu kirim pesan uji QQ."- ],"fields": {"wsUrl": {"label": "URL WebSocket",- "placeholder": "ws://127.0.0.1:3001",- "help": "Gunakan URL Forward WebSocket dari NapCat."+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "Token akses",@@ -32,6 +22,19 @@"allowFrom": {"label": "Pengguna yang diizinkan","placeholder": "ID QQ, dipisahkan koma"+ },+ "groupPolicyOverrides": {+ "label": "Penggantian perilaku grup (JSON)"+ },+ "welcomeNewMembers": {+ "label": "Selamat datang anggota baru",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "maxImageBytes": {+ "label": "Ukuran gambar maksimum"}}}diff --git a/nanobot/channels/napcat/webui/locales/ja.json b/nanobot/channels/napcat/webui/locales/ja.jsonindex bf187ccfc..bb7b3c2ee 100644--- a/nanobot/channels/napcat/webui/locales/ja.json+++ b/nanobot/channels/napcat/webui/locales/ja.json@@ -1,21 +1,11 @@{- "description": "NapCat ゲートウェイ経由で nanobot を接続します。",- "requirements": "NapCat WebSocket エンドポイントと任意のアクセストークン","setup": {"docsLabel": "NapCat 設定ガイドを開く","officialLabel": "NapCat ドキュメントを開く",- "tryIt": "NapCat 経由で QQ のテストメッセージを送信します。",- "summary": "NapCat はローカルまたはリモートの OneBot WebSocket で nanobot を QQ に接続します。",- "steps": [- "NapCat を起動し、Forward WebSocket サービスを有効にします。",- "WebSocket URL を nanobot にコピーします。アクセストークンを設定している場合は、あわせて入力してください。",- "保存して NapCat を有効にし、QQ のテストメッセージを送信します。"- ],"fields": {"wsUrl": {"label": "WebSocket URL",- "placeholder": "ws://127.0.0.1:3001",- "help": "NapCat の Forward WebSocket URL を使います。"+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "アクセストークン",@@ -32,6 +22,19 @@"allowFrom": {"label": "許可するユーザー","placeholder": "QQ ID(カンマ区切り)"+ },+ "groupPolicyOverrides": {+ "label": "グループ動作のオーバーライド (JSON)"+ },+ "welcomeNewMembers": {+ "label": "新しいメンバーを歓迎します",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "maxImageBytes": {+ "label": "最大画像サイズ"}}}diff --git a/nanobot/channels/napcat/webui/locales/ko.json b/nanobot/channels/napcat/webui/locales/ko.jsonindex cc3849f42..68ae78cb3 100644--- a/nanobot/channels/napcat/webui/locales/ko.json+++ b/nanobot/channels/napcat/webui/locales/ko.json@@ -1,21 +1,11 @@{- "description": "NapCat 게이트웨이를 통해 nanobot을 연결합니다.",- "requirements": "NapCat WebSocket 엔드포인트 및 선택적 액세스 토큰","setup": {"docsLabel": "NapCat 설정 가이드 열기","officialLabel": "NapCat 문서 열기",- "tryIt": "NapCat을 통해 QQ 테스트 메시지를 보내세요.",- "summary": "NapCat은 로컬 또는 원격 OneBot WebSocket으로 nanobot을 QQ에 연결합니다.",- "steps": [- "NapCat을 시작하고 Forward WebSocket 서비스를 활성화하세요.",- "WebSocket URL을 nanobot에 복사하세요. 액세스 토큰을 설정했다면 함께 입력하세요.",- "저장하고 NapCat을 활성화한 다음 QQ 테스트 메시지를 보내세요."- ],"fields": {"wsUrl": {"label": "WebSocket URL",- "placeholder": "ws://127.0.0.1:3001",- "help": "NapCat의 Forward WebSocket URL을 사용하세요."+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "액세스 토큰",@@ -32,6 +22,19 @@"allowFrom": {"label": "허용된 사용자","placeholder": "QQ ID, 쉼표로 구분"+ },+ "groupPolicyOverrides": {+ "label": "그룹 동작 재정의(JSON)"+ },+ "welcomeNewMembers": {+ "label": "새로운 회원을 환영합니다",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "maxImageBytes": {+ "label": "최대 이미지 크기"}}}diff --git a/nanobot/channels/napcat/webui/locales/pt-BR.json b/nanobot/channels/napcat/webui/locales/pt-BR.jsonindex 99ecc278d..e0b61014c 100644--- a/nanobot/channels/napcat/webui/locales/pt-BR.json+++ b/nanobot/channels/napcat/webui/locales/pt-BR.json@@ -1,21 +1,11 @@{- "description": "Conecte o nanobot por um gateway NapCat.",- "requirements": "Endpoint WebSocket do NapCat e token de acesso opcional","setup": {"docsLabel": "Abrir guia do NapCat","officialLabel": "Abrir documentação do NapCat",- "tryIt": "Envie uma mensagem de teste do QQ pelo NapCat.",- "summary": "O NapCat conecta o nanobot ao QQ por um endpoint WebSocket OneBot local ou remoto.",- "steps": [- "Inicie o NapCat e ative um serviço Forward WebSocket.",- "Copie a URL WebSocket e o token opcional para o nanobot.",- "Salve e ative o NapCat; depois, envie uma mensagem de teste do QQ."- ],"fields": {"wsUrl": {"label": "URL WebSocket",- "placeholder": "ws://127.0.0.1:3001",- "help": "Use a URL Forward WebSocket do NapCat."+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "Token de acesso",@@ -32,6 +22,19 @@"allowFrom": {"label": "Usuários permitidos","placeholder": "IDs do QQ separados por vírgulas"+ },+ "groupPolicyOverrides": {+ "label": "Substituições de comportamento de grupo (JSON)"+ },+ "welcomeNewMembers": {+ "label": "Bem vindos novos membros",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "maxImageBytes": {+ "label": "Tamanho máximo da imagem"}}}diff --git a/nanobot/channels/napcat/webui/locales/vi.json b/nanobot/channels/napcat/webui/locales/vi.jsonindex e1a182925..3e2279724 100644--- a/nanobot/channels/napcat/webui/locales/vi.json+++ b/nanobot/channels/napcat/webui/locales/vi.json@@ -1,21 +1,11 @@{- "description": "Kết nối nanobot qua gateway NapCat.",- "requirements": "Endpoint WebSocket NapCat và token truy cập tùy chọn","setup": {"docsLabel": "Mở hướng dẫn NapCat","officialLabel": "Mở tài liệu NapCat",- "tryIt": "Gửi tin nhắn thử QQ qua NapCat.",- "summary": "NapCat kết nối nanobot với QQ qua endpoint OneBot WebSocket cục bộ hoặc từ xa.",- "steps": [- "Khởi động NapCat và bật dịch vụ Forward WebSocket.",- "Sao chép URL WebSocket và token tùy chọn vào nanobot.",- "Lưu và bật NapCat, sau đó gửi tin nhắn thử QQ."- ],"fields": {"wsUrl": {"label": "URL WebSocket",- "placeholder": "ws://127.0.0.1:3001",- "help": "Dùng URL Forward WebSocket từ NapCat."+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "Token truy cập",@@ -32,6 +22,19 @@"allowFrom": {"label": "Người dùng được phép","placeholder": "ID QQ, phân tách bằng dấu phẩy"+ },+ "groupPolicyOverrides": {+ "label": "Ghi đè hành vi nhóm (JSON)"+ },+ "welcomeNewMembers": {+ "label": "Chào mừng thành viên mới",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "maxImageBytes": {+ "label": "Kích thước hình ảnh tối đa"}}}diff --git a/nanobot/channels/napcat/webui/locales/zh-CN.json b/nanobot/channels/napcat/webui/locales/zh-CN.jsonindex f9c3f7da0..dd50823e4 100644--- a/nanobot/channels/napcat/webui/locales/zh-CN.json+++ b/nanobot/channels/napcat/webui/locales/zh-CN.json@@ -1,21 +1,11 @@{- "description": "通过 NapCat 网关连接 nanobot。",- "requirements": "NapCat WebSocket 地址和可选访问令牌","setup": {"docsLabel": "打开 NapCat 配置指南","officialLabel": "打开 NapCat 文档",- "tryIt": "通过 NapCat 发送一条 QQ 测试消息。",- "summary": "NapCat 通过本地或远程 OneBot WebSocket 地址将 nanobot 连接到 QQ。",- "steps": [- "启动 NapCat 并启用正向 WebSocket 服务。",- "将 WebSocket 地址和可选访问令牌复制到 nanobot。",- "保存并启用 NapCat,然后发送一条 QQ 测试消息。"- ],"fields": {"wsUrl": {"label": "WebSocket 地址",- "placeholder": "ws://127.0.0.1:3001",- "help": "使用 NapCat 的正向 WebSocket 地址。"+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "访问令牌",@@ -32,6 +22,19 @@"allowFrom": {"label": "允许的用户","placeholder": "QQ ID,用逗号分隔"+ },+ "groupPolicyOverrides": {+ "label": "群组行为覆盖(JSON)"+ },+ "welcomeNewMembers": {+ "label": "欢迎新成员",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "maxImageBytes": {+ "label": "图片大小上限"}}}diff --git a/nanobot/channels/napcat/webui/locales/zh-TW.json b/nanobot/channels/napcat/webui/locales/zh-TW.jsonindex b44ab07fb..0433b580d 100644--- a/nanobot/channels/napcat/webui/locales/zh-TW.json+++ b/nanobot/channels/napcat/webui/locales/zh-TW.json@@ -1,21 +1,11 @@{- "description": "透過 NapCat 閘道連接 nanobot。",- "requirements": "NapCat WebSocket 網址和選填存取權杖","setup": {"docsLabel": "開啟 NapCat 設定指南","officialLabel": "開啟 NapCat 文件",- "tryIt": "透過 NapCat 傳送一則 QQ 測試訊息。",- "summary": "NapCat 透過本機或遠端 OneBot WebSocket 網址將 nanobot 連接到 QQ。",- "steps": [- "啟動 NapCat 並啟用正向 WebSocket 服務。",- "將 WebSocket 網址和選填存取權杖複製到 nanobot。",- "儲存並啟用 NapCat,然後傳送一則 QQ 測試訊息。"- ],"fields": {"wsUrl": {"label": "WebSocket 網址",- "placeholder": "ws://127.0.0.1:3001",- "help": "使用 NapCat 的正向 WebSocket 網址。"+ "placeholder": "ws://127.0.0.1:3001"},"accessToken": {"label": "存取權杖",@@ -32,6 +22,19 @@"allowFrom": {"label": "允許的使用者","placeholder": "QQ ID,以逗號分隔"+ },+ "groupPolicyOverrides": {+ "label": "群组行为覆盖(JSON)"+ },+ "welcomeNewMembers": {+ "label": "歡迎新成員",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "maxImageBytes": {+ "label": "圖片大小上限"}}}diff --git a/nanobot/channels/qq/manifest.py b/nanobot/channels/qq/manifest.pyindex f5b053475..a3e6cf093 100644--- a/nanobot/channels/qq/manifest.py+++ b/nanobot/channels/qq/manifest.py@@ -10,6 +10,10 @@ SETUP_SPEC = ChannelSetupSpec("secret": field("secret"),"allowFrom": field("list"),"msgFormat": field("enum", choices={"plain", "markdown"}, default="plain"),+ "ackMessage": field(default="⏳ Processing..."),+ "mediaDir": field(),+ "downloadChunkSize": field("int", default=1024 * 256),+ "downloadMaxBytes": field("int", default=1024 * 1024 * 200),},required=required_fields("appId", "secret"),official_url="https://q.qq.com/",diff --git a/nanobot/channels/qq/webui/index.ts b/nanobot/channels/qq/webui/index.tsindex 8221659c2..0ddf9a6c7 100644--- a/nanobot/channels/qq/webui/index.ts+++ b/nanobot/channels/qq/webui/index.ts@@ -3,18 +3,18 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://im.qq.com/favicon.ico",displayName: "QQ",initials: "QQ",color: "#12B7F5",- logoUrl: "https://im.qq.com/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("qq"),fields: [- { key: "channels.qq.appId" },- { key: "channels.qq.secret" },- { key: "channels.qq.allowFrom" },- { key: "channels.qq.msgFormat" },+ { key: "channels.qq.appId", section: "credentials" },+ { key: "channels.qq.secret", section: "credentials" },+ { key: "channels.qq.allowFrom", section: "access" },+ { key: "channels.qq.msgFormat", section: "behavior" },],},},diff --git a/nanobot/channels/qq/webui/locales/en.json b/nanobot/channels/qq/webui/locales/en.jsonindex 04310efd3..cb426f104 100644--- a/nanobot/channels/qq/webui/locales/en.json+++ b/nanobot/channels/qq/webui/locales/en.json@@ -1,26 +1,15 @@{- "description": "Use nanobot from QQ chats.",- "requirements": "QQ bot credentials and gateway","setup": {"docsLabel": "Open QQ setup","officialLabel": "Open QQ bot console",- "tryIt": "Send a direct or group test message from QQ.",- "summary": "QQ uses official bot credentials and a persistent WebSocket connection.",- "steps": [- "Create a bot in QQ Open Platform and copy its App ID and Secret.",- "Choose the message format and optional sender allowlist.",- "Save and enable QQ, then send a direct or group test message."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "QQ bot app ID",- "help": "Copy it from QQ Open Platform."+ "placeholder": "QQ bot app ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Save this before leaving the QQ credentials page."+ "placeholder": "••••••"},"allowFrom": {"label": "Allowed users",@@ -32,6 +21,18 @@"plain": "Plain text","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "Acknowledgement message"+ },+ "mediaDir": {+ "label": "Media directory"+ },+ "downloadChunkSize": {+ "label": "Download chunk size"+ },+ "downloadMaxBytes": {+ "label": "Maximum download size"}}}diff --git a/nanobot/channels/qq/webui/locales/es.json b/nanobot/channels/qq/webui/locales/es.jsonindex 1c851c629..0d2f1d528 100644--- a/nanobot/channels/qq/webui/locales/es.json+++ b/nanobot/channels/qq/webui/locales/es.json@@ -1,26 +1,15 @@{- "description": "Usa nanobot desde chats de QQ.",- "requirements": "Credenciales del bot de QQ y pasarela","setup": {"docsLabel": "Abrir guía de QQ","officialLabel": "Abrir consola del bot de QQ",- "tryIt": "Envía un mensaje de prueba directo o grupal desde QQ.",- "summary": "QQ usa las credenciales oficiales del bot y una conexión WebSocket persistente.",- "steps": [- "Crea un bot en QQ Open Platform y copia su App ID y Secret.",- "Elige el formato de mensajes y la lista opcional de remitentes.",- "Guarda y activa QQ; después envía un mensaje de prueba directo o grupal."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "App ID del bot de QQ",- "help": "Cópialo de QQ Open Platform."+ "placeholder": "App ID del bot de QQ"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Guárdalo antes de salir de la página de credenciales de QQ."+ "placeholder": "••••••"},"allowFrom": {"label": "Usuarios permitidos",@@ -32,6 +21,18 @@"plain": "Texto sin formato","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "Mensaje de reconocimiento"+ },+ "mediaDir": {+ "label": "Directorio de medios"+ },+ "downloadChunkSize": {+ "label": "Descargar tamaño de fragmento"+ },+ "downloadMaxBytes": {+ "label": "Tamaño máximo de descarga"}}}diff --git a/nanobot/channels/qq/webui/locales/fr.json b/nanobot/channels/qq/webui/locales/fr.jsonindex 79256cb3a..bf9d51b36 100644--- a/nanobot/channels/qq/webui/locales/fr.json+++ b/nanobot/channels/qq/webui/locales/fr.json@@ -1,26 +1,15 @@{- "description": "Utilisez nanobot depuis les conversations QQ.",- "requirements": "Identifiants du bot QQ et passerelle","setup": {"docsLabel": "Ouvrir le guide QQ","officialLabel": "Ouvrir la console du bot QQ",- "tryIt": "Envoyez un message test privé ou de groupe depuis QQ.",- "summary": "QQ utilise les identifiants officiels du bot et une connexion WebSocket persistante.",- "steps": [- "Créez un bot sur QQ Open Platform et copiez son App ID et son Secret.",- "Choisissez le format des messages et la liste d’expéditeurs facultative.",- "Enregistrez et activez QQ, puis envoyez un message test privé ou de groupe."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "App ID du bot QQ",- "help": "Copiez-le depuis QQ Open Platform."+ "placeholder": "App ID du bot QQ"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Enregistrez-le avant de quitter la page des identifiants QQ."+ "placeholder": "••••••"},"allowFrom": {"label": "Utilisateurs autorisés",@@ -32,6 +21,18 @@"plain": "Texte brut","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "Message d'accusé de réception"+ },+ "mediaDir": {+ "label": "Répertoire des médias"+ },+ "downloadChunkSize": {+ "label": "Taille du morceau de téléchargement"+ },+ "downloadMaxBytes": {+ "label": "Taille maximale de téléchargement"}}}diff --git a/nanobot/channels/qq/webui/locales/id.json b/nanobot/channels/qq/webui/locales/id.jsonindex 0d8552ebd..0641dc835 100644--- a/nanobot/channels/qq/webui/locales/id.json+++ b/nanobot/channels/qq/webui/locales/id.json@@ -1,26 +1,15 @@{- "description": "Gunakan nanobot dari chat QQ.",- "requirements": "Kredensial bot QQ dan gateway","setup": {"docsLabel": "Buka panduan QQ","officialLabel": "Buka konsol bot QQ",- "tryIt": "Kirim pesan uji langsung atau grup dari QQ.",- "summary": "QQ menggunakan kredensial bot resmi dan koneksi WebSocket persisten.",- "steps": [- "Buat bot di QQ Open Platform dan salin App ID serta Secret.",- "Pilih format pesan dan daftar pengirim opsional.",- "Simpan dan aktifkan QQ, lalu kirim pesan uji langsung atau grup."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "App ID bot QQ",- "help": "Salin dari QQ Open Platform."+ "placeholder": "App ID bot QQ"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Simpan sebelum meninggalkan halaman kredensial QQ."+ "placeholder": "••••••"},"allowFrom": {"label": "Pengguna yang diizinkan",@@ -32,6 +21,18 @@"plain": "Teks biasa","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "Pesan pengakuan"+ },+ "mediaDir": {+ "label": "Direktori media"+ },+ "downloadChunkSize": {+ "label": "Unduh ukuran potongan"+ },+ "downloadMaxBytes": {+ "label": "Ukuran unduhan maksimum"}}}diff --git a/nanobot/channels/qq/webui/locales/ja.json b/nanobot/channels/qq/webui/locales/ja.jsonindex 3bdb587cf..2efeba43b 100644--- a/nanobot/channels/qq/webui/locales/ja.json+++ b/nanobot/channels/qq/webui/locales/ja.json@@ -1,26 +1,15 @@{- "description": "QQ チャットから nanobot を利用します。",- "requirements": "QQ ボットの認証情報とゲートウェイ","setup": {"docsLabel": "QQ 設定ガイドを開く","officialLabel": "QQ ボットコンソールを開く",- "tryIt": "QQ から個人またはグループのテストメッセージを送信します。",- "summary": "QQ は公式ボット認証情報と常時接続の WebSocket を使用します。",- "steps": [- "QQ Open Platform でボットを作成し、App ID と Secret をコピーします。",- "メッセージ形式と任意の送信者許可リストを選びます。",- "保存して QQ を有効にし、個人またはグループのテストメッセージを送信します。"- ],"fields": {"appId": {"label": "App ID",- "placeholder": "QQ ボット App ID",- "help": "QQ Open Platform からコピーします。"+ "placeholder": "QQ ボット App ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "QQ の認証情報ページを離れる前に保存してください。"+ "placeholder": "••••••"},"allowFrom": {"label": "許可するユーザー",@@ -32,6 +21,18 @@"plain": "プレーンテキスト","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "確認メッセージ"+ },+ "mediaDir": {+ "label": "メディアディレクトリ"+ },+ "downloadChunkSize": {+ "label": "ダウンロードチャンクサイズ"+ },+ "downloadMaxBytes": {+ "label": "最大ダウンロードサイズ"}}}diff --git a/nanobot/channels/qq/webui/locales/ko.json b/nanobot/channels/qq/webui/locales/ko.jsonindex ff84f890a..228f604d8 100644--- a/nanobot/channels/qq/webui/locales/ko.json+++ b/nanobot/channels/qq/webui/locales/ko.json@@ -1,26 +1,15 @@{- "description": "QQ 채팅에서 nanobot을 사용합니다.",- "requirements": "QQ 봇 인증 정보 및 게이트웨이","setup": {"docsLabel": "QQ 설정 가이드 열기","officialLabel": "QQ 봇 콘솔 열기",- "tryIt": "QQ에서 개인 또는 그룹 테스트 메시지를 보내세요.",- "summary": "QQ는 공식 봇 인증 정보과 지속적인 WebSocket 연결을 사용합니다.",- "steps": [- "QQ Open Platform에서 봇을 만들고 App ID와 Secret을 복사하세요.",- "메시지 형식과 선택적 발신자 허용 목록을 고르세요.",- "저장하고 QQ를 활성화한 다음 개인 또는 그룹 테스트 메시지를 보내세요."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "QQ 봇 App ID",- "help": "QQ Open Platform에서 복사하세요."+ "placeholder": "QQ 봇 App ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "QQ 인증 정보 페이지를 떠나기 전에 저장하세요."+ "placeholder": "••••••"},"allowFrom": {"label": "허용된 사용자",@@ -32,6 +21,18 @@"plain": "일반 텍스트","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "확인 메시지"+ },+ "mediaDir": {+ "label": "미디어 디렉토리"+ },+ "downloadChunkSize": {+ "label": "청크 크기 다운로드"+ },+ "downloadMaxBytes": {+ "label": "최대 다운로드 크기"}}}diff --git a/nanobot/channels/qq/webui/locales/pt-BR.json b/nanobot/channels/qq/webui/locales/pt-BR.jsonindex 026509f56..442a330c8 100644--- a/nanobot/channels/qq/webui/locales/pt-BR.json+++ b/nanobot/channels/qq/webui/locales/pt-BR.json@@ -1,26 +1,15 @@{- "description": "Use o nanobot em conversas do QQ.",- "requirements": "Credenciais do bot QQ e gateway","setup": {"docsLabel": "Abrir guia do QQ","officialLabel": "Abrir console do bot QQ",- "tryIt": "Envie uma mensagem de teste direta ou em grupo pelo QQ.",- "summary": "O QQ usa credenciais oficiais do bot e uma conexão WebSocket persistente.",- "steps": [- "Crie um bot no QQ Open Platform e copie o App ID e o Secret.",- "Escolha o formato das mensagens e a lista opcional de remetentes.",- "Salve e ative o QQ; depois, envie uma mensagem de teste direta ou em grupo."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "App ID do bot QQ",- "help": "Copie do QQ Open Platform."+ "placeholder": "App ID do bot QQ"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Salve antes de sair da página de credenciais do QQ."+ "placeholder": "••••••"},"allowFrom": {"label": "Usuários permitidos",@@ -32,6 +21,18 @@"plain": "Texto simples","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "Mensagem de confirmação"+ },+ "mediaDir": {+ "label": "Diretório de mídia"+ },+ "downloadChunkSize": {+ "label": "Baixar tamanho do pedaço"+ },+ "downloadMaxBytes": {+ "label": "Tamanho máximo de download"}}}diff --git a/nanobot/channels/qq/webui/locales/vi.json b/nanobot/channels/qq/webui/locales/vi.jsonindex 5567666e7..18e84e154 100644--- a/nanobot/channels/qq/webui/locales/vi.json+++ b/nanobot/channels/qq/webui/locales/vi.json@@ -1,26 +1,15 @@{- "description": "Sử dụng nanobot từ các cuộc trò chuyện QQ.",- "requirements": "Thông tin xác thực bot QQ và gateway","setup": {"docsLabel": "Mở hướng dẫn QQ","officialLabel": "Mở bảng điều khiển bot QQ",- "tryIt": "Gửi tin nhắn thử riêng hoặc nhóm từ QQ.",- "summary": "QQ dùng thông tin xác thực bot chính thức và kết nối WebSocket lâu dài.",- "steps": [- "Tạo bot trên QQ Open Platform và sao chép App ID cùng Secret.",- "Chọn định dạng tin nhắn và danh sách người gửi tùy chọn.",- "Lưu và bật QQ, sau đó gửi tin nhắn thử riêng hoặc nhóm."- ],"fields": {"appId": {"label": "App ID",- "placeholder": "App ID bot QQ",- "help": "Sao chép từ QQ Open Platform."+ "placeholder": "App ID bot QQ"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Lưu trước khi rời trang thông tin xác thực QQ."+ "placeholder": "••••••"},"allowFrom": {"label": "Người dùng được phép",@@ -32,6 +21,18 @@"plain": "Văn bản thuần","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "Thông báo xác nhận"+ },+ "mediaDir": {+ "label": "Thư mục phương tiện"+ },+ "downloadChunkSize": {+ "label": "Kích thước khối tải xuống"+ },+ "downloadMaxBytes": {+ "label": "Kích thước tải xuống tối đa"}}}diff --git a/nanobot/channels/qq/webui/locales/zh-CN.json b/nanobot/channels/qq/webui/locales/zh-CN.jsonindex 3c065ade5..a1edc5f37 100644--- a/nanobot/channels/qq/webui/locales/zh-CN.json+++ b/nanobot/channels/qq/webui/locales/zh-CN.json@@ -1,26 +1,15 @@{- "description": "在 QQ 会话中使用 nanobot。",- "requirements": "QQ 机器人凭据和网关","setup": {"docsLabel": "打开 QQ 配置指南","officialLabel": "打开 QQ 机器人后台",- "tryIt": "从 QQ 发送一条私聊或群聊测试消息。",- "summary": "QQ 使用官方机器人凭据,通过 WebSocket 长连接收发消息。",- "steps": [- "在 QQ 开放平台创建机器人并复制 App ID 和 Secret。",- "选择消息格式和可选的发送者白名单。",- "保存并启用 QQ,然后发送一条私聊或群聊测试消息。"- ],"fields": {"appId": {"label": "App ID",- "placeholder": "QQ 机器人 App ID",- "help": "从 QQ 开放平台复制。"+ "placeholder": "QQ 机器人 App ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "离开 QQ 凭据页面前请妥善保存。"+ "placeholder": "••••••"},"allowFrom": {"label": "允许的用户",@@ -32,6 +21,18 @@"plain": "纯文本","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "处理中提示"+ },+ "mediaDir": {+ "label": "媒体目录"+ },+ "downloadChunkSize": {+ "label": "下载分块大小"+ },+ "downloadMaxBytes": {+ "label": "下载大小上限"}}}diff --git a/nanobot/channels/qq/webui/locales/zh-TW.json b/nanobot/channels/qq/webui/locales/zh-TW.jsonindex b6932f020..c3f8a698a 100644--- a/nanobot/channels/qq/webui/locales/zh-TW.json+++ b/nanobot/channels/qq/webui/locales/zh-TW.json@@ -1,26 +1,15 @@{- "description": "在 QQ 對話中使用 nanobot。",- "requirements": "QQ 機器人憑證和閘道","setup": {"docsLabel": "開啟 QQ 設定指南","officialLabel": "開啟 QQ 機器人後台",- "tryIt": "從 QQ 傳送一則私聊或群聊測試訊息。",- "summary": "QQ 使用官方機器人憑證和 WebSocket 長連線。",- "steps": [- "在 QQ 開放平台建立機器人並複製 App ID 和 Secret。",- "選擇訊息格式和選填的傳送者允許清單。",- "儲存並啟用 QQ,然後傳送一則私聊或群聊測試訊息。"- ],"fields": {"appId": {"label": "App ID",- "placeholder": "QQ 機器人 App ID",- "help": "從 QQ 開放平台複製。"+ "placeholder": "QQ 機器人 App ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "離開 QQ 憑證頁面前請妥善儲存。"+ "placeholder": "••••••"},"allowFrom": {"label": "允許的使用者",@@ -32,6 +21,18 @@"plain": "純文字","markdown": "Markdown"}+ },+ "ackMessage": {+ "label": "處理中提示"+ },+ "mediaDir": {+ "label": "媒體目錄"+ },+ "downloadChunkSize": {+ "label": "下載分塊大小"+ },+ "downloadMaxBytes": {+ "label": "下載大小上限"}}}diff --git a/nanobot/channels/signal/manifest.py b/nanobot/channels/signal/manifest.pyindex 3beddfd2f..ff41af082 100644--- a/nanobot/channels/signal/manifest.py+++ b/nanobot/channels/signal/manifest.py@@ -11,6 +11,13 @@ SETUP_SPEC = ChannelSetupSpec("daemonPort": field("int", default=8080),"dm.allowFrom": field("list"),"group.allowFrom": field("list"),+ "groupMessageBufferSize": field("int", default=20),+ "attachmentsDir": field(),+ "dm.enabled": field("bool", default=True),+ "dm.policy": field("enum", choices={"open", "allowlist"}, default="allowlist"),+ "group.enabled": field("bool", default=False),+ "group.policy": field("enum", choices={"open", "allowlist"}, default="allowlist"),+ "group.requireMention": field("bool", default=True),},required=(required("phoneNumber"),),official_url="https://github.com/bbernhard/signal-cli-rest-api",diff --git a/nanobot/channels/signal/runtime.py b/nanobot/channels/signal/runtime.pyindex 18bebc6f3..1235ce5fe 100644--- a/nanobot/channels/signal/runtime.py+++ b/nanobot/channels/signal/runtime.py@@ -301,7 +301,7 @@ def _partition_styles(class SignalDMConfig(Base):"""Signal DM policy configuration."""- enabled: bool = False+ enabled: bool = Truepolicy: str = "allowlist" # "open" or "allowlist"allow_from: list[str] = Field(default_factory=list) # Allowed phone numbers/UUIDsdiff --git a/nanobot/channels/signal/tests/test_signal_channel.py b/nanobot/channels/signal/tests/test_signal_channel.pyindex ff9ddcacf..58b59dcff 100644--- a/nanobot/channels/signal/tests/test_signal_channel.py+++ b/nanobot/channels/signal/tests/test_signal_channel.py@@ -1508,6 +1508,15 @@ async def test_handle_notification_no_source_skipped() -> None:# ---------------------------------------------------------------------------+def test_default_config_enables_private_dms_with_pairing() -> None:+ config = SignalConfig(phone_number="+10000000000")++ assert config.dm.enabled is True+ assert config.dm.policy == "allowlist"+ assert config.dm.allow_from == []+ assert config.group.enabled is False++def test_config_allow_from_aggregates_dm_and_group() -> None:config = SignalConfig(enabled=True,diff --git a/nanobot/channels/signal/webui/index.ts b/nanobot/channels/signal/webui/index.tsindex 76c9a28bd..26aeea231 100644--- a/nanobot/channels/signal/webui/index.ts+++ b/nanobot/channels/signal/webui/index.ts@@ -3,19 +3,19 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://signal.org/favicon.ico",displayName: "Signal",initials: "SG",color: "#3A76F0",- logoUrl: "https://signal.org/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("signal"),fields: [- { key: "channels.signal.phoneNumber" },- { key: "channels.signal.daemonHost" },- { key: "channels.signal.daemonPort" },- { key: "channels.signal.dm.allowFrom" },- { key: "channels.signal.group.allowFrom" },+ { key: "channels.signal.phoneNumber", section: "account" },+ { key: "channels.signal.daemonHost", section: "connection" },+ { key: "channels.signal.daemonPort", section: "connection" },+ { key: "channels.signal.dm.allowFrom", section: "access" },+ { key: "channels.signal.group.allowFrom", section: "access" },],},},diff --git a/nanobot/channels/signal/webui/locales/en.json b/nanobot/channels/signal/webui/locales/en.jsonindex 25a8336e1..d088bd483 100644--- a/nanobot/channels/signal/webui/locales/en.json+++ b/nanobot/channels/signal/webui/locales/en.json@@ -1,21 +1,11 @@{- "description": "Use nanobot from Signal messages.",- "requirements": "signal-cli HTTP daemon, phone number, allowlist","setup": {"docsLabel": "Open Signal setup","officialLabel": "Open signal-cli guide",- "tryIt": "Send a Signal DM to the linked phone number.",- "summary": "Signal connects through a signal-cli HTTP daemon that is already linked to a Signal phone number.",- "steps": [- "Install signal-cli-rest-api and link or register a Signal number.",- "Enter the daemon host, port, and linked phone number.",- "Save and enable Signal, then send a direct test message."- ],"fields": {"phoneNumber": {"label": "Phone number",- "placeholder": "+1234567890",- "help": "Use the Signal number registered with signal-cli."+ "placeholder": "+1234567890"},"daemonHost": {"label": "Daemon host",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "Allowed groups","placeholder": "Group IDs"+ },+ "groupMessageBufferSize": {+ "label": "Group context messages"+ },+ "attachmentsDir": {+ "label": "Attachment directory"+ },+ "dm_enabled": {+ "label": "Enable direct messages",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "dm_policy": {+ "label": "Direct message access",+ "choices": {+ "allowlist": "Allowlist",+ "open": "Open"+ }+ },+ "group_enabled": {+ "label": "Enable groups",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "group_policy": {+ "label": "Group access",+ "choices": {+ "allowlist": "Allowlist",+ "open": "Open"+ }+ },+ "group_requireMention": {+ "label": "Require mention in groups",+ "choices": {+ "true": "On",+ "false": "Off"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/es.json b/nanobot/channels/signal/webui/locales/es.jsonindex 524bb8425..c3fe026e2 100644--- a/nanobot/channels/signal/webui/locales/es.json+++ b/nanobot/channels/signal/webui/locales/es.json@@ -1,21 +1,11 @@{- "description": "Usa nanobot desde mensajes de Signal.",- "requirements": "Daemon HTTP signal-cli, número de teléfono y lista de permitidos","setup": {"docsLabel": "Abrir guía de Signal","officialLabel": "Abrir guía de signal-cli",- "tryIt": "Envía un DM de Signal al número vinculado.",- "summary": "Signal se conecta mediante un daemon HTTP signal-cli ya vinculado a un número de Signal.",- "steps": [- "Instala signal-cli-rest-api y vincula o registra un número de Signal.",- "Introduce el host, puerto y número vinculado.",- "Guarda y activa Signal; después envía un mensaje directo de prueba."- ],"fields": {"phoneNumber": {"label": "Número de teléfono",- "placeholder": "+1234567890",- "help": "Usa el número de Signal registrado con signal-cli."+ "placeholder": "+1234567890"},"daemonHost": {"label": "Host del daemon",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "Grupos permitidos","placeholder": "ID de grupo"+ },+ "groupMessageBufferSize": {+ "label": "Mensajes de contexto grupal"+ },+ "attachmentsDir": {+ "label": "Directorio de archivos adjuntos"+ },+ "dm_enabled": {+ "label": "Habilitar mensajes directos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "dm_policy": {+ "label": "Acceso a mensajes directos",+ "choices": {+ "allowlist": "Lista de permitidos",+ "open": "Abierto"+ }+ },+ "group_enabled": {+ "label": "Habilitar grupos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "group_policy": {+ "label": "Acceso grupal",+ "choices": {+ "allowlist": "Lista de permitidos",+ "open": "Abierto"+ }+ },+ "group_requireMention": {+ "label": "Requerir mención en grupos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/fr.json b/nanobot/channels/signal/webui/locales/fr.jsonindex 755c8c80d..931204ef3 100644--- a/nanobot/channels/signal/webui/locales/fr.json+++ b/nanobot/channels/signal/webui/locales/fr.json@@ -1,21 +1,11 @@{- "description": "Utilisez nanobot depuis les messages Signal.",- "requirements": "Service HTTP signal-cli, numéro de téléphone et liste d’autorisation","setup": {"docsLabel": "Ouvrir le guide Signal","officialLabel": "Ouvrir le guide signal-cli",- "tryIt": "Envoyez un message privé Signal au numéro associé.",- "summary": "Signal se connecte via un service HTTP signal-cli déjà associé à un numéro Signal.",- "steps": [- "Installez signal-cli-rest-api et associez ou enregistrez un numéro Signal.",- "Saisissez l’hôte, le port et le numéro associé.",- "Enregistrez et activez Signal, puis envoyez un message privé test."- ],"fields": {"phoneNumber": {"label": "Numéro de téléphone",- "placeholder": "+1234567890",- "help": "Utilisez le numéro Signal enregistré avec signal-cli."+ "placeholder": "+1234567890"},"daemonHost": {"label": "Hôte du service",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "Groupes autorisés","placeholder": "ID de groupe"+ },+ "groupMessageBufferSize": {+ "label": "Messages contextuels de groupe"+ },+ "attachmentsDir": {+ "label": "Répertoire des pièces jointes"+ },+ "dm_enabled": {+ "label": "Activer les messages directs",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "dm_policy": {+ "label": "Accès aux messages directs",+ "choices": {+ "allowlist": "Liste verte",+ "open": "Ouvert"+ }+ },+ "group_enabled": {+ "label": "Activer les groupes",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "group_policy": {+ "label": "Accès groupe",+ "choices": {+ "allowlist": "Liste verte",+ "open": "Ouvert"+ }+ },+ "group_requireMention": {+ "label": "Exiger une mention dans les groupes",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/id.json b/nanobot/channels/signal/webui/locales/id.jsonindex 589d27c87..936986fca 100644--- a/nanobot/channels/signal/webui/locales/id.json+++ b/nanobot/channels/signal/webui/locales/id.json@@ -1,21 +1,11 @@{- "description": "Gunakan nanobot dari pesan Signal.",- "requirements": "Daemon HTTP signal-cli, nomor telepon, dan daftar izin","setup": {"docsLabel": "Buka panduan Signal","officialLabel": "Buka panduan signal-cli",- "tryIt": "Kirim DM Signal ke nomor yang ditautkan.",- "summary": "Signal terhubung melalui daemon HTTP signal-cli yang sudah ditautkan ke nomor Signal.",- "steps": [- "Pasang signal-cli-rest-api dan tautkan atau daftarkan nomor Signal.",- "Masukkan host daemon, port, dan nomor yang ditautkan.",- "Simpan dan aktifkan Signal, lalu kirim pesan langsung uji."- ],"fields": {"phoneNumber": {"label": "Nomor telepon",- "placeholder": "+1234567890",- "help": "Gunakan nomor Signal yang terdaftar di signal-cli."+ "placeholder": "+1234567890"},"daemonHost": {"label": "Host daemon",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "Grup yang diizinkan","placeholder": "ID grup"+ },+ "groupMessageBufferSize": {+ "label": "Pesan konteks grup"+ },+ "attachmentsDir": {+ "label": "Direktori lampiran"+ },+ "dm_enabled": {+ "label": "Aktifkan pesan langsung",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "dm_policy": {+ "label": "Akses pesan langsung",+ "choices": {+ "allowlist": "Daftar yang diizinkan",+ "open": "Buka"+ }+ },+ "group_enabled": {+ "label": "Aktifkan grup",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "group_policy": {+ "label": "Akses grup",+ "choices": {+ "allowlist": "Daftar yang diizinkan",+ "open": "Buka"+ }+ },+ "group_requireMention": {+ "label": "Perlu disebutkan dalam kelompok",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/ja.json b/nanobot/channels/signal/webui/locales/ja.jsonindex 6fb28b557..ce64f3be2 100644--- a/nanobot/channels/signal/webui/locales/ja.json+++ b/nanobot/channels/signal/webui/locales/ja.json@@ -1,21 +1,11 @@{- "description": "Signal メッセージから nanobot を利用します。",- "requirements": "signal-cli HTTP デーモン、電話番号、許可リスト","setup": {"docsLabel": "Signal 設定ガイドを開く","officialLabel": "signal-cli ガイドを開く",- "tryIt": "連携した電話番号に Signal の DM を送信します。",- "summary": "Signal は、Signal の電話番号に連携済みの signal-cli HTTP デーモン経由で接続します。",- "steps": [- "signal-cli-rest-api をインストールし、Signal 番号を連携または登録します。",- "デーモンのホスト、ポート、連携済み電話番号を入力します。",- "保存して Signal を有効にし、DM でテストします。"- ],"fields": {"phoneNumber": {"label": "電話番号",- "placeholder": "+1234567890",- "help": "signal-cli に登録した Signal 番号を使います。"+ "placeholder": "+1234567890"},"daemonHost": {"label": "デーモンホスト",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "許可するグループ","placeholder": "グループ ID"+ },+ "groupMessageBufferSize": {+ "label": "グループコンテキストメッセージ"+ },+ "attachmentsDir": {+ "label": "添付ファイルディレクトリ"+ },+ "dm_enabled": {+ "label": "ダイレクトメッセージを有効にする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "dm_policy": {+ "label": "ダイレクトメッセージへのアクセス",+ "choices": {+ "allowlist": "ホワイトリスト",+ "open": "開く"+ }+ },+ "group_enabled": {+ "label": "グループを有効にする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "group_policy": {+ "label": "グループアクセス",+ "choices": {+ "allowlist": "ホワイトリスト",+ "open": "開く"+ }+ },+ "group_requireMention": {+ "label": "グループ内での言及が必要",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/ko.json b/nanobot/channels/signal/webui/locales/ko.jsonindex 134fbd57c..112c515ac 100644--- a/nanobot/channels/signal/webui/locales/ko.json+++ b/nanobot/channels/signal/webui/locales/ko.json@@ -1,21 +1,11 @@{- "description": "Signal 메시지에서 nanobot을 사용합니다.",- "requirements": "signal-cli HTTP 데몬, 전화번호 및 허용 목록","setup": {"docsLabel": "Signal 설정 가이드 열기","officialLabel": "signal-cli 가이드 열기",- "tryIt": "연결된 전화번호로 Signal DM을 보내세요.",- "summary": "Signal은 Signal 전화번호에 연결된 signal-cli HTTP 데몬을 통해 접속합니다.",- "steps": [- "signal-cli-rest-api를 설치하고 Signal 번호를 연결하거나 등록하세요.",- "데몬 호스트, 포트, 연결된 전화번호를 입력하세요.",- "저장하고 Signal을 활성화한 다음 DM으로 테스트하세요."- ],"fields": {"phoneNumber": {"label": "전화번호",- "placeholder": "+1234567890",- "help": "signal-cli에 등록된 Signal 번호를 사용하세요."+ "placeholder": "+1234567890"},"daemonHost": {"label": "데몬 호스트",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "허용된 그룹","placeholder": "그룹 ID"+ },+ "groupMessageBufferSize": {+ "label": "그룹 상황 메시지"+ },+ "attachmentsDir": {+ "label": "첨부파일 디렉토리"+ },+ "dm_enabled": {+ "label": "다이렉트 메시지 활성화",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "dm_policy": {+ "label": "다이렉트 메시지 액세스",+ "choices": {+ "allowlist": "허용 목록",+ "open": "열기"+ }+ },+ "group_enabled": {+ "label": "그룹 활성화",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "group_policy": {+ "label": "그룹 액세스",+ "choices": {+ "allowlist": "허용 목록",+ "open": "열기"+ }+ },+ "group_requireMention": {+ "label": "그룹에서 멘션 필요",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/pt-BR.json b/nanobot/channels/signal/webui/locales/pt-BR.jsonindex 8dac779f9..5ba66d0cc 100644--- a/nanobot/channels/signal/webui/locales/pt-BR.json+++ b/nanobot/channels/signal/webui/locales/pt-BR.json@@ -1,21 +1,11 @@{- "description": "Use o nanobot em mensagens do Signal.",- "requirements": "Daemon HTTP signal-cli, número de telefone e lista de permissão","setup": {"docsLabel": "Abrir guia do Signal","officialLabel": "Abrir guia do signal-cli",- "tryIt": "Envie uma DM do Signal ao número vinculado.",- "summary": "O Signal conecta por um daemon HTTP signal-cli já vinculado a um número Signal.",- "steps": [- "Instale o signal-cli-rest-api e vincule ou registre um número Signal.",- "Informe o host, a porta e o número vinculado.",- "Salve e ative o Signal; depois, envie uma mensagem direta de teste."- ],"fields": {"phoneNumber": {"label": "Número de telefone",- "placeholder": "+1234567890",- "help": "Use o número Signal registrado no signal-cli."+ "placeholder": "+1234567890"},"daemonHost": {"label": "Host do daemon",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "Grupos permitidos","placeholder": "IDs de grupo"+ },+ "groupMessageBufferSize": {+ "label": "Mensagens de contexto de grupo"+ },+ "attachmentsDir": {+ "label": "Diretório de anexos"+ },+ "dm_enabled": {+ "label": "Habilitar mensagens diretas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "dm_policy": {+ "label": "Acesso direto a mensagens",+ "choices": {+ "allowlist": "Lista de permissões",+ "open": "Abrir"+ }+ },+ "group_enabled": {+ "label": "Habilitar grupos",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "group_policy": {+ "label": "Acesso ao grupo",+ "choices": {+ "allowlist": "Lista de permissões",+ "open": "Abrir"+ }+ },+ "group_requireMention": {+ "label": "Exigir menção em grupos",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/vi.json b/nanobot/channels/signal/webui/locales/vi.jsonindex 460018035..de0d6149e 100644--- a/nanobot/channels/signal/webui/locales/vi.json+++ b/nanobot/channels/signal/webui/locales/vi.json@@ -1,21 +1,11 @@{- "description": "Sử dụng nanobot từ tin nhắn Signal.",- "requirements": "Dịch vụ HTTP signal-cli, số điện thoại và danh sách cho phép","setup": {"docsLabel": "Mở hướng dẫn Signal","officialLabel": "Mở hướng dẫn signal-cli",- "tryIt": "Gửi tin nhắn riêng Signal đến số đã liên kết.",- "summary": "Signal kết nối qua dịch vụ HTTP signal-cli đã liên kết với một số Signal.",- "steps": [- "Cài signal-cli-rest-api và liên kết hoặc đăng ký một số Signal.",- "Nhập địa chỉ máy chủ, cổng và số điện thoại đã liên kết.",- "Lưu và bật Signal, sau đó gửi tin nhắn riêng thử."- ],"fields": {"phoneNumber": {"label": "Số điện thoại",- "placeholder": "+1234567890",- "help": "Dùng số Signal đã đăng ký với signal-cli."+ "placeholder": "+1234567890"},"daemonHost": {"label": "Máy chủ dịch vụ",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "Nhóm được phép","placeholder": "ID nhóm"+ },+ "groupMessageBufferSize": {+ "label": "Nhóm tin nhắn ngữ cảnh"+ },+ "attachmentsDir": {+ "label": "Thư mục đính kèm"+ },+ "dm_enabled": {+ "label": "Bật tin nhắn trực tiếp",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "dm_policy": {+ "label": "Truy cập tin nhắn trực tiếp",+ "choices": {+ "allowlist": "Danh sách cho phép",+ "open": "Mở"+ }+ },+ "group_enabled": {+ "label": "Bật nhóm",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "group_policy": {+ "label": "Truy cập nhóm",+ "choices": {+ "allowlist": "Danh sách cho phép",+ "open": "Mở"+ }+ },+ "group_requireMention": {+ "label": "Yêu cầu đề cập trong nhóm",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/zh-CN.json b/nanobot/channels/signal/webui/locales/zh-CN.jsonindex 67b8a204a..2c47d5c64 100644--- a/nanobot/channels/signal/webui/locales/zh-CN.json+++ b/nanobot/channels/signal/webui/locales/zh-CN.json@@ -1,21 +1,11 @@{- "description": "通过 Signal 消息使用 nanobot。",- "requirements": "signal-cli HTTP 服务、电话号码和白名单","setup": {"docsLabel": "打开 Signal 配置指南","officialLabel": "打开 signal-cli 指南",- "tryIt": "向已关联的电话号码发送一条 Signal 私信。",- "summary": "Signal 通过已关联 Signal 电话号码的 signal-cli HTTP 服务连接。",- "steps": [- "安装 signal-cli-rest-api,并关联或注册一个 Signal 号码。",- "填写服务主机、端口和已关联的电话号码。",- "保存并启用 Signal,然后发送一条私信测试。"- ],"fields": {"phoneNumber": {"label": "电话号码",- "placeholder": "+1234567890",- "help": "使用在 signal-cli 中注册的 Signal 号码。"+ "placeholder": "+1234567890"},"daemonHost": {"label": "服务主机",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "允许的群组","placeholder": "群组 ID"+ },+ "groupMessageBufferSize": {+ "label": "群组上下文消息数"+ },+ "attachmentsDir": {+ "label": "附件目录"+ },+ "dm_enabled": {+ "label": "启用私聊",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "dm_policy": {+ "label": "私聊权限",+ "choices": {+ "allowlist": "白名单",+ "open": "全部"+ }+ },+ "group_enabled": {+ "label": "启用群组",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "group_policy": {+ "label": "群组权限",+ "choices": {+ "allowlist": "白名单",+ "open": "全部"+ }+ },+ "group_requireMention": {+ "label": "群组中需要提及",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }}}}diff --git a/nanobot/channels/signal/webui/locales/zh-TW.json b/nanobot/channels/signal/webui/locales/zh-TW.jsonindex 74e002e64..1a3fa8772 100644--- a/nanobot/channels/signal/webui/locales/zh-TW.json+++ b/nanobot/channels/signal/webui/locales/zh-TW.json@@ -1,21 +1,11 @@{- "description": "透過 Signal 訊息使用 nanobot。",- "requirements": "signal-cli HTTP 服務、電話號碼和允許清單","setup": {"docsLabel": "開啟 Signal 設定指南","officialLabel": "開啟 signal-cli 指南",- "tryIt": "向已關聯的電話號碼傳送一則 Signal 私訊。",- "summary": "Signal 透過已關聯 Signal 電話號碼的 signal-cli HTTP 服務連線。",- "steps": [- "安裝 signal-cli-rest-api,並關聯或註冊一個 Signal 號碼。",- "填入服務主機、連接埠和已關聯的電話號碼。",- "儲存並啟用 Signal,然後傳送一則私訊測試。"- ],"fields": {"phoneNumber": {"label": "電話號碼",- "placeholder": "+1234567890",- "help": "使用在 signal-cli 中註冊的 Signal 號碼。"+ "placeholder": "+1234567890"},"daemonHost": {"label": "服務主機",@@ -32,6 +22,47 @@"group_allowFrom": {"label": "允許的群組","placeholder": "群組 ID"+ },+ "groupMessageBufferSize": {+ "label": "群組上下文訊息數"+ },+ "attachmentsDir": {+ "label": "附件目錄"+ },+ "dm_enabled": {+ "label": "啟用私聊",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "dm_policy": {+ "label": "私聊權限",+ "choices": {+ "allowlist": "白名單",+ "open": "全部"+ }+ },+ "group_enabled": {+ "label": "啟用群組",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "group_policy": {+ "label": "群組權限",+ "choices": {+ "allowlist": "白名單",+ "open": "全部"+ }+ },+ "group_requireMention": {+ "label": "群組需要提及",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }}}}diff --git a/nanobot/channels/slack/manifest.py b/nanobot/channels/slack/manifest.pyindex 13da98efd..1428ef030 100644--- a/nanobot/channels/slack/manifest.py+++ b/nanobot/channels/slack/manifest.py@@ -10,10 +10,25 @@ SETUP_SPEC = ChannelSetupSpec("appToken": field("secret"),"botToken": field("secret"),"groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"),+ "mode": field("enum", choices={"socket"}, default="socket"),+ "webhookPath": field(default="/slack/events"),+ "replyInThread": field("bool", default=True),+ "reactEmoji": field(default="eyes"),+ "doneEmoji": field(default="white_check_mark"),+ "includeThreadContext": field("bool", default=True),+ "threadContextLimit": field("int", default=20),+ "allowFrom": field("list"),+ "groupAllowFrom": field("list"),+ "groupRequireMention": field("bool", default=False),+ "dm.enabled": field("bool", default=True),+ "dm.policy": field("enum", choices={"open", "allowlist"}, default="open"),+ "dm.allowFrom": field("list"),+ "proxy": field(),},required=required_fields("appToken", "botToken"),official_url="https://api.slack.com/apps",validator=validate,+ verifies_connection=True,)PLUGIN = ChannelPlugin(diff --git a/nanobot/channels/slack/runtime.py b/nanobot/channels/slack/runtime.pyindex eb81a9d6b..689071759 100644--- a/nanobot/channels/slack/runtime.py+++ b/nanobot/channels/slack/runtime.py@@ -7,10 +7,10 @@ from typing import Any, Protocol, castimport httpxfrom pydantic import Field+from slack_sdk.socket_mode.aiohttp import SocketModeClientfrom slack_sdk.socket_mode.async_client import AsyncBaseSocketModeClientfrom slack_sdk.socket_mode.request import SocketModeRequestfrom slack_sdk.socket_mode.response import SocketModeResponse-from slack_sdk.socket_mode.websockets import SocketModeClientfrom slack_sdk.web.async_client import AsyncWebClientfrom slackify_markdown import slackify_markdown # pyright: ignore[reportMissingTypeStubs]@@ -82,6 +82,7 @@ class SlackConfig(Base):# instead of every message). No effect for "mention"/"open" policies.group_require_mention: bool = Falsedm: SlackDMConfig = Field(default_factory=SlackDMConfig)+ proxy: str | None = NoneSLACK_MAX_MESSAGE_LEN = 39_000 # Slack API allows ~40k; leave margin@@ -144,10 +145,15 @@ class SlackChannel(BaseChannel):self._running = True- self._web_client = AsyncWebClient(token=self.config.bot_token)+ proxy = self.config.proxy.strip() if self.config.proxy else ""+ if proxy and "://" not in proxy:+ proxy = f"http://{proxy}"+ proxy = proxy or None+ self._web_client = AsyncWebClient(token=self.config.bot_token, proxy=proxy)self._socket_client = SocketModeClient(app_token=self.config.app_token,web_client=self._web_client,+ proxy=proxy,)self._socket_client.socket_mode_request_listeners.append(self._on_socket_request)@@ -577,7 +583,19 @@ class SlackChannel(BaseChannel):timeout=SLACK_DOWNLOAD_TIMEOUT,follow_redirects=True,transport=PinnedDNSAsyncTransport(),- mounts=httpx_env_proxy_mounts(),+ mounts=(+ {+ "all://": httpx.AsyncHTTPTransport(+ proxy=httpx.Proxy(+ self.config.proxy+ if "://" in self.config.proxy+ else f"http://{self.config.proxy}"+ )+ )+ }+ if self.config.proxy+ else httpx_env_proxy_mounts()+ ),event_hooks={"request": [_validate_slack_download_request]},) as client:response = await client.get(diff --git a/nanobot/channels/slack/tests/test_validation.py b/nanobot/channels/slack/tests/test_validation.pyindex f7ac4478a..8ddb8a185 100644--- a/nanobot/channels/slack/tests/test_validation.py+++ b/nanobot/channels/slack/tests/test_validation.py@@ -34,6 +34,9 @@ def test_validate_channel_does_not_write_config(tmp_path, monkeypatch: pytest.Mo)assert result["status"] == "connected"+ checks = {check["id"]: check for check in result["checks"]}+ assert checks["app_token_prefix"]["action_url"] == "https://api.slack.com/apps"+ assert "action_url" not in checks["bot_token_prefix"]saved = load_config(config_path)assert saved.channels.slack["appToken"] == "xapp-old"assert saved.channels.slack["botToken"] == "xoxb-old"diff --git a/nanobot/channels/slack/validation.py b/nanobot/channels/slack/validation.pyindex 1ee378b1f..4b5e8efc1 100644--- a/nanobot/channels/slack/validation.py+++ b/nanobot/channels/slack/validation.py@@ -19,6 +19,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dictchecks, missing = required_checks("slack", values)app_token = string_value(values.get("appToken"))bot_token = string_value(values.get("botToken"))+ proxy = string_value(values.get("proxy"))if app_token:checks.append(check(@@ -36,7 +37,6 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict"Bot token","pass" if bot_token.startswith("xoxb-") else "fail","Bot tokens start with xoxb- after installing the Slack app.",- action_url=official_action("slack"),))if bot_token.startswith("xoxb-"):@@ -44,6 +44,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dictdata = http_post("https://slack.com/api/auth.test",headers={"Authorization": f"Bearer {bot_token}"},+ proxy=proxy or None,)if data.get("ok"):identity = {diff --git a/nanobot/channels/slack/webui/index.ts b/nanobot/channels/slack/webui/index.tsindex 59bca5869..c2d0368a1 100644--- a/nanobot/channels/slack/webui/index.ts+++ b/nanobot/channels/slack/webui/index.ts@@ -40,10 +40,10 @@ settings:export default {presentation: {+ logoUrl: "https://slack.com/favicon.ico",displayName: "Slack",initials: "SL",color: "#4A154B",- logoUrl: "https://slack.com/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("slack"),@@ -51,13 +51,12 @@ export default {{id: "slack-manifest",copyText: SLACK_SOCKET_MODE_MANIFEST,- logoUrl: "https://slack.com/favicon.ico",},],fields: [- { key: "channels.slack.appToken" },- { key: "channels.slack.botToken" },- { key: "channels.slack.groupPolicy" },+ { key: "channels.slack.appToken", section: "credentials" },+ { key: "channels.slack.botToken", section: "credentials" },+ { key: "channels.slack.groupPolicy", section: "behavior" },],},},diff --git a/nanobot/channels/slack/webui/locales/en.json b/nanobot/channels/slack/webui/locales/en.jsonindex a8cd00fb3..ae32bc9a2 100644--- a/nanobot/channels/slack/webui/locales/en.json+++ b/nanobot/channels/slack/webui/locales/en.json@@ -1,29 +1,18 @@{- "description": "Use nanobot from Slack workspaces.",- "requirements": "Slack app token, bot token, workspace install","setup": {"docsLabel": "Open Slack setup","officialLabel": "Open Slack apps",- "tryIt": "Mention the Slack app or send it a direct message.",- "summary": "Slack uses Socket Mode by default, so it needs both app-level and bot-level tokens.",- "steps": [- "Create a Slack app from the provided manifest and enable Socket Mode.",- "Install the app to your workspace and copy the app and bot tokens.",- "Save and enable Slack, then mention the app or send it a direct message."- ],"actions": {"slack-manifest": "Copy app manifest"},"fields": {"appToken": {"label": "App token",- "placeholder": "xapp-...",- "help": "Create this in your Slack app’s Socket Mode settings."+ "placeholder": "xapp-..."},"botToken": {"label": "Bot token",- "placeholder": "xoxb-...",- "help": "Use the bot token after installing the Slack app."+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "Group behavior",@@ -32,6 +21,72 @@"open": "All messages","allowlist": "Allowlist"}+ },+ "mode": {+ "label": "Connection mode",+ "choices": {+ "socket": "Socket Mode"+ }+ },+ "webhookPath": {+ "label": "Webhook path"+ },+ "replyInThread": {+ "label": "Reply in thread",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "reactEmoji": {+ "label": "Read emoji"+ },+ "doneEmoji": {+ "label": "Done emoji"+ },+ "includeThreadContext": {+ "label": "Include thread context",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "threadContextLimit": {+ "label": "Thread context limit"+ },+ "allowFrom": {+ "label": "Allowed users"+ },+ "groupAllowFrom": {+ "label": "Allowed channels"+ },+ "groupRequireMention": {+ "label": "Require mentions in channels",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "dm_enabled": {+ "label": "Enable direct messages",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "dm_policy": {+ "label": "Direct message access",+ "choices": {+ "allowlist": "Allowlist",+ "open": "Open"+ }+ },+ "dm_allowFrom": {+ "label": "Allowed direct-message users"+ },+ "proxy": {+ "label": "Network proxy",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/es.json b/nanobot/channels/slack/webui/locales/es.jsonindex 5f342c327..f5e5b56fd 100644--- a/nanobot/channels/slack/webui/locales/es.json+++ b/nanobot/channels/slack/webui/locales/es.json@@ -1,29 +1,18 @@{- "description": "Usa nanobot desde espacios de Slack.",- "requirements": "Token de app Slack, token del bot e instalación en el espacio","setup": {"docsLabel": "Abrir guía de Slack","officialLabel": "Abrir aplicaciones de Slack",- "tryIt": "Menciona la app de Slack o envíale un mensaje directo.",- "summary": "Slack usa Socket Mode de forma predeterminada, por lo que necesita tokens de app y de bot.",- "steps": [- "Crea una app de Slack con el manifiesto proporcionado y activa Socket Mode.",- "Instala la app en tu espacio y copia los tokens de app y bot.",- "Guarda y activa Slack; después menciona la app o envíale un mensaje directo."- ],"actions": {"slack-manifest": "Copiar manifiesto de la aplicación"},"fields": {"appToken": {"label": "Token de la app",- "placeholder": "xapp-...",- "help": "Créalo en los ajustes de Socket Mode de tu aplicación de Slack."+ "placeholder": "xapp-..."},"botToken": {"label": "Token del bot",- "placeholder": "xoxb-...",- "help": "Usa el token del bot después de instalar la app."+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "Comportamiento en grupos",@@ -32,6 +21,72 @@"open": "Todos los mensajes","allowlist": "Lista de permitidos"}+ },+ "mode": {+ "label": "Modo de conexión",+ "choices": {+ "socket": "Modo de enchufe"+ }+ },+ "webhookPath": {+ "label": "Ruta del webhook"+ },+ "replyInThread": {+ "label": "Responder en el hilo",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "reactEmoji": {+ "label": "Leer emojis"+ },+ "doneEmoji": {+ "label": "emoji hecho"+ },+ "includeThreadContext": {+ "label": "Incluir contexto de hilo",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "threadContextLimit": {+ "label": "Límite de contexto del hilo"+ },+ "allowFrom": {+ "label": "Usuarios permitidos"+ },+ "groupAllowFrom": {+ "label": "Canales permitidos"+ },+ "groupRequireMention": {+ "label": "Requerir menciones en canales",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "dm_enabled": {+ "label": "Habilitar mensajes directos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "dm_policy": {+ "label": "Acceso a mensajes directos",+ "choices": {+ "allowlist": "Lista de permitidos",+ "open": "Abierto"+ }+ },+ "dm_allowFrom": {+ "label": "Usuarios permitidos de mensajes directos"+ },+ "proxy": {+ "label": "Proxy de red",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/fr.json b/nanobot/channels/slack/webui/locales/fr.jsonindex f09f26efb..5bf13db9c 100644--- a/nanobot/channels/slack/webui/locales/fr.json+++ b/nanobot/channels/slack/webui/locales/fr.json@@ -1,29 +1,18 @@{- "description": "Utilisez nanobot depuis les espaces Slack.",- "requirements": "Jeton d’application Slack, jeton du bot et installation dans l’espace","setup": {"docsLabel": "Ouvrir le guide Slack","officialLabel": "Ouvrir les applications Slack",- "tryIt": "Mentionnez l’application Slack ou envoyez-lui un message privé.",- "summary": "Slack utilise Socket Mode par défaut et nécessite les jetons d’application et de bot.",- "steps": [- "Créez une application Slack avec le manifeste fourni et activez Socket Mode.",- "Installez l’application dans votre espace et copiez les jetons d’application et de bot.",- "Enregistrez et activez Slack, puis mentionnez l’application ou envoyez-lui un message privé."- ],"actions": {"slack-manifest": "Copier le manifeste de l’application"},"fields": {"appToken": {"label": "Jeton d’application",- "placeholder": "xapp-...",- "help": "Créez ce jeton dans les paramètres Socket Mode de votre application Slack."+ "placeholder": "xapp-..."},"botToken": {"label": "Jeton du bot",- "placeholder": "xoxb-...",- "help": "Utilisez le jeton du bot après l’installation de l’application."+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "Comportement en groupe",@@ -32,6 +21,72 @@"open": "Tous les messages","allowlist": "Liste d’autorisation"}+ },+ "mode": {+ "label": "Mode de connexion",+ "choices": {+ "socket": "Mode prise"+ }+ },+ "webhookPath": {+ "label": "Chemin du webhook"+ },+ "replyInThread": {+ "label": "Répondre dans le fil de discussion",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "reactEmoji": {+ "label": "Lire les emoji"+ },+ "doneEmoji": {+ "label": "Terminé emoji"+ },+ "includeThreadContext": {+ "label": "Inclure le contexte du fil de discussion",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "threadContextLimit": {+ "label": "Limite du contexte du fil de discussion"+ },+ "allowFrom": {+ "label": "Utilisateurs autorisés"+ },+ "groupAllowFrom": {+ "label": "Chaînes autorisées"+ },+ "groupRequireMention": {+ "label": "Exiger des mentions dans les chaînes",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "dm_enabled": {+ "label": "Activer les messages directs",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "dm_policy": {+ "label": "Accès aux messages directs",+ "choices": {+ "allowlist": "Liste verte",+ "open": "Ouvert"+ }+ },+ "dm_allowFrom": {+ "label": "Utilisateurs de messagerie directe autorisés"+ },+ "proxy": {+ "label": "Proxy réseau",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/id.json b/nanobot/channels/slack/webui/locales/id.jsonindex 9364344b4..dec3f4d11 100644--- a/nanobot/channels/slack/webui/locales/id.json+++ b/nanobot/channels/slack/webui/locales/id.json@@ -1,29 +1,18 @@{- "description": "Gunakan nanobot dari ruang kerja Slack.",- "requirements": "Token aplikasi Slack, token bot, dan aplikasi terpasang di ruang kerja","setup": {"docsLabel": "Buka panduan Slack","officialLabel": "Buka aplikasi Slack",- "tryIt": "Sebut aplikasi Slack atau kirim pesan langsung.",- "summary": "Slack menggunakan Socket Mode secara default sehingga memerlukan token aplikasi dan token bot.",- "steps": [- "Buat aplikasi Slack dari manifes yang disediakan, lalu aktifkan Socket Mode.",- "Pasang aplikasi ke ruang kerja dan salin token aplikasi serta bot.",- "Simpan dan aktifkan Slack, lalu sebut aplikasi atau kirim DM."- ],"actions": {"slack-manifest": "Salin manifes aplikasi"},"fields": {"appToken": {"label": "Token aplikasi",- "placeholder": "xapp-...",- "help": "Buat token di pengaturan Socket Mode aplikasi Slack Anda."+ "placeholder": "xapp-..."},"botToken": {"label": "Token bot",- "placeholder": "xoxb-...",- "help": "Gunakan token bot setelah memasang aplikasi Slack."+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "Perilaku grup",@@ -32,6 +21,72 @@"open": "Semua pesan","allowlist": "Daftar izin"}+ },+ "mode": {+ "label": "Modus koneksi",+ "choices": {+ "socket": "Mode Soket"+ }+ },+ "webhookPath": {+ "label": "Jalur webhook"+ },+ "replyInThread": {+ "label": "Balas di thread",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "reactEmoji": {+ "label": "Baca emoji"+ },+ "doneEmoji": {+ "label": "Selesai emoji"+ },+ "includeThreadContext": {+ "label": "Sertakan konteks thread",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "threadContextLimit": {+ "label": "Batas konteks thread"+ },+ "allowFrom": {+ "label": "Pengguna yang diizinkan"+ },+ "groupAllowFrom": {+ "label": "Saluran yang diizinkan"+ },+ "groupRequireMention": {+ "label": "Wajibkan penyebutan di saluran",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "dm_enabled": {+ "label": "Aktifkan pesan langsung",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "dm_policy": {+ "label": "Akses pesan langsung",+ "choices": {+ "allowlist": "Daftar yang diizinkan",+ "open": "Buka"+ }+ },+ "dm_allowFrom": {+ "label": "Mengizinkan pengguna pesan langsung"+ },+ "proxy": {+ "label": "Proxy jaringan",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/ja.json b/nanobot/channels/slack/webui/locales/ja.jsonindex a89dd0c49..08cbb6458 100644--- a/nanobot/channels/slack/webui/locales/ja.json+++ b/nanobot/channels/slack/webui/locales/ja.json@@ -1,29 +1,18 @@{- "description": "Slack ワークスペースから nanobot を利用します。",- "requirements": "Slack アプリトークン、ボットトークン、ワークスペースへのインストール","setup": {"docsLabel": "Slack 設定ガイドを開く","officialLabel": "Slack アプリを開く",- "tryIt": "Slack アプリをメンションするか、DM を送信します。",- "summary": "Slack は既定で Socket Mode を使うため、アプリレベルとボットレベルの両方のトークンが必要です。",- "steps": [- "提供されたマニフェストから Slack アプリを作成し、Socket Mode を有効にします。",- "アプリをワークスペースにインストールし、アプリとボットのトークンをコピーします。",- "保存して Slack を有効にし、アプリをメンションするか DM を送信します。"- ],"actions": {"slack-manifest": "アプリマニフェストをコピー"},"fields": {"appToken": {"label": "アプリトークン",- "placeholder": "xapp-...",- "help": "Slack アプリの Socket Mode 設定で作成します。"+ "placeholder": "xapp-..."},"botToken": {"label": "ボットトークン",- "placeholder": "xoxb-...",- "help": "Slack アプリのインストール後にボットトークンを使います。"+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "グループでの動作",@@ -32,6 +21,72 @@"open": "すべてのメッセージ","allowlist": "許可リスト"}+ },+ "mode": {+ "label": "接続モード",+ "choices": {+ "socket": "ソケットモード"+ }+ },+ "webhookPath": {+ "label": "Webhook パス"+ },+ "replyInThread": {+ "label": "スレッド内で返信する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "reactEmoji": {+ "label": "絵文字を読む"+ },+ "doneEmoji": {+ "label": "完了絵文字"+ },+ "includeThreadContext": {+ "label": "スレッドコンテキストを含める",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "threadContextLimit": {+ "label": "スレッドコンテキストの制限"+ },+ "allowFrom": {+ "label": "許可されたユーザー"+ },+ "groupAllowFrom": {+ "label": "許可されたチャネル"+ },+ "groupRequireMention": {+ "label": "チャンネルでのメンションを必須にする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "dm_enabled": {+ "label": "ダイレクトメッセージを有効にする",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "dm_policy": {+ "label": "ダイレクトメッセージへのアクセス",+ "choices": {+ "allowlist": "ホワイトリスト",+ "open": "開く"+ }+ },+ "dm_allowFrom": {+ "label": "許可されたダイレクトメッセージユーザー"+ },+ "proxy": {+ "label": "ネットワークプロキシ",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/ko.json b/nanobot/channels/slack/webui/locales/ko.jsonindex 4456f13fe..a68fefbb9 100644--- a/nanobot/channels/slack/webui/locales/ko.json+++ b/nanobot/channels/slack/webui/locales/ko.json@@ -1,29 +1,18 @@{- "description": "Slack 작업 공간에서 nanobot을 사용합니다.",- "requirements": "Slack 앱 토큰, 봇 토큰 및 작업 공간 설치","setup": {"docsLabel": "Slack 설정 가이드 열기","officialLabel": "Slack 앱 열기",- "tryIt": "Slack 앱을 멘션하거나 DM을 보내세요.",- "summary": "Slack은 기본적으로 Socket Mode를 사용하므로 앱 수준 토큰과 봇 토큰이 모두 필요합니다.",- "steps": [- "제공된 앱 매니페스트로 Slack 앱을 만들고 Socket Mode를 활성화하세요.",- "앱을 작업 공간에 설치하고 앱 및 봇 토큰을 복사하세요.",- "저장하고 Slack을 활성화한 다음 앱을 멘션하거나 DM을 보내세요."- ],"actions": {"slack-manifest": "앱 매니페스트 복사"},"fields": {"appToken": {"label": "앱 토큰",- "placeholder": "xapp-...",- "help": "Slack 앱의 Socket Mode 설정에서 생성하세요."+ "placeholder": "xapp-..."},"botToken": {"label": "봇 토큰",- "placeholder": "xoxb-...",- "help": "Slack 앱을 설치한 뒤 봇 토큰을 사용하세요."+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "그룹 동작",@@ -32,6 +21,72 @@"open": "모든 메시지","allowlist": "허용 목록"}+ },+ "mode": {+ "label": "연결 모드",+ "choices": {+ "socket": "소켓 모드"+ }+ },+ "webhookPath": {+ "label": "웹훅 경로"+ },+ "replyInThread": {+ "label": "스레드로 답장하기",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "reactEmoji": {+ "label": "이모티콘 읽기"+ },+ "doneEmoji": {+ "label": "이모티콘 완료"+ },+ "includeThreadContext": {+ "label": "스레드 컨텍스트 포함",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "threadContextLimit": {+ "label": "스레드 컨텍스트 제한"+ },+ "allowFrom": {+ "label": "허용된 사용자"+ },+ "groupAllowFrom": {+ "label": "허용된 채널"+ },+ "groupRequireMention": {+ "label": "채널에서 멘션 필요",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "dm_enabled": {+ "label": "다이렉트 메시지 활성화",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "dm_policy": {+ "label": "다이렉트 메시지 액세스",+ "choices": {+ "allowlist": "허용 목록",+ "open": "열기"+ }+ },+ "dm_allowFrom": {+ "label": "허용된 직접 메시지 사용자"+ },+ "proxy": {+ "label": "네트워크 프록시",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/pt-BR.json b/nanobot/channels/slack/webui/locales/pt-BR.jsonindex 365419034..d7fd594bc 100644--- a/nanobot/channels/slack/webui/locales/pt-BR.json+++ b/nanobot/channels/slack/webui/locales/pt-BR.json@@ -1,29 +1,18 @@{- "description": "Use o nanobot em workspaces do Slack.",- "requirements": "Token do app Slack, token do bot e instalação no workspace","setup": {"docsLabel": "Abrir guia do Slack","officialLabel": "Abrir aplicativos do Slack",- "tryIt": "Mencione o app Slack ou envie uma mensagem direta.",- "summary": "O Slack usa Socket Mode por padrão e precisa dos tokens do app e do bot.",- "steps": [- "Crie um app Slack com o manifesto fornecido e ative o Socket Mode.",- "Instale o app no workspace e copie os tokens do app e do bot.",- "Salve e ative o Slack; depois, mencione o app ou envie uma DM."- ],"actions": {"slack-manifest": "Copiar manifesto do aplicativo"},"fields": {"appToken": {"label": "Token do app",- "placeholder": "xapp-...",- "help": "Crie o token nas configurações de Socket Mode do seu aplicativo Slack."+ "placeholder": "xapp-..."},"botToken": {"label": "Token do bot",- "placeholder": "xoxb-...",- "help": "Use o token do bot após instalar o app Slack."+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "Comportamento em grupos",@@ -32,6 +21,72 @@"open": "Todas as mensagens","allowlist": "Lista de permissão"}+ },+ "mode": {+ "label": "Modo de conexão",+ "choices": {+ "socket": "Modo de soquete"+ }+ },+ "webhookPath": {+ "label": "Caminho do webhook"+ },+ "replyInThread": {+ "label": "Responder no tópico",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "reactEmoji": {+ "label": "Ler emoticons"+ },+ "doneEmoji": {+ "label": "Emoji pronto"+ },+ "includeThreadContext": {+ "label": "Incluir contexto do thread",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "threadContextLimit": {+ "label": "Limite de contexto do thread"+ },+ "allowFrom": {+ "label": "Usuários permitidos"+ },+ "groupAllowFrom": {+ "label": "Canais permitidos"+ },+ "groupRequireMention": {+ "label": "Exigir menções nos canais",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "dm_enabled": {+ "label": "Habilitar mensagens diretas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "dm_policy": {+ "label": "Acesso direto a mensagens",+ "choices": {+ "allowlist": "Lista de permissões",+ "open": "Abrir"+ }+ },+ "dm_allowFrom": {+ "label": "Usuários de mensagens diretas permitidos"+ },+ "proxy": {+ "label": "Proxy de rede",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/vi.json b/nanobot/channels/slack/webui/locales/vi.jsonindex bda92d53c..b982affd5 100644--- a/nanobot/channels/slack/webui/locales/vi.json+++ b/nanobot/channels/slack/webui/locales/vi.json@@ -1,29 +1,18 @@{- "description": "Sử dụng nanobot trong không gian Slack.",- "requirements": "Token ứng dụng Slack, token bot và ứng dụng đã cài vào không gian làm việc","setup": {"docsLabel": "Mở hướng dẫn Slack","officialLabel": "Mở ứng dụng Slack",- "tryIt": "Nhắc ứng dụng Slack hoặc gửi tin nhắn riêng.",- "summary": "Slack mặc định dùng Socket Mode nên cần cả token ứng dụng và token bot.",- "steps": [- "Tạo ứng dụng Slack từ bản khai được cung cấp và bật Socket Mode.",- "Cài ứng dụng vào không gian làm việc rồi sao chép token ứng dụng và token bot.",- "Lưu và bật Slack, sau đó nhắc ứng dụng hoặc gửi tin nhắn riêng."- ],"actions": {"slack-manifest": "Sao chép bản khai ứng dụng"},"fields": {"appToken": {"label": "Token ứng dụng",- "placeholder": "xapp-...",- "help": "Tạo token trong phần cài đặt Socket Mode của ứng dụng Slack."+ "placeholder": "xapp-..."},"botToken": {"label": "Token bot",- "placeholder": "xoxb-...",- "help": "Dùng token bot sau khi cài ứng dụng Slack."+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "Hành vi trong nhóm",@@ -32,6 +21,72 @@"open": "Mọi tin nhắn","allowlist": "Danh sách cho phép"}+ },+ "mode": {+ "label": "Chế độ kết nối",+ "choices": {+ "socket": "Chế độ ổ cắm"+ }+ },+ "webhookPath": {+ "label": "Đường dẫn webhook"+ },+ "replyInThread": {+ "label": "Trả lời trong chủ đề",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "reactEmoji": {+ "label": "Đọc biểu tượng cảm xúc"+ },+ "doneEmoji": {+ "label": "biểu tượng cảm xúc xong"+ },+ "includeThreadContext": {+ "label": "Bao gồm bối cảnh chủ đề",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "threadContextLimit": {+ "label": "Giới hạn bối cảnh của chủ đề"+ },+ "allowFrom": {+ "label": "Người dùng được phép"+ },+ "groupAllowFrom": {+ "label": "Các kênh được phép"+ },+ "groupRequireMention": {+ "label": "Yêu cầu đề cập trong các kênh",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "dm_enabled": {+ "label": "Bật tin nhắn trực tiếp",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "dm_policy": {+ "label": "Truy cập tin nhắn trực tiếp",+ "choices": {+ "allowlist": "Danh sách cho phép",+ "open": "Mở"+ }+ },+ "dm_allowFrom": {+ "label": "Cho phép người dùng nhắn tin trực tiếp"+ },+ "proxy": {+ "label": "Proxy mạng",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/zh-CN.json b/nanobot/channels/slack/webui/locales/zh-CN.jsonindex fdaae0838..93894b3f1 100644--- a/nanobot/channels/slack/webui/locales/zh-CN.json+++ b/nanobot/channels/slack/webui/locales/zh-CN.json@@ -1,29 +1,18 @@{- "description": "在 Slack 工作区中使用 nanobot。",- "requirements": "Slack 应用令牌、机器人令牌和工作区安装","setup": {"docsLabel": "打开 Slack 配置指南","officialLabel": "打开 Slack 应用后台",- "tryIt": "提及 Slack 应用,或向它发送私信。",- "summary": "Slack 默认使用 Socket Mode,因此同时需要应用级令牌和机器人令牌。",- "steps": [- "使用提供的 manifest 创建 Slack 应用并启用 Socket Mode。",- "将应用安装到工作区,并复制应用令牌和机器人令牌。",- "保存并启用 Slack,然后提及应用或发送私信。"- ],"actions": {"slack-manifest": "复制应用清单"},"fields": {"appToken": {"label": "应用令牌",- "placeholder": "xapp-...",- "help": "在 Slack 应用的 Socket Mode 设置中创建。"+ "placeholder": "xapp-..."},"botToken": {"label": "机器人令牌",- "placeholder": "xoxb-...",- "help": "安装 Slack 应用后使用机器人令牌。"+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "群组行为",@@ -32,6 +21,72 @@"open": "所有消息","allowlist": "白名单"}+ },+ "mode": {+ "label": "连接方式",+ "choices": {+ "socket": "Socket 模式"+ }+ },+ "webhookPath": {+ "label": "Webhook 路径"+ },+ "replyInThread": {+ "label": "在话题中回复",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "reactEmoji": {+ "label": "已读表情"+ },+ "doneEmoji": {+ "label": "完成表情"+ },+ "includeThreadContext": {+ "label": "包含话题上下文",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "threadContextLimit": {+ "label": "话题上下文上限"+ },+ "allowFrom": {+ "label": "允许的用户"+ },+ "groupAllowFrom": {+ "label": "允许的频道"+ },+ "groupRequireMention": {+ "label": "频道中需要提及",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "dm_enabled": {+ "label": "启用私聊",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "dm_policy": {+ "label": "私聊权限",+ "choices": {+ "allowlist": "白名单",+ "open": "全部"+ }+ },+ "dm_allowFrom": {+ "label": "允许私聊的用户"+ },+ "proxy": {+ "label": "网络代理",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/slack/webui/locales/zh-TW.json b/nanobot/channels/slack/webui/locales/zh-TW.jsonindex bd700196d..205b53e4d 100644--- a/nanobot/channels/slack/webui/locales/zh-TW.json+++ b/nanobot/channels/slack/webui/locales/zh-TW.json@@ -1,29 +1,18 @@{- "description": "在 Slack 工作區中使用 nanobot。",- "requirements": "Slack 應用程式權杖、機器人權杖和工作區安裝","setup": {"docsLabel": "開啟 Slack 設定指南","officialLabel": "開啟 Slack 應用程式後台",- "tryIt": "提及 Slack 應用程式,或向它傳送私訊。",- "summary": "Slack 預設使用 Socket Mode,因此同時需要應用程式層級權杖和機器人權杖。",- "steps": [- "使用提供的應用程式資訊清單建立 Slack 應用程式,並啟用 Socket Mode。",- "將應用程式安裝到工作區,並複製應用程式權杖和機器人權杖。",- "儲存並啟用 Slack,然後提及應用程式或傳送私訊。"- ],"actions": {"slack-manifest": "複製應用程式資訊清單"},"fields": {"appToken": {"label": "應用程式權杖",- "placeholder": "xapp-...",- "help": "在 Slack 應用程式的 Socket Mode 設定中建立。"+ "placeholder": "xapp-..."},"botToken": {"label": "機器人權杖",- "placeholder": "xoxb-...",- "help": "安裝 Slack 應用程式後使用機器人權杖。"+ "placeholder": "xoxb-..."},"groupPolicy": {"label": "群組行為",@@ -32,6 +21,72 @@"open": "所有訊息","allowlist": "允許清單"}+ },+ "mode": {+ "label": "連接方式",+ "choices": {+ "socket": "Socket 模式"+ }+ },+ "webhookPath": {+ "label": "Webhook 路徑"+ },+ "replyInThread": {+ "label": "在話題中回复",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "reactEmoji": {+ "label": "已讀表情"+ },+ "doneEmoji": {+ "label": "完成表情"+ },+ "includeThreadContext": {+ "label": "包含話題上下文",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "threadContextLimit": {+ "label": "話題上下文上限"+ },+ "allowFrom": {+ "label": "允許的用戶"+ },+ "groupAllowFrom": {+ "label": "允許的頻道"+ },+ "groupRequireMention": {+ "label": "頻道中需要提及",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "dm_enabled": {+ "label": "啟用私聊",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "dm_policy": {+ "label": "私聊權限",+ "choices": {+ "allowlist": "白名單",+ "open": "全部"+ }+ },+ "dm_allowFrom": {+ "label": "允許私聊的用戶"+ },+ "proxy": {+ "label": "網路代理",+ "placeholder": "http://127.0.0.1:7890"}}}diff --git a/nanobot/channels/telegram/manifest.py b/nanobot/channels/telegram/manifest.pyindex f02a7a401..93d806ee3 100644--- a/nanobot/channels/telegram/manifest.py+++ b/nanobot/channels/telegram/manifest.py@@ -8,13 +8,29 @@ from nanobot.channels.telegram.validation import validateSETUP_SPEC = ChannelSetupSpec(fields={"token": field("secret"),- "proxy": field("secret"),+ "proxy": field(),"allowFrom": field("list"),"groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"),+ "mode": field("enum", choices={"polling", "webhook"}, default="polling"),+ "replyToMessage": field("bool", default=False),+ "reactEmoji": field(default="👀"),+ "connectionPoolSize": field("int", default=32),+ "poolTimeout": field("float", default=5.0),+ "streaming": field("bool", default=True),+ "inlineKeyboards": field("bool", default=False),+ "richMessages": field("bool", default=False),+ "streamEditInterval": field("float", default=0.6),+ "webhookUrl": field(),+ "webhookListenHost": field(default="127.0.0.1"),+ "webhookListenPort": field("int", default=8081),+ "webhookPath": field(default="/telegram"),+ "webhookSecretToken": field("secret"),+ "webhookMaxConnections": field("int", default=4),},required=(required("token"),),official_url="https://t.me/BotFather",validator=validate,+ verifies_connection=True,)PLUGIN = ChannelPlugin(diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.pyindex f104e35d2..532b04a1d 100644--- a/nanobot/channels/telegram/runtime.py+++ b/nanobot/channels/telegram/runtime.py@@ -659,6 +659,8 @@ class TelegramChannel(BaseChannel):async def _start_app(self) -> None:"""Build, initialize and start the Telegram application."""proxy = self.config.proxy or None+ if proxy and "://" not in proxy:+ proxy = f"http://{proxy}"# Separate pools so long-polling (getUpdates) never starves outbound sends.api_request = HTTPXRequest(diff --git a/nanobot/channels/telegram/tests/test_validation.py b/nanobot/channels/telegram/tests/test_validation.pyindex 95c8278c1..81fe982ba 100644--- a/nanobot/channels/telegram/tests/test_validation.py+++ b/nanobot/channels/telegram/tests/test_validation.py@@ -10,10 +10,10 @@ from nanobot.config.loader import save_configfrom nanobot.config.schema import Config-def test_telegram_setup_exposes_proxy_as_an_optional_secret() -> None:+def test_telegram_setup_exposes_proxy_as_an_optional_field() -> None:proxy = SETUP_SPEC.fields["proxy"]- assert proxy.kind == "secret"+ assert proxy.kind == "string"assert "proxy" not in SETUP_SPEC.simple_required_fields@@ -58,6 +58,38 @@ def test_get_me_builds_http_client_with_explicit_proxy(assert captured["url"] == f"https://api.telegram.org/bot{token}/getMe"+def test_get_me_normalizes_proxy_without_a_scheme(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, object] = {}++ class FakeResponse:+ def raise_for_status(self) -> None:+ return None++ def json(self) -> dict:+ return {"ok": True, "result": {"id": 42}}++ class FakeClient:+ def __init__(self, **kwargs) -> None:+ captured.update(kwargs)++ def __enter__(self):+ return self++ def __exit__(self, *_args) -> None:+ return None++ def get(self, _url: str) -> FakeResponse:+ return FakeResponse()++ monkeypatch.setattr(telegram_validation.httpx, "Client", FakeClient)++ telegram_validation._get_me("123456:abcdefghijklmnopqrstuvwxyz", "127.0.0.1:7890")++ assert captured["proxy"] == "http://127.0.0.1:7890"++def test_validate_telegram_bad_token_is_invalid(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:config_path = tmp_path / "config.json"save_config(Config(), config_path)@@ -279,7 +311,7 @@ def test_validate_telegram_uses_proxy_submitted_with_new_token(assert captured == {"token": token, "proxy": proxy}[email protected]("proxy", ["127.0.0.1:7890", "http://[", "http://localhost:not-a-port"])[email protected]("proxy", ["http://[", "http://localhost:not-a-port"])def test_validate_telegram_rejects_invalid_proxy_without_trying_token(tmp_path,monkeypatch: pytest.MonkeyPatch,diff --git a/nanobot/channels/telegram/validation.py b/nanobot/channels/telegram/validation.pyindex 5931a5de6..67302566c 100644--- a/nanobot/channels/telegram/validation.py+++ b/nanobot/channels/telegram/validation.py@@ -22,6 +22,8 @@ _SUPPORTED_PROXY_SCHEMES = {"http", "https", "socks5", "socks5h"}def _proxy_url_is_valid(proxy: str) -> bool:+ if "://" not in proxy:+ proxy = f"http://{proxy}"try:parsed = urlparse(proxy)hostname = parsed.hostname@@ -32,6 +34,8 @@ def _proxy_url_is_valid(proxy: str) -> bool:def _get_me(token: str, proxy: str | None) -> dict[str, Any]:+ if proxy and "://" not in proxy:+ proxy = f"http://{proxy}"client_kwargs: dict[str, Any] = {"timeout": _TIMEOUT_SECONDS}if proxy:client_kwargs.update(proxy=proxy, trust_env=False)@@ -74,7 +78,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict"proxy_format","Network proxy","fail",- "Enter a full HTTP or SOCKS proxy URL.",+ "Enter a valid HTTP or SOCKS proxy.",))return status_from_checks("telegram", checks, missing)diff --git a/nanobot/channels/telegram/webui/index.ts b/nanobot/channels/telegram/webui/index.tsindex 57d4cdc83..4def46c0b 100644--- a/nanobot/channels/telegram/webui/index.ts+++ b/nanobot/channels/telegram/webui/index.ts@@ -3,18 +3,18 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://telegram.org/favicon.ico",displayName: "Telegram",initials: "TG",color: "#229ED9",- logoUrl: "https://telegram.org/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("telegram"),fields: [- { key: "channels.telegram.token" },- { key: "channels.telegram.proxy" },- { key: "channels.telegram.allowFrom" },- { key: "channels.telegram.groupPolicy" },+ { key: "channels.telegram.token", section: "credentials" },+ { key: "channels.telegram.proxy", section: "connection" },+ { key: "channels.telegram.allowFrom", section: "access" },+ { key: "channels.telegram.groupPolicy", section: "behavior" },],},},diff --git a/nanobot/channels/telegram/webui/locales/en.json b/nanobot/channels/telegram/webui/locales/en.jsonindex 72b01523b..faf5f0071 100644--- a/nanobot/channels/telegram/webui/locales/en.json+++ b/nanobot/channels/telegram/webui/locales/en.json@@ -1,21 +1,11 @@{- "description": "Chat with nanobot on Telegram.",- "requirements": "Bot token, allowed users, gateway","setup": {"docsLabel": "Open Telegram setup","officialLabel": "Open BotFather",- "tryIt": "Send /start or a short DM to your Telegram bot.",- "summary": "Add the bot token from BotFather to send and receive Telegram messages.",- "steps": [- "Create a bot with BotFather and copy its token.",- "Add the token and choose who can message the bot.",- "Save and enable Telegram, then send the bot a direct message or mention it in a group."- ],"fields": {"token": {"label": "Bot token",- "placeholder": "123456:ABC...",- "help": "Create it with BotFather."+ "placeholder": "123456:ABC..."},"proxy": {"label": "Network proxy",@@ -23,8 +13,7 @@},"allowFrom": {"label": "Allowed users",- "placeholder": "* or Telegram user IDs",- "help": "Leave empty to use pairing codes."+ "placeholder": "* or Telegram user IDs"},"groupPolicy": {"label": "Group behavior",@@ -33,6 +22,71 @@"open": "All messages","allowlist": "Allowlist"}+ },+ "mode": {+ "label": "Connection mode",+ "choices": {+ "polling": "Long polling",+ "webhook": "Webhook"+ }+ },+ "replyToMessage": {+ "label": "Reply to message",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "reactEmoji": {+ "label": "Read emoji"+ },+ "connectionPoolSize": {+ "label": "Connection pool size"+ },+ "poolTimeout": {+ "label": "Connection pool timeout"+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "inlineKeyboards": {+ "label": "Inline keyboards",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "richMessages": {+ "label": "Rich messages",+ "choices": {+ "true": "On",+ "false": "Off"+ }+ },+ "streamEditInterval": {+ "label": "Stream update interval"+ },+ "webhookUrl": {+ "label": "Webhook URL"+ },+ "webhookListenHost": {+ "label": "Webhook listen host"+ },+ "webhookListenPort": {+ "label": "Webhook listen port"+ },+ "webhookPath": {+ "label": "Webhook path"+ },+ "webhookSecretToken": {+ "label": "Webhook secret token"+ },+ "webhookMaxConnections": {+ "label": "Maximum webhook connections"}}}diff --git a/nanobot/channels/telegram/webui/locales/es.json b/nanobot/channels/telegram/webui/locales/es.jsonindex c3254e367..bdf9059ee 100644--- a/nanobot/channels/telegram/webui/locales/es.json+++ b/nanobot/channels/telegram/webui/locales/es.json@@ -1,21 +1,11 @@{- "description": "Chatea con nanobot desde Telegram.",- "requirements": "Token del bot, usuarios permitidos y pasarela","setup": {"docsLabel": "Abrir guía de Telegram","officialLabel": "Abrir BotFather",- "tryIt": "Envía /start o un DM corto a tu bot de Telegram.",- "summary": "Añade el token de bot obtenido en BotFather para enviar y recibir mensajes de Telegram.",- "steps": [- "Crea un bot con BotFather y copia su token.",- "Añade el token y elige quién puede escribir al bot.",- "Guarda y activa Telegram; después envía un DM o menciona el bot en un grupo."- ],"fields": {"token": {"label": "Token del bot",- "placeholder": "123456:ABC...",- "help": "Créalo con BotFather."+ "placeholder": "123456:ABC..."},"proxy": {"label": "Proxy de red",@@ -23,8 +13,7 @@},"allowFrom": {"label": "Usuarios permitidos",- "placeholder": "* o ID de usuario de Telegram",- "help": "Déjalo vacío para usar códigos de vinculación."+ "placeholder": "* o ID de usuario de Telegram"},"groupPolicy": {"label": "Comportamiento en grupos",@@ -33,6 +22,71 @@"open": "Todos los mensajes","allowlist": "Lista de permitidos"}+ },+ "mode": {+ "label": "Modo de conexión",+ "choices": {+ "polling": "sondeo largo",+ "webhook": "gancho web"+ }+ },+ "replyToMessage": {+ "label": "Responder al mensaje",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "reactEmoji": {+ "label": "Leer emojis"+ },+ "connectionPoolSize": {+ "label": "Tamaño del grupo de conexiones"+ },+ "poolTimeout": {+ "label": "Tiempo de espera del grupo de conexiones"+ },+ "streaming": {+ "label": "Transmisión",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "inlineKeyboards": {+ "label": "teclados en línea",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "richMessages": {+ "label": "Mensajes ricos",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }+ },+ "streamEditInterval": {+ "label": "Intervalo de actualización de la transmisión"+ },+ "webhookUrl": {+ "label": "URL de webhook"+ },+ "webhookListenHost": {+ "label": "Anfitrión de escucha de webhook"+ },+ "webhookListenPort": {+ "label": "Puerto de escucha de webhook"+ },+ "webhookPath": {+ "label": "Ruta del webhook"+ },+ "webhookSecretToken": {+ "label": "Token secreto de webhook"+ },+ "webhookMaxConnections": {+ "label": "Conexiones máximas de webhooks"}}}diff --git a/nanobot/channels/telegram/webui/locales/fr.json b/nanobot/channels/telegram/webui/locales/fr.jsonindex e1d1c995d..132bed936 100644--- a/nanobot/channels/telegram/webui/locales/fr.json+++ b/nanobot/channels/telegram/webui/locales/fr.json@@ -1,21 +1,11 @@{- "description": "Discutez avec nanobot depuis Telegram.",- "requirements": "Jeton du bot, utilisateurs autorisés et passerelle","setup": {"docsLabel": "Ouvrir le guide Telegram","officialLabel": "Ouvrir BotFather",- "tryIt": "Envoyez /start ou un court message privé à votre bot Telegram.",- "summary": "Ajoutez le jeton de bot obtenu auprès de BotFather pour envoyer et recevoir des messages Telegram.",- "steps": [- "Créez un bot avec BotFather et copiez son jeton.",- "Ajoutez le jeton et choisissez qui peut contacter le bot.",- "Enregistrez et activez Telegram, puis envoyez un message privé ou mentionnez le bot dans un groupe."- ],"fields": {"token": {"label": "Jeton du bot",- "placeholder": "123456:ABC...",- "help": "Créez-le avec BotFather."+ "placeholder": "123456:ABC..."},"proxy": {"label": "Proxy réseau",@@ -23,8 +13,7 @@},"allowFrom": {"label": "Utilisateurs autorisés",- "placeholder": "* ou ID utilisateur Telegram",- "help": "Laissez vide pour utiliser les codes d’association."+ "placeholder": "* ou ID utilisateur Telegram"},"groupPolicy": {"label": "Comportement en groupe",@@ -33,6 +22,71 @@"open": "Tous les messages","allowlist": "Liste d’autorisation"}+ },+ "mode": {+ "label": "Mode de connexion",+ "choices": {+ "polling": "Sondage long",+ "webhook": "Webhook"+ }+ },+ "replyToMessage": {+ "label": "Répondre au message",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "reactEmoji": {+ "label": "Lire les emoji"+ },+ "connectionPoolSize": {+ "label": "Taille du pool de connexions"+ },+ "poolTimeout": {+ "label": "Expiration du délai du pool de connexions"+ },+ "streaming": {+ "label": "Diffusion en continu",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "inlineKeyboards": {+ "label": "Claviers en ligne",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "richMessages": {+ "label": "Messages riches",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }+ },+ "streamEditInterval": {+ "label": "Intervalle de mise à jour du flux"+ },+ "webhookUrl": {+ "label": "URL du webhook"+ },+ "webhookListenHost": {+ "label": "Hôte d'écoute du webhook"+ },+ "webhookListenPort": {+ "label": "Port d'écoute du webhook"+ },+ "webhookPath": {+ "label": "Chemin du webhook"+ },+ "webhookSecretToken": {+ "label": "Jeton secret Webhook"+ },+ "webhookMaxConnections": {+ "label": "Nombre maximal de connexions webhook"}}}diff --git a/nanobot/channels/telegram/webui/locales/id.json b/nanobot/channels/telegram/webui/locales/id.jsonindex 73b6a4b87..049bd7084 100644--- a/nanobot/channels/telegram/webui/locales/id.json+++ b/nanobot/channels/telegram/webui/locales/id.json@@ -1,21 +1,11 @@{- "description": "Mengobrol dengan nanobot dari Telegram.",- "requirements": "Token bot, pengguna yang diizinkan, dan gateway","setup": {"docsLabel": "Buka panduan Telegram","officialLabel": "Buka BotFather",- "tryIt": "Kirim /start atau DM singkat ke bot Telegram Anda.",- "summary": "Tambahkan token bot dari BotFather untuk mengirim dan menerima pesan Telegram.",- "steps": [- "Buat bot dengan BotFather dan salin tokennya.",- "Tambahkan token dan pilih siapa yang boleh mengirim pesan ke bot.",- "Simpan dan aktifkan Telegram, lalu kirim DM atau sebut bot di grup."- ],"fields": {"token": {"label": "Token bot",- "placeholder": "123456:ABC...",- "help": "Buat dengan BotFather."+ "placeholder": "123456:ABC..."},"proxy": {"label": "Proxy jaringan",@@ -23,8 +13,7 @@},"allowFrom": {"label": "Pengguna yang diizinkan",- "placeholder": "* atau ID pengguna Telegram",- "help": "Kosongkan untuk memakai kode pairing."+ "placeholder": "* atau ID pengguna Telegram"},"groupPolicy": {"label": "Perilaku grup",@@ -33,6 +22,71 @@"open": "Semua pesan","allowlist": "Daftar izin"}+ },+ "mode": {+ "label": "Modus koneksi",+ "choices": {+ "polling": "Jajak pendapat yang panjang",+ "webhook": "kait web"+ }+ },+ "replyToMessage": {+ "label": "Membalas pesan",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "reactEmoji": {+ "label": "Baca emoji"+ },+ "connectionPoolSize": {+ "label": "Ukuran kumpulan koneksi"+ },+ "poolTimeout": {+ "label": "Batas waktu kumpulan koneksi habis"+ },+ "streaming": {+ "label": "Streaming",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "inlineKeyboards": {+ "label": "Keyboard sebaris",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "richMessages": {+ "label": "Pesan yang kaya",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }+ },+ "streamEditInterval": {+ "label": "Interval pembaruan aliran"+ },+ "webhookUrl": {+ "label": "URL kait web"+ },+ "webhookListenHost": {+ "label": "Tuan rumah mendengarkan webhook"+ },+ "webhookListenPort": {+ "label": "Port mendengarkan webhook"+ },+ "webhookPath": {+ "label": "Jalur webhook"+ },+ "webhookSecretToken": {+ "label": "Token rahasia webhook"+ },+ "webhookMaxConnections": {+ "label": "Koneksi webhook maksimum"}}}diff --git a/nanobot/channels/telegram/webui/locales/ja.json b/nanobot/channels/telegram/webui/locales/ja.jsonindex 82d283081..e5f6f1e59 100644--- a/nanobot/channels/telegram/webui/locales/ja.json+++ b/nanobot/channels/telegram/webui/locales/ja.json@@ -1,21 +1,11 @@{- "description": "Telegram で nanobot とチャットします。",- "requirements": "ボットトークン、許可するユーザー、ゲートウェイ","setup": {"docsLabel": "Telegram 設定ガイドを開く","officialLabel": "BotFather を開く",- "tryIt": "Telegram ボットに /start または短い DM を送信します。",- "summary": "Telegram でメッセージを送受信するには、BotFather で取得したボットトークンを入力してください。",- "steps": [- "BotFather でボットを作成し、トークンをコピーします。",- "トークンを追加し、ボットに連絡できるユーザーを選びます。",- "保存して Telegram を有効にし、DM を送るかグループでメンションします。"- ],"fields": {"token": {"label": "ボットトークン",- "placeholder": "123456:ABC...",- "help": "BotFather で作成します。"+ "placeholder": "123456:ABC..."},"proxy": {"label": "ネットワークプロキシ",@@ -23,8 +13,7 @@},"allowFrom": {"label": "許可するユーザー",- "placeholder": "* または Telegram ユーザー ID",- "help": "ペアリングコードを使う場合は空欄にします。"+ "placeholder": "* または Telegram ユーザー ID"},"groupPolicy": {"label": "グループでの動作",@@ -33,6 +22,71 @@"open": "すべてのメッセージ","allowlist": "許可リスト"}+ },+ "mode": {+ "label": "接続モード",+ "choices": {+ "polling": "ロングポーリング",+ "webhook": "Webhook"+ }+ },+ "replyToMessage": {+ "label": "メッセージに返信する",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "reactEmoji": {+ "label": "絵文字を読む"+ },+ "connectionPoolSize": {+ "label": "接続プールのサイズ"+ },+ "poolTimeout": {+ "label": "接続プールのタイムアウト"+ },+ "streaming": {+ "label": "ストリーミング",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "inlineKeyboards": {+ "label": "インラインキーボード",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "richMessages": {+ "label": "リッチメッセージ",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }+ },+ "streamEditInterval": {+ "label": "ストリーム更新間隔"+ },+ "webhookUrl": {+ "label": "Webhook URL"+ },+ "webhookListenHost": {+ "label": "Webhook リッスン ホスト"+ },+ "webhookListenPort": {+ "label": "Webhook リッスン ポート"+ },+ "webhookPath": {+ "label": "Webhook パス"+ },+ "webhookSecretToken": {+ "label": "Webhook シークレット トークン"+ },+ "webhookMaxConnections": {+ "label": "Webhook 接続の最大数"}}}diff --git a/nanobot/channels/telegram/webui/locales/ko.json b/nanobot/channels/telegram/webui/locales/ko.jsonindex 66d66cc5b..d148fe437 100644--- a/nanobot/channels/telegram/webui/locales/ko.json+++ b/nanobot/channels/telegram/webui/locales/ko.json@@ -1,21 +1,11 @@{- "description": "Telegram 채팅에서 nanobot과 대화합니다.",- "requirements": "봇 토큰, 허용된 사용자 및 게이트웨이","setup": {"docsLabel": "Telegram 설정 가이드 열기","officialLabel": "BotFather 열기",- "tryIt": "Telegram 봇에 /start 또는 짧은 DM을 보내세요.",- "summary": "Telegram 메시지를 주고받으려면 BotFather에서 발급받은 봇 토큰을 입력하세요.",- "steps": [- "BotFather로 봇을 만들고 토큰을 복사하세요.",- "토큰을 추가하고 봇에 메시지를 보낼 사용자를 선택하세요.",- "저장하고 Telegram을 활성화한 다음 DM을 보내거나 그룹에서 멘션하세요."- ],"fields": {"token": {"label": "봇 토큰",- "placeholder": "123456:ABC...",- "help": "BotFather에서 생성하세요."+ "placeholder": "123456:ABC..."},"proxy": {"label": "네트워크 프록시",@@ -23,8 +13,7 @@},"allowFrom": {"label": "허용된 사용자",- "placeholder": "* 또는 Telegram 사용자 ID",- "help": "페어링 코드를 사용하려면 비워 두세요."+ "placeholder": "* 또는 Telegram 사용자 ID"},"groupPolicy": {"label": "그룹 동작",@@ -33,6 +22,71 @@"open": "모든 메시지","allowlist": "허용 목록"}+ },+ "mode": {+ "label": "연결 모드",+ "choices": {+ "polling": "긴 폴링",+ "webhook": "웹훅"+ }+ },+ "replyToMessage": {+ "label": "메시지에 답장하기",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "reactEmoji": {+ "label": "이모티콘 읽기"+ },+ "connectionPoolSize": {+ "label": "연결 풀 크기"+ },+ "poolTimeout": {+ "label": "연결 풀 시간 초과"+ },+ "streaming": {+ "label": "스트리밍",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "inlineKeyboards": {+ "label": "인라인 키보드",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "richMessages": {+ "label": "리치 메시지",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }+ },+ "streamEditInterval": {+ "label": "스트림 업데이트 간격"+ },+ "webhookUrl": {+ "label": "웹훅 URL"+ },+ "webhookListenHost": {+ "label": "웹훅 청취 호스트"+ },+ "webhookListenPort": {+ "label": "웹훅 수신 포트"+ },+ "webhookPath": {+ "label": "웹훅 경로"+ },+ "webhookSecretToken": {+ "label": "웹훅 비밀 토큰"+ },+ "webhookMaxConnections": {+ "label": "최대 웹훅 연결"}}}diff --git a/nanobot/channels/telegram/webui/locales/pt-BR.json b/nanobot/channels/telegram/webui/locales/pt-BR.jsonindex 7db3344d3..9a5505450 100644--- a/nanobot/channels/telegram/webui/locales/pt-BR.json+++ b/nanobot/channels/telegram/webui/locales/pt-BR.json@@ -1,21 +1,11 @@{- "description": "Converse com o nanobot pelo Telegram.",- "requirements": "Token do bot, usuários permitidos e gateway","setup": {"docsLabel": "Abrir guia do Telegram","officialLabel": "Abrir BotFather",- "tryIt": "Envie /start ou uma DM curta ao seu bot do Telegram.",- "summary": "Adicione o token de bot obtido no BotFather para enviar e receber mensagens do Telegram.",- "steps": [- "Crie um bot com o BotFather e copie o token.",- "Adicione o token e escolha quem pode enviar mensagens ao bot.",- "Salve e ative o Telegram; depois, envie uma DM ou mencione o bot em um grupo."- ],"fields": {"token": {"label": "Token do bot",- "placeholder": "123456:ABC...",- "help": "Crie-o com o BotFather."+ "placeholder": "123456:ABC..."},"proxy": {"label": "Proxy de rede",@@ -23,8 +13,7 @@},"allowFrom": {"label": "Usuários permitidos",- "placeholder": "* ou IDs de usuário do Telegram",- "help": "Deixe vazio para usar códigos de pareamento."+ "placeholder": "* ou IDs de usuário do Telegram"},"groupPolicy": {"label": "Comportamento em grupos",@@ -33,6 +22,71 @@"open": "Todas as mensagens","allowlist": "Lista de permissão"}+ },+ "mode": {+ "label": "Modo de conexão",+ "choices": {+ "polling": "Votação longa",+ "webhook": "Webhook"+ }+ },+ "replyToMessage": {+ "label": "Responder à mensagem",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "reactEmoji": {+ "label": "Ler emoticons"+ },+ "connectionPoolSize": {+ "label": "Tamanho do pool de conexões"+ },+ "poolTimeout": {+ "label": "Tempo limite do pool de conexões"+ },+ "streaming": {+ "label": "Transmissão",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "inlineKeyboards": {+ "label": "Teclados embutidos",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "richMessages": {+ "label": "Mensagens ricas",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }+ },+ "streamEditInterval": {+ "label": "Intervalo de atualização de fluxo"+ },+ "webhookUrl": {+ "label": "URL do webhook"+ },+ "webhookListenHost": {+ "label": "Host de escuta do webhook"+ },+ "webhookListenPort": {+ "label": "Porta de escuta do webhook"+ },+ "webhookPath": {+ "label": "Caminho do webhook"+ },+ "webhookSecretToken": {+ "label": "Token secreto do webhook"+ },+ "webhookMaxConnections": {+ "label": "Máximo de conexões de webhook"}}}diff --git a/nanobot/channels/telegram/webui/locales/vi.json b/nanobot/channels/telegram/webui/locales/vi.jsonindex 3431b5223..71a28c498 100644--- a/nanobot/channels/telegram/webui/locales/vi.json+++ b/nanobot/channels/telegram/webui/locales/vi.json@@ -1,21 +1,11 @@{- "description": "Trò chuyện với nanobot từ Telegram.",- "requirements": "Token bot, người dùng được phép và gateway","setup": {"docsLabel": "Mở hướng dẫn Telegram","officialLabel": "Mở BotFather",- "tryIt": "Gửi /start hoặc tin nhắn riêng ngắn đến bot Telegram.",- "summary": "Thêm token bot lấy từ BotFather để gửi và nhận tin nhắn Telegram.",- "steps": [- "Tạo bot bằng BotFather và sao chép token.",- "Thêm token và chọn người có thể nhắn cho bot.",- "Lưu và bật Telegram, sau đó gửi tin nhắn riêng hoặc nhắc bot trong nhóm."- ],"fields": {"token": {"label": "Token bot",- "placeholder": "123456:ABC...",- "help": "Tạo bằng BotFather."+ "placeholder": "123456:ABC..."},"proxy": {"label": "Proxy mạng",@@ -23,8 +13,7 @@},"allowFrom": {"label": "Người dùng được phép",- "placeholder": "* hoặc ID người dùng Telegram",- "help": "Để trống để dùng mã ghép nối."+ "placeholder": "* hoặc ID người dùng Telegram"},"groupPolicy": {"label": "Hành vi trong nhóm",@@ -33,6 +22,71 @@"open": "Mọi tin nhắn","allowlist": "Danh sách cho phép"}+ },+ "mode": {+ "label": "Chế độ kết nối",+ "choices": {+ "polling": "Bỏ phiếu dài",+ "webhook": "Webhook"+ }+ },+ "replyToMessage": {+ "label": "Trả lời tin nhắn",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "reactEmoji": {+ "label": "Đọc biểu tượng cảm xúc"+ },+ "connectionPoolSize": {+ "label": "Kích thước nhóm kết nối"+ },+ "poolTimeout": {+ "label": "Hết thời gian chờ nhóm kết nối"+ },+ "streaming": {+ "label": "Truyền phát",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "inlineKeyboards": {+ "label": "Bàn phím nội tuyến",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "richMessages": {+ "label": "Tin nhắn phong phú",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }+ },+ "streamEditInterval": {+ "label": "Khoảng thời gian cập nhật luồng"+ },+ "webhookUrl": {+ "label": "URL webhook"+ },+ "webhookListenHost": {+ "label": "Máy chủ lắng nghe Webhook"+ },+ "webhookListenPort": {+ "label": "Cổng nghe Webhook"+ },+ "webhookPath": {+ "label": "Đường dẫn webhook"+ },+ "webhookSecretToken": {+ "label": "Mã thông báo bí mật Webhook"+ },+ "webhookMaxConnections": {+ "label": "Kết nối webhook tối đa"}}}diff --git a/nanobot/channels/telegram/webui/locales/zh-CN.json b/nanobot/channels/telegram/webui/locales/zh-CN.jsonindex c8e80ef62..64962d355 100644--- a/nanobot/channels/telegram/webui/locales/zh-CN.json+++ b/nanobot/channels/telegram/webui/locales/zh-CN.json@@ -1,21 +1,11 @@{- "description": "在 Telegram 中与 nanobot 聊天。",- "requirements": "机器人令牌、允许的用户和网关","setup": {"docsLabel": "打开 Telegram 配置指南","officialLabel": "打开 BotFather",- "tryIt": "向 Telegram 机器人发送 /start 或一条简短私信。",- "summary": "填写从 BotFather 获取的机器人令牌后,即可收发 Telegram 消息。",- "steps": [- "使用 BotFather 创建机器人并复制令牌。",- "填写令牌并选择哪些用户可以向机器人发送消息。",- "保存并启用 Telegram,然后向机器人发送私信或在群组中提及它。"- ],"fields": {"token": {"label": "机器人令牌",- "placeholder": "123456:ABC...",- "help": "使用 BotFather 创建。"+ "placeholder": "123456:ABC..."},"proxy": {"label": "网络代理",@@ -23,8 +13,7 @@},"allowFrom": {"label": "允许的用户",- "placeholder": "* 或 Telegram 用户 ID",- "help": "留空则使用配对码。"+ "placeholder": "* 或 Telegram 用户 ID"},"groupPolicy": {"label": "群组行为",@@ -33,6 +22,71 @@"open": "所有消息","allowlist": "白名单"}+ },+ "mode": {+ "label": "连接方式",+ "choices": {+ "polling": "长轮询",+ "webhook": "Webhook"+ }+ },+ "replyToMessage": {+ "label": "引用回复",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "reactEmoji": {+ "label": "已读表情"+ },+ "connectionPoolSize": {+ "label": "连接池大小"+ },+ "poolTimeout": {+ "label": "连接池超时"+ },+ "streaming": {+ "label": "流式输出",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "inlineKeyboards": {+ "label": "内联键盘",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "richMessages": {+ "label": "富文本消息",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }+ },+ "streamEditInterval": {+ "label": "流式更新间隔"+ },+ "webhookUrl": {+ "label": "Webhook 地址"+ },+ "webhookListenHost": {+ "label": "Webhook 监听地址"+ },+ "webhookListenPort": {+ "label": "Webhook 监听端口"+ },+ "webhookPath": {+ "label": "Webhook 路径"+ },+ "webhookSecretToken": {+ "label": "Webhook 密钥"+ },+ "webhookMaxConnections": {+ "label": "Webhook 最大连接数"}}}diff --git a/nanobot/channels/telegram/webui/locales/zh-TW.json b/nanobot/channels/telegram/webui/locales/zh-TW.jsonindex 6aeb9b3a8..e759698bb 100644--- a/nanobot/channels/telegram/webui/locales/zh-TW.json+++ b/nanobot/channels/telegram/webui/locales/zh-TW.json@@ -1,21 +1,11 @@{- "description": "在 Telegram 中與 nanobot 聊天。",- "requirements": "機器人權杖、允許的使用者和閘道","setup": {"docsLabel": "開啟 Telegram 設定指南","officialLabel": "開啟 BotFather",- "tryIt": "向 Telegram 機器人傳送 /start 或一則簡短私訊。",- "summary": "填入從 BotFather 取得的機器人權杖,才能收發 Telegram 訊息。",- "steps": [- "使用 BotFather 建立機器人並複製權杖。",- "填入權杖並選擇哪些使用者可以向機器人傳送訊息。",- "儲存並啟用 Telegram,然後傳送私訊或在群組中提及機器人。"- ],"fields": {"token": {"label": "機器人權杖",- "placeholder": "123456:ABC...",- "help": "使用 BotFather 建立。"+ "placeholder": "123456:ABC..."},"proxy": {"label": "網路代理",@@ -23,8 +13,7 @@},"allowFrom": {"label": "允許的使用者",- "placeholder": "* 或 Telegram 使用者 ID",- "help": "留空則使用配對碼。"+ "placeholder": "* 或 Telegram 使用者 ID"},"groupPolicy": {"label": "群組行為",@@ -33,6 +22,71 @@"open": "所有訊息","allowlist": "允許清單"}+ },+ "mode": {+ "label": "連接方式",+ "choices": {+ "polling": "長輪詢",+ "webhook": "Webhook"+ }+ },+ "replyToMessage": {+ "label": "引用回覆",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "reactEmoji": {+ "label": "已讀表情"+ },+ "connectionPoolSize": {+ "label": "連線池大小"+ },+ "poolTimeout": {+ "label": "連接池逾時"+ },+ "streaming": {+ "label": "串流輸出",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "inlineKeyboards": {+ "label": "內聯鍵盤",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "richMessages": {+ "label": "富文本訊息",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }+ },+ "streamEditInterval": {+ "label": "串流更新間隔"+ },+ "webhookUrl": {+ "label": "Webhook 地址"+ },+ "webhookListenHost": {+ "label": "Webhook 監聽地址"+ },+ "webhookListenPort": {+ "label": "Webhook 監聽端口"+ },+ "webhookPath": {+ "label": "Webhook 路徑"+ },+ "webhookSecretToken": {+ "label": "Webhook 密鑰"+ },+ "webhookMaxConnections": {+ "label": "Webhook 最大連線數"}}}diff --git a/nanobot/channels/validation.py b/nanobot/channels/validation.pyindex 661664ca1..4432ffdee 100644--- a/nanobot/channels/validation.py+++ b/nanobot/channels/validation.py@@ -135,9 +135,9 @@ def _merge_form_values(if not raw_key:continuefield = raw_key[len(prefix):] if raw_key.startswith(prefix) else raw_key- if field in secrets and not _str(raw_value):+ if field in secrets and raw_value is not None and not _str(raw_value):continue- _assign(merged, field, raw_value)+ _assign(merged, field, "" if field in secrets and raw_value is None else raw_value)return merged@@ -341,16 +341,30 @@ def _message_from_response(data: dict[str, Any], fallback: str) -> str:return str(error) if error else fallback-def _http_get(url: str, *, headers: dict[str, str] | None = None) -> dict[str, Any]:- with httpx.Client(timeout=_TIMEOUT_SECONDS) as client:+def _http_get(+ url: str,+ *,+ headers: dict[str, str] | None = None,+ proxy: str | None = None,+) -> dict[str, Any]:+ if proxy and "://" not in proxy:+ proxy = f"http://{proxy}"+ with httpx.Client(timeout=_TIMEOUT_SECONDS, proxy=proxy) as client:response = client.get(url, headers=headers)response.raise_for_status()data = response.json()return cast(dict[str, Any], data) if isinstance(data, dict) else {}-def _http_post(url: str, *, headers: dict[str, str] | None = None) -> dict[str, Any]:- with httpx.Client(timeout=_TIMEOUT_SECONDS) as client:+def _http_post(+ url: str,+ *,+ headers: dict[str, str] | None = None,+ proxy: str | None = None,+) -> dict[str, Any]:+ if proxy and "://" not in proxy:+ proxy = f"http://{proxy}"+ with httpx.Client(timeout=_TIMEOUT_SECONDS, proxy=proxy) as client:response = client.post(url, headers=headers)response.raise_for_status()data = response.json()diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.pyindex 72ea672ed..9c61e051b 100644--- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py+++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py@@ -1344,6 +1344,67 @@ async def test_nanobot_feature_channel_action_can_apply_without_restart(assert body["last_action"]["message"].endswith("Matrix channel applied without restart.")+async def test_nanobot_feature_install_only_does_not_start_channel(+ bus: MagicMock,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ runtime_calls: list[tuple[str, str, str | None]] = []++ def feature_action(+ action: str,+ query: dict[str, list[str]],+ *,+ allow_install: bool,+ config_path: Path,+ ) -> dict[str, Any]:+ assert action == "enable"+ assert query == {"name": ["whatsapp"], "install_only": ["true"]}+ assert allow_install is True+ return {+ "features": [{+ "name": "whatsapp",+ "type": "channel",+ "enabled": False,+ "installed": True,+ "ready": False,+ "status": "not_enabled",+ }],+ "enabled_count": 0,+ "requires_restart": False,+ }++ async def channel_feature_action(+ action: str,+ name: str,+ instance_id: str | None,+ ) -> dict[str, Any]:+ runtime_calls.append((action, name, instance_id))+ return {"handled": True, "ok": True, "requires_restart": False}++ monkeypatch.setattr(+ "nanobot.webui.settings_routes.nanobot_features_action",+ feature_action,+ )+ channel = _ch(+ bus,+ session_manager=_seed_session(tmp_path),+ port=_free_port(),+ channel_feature_action=channel_feature_action,+ )++ response = await _webui_mutate(+ channel,+ "settings.feature.enable",+ {"name": "whatsapp", "install_only": True},+ )++ assert response.status_code == 200+ assert runtime_calls == []+ assert response.json()["features"][0]["enabled"] is False++@pytest.mark.asyncioasync def test_channel_connect_runtime_import_error_is_not_reported_as_unsupported(bus: MagicMock,diff --git a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.pyindex f0a23a902..feee6e51f 100644--- a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py+++ b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport asyncioimport errno-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport pytest@@ -44,6 +44,7 @@ class _FakeServer:def _channel() -> WebSocketChannel:gateway = MagicMock()gateway.session_manager = None+ gateway.http.settings_routes.close = AsyncMock()return WebSocketChannel({"enabled": True, "allowFrom": ["*"]},MessageBus(),diff --git a/nanobot/channels/websocket/webui/WebSocketIcon.tsx b/nanobot/channels/websocket/webui/WebSocketIcon.tsxnew file mode 100644index 000000000..64133cb78--- /dev/null+++ b/nanobot/channels/websocket/webui/WebSocketIcon.tsx@@ -0,0 +1,5 @@+export function WebSocketIcon() {+ return (+ <img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6 object-contain" draggable={false} />+ );+}diff --git a/nanobot/channels/websocket/webui/index.ts b/nanobot/channels/websocket/webui/index.tsindex 94f9509c2..ef055a513 100644--- a/nanobot/channels/websocket/webui/index.ts+++ b/nanobot/channels/websocket/webui/index.ts@@ -1,14 +1,14 @@-import { Network } from "lucide-react";-import type { ChannelUiContribution } from "@/channel-plugins/types";import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { WebSocketIcon } from "./WebSocketIcon";+export default {presentation: {- displayName: "WebSocket",+ displayName: "nanobot WebUI",initials: "WS",color: "#111827",- icon: Network,+ icon: WebSocketIcon,setup: {mode: "webui",docsUrl: chatAppGuideUrl("websocket"),diff --git a/nanobot/channels/websocket/webui/locales/en.json b/nanobot/channels/websocket/webui/locales/en.jsonindex cd21b2168..ddd3e7621 100644--- a/nanobot/channels/websocket/webui/locales/en.json+++ b/nanobot/channels/websocket/webui/locales/en.json@@ -1,15 +1,6 @@{- "description": "Use nanobot in your browser.",- "requirements": "Local gateway, WebSocket token","setup": {"docsLabel": "Open WebSocket setup",- "officialLabel": "Open local WebUI",- "tryIt": "Open the WebUI and send a short message.",- "summary": "The WebUI connects to nanobot over WebSocket. Running nanobot webui sets up this connection automatically.",- "steps": [- "Start nanobot with the webui command.",- "Open the local URL printed in the terminal.",- "Keep WebSocket enabled while using the browser workbench."- ]+ "officialLabel": "Open local WebUI"}}diff --git a/nanobot/channels/websocket/webui/locales/es.json b/nanobot/channels/websocket/webui/locales/es.jsonindex 6cb377203..3de5638c2 100644--- a/nanobot/channels/websocket/webui/locales/es.json+++ b/nanobot/channels/websocket/webui/locales/es.json@@ -1,15 +1,6 @@{- "description": "Usa nanobot en tu navegador.",- "requirements": "Pasarela local y token WebSocket","setup": {"docsLabel": "Abrir guía de WebSocket",- "officialLabel": "Abrir WebUI local",- "tryIt": "Abre la WebUI y envía un mensaje corto.",- "summary": "La WebUI se conecta a nanobot mediante WebSocket. El comando nanobot webui configura esta conexión automáticamente.",- "steps": [- "Inicia nanobot con el comando webui.",- "Abre la URL local mostrada en la terminal.",- "Mantén WebSocket activado mientras uses la WebUI."- ]+ "officialLabel": "Abrir WebUI local"}}diff --git a/nanobot/channels/websocket/webui/locales/fr.json b/nanobot/channels/websocket/webui/locales/fr.jsonindex 1bbf5aeed..6dca17f13 100644--- a/nanobot/channels/websocket/webui/locales/fr.json+++ b/nanobot/channels/websocket/webui/locales/fr.json@@ -1,15 +1,6 @@{- "description": "Utilisez nanobot dans votre navigateur.",- "requirements": "Passerelle locale et jeton WebSocket","setup": {"docsLabel": "Ouvrir le guide WebSocket",- "officialLabel": "Ouvrir la WebUI locale",- "tryIt": "Ouvrez la WebUI et envoyez un court message.",- "summary": "La WebUI se connecte à nanobot via WebSocket. La commande nanobot webui configure automatiquement cette connexion.",- "steps": [- "Démarrez nanobot avec la commande webui.",- "Ouvrez l’URL locale affichée dans le terminal.",- "Gardez WebSocket activé pendant l’utilisation de la WebUI."- ]+ "officialLabel": "Ouvrir la WebUI locale"}}diff --git a/nanobot/channels/websocket/webui/locales/id.json b/nanobot/channels/websocket/webui/locales/id.jsonindex d0407626b..dd91c4272 100644--- a/nanobot/channels/websocket/webui/locales/id.json+++ b/nanobot/channels/websocket/webui/locales/id.json@@ -1,15 +1,6 @@{- "description": "Gunakan nanobot di browser Anda.",- "requirements": "Gateway lokal dan token WebSocket","setup": {"docsLabel": "Buka panduan WebSocket",- "officialLabel": "Buka WebUI lokal",- "tryIt": "Buka WebUI dan kirim pesan singkat.",- "summary": "WebUI terhubung ke nanobot melalui WebSocket. Perintah nanobot webui menyiapkan koneksi ini secara otomatis.",- "steps": [- "Mulai nanobot dengan perintah webui.",- "Buka URL lokal yang ditampilkan di terminal.",- "Biarkan WebSocket aktif selama menggunakan WebUI."- ]+ "officialLabel": "Buka WebUI lokal"}}diff --git a/nanobot/channels/websocket/webui/locales/ja.json b/nanobot/channels/websocket/webui/locales/ja.jsonindex b8fcf1dd7..5290e1fee 100644--- a/nanobot/channels/websocket/webui/locales/ja.json+++ b/nanobot/channels/websocket/webui/locales/ja.json@@ -1,15 +1,6 @@{- "description": "ブラウザーで nanobot を利用します。",- "requirements": "ローカルゲートウェイと WebSocket トークン","setup": {"docsLabel": "WebSocket 設定ガイドを開く",- "officialLabel": "ローカル WebUI を開く",- "tryIt": "WebUI を開き、短いメッセージを送信します。",- "summary": "WebUI は WebSocket 経由で nanobot に接続します。nanobot webui コマンドを実行すると、この接続が自動で設定されます。",- "steps": [- "webui コマンドで nanobot を起動します。",- "ターミナルに表示されたローカル URL を開きます。",- "WebUI の使用中は WebSocket を有効にしておいてください。"- ]+ "officialLabel": "ローカル WebUI を開く"}}diff --git a/nanobot/channels/websocket/webui/locales/ko.json b/nanobot/channels/websocket/webui/locales/ko.jsonindex 47737c9e4..da2beb669 100644--- a/nanobot/channels/websocket/webui/locales/ko.json+++ b/nanobot/channels/websocket/webui/locales/ko.json@@ -1,15 +1,6 @@{- "description": "브라우저에서 nanobot을 사용합니다.",- "requirements": "로컬 게이트웨이 및 WebSocket 토큰","setup": {"docsLabel": "WebSocket 설정 가이드 열기",- "officialLabel": "로컬 WebUI 열기",- "tryIt": "WebUI를 열고 짧은 메시지를 보내세요.",- "summary": "WebUI는 WebSocket으로 nanobot에 연결됩니다. nanobot webui 명령을 실행하면 이 연결이 자동으로 설정됩니다.",- "steps": [- "webui 명령으로 nanobot을 시작하세요.",- "터미널에 표시된 로컬 URL을 여세요.",- "WebUI를 사용하는 동안 WebSocket을 활성화해 두세요."- ]+ "officialLabel": "로컬 WebUI 열기"}}diff --git a/nanobot/channels/websocket/webui/locales/pt-BR.json b/nanobot/channels/websocket/webui/locales/pt-BR.jsonindex 6ccc23aef..37bf12db5 100644--- a/nanobot/channels/websocket/webui/locales/pt-BR.json+++ b/nanobot/channels/websocket/webui/locales/pt-BR.json@@ -1,15 +1,6 @@{- "description": "Use o nanobot no navegador.",- "requirements": "Gateway local e token WebSocket","setup": {"docsLabel": "Abrir guia do WebSocket",- "officialLabel": "Abrir WebUI local",- "tryIt": "Abra a WebUI e envie uma mensagem curta.",- "summary": "A WebUI se conecta ao nanobot por WebSocket. O comando nanobot webui configura essa conexão automaticamente.",- "steps": [- "Inicie o nanobot com o comando webui.",- "Abra a URL local exibida no terminal.",- "Mantenha o WebSocket ativado enquanto usa a WebUI."- ]+ "officialLabel": "Abrir WebUI local"}}diff --git a/nanobot/channels/websocket/webui/locales/vi.json b/nanobot/channels/websocket/webui/locales/vi.jsonindex ee2892da1..560c9e9f8 100644--- a/nanobot/channels/websocket/webui/locales/vi.json+++ b/nanobot/channels/websocket/webui/locales/vi.json@@ -1,15 +1,6 @@{- "description": "Sử dụng nanobot trong trình duyệt.",- "requirements": "Gateway cục bộ và token WebSocket","setup": {"docsLabel": "Mở hướng dẫn WebSocket",- "officialLabel": "Mở WebUI cục bộ",- "tryIt": "Mở WebUI và gửi một tin nhắn ngắn.",- "summary": "WebUI kết nối với nanobot qua WebSocket. Lệnh nanobot webui tự động thiết lập kết nối này.",- "steps": [- "Khởi động nanobot bằng lệnh webui.",- "Mở URL cục bộ hiển thị trong terminal.",- "Giữ WebSocket bật khi sử dụng WebUI."- ]+ "officialLabel": "Mở WebUI cục bộ"}}diff --git a/nanobot/channels/websocket/webui/locales/zh-CN.json b/nanobot/channels/websocket/webui/locales/zh-CN.jsonindex 1fbda6f36..2ea487125 100644--- a/nanobot/channels/websocket/webui/locales/zh-CN.json+++ b/nanobot/channels/websocket/webui/locales/zh-CN.json@@ -1,15 +1,6 @@{- "description": "在浏览器中使用 nanobot。",- "requirements": "本地网关和 WebSocket 令牌","setup": {"docsLabel": "打开 WebSocket 配置指南",- "officialLabel": "打开本地 WebUI",- "tryIt": "打开 WebUI 并发送一条简短消息。",- "summary": "WebUI 通过 WebSocket 连接 nanobot。运行 nanobot webui 时会自动配置此连接。",- "steps": [- "使用 webui 命令启动 nanobot。",- "打开终端中显示的本地地址。",- "使用浏览器工作台期间请保持 WebSocket 启用。"- ]+ "officialLabel": "打开本地 WebUI"}}diff --git a/nanobot/channels/websocket/webui/locales/zh-TW.json b/nanobot/channels/websocket/webui/locales/zh-TW.jsonindex cd6ca63d8..f57999647 100644--- a/nanobot/channels/websocket/webui/locales/zh-TW.json+++ b/nanobot/channels/websocket/webui/locales/zh-TW.json@@ -1,15 +1,6 @@{- "description": "在瀏覽器中使用 nanobot。",- "requirements": "本機閘道和 WebSocket 權杖","setup": {"docsLabel": "開啟 WebSocket 設定指南",- "officialLabel": "開啟本機 WebUI",- "tryIt": "開啟 WebUI 並傳送一則簡短訊息。",- "summary": "WebUI 透過 WebSocket 連接 nanobot。執行 nanobot webui 時會自動設定此連線。",- "steps": [- "使用 webui 指令啟動 nanobot。",- "開啟終端機中顯示的本機網址。",- "使用 WebUI 時,請保持 WebSocket 啟用。"- ]+ "officialLabel": "開啟本機 WebUI"}}diff --git a/nanobot/channels/wecom/manifest.py b/nanobot/channels/wecom/manifest.pyindex f56d12d3d..208964068 100644--- a/nanobot/channels/wecom/manifest.py+++ b/nanobot/channels/wecom/manifest.py@@ -9,6 +9,7 @@ SETUP_SPEC = ChannelSetupSpec("botId": field(),"secret": field("secret"),"allowFrom": field("list"),+ "welcomeMessage": field(),},required=required_fields("botId", "secret"),official_url="https://developer.work.weixin.qq.com/",diff --git a/nanobot/channels/wecom/runtime.py b/nanobot/channels/wecom/runtime.pyindex 8ce5b8cda..3fa4fb186 100644--- a/nanobot/channels/wecom/runtime.py+++ b/nanobot/channels/wecom/runtime.py@@ -20,6 +20,7 @@ from nanobot.config.paths import get_media_dirfrom nanobot.config.schema import BaseWECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None+WECOM_WEBSOCKET_HOST = "openws.work.weixin.qq.com"# Inbound media safety limit (matching QQ channel defaults)WECOM_DOWNLOAD_MAX_BYTES = 1024 * 1024 * 200 # 200MB@@ -28,6 +29,14 @@ WECOM_DOWNLOAD_MAX_BYTES = 1024 * 1024 * 200 # 200MB_SAFE_NAME_RE = re.compile(r"[^\w.\-()\[\]()【】\u4e00-\u9fff]+", re.UNICODE)+def _bypass_system_proxy(host: str) -> None:+ """Keep the WeCom SDK's WebSocket on its direct connection path."""+ for key in ("NO_PROXY", "no_proxy"):+ entries = [entry.strip() for entry in os.environ.get(key, "").split(",") if entry.strip()]+ if host not in entries:+ os.environ[key] = ",".join([*entries, host])++def _sanitize_filename(name: str, fallback: str = "unnamed") -> str:"""Sanitize filename to avoid traversal and problematic chars."""def _clean(value: str) -> str:@@ -96,6 +105,10 @@ class WecomChannel(BaseChannel):self.logger.error("bot_id and secret not configured")return+ # websockets 15+ automatically uses the system proxy. The current WeCom SDK+ # doesn't expose its proxy argument and expects this endpoint to connect directly.+ _bypass_system_proxy(WECOM_WEBSOCKET_HOST)+from wecom_aibot_sdk import WSClient, generate_req_idself._running = Truediff --git a/nanobot/channels/wecom/tests/test_wecom_channel.py b/nanobot/channels/wecom/tests/test_wecom_channel.pyindex 41e9b0280..c0bf4b80e 100644--- a/nanobot/channels/wecom/tests/test_wecom_channel.py+++ b/nanobot/channels/wecom/tests/test_wecom_channel.py@@ -23,8 +23,10 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.wecom.runtime import (+ WECOM_WEBSOCKET_HOST,WecomChannel,WecomConfig,+ _bypass_system_proxy,_sanitize_filename,)@@ -58,6 +60,20 @@ def test_sdk_exposes_media_upload_api() -> None:assert callable(WSClient.upload_media)+def test_wecom_websocket_bypasses_system_proxy(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("NO_PROXY", "localhost,127.0.0.1")++ _bypass_system_proxy(WECOM_WEBSOCKET_HOST)+ _bypass_system_proxy(WECOM_WEBSOCKET_HOST)++ assert os.environ["NO_PROXY"].split(",") == [+ "localhost",+ "127.0.0.1",+ WECOM_WEBSOCKET_HOST,+ ]+ assert os.environ["no_proxy"].split(",").count(WECOM_WEBSOCKET_HOST) == 1++def test_sanitize_filename_strips_path_traversal() -> None:assert _sanitize_filename("../../etc/passwd") == "passwd"diff --git a/nanobot/channels/wecom/webui/index.ts b/nanobot/channels/wecom/webui/index.tsindex cddc80479..d8829be7a 100644--- a/nanobot/channels/wecom/webui/index.ts+++ b/nanobot/channels/wecom/webui/index.ts@@ -3,17 +3,17 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog";export default {presentation: {+ logoUrl: "https://work.weixin.qq.com/favicon.ico",displayName: "WeCom",initials: "WC",color: "#2F7DFF",- logoUrl: "https://work.weixin.qq.com/favicon.ico",setup: {mode: "credentials",docsUrl: chatAppGuideUrl("wecom"),fields: [- { key: "channels.wecom.botId" },- { key: "channels.wecom.secret" },- { key: "channels.wecom.allowFrom" },+ { key: "channels.wecom.botId", section: "credentials" },+ { key: "channels.wecom.secret", section: "credentials" },+ { key: "channels.wecom.allowFrom", section: "access" },],},},diff --git a/nanobot/channels/wecom/webui/locales/en.json b/nanobot/channels/wecom/webui/locales/en.jsonindex 739c4129f..eb1dc779a 100644--- a/nanobot/channels/wecom/webui/locales/en.json+++ b/nanobot/channels/wecom/webui/locales/en.json@@ -1,30 +1,22 @@{- "description": "Use nanobot from WeCom work chats.",- "requirements": "WeCom AI bot ID and secret","setup": {"docsLabel": "Open WeCom setup","officialLabel": "Open WeCom console",- "tryIt": "Send a test message to the WeCom bot.",- "summary": "WeCom needs an AI bot ID and secret from the WeCom admin console.",- "steps": [- "Create an AI bot in WeCom and choose API mode.",- "Copy the Bot ID and Secret into nanobot.",- "Save and enable WeCom, then send a test message."- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "WeCom bot ID",- "help": "Copy it from the WeCom AI Bot API mode page."+ "placeholder": "WeCom bot ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Keep the WeCom bot secret private."+ "placeholder": "••••••"},"allowFrom": {"label": "Allowed users","placeholder": "User IDs, comma separated"+ },+ "welcomeMessage": {+ "label": "Welcome message"}}}diff --git a/nanobot/channels/wecom/webui/locales/es.json b/nanobot/channels/wecom/webui/locales/es.jsonindex cfec1bd41..e53ea1119 100644--- a/nanobot/channels/wecom/webui/locales/es.json+++ b/nanobot/channels/wecom/webui/locales/es.json@@ -1,30 +1,22 @@{- "description": "Usa nanobot desde chats de trabajo de WeCom.",- "requirements": "Bot ID y Secret del bot de IA de WeCom","setup": {"docsLabel": "Abrir guía de WeCom","officialLabel": "Abrir consola de WeCom",- "tryIt": "Envía un mensaje de prueba al bot de WeCom.",- "summary": "WeCom necesita el ID y el secreto de un bot de IA desde la consola de administración.",- "steps": [- "Crea un bot de IA en WeCom y elige el modo API.",- "Copia el Bot ID y el Secret en nanobot.",- "Guarda y activa WeCom; después envía un mensaje de prueba."- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "Bot ID de WeCom",- "help": "Cópialo de la página del modo API del bot de IA de WeCom."+ "placeholder": "Bot ID de WeCom"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Mantén privado el secreto del bot de WeCom."+ "placeholder": "••••••"},"allowFrom": {"label": "Usuarios permitidos","placeholder": "ID de usuario separados por comas"+ },+ "welcomeMessage": {+ "label": "Mensaje de bienvenida"}}}diff --git a/nanobot/channels/wecom/webui/locales/fr.json b/nanobot/channels/wecom/webui/locales/fr.jsonindex 898f05633..aaf4c85ef 100644--- a/nanobot/channels/wecom/webui/locales/fr.json+++ b/nanobot/channels/wecom/webui/locales/fr.json@@ -1,30 +1,22 @@{- "description": "Utilisez nanobot dans les conversations professionnelles WeCom.",- "requirements": "Bot ID et Secret du bot IA WeCom","setup": {"docsLabel": "Ouvrir le guide WeCom","officialLabel": "Ouvrir la console WeCom",- "tryIt": "Envoyez un message test au bot WeCom.",- "summary": "WeCom nécessite l’ID et le secret d’un bot IA depuis la console d’administration.",- "steps": [- "Créez un bot IA dans WeCom et choisissez le mode API.",- "Copiez le Bot ID et le Secret dans nanobot.",- "Enregistrez et activez WeCom, puis envoyez un message test."- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "Bot ID WeCom",- "help": "Copiez-le depuis la page du mode API du bot IA WeCom."+ "placeholder": "Bot ID WeCom"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Gardez le secret du bot WeCom confidentiel."+ "placeholder": "••••••"},"allowFrom": {"label": "Utilisateurs autorisés","placeholder": "ID utilisateur séparés par des virgules"+ },+ "welcomeMessage": {+ "label": "Message de bienvenue"}}}diff --git a/nanobot/channels/wecom/webui/locales/id.json b/nanobot/channels/wecom/webui/locales/id.jsonindex 06d077148..ca511e3f8 100644--- a/nanobot/channels/wecom/webui/locales/id.json+++ b/nanobot/channels/wecom/webui/locales/id.json@@ -1,30 +1,22 @@{- "description": "Gunakan nanobot dari chat kerja WeCom.",- "requirements": "Bot ID dan Secret bot AI WeCom","setup": {"docsLabel": "Buka panduan WeCom","officialLabel": "Buka konsol WeCom",- "tryIt": "Kirim pesan uji ke bot WeCom.",- "summary": "WeCom memerlukan ID dan secret bot AI dari konsol admin.",- "steps": [- "Buat bot AI di WeCom dan pilih mode API.",- "Salin Bot ID dan Secret ke nanobot.",- "Simpan dan aktifkan WeCom, lalu kirim pesan uji."- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "Bot ID WeCom",- "help": "Salin dari halaman mode API Bot AI WeCom."+ "placeholder": "Bot ID WeCom"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Jaga kerahasiaan secret bot WeCom."+ "placeholder": "••••••"},"allowFrom": {"label": "Pengguna yang diizinkan","placeholder": "ID pengguna, dipisahkan koma"+ },+ "welcomeMessage": {+ "label": "Pesan selamat datang"}}}diff --git a/nanobot/channels/wecom/webui/locales/ja.json b/nanobot/channels/wecom/webui/locales/ja.jsonindex 2eebed6e8..da3bf2e5c 100644--- a/nanobot/channels/wecom/webui/locales/ja.json+++ b/nanobot/channels/wecom/webui/locales/ja.json@@ -1,30 +1,22 @@{- "description": "WeCom の業務チャットから nanobot を利用します。",- "requirements": "WeCom AI ボットの Bot ID と Secret","setup": {"docsLabel": "WeCom 設定ガイドを開く","officialLabel": "WeCom コンソールを開く",- "tryIt": "WeCom ボットにテストメッセージを送信します。",- "summary": "WeCom 管理コンソールの AI ボット ID とシークレットが必要です。",- "steps": [- "WeCom で AI ボットを作成し、API モードを選択します。",- "Bot ID と Secret を nanobot にコピーします。",- "保存して WeCom を有効にし、テストメッセージを送信します。"- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "WeCom Bot ID",- "help": "WeCom AI ボットの API モードページからコピーします。"+ "placeholder": "WeCom Bot ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "WeCom ボットのシークレットは安全に保管してください。"+ "placeholder": "••••••"},"allowFrom": {"label": "許可するユーザー","placeholder": "ユーザー ID(カンマ区切り)"+ },+ "welcomeMessage": {+ "label": "ウェルカムメッセージ"}}}diff --git a/nanobot/channels/wecom/webui/locales/ko.json b/nanobot/channels/wecom/webui/locales/ko.jsonindex 8f1262dac..33a756ba7 100644--- a/nanobot/channels/wecom/webui/locales/ko.json+++ b/nanobot/channels/wecom/webui/locales/ko.json@@ -1,30 +1,22 @@{- "description": "WeCom 업무 채팅에서 nanobot을 사용합니다.",- "requirements": "WeCom AI 봇의 Bot ID와 Secret","setup": {"docsLabel": "WeCom 설정 가이드 열기","officialLabel": "WeCom 콘솔 열기",- "tryIt": "WeCom 봇에 테스트 메시지를 보내세요.",- "summary": "WeCom 관리 콘솔의 AI 봇 ID와 Secret이 필요합니다.",- "steps": [- "WeCom에서 AI 봇을 만들고 API 모드를 선택하세요.",- "Bot ID와 Secret을 nanobot에 복사하세요.",- "저장하고 WeCom을 활성화한 다음 테스트 메시지를 보내세요."- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "WeCom Bot ID",- "help": "WeCom AI 봇 API 모드 페이지에서 복사하세요."+ "placeholder": "WeCom Bot ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "WeCom 봇 Secret을 안전하게 보관하세요."+ "placeholder": "••••••"},"allowFrom": {"label": "허용된 사용자","placeholder": "사용자 ID, 쉼표로 구분"+ },+ "welcomeMessage": {+ "label": "환영 메시지"}}}diff --git a/nanobot/channels/wecom/webui/locales/pt-BR.json b/nanobot/channels/wecom/webui/locales/pt-BR.jsonindex 00c23eef2..7e8e0aa21 100644--- a/nanobot/channels/wecom/webui/locales/pt-BR.json+++ b/nanobot/channels/wecom/webui/locales/pt-BR.json@@ -1,30 +1,22 @@{- "description": "Use o nanobot em conversas de trabalho do WeCom.",- "requirements": "Bot ID e Secret do bot de IA do WeCom","setup": {"docsLabel": "Abrir guia do WeCom","officialLabel": "Abrir console do WeCom",- "tryIt": "Envie uma mensagem de teste ao bot do WeCom.",- "summary": "O WeCom precisa do ID e do segredo de um bot de IA do console administrativo.",- "steps": [- "Crie um bot de IA no WeCom e escolha o modo API.",- "Copie o Bot ID e o Secret para o nanobot.",- "Salve e ative o WeCom; depois, envie uma mensagem de teste."- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "Bot ID do WeCom",- "help": "Copie da página do modo API do bot de IA do WeCom."+ "placeholder": "Bot ID do WeCom"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Mantenha privado o segredo do bot do WeCom."+ "placeholder": "••••••"},"allowFrom": {"label": "Usuários permitidos","placeholder": "IDs de usuário separados por vírgulas"+ },+ "welcomeMessage": {+ "label": "Mensagem de boas-vindas"}}}diff --git a/nanobot/channels/wecom/webui/locales/vi.json b/nanobot/channels/wecom/webui/locales/vi.jsonindex baddb8d8a..20feb67fb 100644--- a/nanobot/channels/wecom/webui/locales/vi.json+++ b/nanobot/channels/wecom/webui/locales/vi.json@@ -1,30 +1,22 @@{- "description": "Sử dụng nanobot trong các cuộc trò chuyện công việc WeCom.",- "requirements": "Bot ID và Secret của bot AI WeCom","setup": {"docsLabel": "Mở hướng dẫn WeCom","officialLabel": "Mở bảng điều khiển WeCom",- "tryIt": "Gửi tin nhắn thử đến bot WeCom.",- "summary": "WeCom cần ID và secret của bot AI từ bảng điều khiển quản trị.",- "steps": [- "Tạo bot AI trong WeCom và chọn chế độ API.",- "Sao chép Bot ID và Secret vào nanobot.",- "Lưu và bật WeCom, sau đó gửi tin nhắn thử."- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "Bot ID WeCom",- "help": "Sao chép từ trang chế độ API của bot AI WeCom."+ "placeholder": "Bot ID WeCom"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "Giữ kín khóa Secret của bot WeCom."+ "placeholder": "••••••"},"allowFrom": {"label": "Người dùng được phép","placeholder": "ID người dùng, phân tách bằng dấu phẩy"+ },+ "welcomeMessage": {+ "label": "Tin nhắn chào mừng"}}}diff --git a/nanobot/channels/wecom/webui/locales/zh-CN.json b/nanobot/channels/wecom/webui/locales/zh-CN.jsonindex 8ac79bbe7..ac158388c 100644--- a/nanobot/channels/wecom/webui/locales/zh-CN.json+++ b/nanobot/channels/wecom/webui/locales/zh-CN.json@@ -1,31 +1,23 @@{"displayName": "企业微信",- "description": "在企业微信工作会话中使用 nanobot。",- "requirements": "企业微信 AI 机器人的 Bot ID 和 Secret","setup": {"docsLabel": "打开企业微信配置指南","officialLabel": "打开企业微信管理后台",- "tryIt": "向企业微信机器人发送一条测试消息。",- "summary": "企业微信需要管理后台中 AI 机器人的 Bot ID 和 Secret。",- "steps": [- "在企业微信中创建 AI 机器人并选择 API 模式。",- "将 Bot ID 和 Secret 复制到 nanobot。",- "保存并启用企业微信,然后发送一条测试消息。"- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "企业微信 Bot ID",- "help": "从企业微信 AI 机器人 API 模式页面复制。"+ "placeholder": "企业微信 Bot ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "请妥善保管企业微信机器人 Secret。"+ "placeholder": "••••••"},"allowFrom": {"label": "允许的用户","placeholder": "用户 ID,用逗号分隔"+ },+ "welcomeMessage": {+ "label": "欢迎消息"}}}diff --git a/nanobot/channels/wecom/webui/locales/zh-TW.json b/nanobot/channels/wecom/webui/locales/zh-TW.jsonindex 0c84afe3c..5f1a13753 100644--- a/nanobot/channels/wecom/webui/locales/zh-TW.json+++ b/nanobot/channels/wecom/webui/locales/zh-TW.json@@ -1,31 +1,23 @@{"displayName": "企業微信",- "description": "在企業微信工作對話中使用 nanobot。",- "requirements": "企業微信 AI 機器人的 Bot ID 和 Secret","setup": {"docsLabel": "開啟企業微信設定指南","officialLabel": "開啟企業微信管理後台",- "tryIt": "向企業微信機器人傳送一則測試訊息。",- "summary": "企業微信需要管理後台中 AI 機器人的 Bot ID 和 Secret。",- "steps": [- "在企業微信中建立 AI 機器人並選擇 API 模式。",- "將 Bot ID 和 Secret 複製到 nanobot。",- "儲存並啟用企業微信,然後傳送一則測試訊息。"- ],"fields": {"botId": {"label": "Bot ID",- "placeholder": "企業微信 Bot ID",- "help": "從企業微信 AI 機器人 API 模式頁面複製。"+ "placeholder": "企業微信 Bot ID"},"secret": {"label": "Secret",- "placeholder": "••••••",- "help": "請妥善保管企業微信機器人 Secret。"+ "placeholder": "••••••"},"allowFrom": {"label": "允許的使用者","placeholder": "使用者 ID,以逗號分隔"+ },+ "welcomeMessage": {+ "label": "歡迎消息"}}}diff --git a/nanobot/channels/weixin/manifest.py b/nanobot/channels/weixin/manifest.pyindex 7e683484d..03c19121b 100644--- a/nanobot/channels/weixin/manifest.py+++ b/nanobot/channels/weixin/manifest.py@@ -8,7 +8,8 @@ from nanobot.channels.weixin.validation import validateSETUP_SPEC = ChannelSetupSpec(fields={- "token": field("secret"),+ # QR-managed credentials must not be exposed to generic WebUI autosave.+ "token": field("secret", writable=False, snapshot=False),"allowFrom": field("list"),"baseUrl": field(default="https://ilinkai.weixin.qq.com"),"cdnBaseUrl": field(default="https://novac2c.cdn.weixin.qq.com/c2c"),diff --git a/nanobot/channels/weixin/tests/test_weixin_channel.py b/nanobot/channels/weixin/tests/test_weixin_channel.pyindex cac4e1d55..8b5379837 100644--- a/nanobot/channels/weixin/tests/test_weixin_channel.py+++ b/nanobot/channels/weixin/tests/test_weixin_channel.py@@ -55,6 +55,14 @@ def no_qr_poll_delay(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(weixin_mod, "asyncio", AsyncioProxy())[email protected](autouse=True)+def isolate_config_file(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep mocked QR credentials out of the user's real config file."""+ config_path = tmp_path / "config.json"+ config_path.write_text("{}", encoding="utf-8")+ monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)++def test_make_headers_includes_route_tag_when_configured() -> None:bus = MessageBus()channel = WeixinChannel(diff --git a/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx b/nanobot/channels/weixin/webui/WeixinConnectFlow.tsxindex f4211e755..523465b6b 100644--- a/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx+++ b/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx@@ -69,18 +69,22 @@ function weixinConnectMessage(export function WeixinConnectFlow({token,feature,+ authRecoveryActive = false,idleLabel,connectRequestId,onFeaturesUpdate,-}: ChannelPluginConnectFlowProps) {+}: ChannelPluginConnectFlowProps & { authRecoveryActive?: boolean }) {const { t } = useTranslation();const tx = channelTranslator(t, "weixin");const [verificationCode, setVerificationCode] = useState("");- const authExpired = feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE;+ const authExpired = authRecoveryActive+ || feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE;const scanAgainLabel = t("settings.channels.scanAgain", {defaultValue: "Scan again",});+ if (feature.configured && !authExpired) return null;+const renderVerification = ({connect,busy,@@ -134,9 +138,11 @@ export function WeixinConnectFlow({<ChannelQrConnectFlowtoken={token}channelName="weixin"- startOptions={{ force: authExpired }}+ startParams={authExpired ? { force: true } : {}}idleLabel={authExpired ? scanAgainLabel : idleLabel}connectRequestId={connectRequestId}+ autoStart={!feature.configured || authExpired}+ minimalPendingforceOnRepeatonFeaturesUpdate={onFeaturesUpdate}pausePolling={isVerificationChallenge}@@ -146,10 +152,7 @@ export function WeixinConnectFlow({labels={{qrAlt: tx("custom.qrAlt", "WeChat login QR code"),scanTitle: tx("custom.scanTitle", "Scan with WeChat"),- scanDescription: tx(- "custom.scanDescription",- "Use WeChat on your phone to scan this code. nanobot saves the account state locally after login.",- ),+ scanDescription: "",waiting: tx("custom.waiting", "Waiting for WeChat scan..."),connected: tx("custom.connected", "WeChat is connected."),stopped: tx("custom.stopped", "WeChat login stopped."),diff --git a/nanobot/channels/weixin/webui/WeixinPanel.tsx b/nanobot/channels/weixin/webui/WeixinPanel.tsxindex 07c7668ea..6836b7cdc 100644--- a/nanobot/channels/weixin/webui/WeixinPanel.tsx+++ b/nanobot/channels/weixin/webui/WeixinPanel.tsx@@ -1,13 +1,11 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Check, ChevronDown, ExternalLink, Loader2, Plus } from "lucide-react";+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";+import { Check, ChevronDown, Loader2, Plus } from "lucide-react";import { useTranslation } from "react-i18next";import { channelFieldMessageKey, channelTranslator } from "@/channel-plugins/i18n";import { channelLocaleMessages } from "@/channel-plugins/locale-registry";import type { ChannelPluginPanelProps } from "@/channel-plugins/types";import {- chatAppGuideUrl,- docsUrlWithBase,type ChannelConfigField,} from "@/components/settings/channels/catalog";import {@@ -15,11 +13,13 @@ import {channelValuesForSave,defaultChannelFieldValues,} from "@/components/settings/channels/CredentialForm";+import {+ CHANNEL_SETUP_PANEL_CLASS_NAME,+ ChannelLogo,+} from "@/components/settings/channels/ChannelIdentity";import { Button } from "@/components/ui/button";-import { useLogoFallback } from "@/hooks/useLogoFallback";import { normalizeLocale } from "@/i18n/config";import { configureChannel } from "@/lib/api";-import { logoFallbackUrls } from "@/lib/provider-brand";import type {ChannelSetupContractField,NanobotFeatureInfo,@@ -34,13 +34,13 @@ import {import {WEIXIN_ADVANCED_FIELD_KEYS,WEIXIN_PRIMARY_FIELD_KEYS,+ WEIXIN_QR_TOKEN_FIELD_KEY,} from "./presentation";export function WeixinPanel({token,feature,actionKey,- chatAppsDocsUrl,showBrandLogos,onAction,onFeaturesUpdate,@@ -50,11 +50,16 @@ export function WeixinPanel({const { t, i18n } = useTranslation();const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });const channelTx = channelTranslator(t, "weixin");- const runtimeError = weixinRuntimeError(feature.runtime_error, channelTx);+ const authExpired = feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE;+ const [authRecoveryActive, setAuthRecoveryActive] = useState(authExpired);+ const runtimeError = weixinRuntimeError(feature.runtime_error, channelTx)+ ?? (authRecoveryActive ? channelTx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE) : undefined);const displayName = channelTx("displayName", "WeChat");const enabledBusy = actionKey === `enable:${feature.name}`;const missingSupport = feature.enabled && !feature.installed;const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});+ const [advancedOpen, setAdvancedOpen] = useState(false);+ const advancedPanelId = useId();const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());const [saving, setSaving] = useState(false);const [saveRevision, setSaveRevision] = useState(0);@@ -76,8 +81,6 @@ export function WeixinPanel({const primaryFields = localizeBooleanFields(setupFields.primary, onLabel, offLabel);const advancedFields = localizeBooleanFields(setupFields.advanced, onLabel, offLabel);const editableFields = [...primaryFields, ...advancedFields];- const docsUrl = docsUrlWithBase(chatAppGuideUrl("wechat"), chatAppsDocsUrl)- ?? chatAppGuideUrl("wechat");const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>defaultChannelFieldValues(editableFields, feature.config_values),);@@ -96,6 +99,14 @@ export function WeixinPanel({onFeaturesUpdate,};+ useEffect(() => {+ if (authExpired) {+ setAuthRecoveryActive(true);+ } else if (feature.runtime_status === "running") {+ setAuthRecoveryActive(false);+ }+ }, [authExpired, feature.runtime_status]);+useEffect(() => {const nextValues = defaultChannelFieldValues(editableFields, feature.config_values);for (const key of touchedFieldsRef.current) {@@ -180,33 +191,44 @@ export function WeixinPanel({};return (- <aside className="settings-editor rounded-panel bg-settings-surface">- <div className="flex items-start justify-between gap-4 pr-8">- <div className="flex min-w-0 items-start gap-3">- <WeixinLogo showBrandLogos={showBrandLogos} />- <div className="min-w-0 flex-1">- <h3 className="truncate select-none text-[14px] font-semibold leading-5 text-foreground">- {displayName}- </h3>- {missingSupport && feature.install_supported ? (- <Button- type="button"- size="sm"- variant="secondary"- disabled={enabledBusy}- onClick={() => onAction("enable", feature.name)}- className="mt-2 h-8 rounded-full px-3 text-[12px] font-semibold"- >- {enabledBusy ? (- <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />- ) : (- <Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />- )}- {tx("settings.nanobotFeatures.installSupport", "Install support")}- </Button>- ) : null}- </div>+ <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">+ <div className="flex min-w-0 max-w-full items-center gap-3">+ <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />+ <h3 className="sr-only">{displayName}</h3>+ {missingSupport && feature.install_supported ? (+ <Button+ type="button"+ size="sm"+ variant="secondary"+ disabled={enabledBusy}+ onClick={() => onAction("enable", feature.name)}+ className="h-8 rounded-full px-3 text-[12px] font-semibold"+ >+ {enabledBusy ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />+ )}+ {tx("settings.nanobotFeatures.installSupport", "Install support")}+ </Button>+ ) : null}</div>+ {advancedFields.length ? (+ <button+ type="button"+ className="ms-auto inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"+ aria-expanded={advancedOpen}+ aria-controls={advancedPanelId}+ onClick={() => setAdvancedOpen((current) => !current)}+ >+ {tx("settings.channels.advanced", "Advanced")}+ <ChevronDown className={cn(+ "h-3.5 w-3.5 transition-transform motion-reduce:transition-none",+ advancedOpen && "rotate-180",+ )} aria-hidden />+ </button>+ ) : null}</div>{runtimeError ? (@@ -219,6 +241,7 @@ export function WeixinPanel({<WeixinConnectFlowtoken={token}feature={feature}+ authRecoveryActive={authRecoveryActive}idleLabel={channelTx("setup.primaryAction", "Connect WeChat")}connectRequestId={connectRequestId}onFeaturesUpdate={onFeaturesUpdate}@@ -270,38 +293,21 @@ export function WeixinPanel({) : null}{advancedFields.length ? (- <details className="group text-[12px] leading-5 text-muted-foreground">- <summary className="cursor-pointer list-none text-[12px] font-semibold text-foreground">- <span className="inline-flex items-center gap-1.5">- {tx("settings.channels.advanced", "Advanced")}- <ChevronDown- className="h-3.5 w-3.5 transition-transform group-open:rotate-180"- aria-hidden- />- </span>- </summary>- <div className="mt-3">- <CredentialForm- fields={advancedFields}- values={fieldValues}- configuredFields={configuredFields}- visibleSecrets={visibleSecrets}- onChange={setFieldValue}- onToggleSecret={(key) => {- setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));- }}- compact- />- </div>- </details>+ <div id={advancedPanelId} hidden={!advancedOpen} className="text-[12px] leading-5 text-muted-foreground">+ <CredentialForm+ fields={advancedFields}+ values={fieldValues}+ configuredFields={configuredFields}+ visibleSecrets={visibleSecrets}+ onChange={setFieldValue}+ onToggleSecret={(key) => {+ setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));+ }}+ compact+ />+ </div>) : null}- <div className="flex justify-end">- <WeixinGuideLink- url={docsUrl}- label={channelTx("setup.docsLabel", "Open WeChat setup")}- />- </div></div></aside>);@@ -311,7 +317,9 @@ function weixinSetupFields(feature: NanobotFeatureInfo,locale: string,): { primary: ChannelConfigField[]; advanced: ChannelConfigField[] } {- const fields = feature.setup?.fields ?? [];+ const fields = (feature.setup?.fields ?? []).filter(+ (field) => field.key !== WEIXIN_QR_TOKEN_FIELD_KEY,+ );const fieldsByKey = new Map(fields.map((field) => [field.key, field]));const messages = channelLocaleMessages("weixin", normalizeLocale(locale))?.setup;const knownKeys = new Set<string>([@@ -336,7 +344,7 @@ function weixinSetupFields(function weixinConfigField(field: ChannelSetupContractField,- copy: { label: string; placeholder?: string; help?: string; choices?: Record<string, string> }+ copy: { label: string; placeholder?: string; choices?: Record<string, string> }| undefined,): ChannelConfigField {const choices = field.kind === "bool" ? ["true", "false"] : field.choices;@@ -344,7 +352,6 @@ function weixinConfigField(key: field.key,label: copy?.label ?? fieldLabel(field.field),placeholder: copy?.placeholder,- help: copy?.help,secret: field.kind === "secret",optional: !field.required,inputType: field.kind === "int" ? "number" : undefined,@@ -367,70 +374,6 @@ function fieldLabel(value: string): string {return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : value;}-function WeixinLogo({ showBrandLogos }: { showBrandLogos: boolean }) {- const logoUrls = useMemo(() => logoFallbackUrls("https://weixin.qq.com/favicon.ico"), []);- const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);- if (showBrandLogos && logoUrl) {- return (- <span className="grid h-10 w-10 shrink-0 place-items-center rounded-control bg-background">- <img- src={logoUrl}- alt=""- decoding="async"- loading="lazy"- className="h-5.5 w-5.5 max-h-6 max-w-6 object-contain"- onLoad={onLogoLoad}- onError={onLogoError}- />- </span>- );- }- return (- <span- className="flex h-10 w-10 shrink-0 items-center justify-center rounded-control bg-background text-[11px] font-bold"- style={{ color: "#07C160" }}- aria-hidden- >- WX- </span>- );-}--function WeixinGuideLink({ url, label }: { url: string; label: string }) {- const logoUrls = useMemo(() => logoFallbackUrls("https://weixin.qq.com/favicon.ico"), []);- const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);- return (- <a- href={url}- target="_blank"- rel="noreferrer"- className="inline-flex max-w-full items-center gap-2 rounded-full bg-background/80 py-1 pl-1 pr-2.5 text-[11.5px] font-semibold text-foreground transition-colors hover:bg-background"- >- <span- className="grid h-5 w-5 shrink-0 place-items-center overflow-hidden rounded-full bg-muted/70 text-[9px] font-bold"- style={{ color: "#07C160" }}- aria-hidden- >- {logoUrl ? (- <img- src={logoUrl}- alt=""- decoding="async"- loading="lazy"- className="h-3.5 w-3.5 object-contain"- onLoad={onLogoLoad}- onError={onLogoError}- />- ) : (- "WX"- )}- </span>- <span className="truncate">{label}</span>- <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />- </a>- );-}-function weixinRuntimeError(error: string | undefined,tx: (key: string, fallback: string) => string,diff --git a/nanobot/channels/weixin/webui/index.tsx b/nanobot/channels/weixin/webui/index.tsxindex 5fb35ca77..35ef192cf 100644--- a/nanobot/channels/weixin/webui/index.tsx+++ b/nanobot/channels/weixin/webui/index.tsx@@ -25,10 +25,10 @@ export default {wechat: {},},presentation: {+ logoUrl: "https://weixin.qq.com/favicon.ico",displayName: "WeChat",initials: "WX",color: "#07C160",- logoUrl: "https://weixin.qq.com/favicon.ico",setup: {mode: "connect",command: "nanobot channels login weixin",diff --git a/nanobot/channels/weixin/webui/locales/en.json b/nanobot/channels/weixin/webui/locales/en.jsonindex f34695156..fda191024 100644--- a/nanobot/channels/weixin/webui/locales/en.json+++ b/nanobot/channels/weixin/webui/locales/en.json@@ -1,17 +1,8 @@{- "description": "Use nanobot from WeChat conversations.",- "requirements": "WeChat channel setup and gateway","setup": {"primaryAction": "Connect WeChat","docsLabel": "Open WeChat setup","officialLabel": "Open WeChat",- "tryIt": "After the QR login finishes, send a WeChat DM to the connected account.",- "summary": "WeChat signs in with a QR code and saves the account state locally.",- "steps": [- "Click Connect and scan the QR code with WeChat on your phone.",- "Keep the local gateway running while WeChat receives messages.",- "Send a direct test message to confirm the account is connected."- ],"fields": {"allowFrom": {"label": "Allowed users",@@ -40,7 +31,6 @@"custom": {"qrAlt": "WeChat login QR code","scanTitle": "Scan with WeChat",- "scanDescription": "Use WeChat on your phone to scan this code. nanobot saves the account state locally after login.","waiting": "Waiting for you to scan with WeChat…","connected": "WeChat is connected.","stopped": "WeChat login stopped.",diff --git a/nanobot/channels/weixin/webui/locales/es.json b/nanobot/channels/weixin/webui/locales/es.jsonindex a3f996d3e..d90df2dc0 100644--- a/nanobot/channels/weixin/webui/locales/es.json+++ b/nanobot/channels/weixin/webui/locales/es.json@@ -1,17 +1,8 @@{- "description": "Usa nanobot desde conversaciones de WeChat.",- "requirements": "Configuración del canal WeChat y pasarela","setup": {"primaryAction": "Conectar WeChat","docsLabel": "Abrir guía de WeChat","officialLabel": "Abrir WeChat",- "tryIt": "Tras iniciar sesión por QR, envía un DM al usuario conectado.",- "summary": "WeChat inicia sesión con un QR y guarda el estado de la cuenta localmente.",- "steps": [- "Haz clic en Conectar y escanea el QR con WeChat.",- "Mantén la pasarela local en ejecución mientras WeChat recibe mensajes.",- "Envía un mensaje directo de prueba para confirmar la conexión."- ],"fields": {"allowFrom": {"label": "Usuarios permitidos",@@ -21,26 +12,53 @@"label": "Token","placeholder": "Guardado al iniciar sesión por QR"},- "sendProgress": { "label": "Enviar progreso" },- "sendToolHints": { "label": "Enviar resúmenes de actividad de las herramientas" },- "streaming": { "label": "Usar API de streaming" },- "replyProgressMessages": { "label": "Enviar progreso estructurado" },- "replyProgressMaxMessages": { "label": "Límite de progreso estructurado" },- "contextMessageBudget": { "label": "Máximo de mensajes de contexto" },- "blockStreaming": { "label": "Enviar respuestas por bloques" },- "blockStreamingMinChars": { "label": "Mínimo de caracteres por bloque" },- "blockStreamingMaxMessages": { "label": "Límite de mensajes por bloques" },- "baseUrl": { "label": "URL de la API" },- "cdnBaseUrl": { "label": "URL de la CDN" },- "routeTag": { "label": "Etiqueta de ruta" },- "stateDir": { "label": "Directorio de estado" },- "pollTimeout": { "label": "Tiempo de espera de consulta (segundos)" }+ "sendProgress": {+ "label": "Enviar progreso"+ },+ "sendToolHints": {+ "label": "Enviar resúmenes de actividad de las herramientas"+ },+ "streaming": {+ "label": "Usar API de streaming"+ },+ "replyProgressMessages": {+ "label": "Enviar progreso estructurado"+ },+ "replyProgressMaxMessages": {+ "label": "Límite de progreso estructurado"+ },+ "contextMessageBudget": {+ "label": "Máximo de mensajes de contexto"+ },+ "blockStreaming": {+ "label": "Enviar respuestas por bloques"+ },+ "blockStreamingMinChars": {+ "label": "Mínimo de caracteres por bloque"+ },+ "blockStreamingMaxMessages": {+ "label": "Límite de mensajes por bloques"+ },+ "baseUrl": {+ "label": "URL de la API"+ },+ "cdnBaseUrl": {+ "label": "URL de la CDN"+ },+ "routeTag": {+ "label": "Etiqueta de ruta"+ },+ "stateDir": {+ "label": "Directorio de estado"+ },+ "pollTimeout": {+ "label": "Tiempo de espera de consulta (segundos)"+ }}},"custom": {"qrAlt": "Código QR de inicio de WeChat","scanTitle": "Escanea con WeChat",- "scanDescription": "Escanea este código con WeChat en tu teléfono. nanobot guarda el estado de la cuenta localmente después de iniciar sesión.","waiting": "Esperando a que escanees el código con WeChat…","connected": "WeChat está conectado.","stopped": "Inicio de sesión en WeChat detenido.",diff --git a/nanobot/channels/weixin/webui/locales/fr.json b/nanobot/channels/weixin/webui/locales/fr.jsonindex 22ee6376b..e2988a5d4 100644--- a/nanobot/channels/weixin/webui/locales/fr.json+++ b/nanobot/channels/weixin/webui/locales/fr.json@@ -1,17 +1,8 @@{- "description": "Utilisez nanobot depuis les conversations WeChat.",- "requirements": "Configuration du canal WeChat et passerelle","setup": {"primaryAction": "Connecter WeChat","docsLabel": "Ouvrir le guide WeChat","officialLabel": "Ouvrir WeChat",- "tryIt": "Après la connexion par QR code, envoyez un message privé au compte connecté.",- "summary": "WeChat se connecte par QR code et enregistre localement l’état du compte.",- "steps": [- "Cliquez sur Connecter et scannez le QR code avec WeChat.",- "Gardez la passerelle locale active pendant la réception des messages.",- "Envoyez un message privé test pour confirmer la connexion."- ],"fields": {"allowFrom": {"label": "Utilisateurs autorisés",@@ -21,26 +12,53 @@"label": "Jeton","placeholder": "Enregistré après la connexion QR"},- "sendProgress": { "label": "Envoyer la progression" },- "sendToolHints": { "label": "Envoyer un résumé de l’activité des outils" },- "streaming": { "label": "Utiliser l’API de streaming" },- "replyProgressMessages": { "label": "Envoyer la progression structurée" },- "replyProgressMaxMessages": { "label": "Limite de progression structurée" },- "contextMessageBudget": { "label": "Nombre maximal de messages de contexte" },- "blockStreaming": { "label": "Envoyer la réponse par blocs" },- "blockStreamingMinChars": { "label": "Taille minimale d’un bloc" },- "blockStreamingMaxMessages": { "label": "Limite de messages par blocs" },- "baseUrl": { "label": "URL de l’API" },- "cdnBaseUrl": { "label": "URL du CDN" },- "routeTag": { "label": "Étiquette de routage" },- "stateDir": { "label": "Répertoire d’état" },- "pollTimeout": { "label": "Délai d’interrogation (secondes)" }+ "sendProgress": {+ "label": "Envoyer la progression"+ },+ "sendToolHints": {+ "label": "Envoyer un résumé de l’activité des outils"+ },+ "streaming": {+ "label": "Utiliser l’API de streaming"+ },+ "replyProgressMessages": {+ "label": "Envoyer la progression structurée"+ },+ "replyProgressMaxMessages": {+ "label": "Limite de progression structurée"+ },+ "contextMessageBudget": {+ "label": "Nombre maximal de messages de contexte"+ },+ "blockStreaming": {+ "label": "Envoyer la réponse par blocs"+ },+ "blockStreamingMinChars": {+ "label": "Taille minimale d’un bloc"+ },+ "blockStreamingMaxMessages": {+ "label": "Limite de messages par blocs"+ },+ "baseUrl": {+ "label": "URL de l’API"+ },+ "cdnBaseUrl": {+ "label": "URL du CDN"+ },+ "routeTag": {+ "label": "Étiquette de routage"+ },+ "stateDir": {+ "label": "Répertoire d’état"+ },+ "pollTimeout": {+ "label": "Délai d’interrogation (secondes)"+ }}},"custom": {"qrAlt": "QR code de connexion WeChat","scanTitle": "Scanner avec WeChat",- "scanDescription": "Scannez ce code avec WeChat. nanobot enregistre localement l’état du compte après la connexion.","waiting": "En attente de lecture du QR code avec WeChat…","connected": "WeChat est connecté.","stopped": "Connexion WeChat arrêtée.",diff --git a/nanobot/channels/weixin/webui/locales/id.json b/nanobot/channels/weixin/webui/locales/id.jsonindex ba2047503..b89f560ff 100644--- a/nanobot/channels/weixin/webui/locales/id.json+++ b/nanobot/channels/weixin/webui/locales/id.json@@ -1,17 +1,8 @@{- "description": "Gunakan nanobot dari percakapan WeChat.",- "requirements": "Pengaturan kanal WeChat dan gateway","setup": {"primaryAction": "Hubungkan WeChat","docsLabel": "Buka panduan WeChat","officialLabel": "Buka WeChat",- "tryIt": "Setelah login QR, kirim DM ke akun yang terhubung.",- "summary": "WeChat login dengan kode QR dan menyimpan status akun secara lokal.",- "steps": [- "Klik Hubungkan dan pindai QR dengan WeChat.",- "Biarkan gateway lokal berjalan saat WeChat menerima pesan.",- "Kirim pesan langsung uji untuk memastikan akun terhubung."- ],"fields": {"allowFrom": {"label": "Pengguna yang diizinkan",@@ -21,26 +12,53 @@"label": "Token","placeholder": "Disimpan saat login QR"},- "sendProgress": { "label": "Kirim progres" },- "sendToolHints": { "label": "Kirim ringkasan aktivitas alat" },- "streaming": { "label": "Gunakan API streaming" },- "replyProgressMessages": { "label": "Kirim progres terstruktur" },- "replyProgressMaxMessages": { "label": "Batas progres terstruktur" },- "contextMessageBudget": { "label": "Jumlah maksimum pesan konteks" },- "blockStreaming": { "label": "Kirim respons per blok" },- "blockStreamingMinChars": { "label": "Jumlah minimum karakter per blok" },- "blockStreamingMaxMessages": { "label": "Batas pesan blok" },- "baseUrl": { "label": "URL API" },- "cdnBaseUrl": { "label": "URL CDN" },- "routeTag": { "label": "Tag rute" },- "stateDir": { "label": "Direktori status" },- "pollTimeout": { "label": "Batas waktu polling (detik)" }+ "sendProgress": {+ "label": "Kirim progres"+ },+ "sendToolHints": {+ "label": "Kirim ringkasan aktivitas alat"+ },+ "streaming": {+ "label": "Gunakan API streaming"+ },+ "replyProgressMessages": {+ "label": "Kirim progres terstruktur"+ },+ "replyProgressMaxMessages": {+ "label": "Batas progres terstruktur"+ },+ "contextMessageBudget": {+ "label": "Jumlah maksimum pesan konteks"+ },+ "blockStreaming": {+ "label": "Kirim respons per blok"+ },+ "blockStreamingMinChars": {+ "label": "Jumlah minimum karakter per blok"+ },+ "blockStreamingMaxMessages": {+ "label": "Batas pesan blok"+ },+ "baseUrl": {+ "label": "URL API"+ },+ "cdnBaseUrl": {+ "label": "URL CDN"+ },+ "routeTag": {+ "label": "Tag rute"+ },+ "stateDir": {+ "label": "Direktori status"+ },+ "pollTimeout": {+ "label": "Batas waktu polling (detik)"+ }}},"custom": {"qrAlt": "Kode QR login WeChat","scanTitle": "Pindai dengan WeChat",- "scanDescription": "Pindai dengan WeChat di ponsel. nanobot menyimpan status akun secara lokal setelah login.","waiting": "Menunggu Anda memindai kode dengan WeChat…","connected": "WeChat sudah terhubung.","stopped": "Login WeChat dihentikan.",diff --git a/nanobot/channels/weixin/webui/locales/ja.json b/nanobot/channels/weixin/webui/locales/ja.jsonindex 8b975eb1b..9983a074e 100644--- a/nanobot/channels/weixin/webui/locales/ja.json+++ b/nanobot/channels/weixin/webui/locales/ja.json@@ -1,17 +1,8 @@{- "description": "WeChat の会話から nanobot を利用します。",- "requirements": "WeChat チャンネル設定とゲートウェイ","setup": {"primaryAction": "WeChat に接続","docsLabel": "WeChat 設定ガイドを開く","officialLabel": "WeChat を開く",- "tryIt": "QR ログイン後、接続したアカウントに WeChat の DM を送信します。",- "summary": "WeChat は QR コードでログインし、アカウント状態をローカルに保存します。",- "steps": [- "接続をクリックし、スマートフォンの WeChat で QR コードを読み取ります。",- "WeChat がメッセージを受信する間、ローカルゲートウェイを起動しておきます。",- "DM でテストし、アカウントの接続を確認します。"- ],"fields": {"allowFrom": {"label": "許可するユーザー",@@ -21,26 +12,53 @@"label": "トークン","placeholder": "QR ログインで保存"},- "sendProgress": { "label": "進捗を送信" },- "sendToolHints": { "label": "ツールの動作概要を送信" },- "streaming": { "label": "ストリーミング API を使用" },- "replyProgressMessages": { "label": "構造化された進捗を送信" },- "replyProgressMaxMessages": { "label": "構造化進捗の上限" },- "contextMessageBudget": { "label": "コンテキストに含めるメッセージ数の上限" },- "blockStreaming": { "label": "応答をブロック単位で送信" },- "blockStreamingMinChars": { "label": "1 ブロックの最小文字数" },- "blockStreamingMaxMessages": { "label": "ブロックメッセージの上限" },- "baseUrl": { "label": "API URL" },- "cdnBaseUrl": { "label": "CDN URL" },- "routeTag": { "label": "ルートタグ" },- "stateDir": { "label": "状態ディレクトリ" },- "pollTimeout": { "label": "ポーリングのタイムアウト(秒)" }+ "sendProgress": {+ "label": "進捗を送信"+ },+ "sendToolHints": {+ "label": "ツールの動作概要を送信"+ },+ "streaming": {+ "label": "ストリーミング API を使用"+ },+ "replyProgressMessages": {+ "label": "構造化された進捗を送信"+ },+ "replyProgressMaxMessages": {+ "label": "構造化進捗の上限"+ },+ "contextMessageBudget": {+ "label": "コンテキストに含めるメッセージ数の上限"+ },+ "blockStreaming": {+ "label": "応答をブロック単位で送信"+ },+ "blockStreamingMinChars": {+ "label": "1 ブロックの最小文字数"+ },+ "blockStreamingMaxMessages": {+ "label": "ブロックメッセージの上限"+ },+ "baseUrl": {+ "label": "API URL"+ },+ "cdnBaseUrl": {+ "label": "CDN URL"+ },+ "routeTag": {+ "label": "ルートタグ"+ },+ "stateDir": {+ "label": "状態ディレクトリ"+ },+ "pollTimeout": {+ "label": "ポーリングのタイムアウト(秒)"+ }}},"custom": {"qrAlt": "WeChat ログイン QR コード","scanTitle": "WeChat でスキャン",- "scanDescription": "スマートフォンの WeChat でスキャンしてください。ログイン後、nanobot が状態をローカルに保存します。","waiting": "WeChat で QR コードを読み取ってください…","connected": "WeChat に接続しました。","stopped": "WeChat ログインを停止しました。",diff --git a/nanobot/channels/weixin/webui/locales/ko.json b/nanobot/channels/weixin/webui/locales/ko.jsonindex 6ca496925..3180ddc9d 100644--- a/nanobot/channels/weixin/webui/locales/ko.json+++ b/nanobot/channels/weixin/webui/locales/ko.json@@ -1,17 +1,8 @@{- "description": "WeChat 대화에서 nanobot을 사용합니다.",- "requirements": "WeChat 채널 설정 및 게이트웨이","setup": {"primaryAction": "WeChat 연결","docsLabel": "WeChat 설정 가이드 열기","officialLabel": "WeChat 열기",- "tryIt": "QR 로그인 후 연결된 계정으로 WeChat DM을 보내세요.",- "summary": "WeChat은 QR 코드로 로그인하고 계정 상태를 로컬에 저장합니다.",- "steps": [- "연결을 클릭하고 휴대폰 WeChat으로 QR 코드를 스캔하세요.",- "WeChat이 메시지를 받는 동안 로컬 게이트웨이를 실행해 두세요.",- "DM으로 테스트해 계정 연결을 확인하세요."- ],"fields": {"allowFrom": {"label": "허용된 사용자",@@ -21,26 +12,53 @@"label": "토큰","placeholder": "QR 로그인으로 저장됨"},- "sendProgress": { "label": "진행 상황 보내기" },- "sendToolHints": { "label": "도구 실행 요약 보내기" },- "streaming": { "label": "스트리밍 API 사용" },- "replyProgressMessages": { "label": "구조화된 진행 상황 보내기" },- "replyProgressMaxMessages": { "label": "구조화된 진행 메시지 한도" },- "contextMessageBudget": { "label": "컨텍스트에 포함할 최대 메시지 수" },- "blockStreaming": { "label": "응답을 블록으로 보내기" },- "blockStreamingMinChars": { "label": "블록당 최소 글자 수" },- "blockStreamingMaxMessages": { "label": "블록 메시지 한도" },- "baseUrl": { "label": "API URL" },- "cdnBaseUrl": { "label": "CDN URL" },- "routeTag": { "label": "경로 태그" },- "stateDir": { "label": "상태 디렉터리" },- "pollTimeout": { "label": "폴링 제한 시간(초)" }+ "sendProgress": {+ "label": "진행 상황 보내기"+ },+ "sendToolHints": {+ "label": "도구 실행 요약 보내기"+ },+ "streaming": {+ "label": "스트리밍 API 사용"+ },+ "replyProgressMessages": {+ "label": "구조화된 진행 상황 보내기"+ },+ "replyProgressMaxMessages": {+ "label": "구조화된 진행 메시지 한도"+ },+ "contextMessageBudget": {+ "label": "컨텍스트에 포함할 최대 메시지 수"+ },+ "blockStreaming": {+ "label": "응답을 블록으로 보내기"+ },+ "blockStreamingMinChars": {+ "label": "블록당 최소 글자 수"+ },+ "blockStreamingMaxMessages": {+ "label": "블록 메시지 한도"+ },+ "baseUrl": {+ "label": "API URL"+ },+ "cdnBaseUrl": {+ "label": "CDN URL"+ },+ "routeTag": {+ "label": "경로 태그"+ },+ "stateDir": {+ "label": "상태 디렉터리"+ },+ "pollTimeout": {+ "label": "폴링 제한 시간(초)"+ }}},"custom": {"qrAlt": "WeChat 로그인 QR 코드","scanTitle": "WeChat으로 스캔",- "scanDescription": "휴대폰 WeChat으로 스캔하세요. 로그인 후 nanobot이 계정 상태를 로컬에 저장합니다.","waiting": "WeChat으로 QR 코드를 스캔해 주세요…","connected": "WeChat이 연결되었습니다.","stopped": "WeChat 로그인이 중지되었습니다.",diff --git a/nanobot/channels/weixin/webui/locales/pt-BR.json b/nanobot/channels/weixin/webui/locales/pt-BR.jsonindex 36388eee4..1b3a6e600 100644--- a/nanobot/channels/weixin/webui/locales/pt-BR.json+++ b/nanobot/channels/weixin/webui/locales/pt-BR.json@@ -1,17 +1,8 @@{- "description": "Use o nanobot em conversas do WeChat.",- "requirements": "Configuração do canal WeChat e gateway","setup": {"primaryAction": "Conectar WeChat","docsLabel": "Abrir guia do WeChat","officialLabel": "Abrir WeChat",- "tryIt": "Após o login por QR, envie uma DM à conta conectada.",- "summary": "O WeChat entra por QR code e salva o estado da conta localmente.",- "steps": [- "Clique em Conectar e escaneie o QR com o WeChat.",- "Mantenha o gateway local ativo enquanto o WeChat recebe mensagens.",- "Envie uma mensagem direta de teste para confirmar a conexão."- ],"fields": {"allowFrom": {"label": "Usuários permitidos",@@ -21,26 +12,53 @@"label": "Token","placeholder": "Salvo pelo login via QR"},- "sendProgress": { "label": "Enviar progresso" },- "sendToolHints": { "label": "Enviar resumos da atividade das ferramentas" },- "streaming": { "label": "Usar API de streaming" },- "replyProgressMessages": { "label": "Enviar progresso estruturado" },- "replyProgressMaxMessages": { "label": "Limite de progresso estruturado" },- "contextMessageBudget": { "label": "Máximo de mensagens de contexto" },- "blockStreaming": { "label": "Enviar resposta em blocos" },- "blockStreamingMinChars": { "label": "Mínimo de caracteres por bloco" },- "blockStreamingMaxMessages": { "label": "Limite de mensagens em blocos" },- "baseUrl": { "label": "URL da API" },- "cdnBaseUrl": { "label": "URL da CDN" },- "routeTag": { "label": "Etiqueta de rota" },- "stateDir": { "label": "Diretório de estado" },- "pollTimeout": { "label": "Tempo limite da consulta (segundos)" }+ "sendProgress": {+ "label": "Enviar progresso"+ },+ "sendToolHints": {+ "label": "Enviar resumos da atividade das ferramentas"+ },+ "streaming": {+ "label": "Usar API de streaming"+ },+ "replyProgressMessages": {+ "label": "Enviar progresso estruturado"+ },+ "replyProgressMaxMessages": {+ "label": "Limite de progresso estruturado"+ },+ "contextMessageBudget": {+ "label": "Máximo de mensagens de contexto"+ },+ "blockStreaming": {+ "label": "Enviar resposta em blocos"+ },+ "blockStreamingMinChars": {+ "label": "Mínimo de caracteres por bloco"+ },+ "blockStreamingMaxMessages": {+ "label": "Limite de mensagens em blocos"+ },+ "baseUrl": {+ "label": "URL da API"+ },+ "cdnBaseUrl": {+ "label": "URL da CDN"+ },+ "routeTag": {+ "label": "Etiqueta de rota"+ },+ "stateDir": {+ "label": "Diretório de estado"+ },+ "pollTimeout": {+ "label": "Tempo limite da consulta (segundos)"+ }}},"custom": {"qrAlt": "QR code de login do WeChat","scanTitle": "Escaneie com o WeChat",- "scanDescription": "Escaneie com o WeChat no celular. O nanobot salva o estado localmente após o login.","waiting": "Aguardando você escanear o código com o WeChat…","connected": "WeChat está conectado.","stopped": "Login do WeChat interrompido.",diff --git a/nanobot/channels/weixin/webui/locales/vi.json b/nanobot/channels/weixin/webui/locales/vi.jsonindex df43f8013..becf9636d 100644--- a/nanobot/channels/weixin/webui/locales/vi.json+++ b/nanobot/channels/weixin/webui/locales/vi.json@@ -1,17 +1,8 @@{- "description": "Sử dụng nanobot từ các cuộc trò chuyện WeChat.",- "requirements": "Cài đặt kênh WeChat và gateway","setup": {"primaryAction": "Kết nối WeChat","docsLabel": "Mở hướng dẫn WeChat","officialLabel": "Mở WeChat",- "tryIt": "Sau khi đăng nhập QR, gửi tin nhắn riêng đến tài khoản đã kết nối.",- "summary": "WeChat đăng nhập bằng mã QR và lưu trạng thái tài khoản cục bộ.",- "steps": [- "Nhấn Kết nối và quét QR bằng WeChat.",- "Giữ gateway cục bộ chạy khi WeChat nhận tin nhắn.",- "Gửi tin nhắn riêng thử để xác nhận kết nối."- ],"fields": {"allowFrom": {"label": "Người dùng được phép",@@ -21,26 +12,53 @@"label": "Token","placeholder": "Được lưu khi đăng nhập QR"},- "sendProgress": { "label": "Gửi thông báo tiến độ" },- "sendToolHints": { "label": "Gửi tóm tắt hoạt động công cụ" },- "streaming": { "label": "Dùng API truyền theo luồng" },- "replyProgressMessages": { "label": "Gửi tiến độ theo từng bước" },- "replyProgressMaxMessages": { "label": "Số thông báo tiến độ tối đa" },- "contextMessageBudget": { "label": "Số tin nhắn ngữ cảnh tối đa" },- "blockStreaming": { "label": "Gửi phản hồi theo khối" },- "blockStreamingMinChars": { "label": "Số ký tự tối thiểu mỗi phần" },- "blockStreamingMaxMessages": { "label": "Giới hạn tin nhắn theo khối" },- "baseUrl": { "label": "URL API" },- "cdnBaseUrl": { "label": "URL CDN" },- "routeTag": { "label": "Thẻ định tuyến" },- "stateDir": { "label": "Thư mục trạng thái" },- "pollTimeout": { "label": "Thời gian chờ thăm dò (giây)" }+ "sendProgress": {+ "label": "Gửi thông báo tiến độ"+ },+ "sendToolHints": {+ "label": "Gửi tóm tắt hoạt động công cụ"+ },+ "streaming": {+ "label": "Dùng API truyền theo luồng"+ },+ "replyProgressMessages": {+ "label": "Gửi tiến độ theo từng bước"+ },+ "replyProgressMaxMessages": {+ "label": "Số thông báo tiến độ tối đa"+ },+ "contextMessageBudget": {+ "label": "Số tin nhắn ngữ cảnh tối đa"+ },+ "blockStreaming": {+ "label": "Gửi phản hồi theo khối"+ },+ "blockStreamingMinChars": {+ "label": "Số ký tự tối thiểu mỗi phần"+ },+ "blockStreamingMaxMessages": {+ "label": "Giới hạn tin nhắn theo khối"+ },+ "baseUrl": {+ "label": "URL API"+ },+ "cdnBaseUrl": {+ "label": "URL CDN"+ },+ "routeTag": {+ "label": "Thẻ định tuyến"+ },+ "stateDir": {+ "label": "Thư mục trạng thái"+ },+ "pollTimeout": {+ "label": "Thời gian chờ thăm dò (giây)"+ }}},"custom": {"qrAlt": "Mã QR đăng nhập WeChat","scanTitle": "Quét bằng WeChat",- "scanDescription": "Quét bằng WeChat trên điện thoại. nanobot lưu trạng thái cục bộ sau khi đăng nhập.","waiting": "Đang chờ bạn quét mã bằng WeChat…","connected": "WeChat đã kết nối.","stopped": "Đăng nhập WeChat đã dừng.",diff --git a/nanobot/channels/weixin/webui/locales/zh-CN.json b/nanobot/channels/weixin/webui/locales/zh-CN.jsonindex 5053c44d7..9df8144dd 100644--- a/nanobot/channels/weixin/webui/locales/zh-CN.json+++ b/nanobot/channels/weixin/webui/locales/zh-CN.json@@ -1,18 +1,9 @@{"displayName": "微信",- "description": "在微信会话中使用 nanobot。",- "requirements": "微信渠道配置和网关","setup": {"primaryAction": "连接微信","docsLabel": "打开微信配置指南","officialLabel": "打开微信",- "tryIt": "二维码登录完成后,向已连接的账户发送一条微信私信。",- "summary": "微信通过二维码登录,并将账户状态保存在本地。",- "steps": [- "点击连接,用手机微信扫描二维码。",- "微信接收消息期间请保持本地网关运行。",- "发送一条私信测试,确认账户已连接。"- ],"fields": {"allowFrom": {"label": "允许的用户",@@ -22,26 +13,53 @@"label": "令牌","placeholder": "二维码登录后自动保存"},- "sendProgress": { "label": "发送进度消息" },- "sendToolHints": { "label": "发送工具执行提示" },- "streaming": { "label": "使用流式 API" },- "replyProgressMessages": { "label": "发送结构化进度" },- "replyProgressMaxMessages": { "label": "结构化进度消息上限" },- "contextMessageBudget": { "label": "上下文消息数量上限" },- "blockStreaming": { "label": "分块发送回复" },- "blockStreamingMinChars": { "label": "最小分块字符数" },- "blockStreamingMaxMessages": { "label": "分块消息上限" },- "baseUrl": { "label": "API 地址" },- "cdnBaseUrl": { "label": "CDN 地址" },- "routeTag": { "label": "路由标签" },- "stateDir": { "label": "状态目录" },- "pollTimeout": { "label": "轮询超时(秒)" }+ "sendProgress": {+ "label": "发送进度消息"+ },+ "sendToolHints": {+ "label": "发送工具执行提示"+ },+ "streaming": {+ "label": "使用流式 API"+ },+ "replyProgressMessages": {+ "label": "发送结构化进度"+ },+ "replyProgressMaxMessages": {+ "label": "结构化进度消息上限"+ },+ "contextMessageBudget": {+ "label": "上下文消息数量上限"+ },+ "blockStreaming": {+ "label": "分块发送回复"+ },+ "blockStreamingMinChars": {+ "label": "最小分块字符数"+ },+ "blockStreamingMaxMessages": {+ "label": "分块消息上限"+ },+ "baseUrl": {+ "label": "API 地址"+ },+ "cdnBaseUrl": {+ "label": "CDN 地址"+ },+ "routeTag": {+ "label": "路由标签"+ },+ "stateDir": {+ "label": "状态目录"+ },+ "pollTimeout": {+ "label": "轮询超时(秒)"+ }}},"custom": {"qrAlt": "微信登录二维码","scanTitle": "使用微信扫码",- "scanDescription": "用手机微信扫描此二维码。登录后,nanobot 会将账户状态保存在本地。","waiting": "等待用微信扫码…","connected": "微信已连接。","stopped": "微信登录已停止。",diff --git a/nanobot/channels/weixin/webui/locales/zh-TW.json b/nanobot/channels/weixin/webui/locales/zh-TW.jsonindex 76414db17..2b4a74486 100644--- a/nanobot/channels/weixin/webui/locales/zh-TW.json+++ b/nanobot/channels/weixin/webui/locales/zh-TW.json@@ -1,18 +1,9 @@{"displayName": "微信",- "description": "在微信對話中使用 nanobot。",- "requirements": "微信管道設定和閘道","setup": {"primaryAction": "連接微信","docsLabel": "開啟微信設定指南","officialLabel": "開啟微信",- "tryIt": "QR Code登入完成後,向已連接的帳戶傳送一則微信私訊。",- "summary": "微信透過QR Code登入,並將帳戶狀態儲存在本機。",- "steps": [- "點選連接,用手機微信掃描QR Code。",- "微信接收訊息期間請保持本機閘道執行。",- "傳送一則私訊測試,確認帳戶已連接。"- ],"fields": {"allowFrom": {"label": "允許的使用者",@@ -22,26 +13,53 @@"label": "權杖","placeholder": "QR Code登入後自動儲存"},- "sendProgress": { "label": "傳送進度訊息" },- "sendToolHints": { "label": "傳送工具執行摘要" },- "streaming": { "label": "使用串流 API" },- "replyProgressMessages": { "label": "傳送結構化進度" },- "replyProgressMaxMessages": { "label": "結構化進度訊息上限" },- "contextMessageBudget": { "label": "上下文訊息數量上限" },- "blockStreaming": { "label": "分塊傳送回覆" },- "blockStreamingMinChars": { "label": "最小分塊字元數" },- "blockStreamingMaxMessages": { "label": "分塊訊息上限" },- "baseUrl": { "label": "API 位址" },- "cdnBaseUrl": { "label": "CDN 位址" },- "routeTag": { "label": "路由標籤" },- "stateDir": { "label": "狀態目錄" },- "pollTimeout": { "label": "輪詢逾時(秒)" }+ "sendProgress": {+ "label": "傳送進度訊息"+ },+ "sendToolHints": {+ "label": "傳送工具執行摘要"+ },+ "streaming": {+ "label": "使用串流 API"+ },+ "replyProgressMessages": {+ "label": "傳送結構化進度"+ },+ "replyProgressMaxMessages": {+ "label": "結構化進度訊息上限"+ },+ "contextMessageBudget": {+ "label": "上下文訊息數量上限"+ },+ "blockStreaming": {+ "label": "分塊傳送回覆"+ },+ "blockStreamingMinChars": {+ "label": "最小分塊字元數"+ },+ "blockStreamingMaxMessages": {+ "label": "分塊訊息上限"+ },+ "baseUrl": {+ "label": "API 位址"+ },+ "cdnBaseUrl": {+ "label": "CDN 位址"+ },+ "routeTag": {+ "label": "路由標籤"+ },+ "stateDir": {+ "label": "狀態目錄"+ },+ "pollTimeout": {+ "label": "輪詢逾時(秒)"+ }}},"custom": {"qrAlt": "微信登入QR Code","scanTitle": "使用微信掃描 QR Code",- "scanDescription": "用手機微信掃描此QR Code。登入後,nanobot 會將帳戶狀態儲存在本機。","waiting": "等待使用微信掃描 QR Code…","connected": "微信已連接。","stopped": "微信登入已停止。",diff --git a/nanobot/channels/weixin/webui/presentation.ts b/nanobot/channels/weixin/webui/presentation.tsindex ad04026b1..f97913b16 100644--- a/nanobot/channels/weixin/webui/presentation.ts+++ b/nanobot/channels/weixin/webui/presentation.ts@@ -4,9 +4,10 @@ export const WEIXIN_PRIMARY_FIELD_KEYS = ["channels.weixin.streaming",] as const;+export const WEIXIN_QR_TOKEN_FIELD_KEY = "channels.weixin.token";+export const WEIXIN_ADVANCED_FIELD_KEYS = ["channels.weixin.allowFrom",- "channels.weixin.token","channels.weixin.replyProgressMessages","channels.weixin.replyProgressMaxMessages","channels.weixin.contextMessageBudget",diff --git a/nanobot/channels/whatsapp/connect.py b/nanobot/channels/whatsapp/connect.pynew file mode 100644index 000000000..41eb4de43--- /dev/null+++ b/nanobot/channels/whatsapp/connect.py@@ -0,0 +1,338 @@+"""WhatsApp-owned interactive QR connection flow."""++from __future__ import annotations++import asyncio+import os+import secrets+import time+from contextlib import suppress+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING, Any, cast++from nanobot.channels.connect import ChannelConnectError, QueryParams, query_first+from nanobot.config.loader import load_config++if TYPE_CHECKING:+ from nanobot.channels.whatsapp.runtime import WhatsAppChannel+++_NATIVE_STOP_TIMEOUT_SECONDS = 10.0+_DATABASE_REPLACE_TIMEOUT_SECONDS = 10.0+_FINALIZE_POLL_WAIT_SECONDS = 0.05+++@dataclass(slots=True)+class WhatsAppConnectSession:+ id: str+ channel: WhatsAppChannel+ client: Any+ result: asyncio.Future[None]+ connect_task: asyncio.Task[asyncio.Task[Any] | None]+ target_path: Path+ pending_path: Path+ created_wall: float+ deadline: float+ qr_url: str = ""+ finalize_task: asyncio.Task[None] | None = None+++class WhatsAppConnectStore:+ """In-memory WhatsApp linked-device sessions for the WebUI."""++ def __init__(self) -> None:+ self._sessions: dict[str, WhatsAppConnectSession] = {}++ async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:+ if action == "start":+ force = (query_first(query, "force") or "").strip().lower() in {+ "1",+ "true",+ "yes",+ }+ return await self.start(force=force)++ session_id = (query_first(query, "session_id") or "").strip()+ if not session_id:+ raise ChannelConnectError("missing WhatsApp connect session")+ if action == "poll":+ return await self.poll(session_id)+ if action == "cancel":+ return await self.cancel(session_id)+ raise ChannelConnectError(f"unsupported WhatsApp connect action: {action}", status=404)++ async def start(self, *, force: bool = False) -> dict[str, Any]:+ await self._cleanup()+ channel, target_path = self._build_channel()+ if not force and self._local_state_present(target_path):+ return {+ "session_id": "",+ "status": "succeeded",+ "message": "WhatsApp is already connected.",+ "interval_ms": 2000,+ }++ session_id = secrets.token_urlsafe(18)+ pending_path = target_path.with_name(f".{target_path.name}.{session_id}.connect")+ pending_path.parent.mkdir(parents=True, exist_ok=True)+ self._remove_database(pending_path)+ channel.config.database_path = str(pending_path)+ now_wall = time.time()++ async def capture_qr(qr_data: bytes) -> None:+ session = self._sessions.get(session_id)+ if session is not None:+ session.qr_url = qr_data.decode("utf-8")++ client, result = channel.connect_open_client(capture_qr)+ connect_task = asyncio.create_task(+ self._connect(channel, client, result),+ name=f"whatsapp-connect-{session_id}",+ )+ session = WhatsAppConnectSession(+ id=session_id,+ channel=channel,+ client=client,+ result=result,+ connect_task=connect_task,+ target_path=target_path,+ pending_path=pending_path,+ created_wall=now_wall,+ deadline=time.monotonic() + 600,+ )+ self._sessions[session_id] = session++ qr_wait = asyncio.create_task(self._wait_for_qr(session))+ try:+ await asyncio.wait(+ {qr_wait, connect_task},+ timeout=3,+ return_when=asyncio.FIRST_COMPLETED,+ )+ finally:+ if not qr_wait.done():+ qr_wait.cancel()+ return self._pending_payload(session)++ async def poll(self, session_id: str) -> dict[str, Any]:+ await self._cleanup()+ session = self._sessions.get(session_id)+ if session is None:+ return {+ "session_id": session_id,+ "status": "expired",+ "message": "This WhatsApp login has expired. Start again.",+ }+ if not session.result.done():+ return self._pending_payload(session)++ finalize_task = session.finalize_task+ if finalize_task is None:+ finalize_task = asyncio.create_task(+ self._finalize_session(session),+ name=f"whatsapp-connect-finalize-{session.id}",+ )+ session.finalize_task = finalize_task+ if not finalize_task.done():+ # Finish fast clients in this request without letting native shutdown+ # block the polling response path.+ await asyncio.wait({finalize_task}, timeout=_FINALIZE_POLL_WAIT_SECONDS)+ if not finalize_task.done():+ payload = self._pending_payload(session)+ payload["qr_url"] = ""+ payload["message"] = "Finishing the WhatsApp connection."+ return payload++ self._sessions.pop(session_id, None)+ try:+ finalize_task.result()+ except Exception as exc:+ return {+ "session_id": session_id,+ "status": "failed",+ "message": f"WhatsApp QR login failed: {exc}",+ }+ return {+ "session_id": session_id,+ "status": "succeeded",+ "message": "WhatsApp is connected.",+ }++ async def _finalize_session(self, session: WhatsAppConnectSession) -> None:+ try:+ session.result.result()+ await self._close_session(session)+ await self._commit_database(session.pending_path, session.target_path)+ except BaseException:+ await self._close_session(session)+ self._remove_database(session.pending_path)+ raise++ async def cancel(self, session_id: str) -> dict[str, Any]:+ session = self._sessions.pop(session_id, None)+ if session is not None:+ await self._discard_session(session)+ return {+ "session_id": session_id,+ "status": "cancelled",+ "message": "WhatsApp login cancelled.",+ }++ async def _cleanup(self) -> None:+ expired = [+ session_id+ for session_id, session in self._sessions.items()+ if time.monotonic() >= session.deadline+ ]+ for session_id in expired:+ session = self._sessions.pop(session_id)+ await self._discard_session(session)++ async def close(self) -> None:+ """Stop every login client before the gateway event loop closes."""+ sessions = tuple(self._sessions.values())+ self._sessions.clear()+ for session in sessions:+ await self._discard_session(session)++ async def _discard_session(self, session: WhatsAppConnectSession) -> None:+ finalize_task = session.finalize_task+ if (+ finalize_task is not None+ and finalize_task is not asyncio.current_task()+ ):+ if not finalize_task.done():+ finalize_task.cancel()+ await asyncio.gather(finalize_task, return_exceptions=True)+ else:+ await self._close_session(session)+ self._remove_database(session.pending_path)++ @staticmethod+ async def _connect(+ channel: WhatsAppChannel,+ client: Any,+ result: asyncio.Future[None],+ ) -> asyncio.Task[Any] | None:+ try:+ return await channel.connect_start_client(client, result)+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ if not result.done():+ result.set_exception(exc)+ return None++ @staticmethod+ async def _wait_for_qr(session: WhatsAppConnectSession) -> None:+ while not session.qr_url and not session.result.done():+ await asyncio.sleep(0.05)++ @staticmethod+ async def _close_session(session: WhatsAppConnectSession) -> None:+ if not session.result.done():+ session.result.cancel()+ if not session.connect_task.done():+ session.connect_task.cancel()+ with suppress(Exception, asyncio.CancelledError):+ await session.connect_task+ native_task: asyncio.Task[Any] | None = None+ if session.connect_task.done() and not session.connect_task.cancelled():+ with suppress(Exception, asyncio.CancelledError):+ native_task = session.connect_task.result()+ client_native_task = getattr(session.client, "connect_task", None)+ if native_task is None and isinstance(client_native_task, asyncio.Task):+ native_task = cast(asyncio.Task[Any], client_native_task)+ with suppress(Exception):+ await asyncio.wait_for(session.client.stop(), timeout=5)+ if native_task is not None:+ if not native_task.done():+ try:+ # Stop only signals neonize's Go worker. Wait for that worker+ # to return so Windows releases its SQLite file handle before+ # the temporary login database is promoted.+ await asyncio.wait_for(+ asyncio.shield(native_task),+ timeout=_NATIVE_STOP_TIMEOUT_SECONDS,+ )+ except TimeoutError:+ native_task.cancel()+ await asyncio.gather(native_task, return_exceptions=True)++ @staticmethod+ def _build_channel() -> tuple[WhatsAppChannel, Path]:+ from nanobot.bus.queue import MessageBus+ from nanobot.channels.whatsapp.runtime import WhatsAppChannel++ section = getattr(load_config().channels, "whatsapp", None)+ if section is not None and hasattr(section, "model_dump"):+ config = section.model_dump(mode="json", by_alias=True)+ elif isinstance(section, dict):+ config = dict(cast(dict[str, Any], section))+ else:+ config = {}+ channel = WhatsAppChannel(config, MessageBus())+ return channel, channel.connect_database_path()++ @staticmethod+ def _local_state_present(path: Path) -> bool:+ try:+ return path.is_file() and path.stat().st_size > 0+ except OSError:+ return False++ @classmethod+ async def _commit_database(cls, pending: Path, target: Path) -> None:+ if not cls._local_state_present(pending):+ raise RuntimeError("WhatsApp connected but did not create a local session database")+ target.parent.mkdir(parents=True, exist_ok=True)+ for pending_file, target_file in cls._database_files(pending, target):+ if pending_file.exists():+ await cls._replace_database_file(pending_file, target_file)+ elif target_file != target and target_file.exists():+ target_file.unlink()++ @staticmethod+ async def _replace_database_file(source: Path, target: Path) -> None:+ deadline = time.monotonic() + _DATABASE_REPLACE_TIMEOUT_SECONDS+ while True:+ try:+ os.replace(source, target)+ return+ except PermissionError as exc:+ if time.monotonic() >= deadline:+ raise RuntimeError(+ "WhatsApp paired, but its local session database is still in use"+ ) from exc+ await asyncio.sleep(0.1)++ @classmethod+ def _remove_database(cls, path: Path) -> None:+ for candidate, _ in cls._database_files(path, path):+ with suppress(OSError):+ candidate.unlink()++ @staticmethod+ def _database_files(source: Path, target: Path) -> tuple[tuple[Path, Path], ...]:+ return (+ (source, target),+ (source.with_name(source.name + "-shm"), target.with_name(target.name + "-shm")),+ (source.with_name(source.name + "-wal"), target.with_name(target.name + "-wal")),+ )++ @staticmethod+ def _pending_payload(session: WhatsAppConnectSession) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "session_id": session.id,+ "status": "pending",+ "interval_ms": 2000,+ "expires_at_ms": int((session.created_wall + 600) * 1000),+ "message": "Waiting for the WhatsApp scan.",+ }+ if session.qr_url:+ payload["qr_url"] = session.qr_url+ return payload+++__all__ = ["WhatsAppConnectStore"]diff --git a/nanobot/channels/whatsapp/manifest.py b/nanobot/channels/whatsapp/manifest.pyindex e874804ec..00535ae0b 100644--- a/nanobot/channels/whatsapp/manifest.py+++ b/nanobot/channels/whatsapp/manifest.py@@ -8,6 +8,7 @@ from nanobot.channels.whatsapp.validation import validateSETUP_SPEC = ChannelSetupSpec(fields={+ "proxy": field(),"allowFrom": field("list", snapshot=False),"groupPolicy": field("enum",@@ -16,6 +17,7 @@ SETUP_SPEC = ChannelSetupSpec(snapshot=False,),"databasePath": field(writable=False, snapshot=False),+ "lidMappings": field("json", writable=False, snapshot=False),},official_url="https://faq.whatsapp.com/",validator=validate,@@ -25,11 +27,12 @@ PLUGIN = ChannelPlugin(name="whatsapp",display_name="WhatsApp",runtime=f"{__package__}.runtime:WhatsAppChannel",+ connector=f"{__package__}.connect:WhatsAppConnectStore",setup=SETUP_SPEC,management=ChannelManagementSpec(local_state_present=local_state_present),dependencies=(- "neonize>=0.3.18.post0,<0.4.0",+ "neonize>=0.4.3.post0,<0.5.0","segno>=1.6.1,<2.0.0",),- webui="webui/index.ts",+ webui="webui/index.tsx",)diff --git a/nanobot/channels/whatsapp/runtime.py b/nanobot/channels/whatsapp/runtime.pyindex 7a24e920c..73eb89863 100644--- a/nanobot/channels/whatsapp/runtime.py+++ b/nanobot/channels/whatsapp/runtime.py@@ -9,6 +9,7 @@ import reimport secretsimport timefrom collections import OrderedDict+from collections.abc import Awaitable, Callablefrom contextlib import suppressfrom pathlib import Pathfrom typing import Any, Literal, NamedTuple, cast@@ -32,6 +33,7 @@ class WhatsAppConfig(Base):allow_from: list[str] = Field(default_factory=list)group_policy: Literal["open", "mention"] = "open"database_path: str = ""+ proxy: str = ""lid_mappings: dict[str, str] = Field(default_factory=dict)@@ -325,6 +327,10 @@ class WhatsAppChannel(BaseChannel):configured = self.config.database_path.strip()return Path(configured).expanduser() if configured else _default_database_path()+ def connect_database_path(self) -> Path:+ """Return the session database target used by package-owned setup flows."""+ return self._database_path()+def _load_lid_mappings(self) -> dict[str, str]:mapping: dict[str, str] = {}for lid, phone in self.config.lid_mappings.items():@@ -339,19 +345,52 @@ class WhatsAppChannel(BaseChannel):db_path.parent.mkdir(parents=True, exist_ok=True)return api.NewAClient(str(db_path))+ async def _connect_client(self, client: Any) -> Any:+ proxy = self.config.proxy.strip()+ if not proxy:+ return await client.connect()+ if "://" not in proxy:+ proxy = f"http://{proxy}"+ from neonize._binder import ProxySettings++ return await client.connect(ProxySettings(proxy_address=proxy))++ def connect_open_client(+ self,+ qr_handler: Callable[[bytes], Awaitable[None]] | None = None,+ ) -> tuple[Any, asyncio.Future[None]]:+ """Create a login-only client for CLI or package-owned WebUI setup."""+ client = self._new_client()+ result = asyncio.get_running_loop().create_future()+ self._register_handlers(+ client,+ login_result=result,+ handle_messages=False,+ qr_handler=qr_handler,+ )+ return client, result++ async def connect_start_client(+ self,+ client: Any,+ result: asyncio.Future[None],+ ) -> asyncio.Task[Any] | None:+ """Start a login client and watch neonize's optional background task."""+ connect_task = await self._connect_client(client)+ self._fail_login_on_connect_task_done(connect_task, result)+ return connect_task+async def login(self, force: bool = False) -> bool:db_path = self._database_path()if force:self._reset_database(db_path)- client = self._new_client()- login_result = asyncio.get_running_loop().create_future()- self._register_handlers(client, login_result=login_result, handle_messages=False)+ client, login_result = self.connect_open_client()+ connect_task: asyncio.Task[Any] | None = Nonetry:self.logger.info("Starting WhatsApp login with neonize...")- connect_task = await client.connect()- self._fail_login_on_connect_task_done(connect_task, login_result)+ connect_task = await self.connect_start_client(client, login_result)await login_resultself.logger.info("WhatsApp login complete")return True@@ -359,6 +398,10 @@ class WhatsAppChannel(BaseChannel):self.logger.error("WhatsApp login failed: {}", exc)return Falsefinally:+ if connect_task is not None and not connect_task.done():+ connect_task.cancel()+ with suppress(Exception, asyncio.CancelledError):+ await connect_taskwith suppress(Exception):await client.stop()@@ -371,7 +414,7 @@ class WhatsAppChannel(BaseChannel):try:self.logger.info("Connecting WhatsApp channel with neonize...")- await client.connect()+ await self._connect_client(client)await client.idle()except asyncio.CancelledError:raise@@ -523,11 +566,15 @@ class WhatsAppChannel(BaseChannel):*,login_result: asyncio.Future[None] | None = None,handle_messages: bool,+ qr_handler: Callable[[bytes], Awaitable[None]] | None = None,) -> None:api = _load_neonize()@client.qrasync def _on_qr(_: Any, qr_data: bytes) -> None:+ if qr_handler is not None:+ await qr_handler(qr_data)+ returnimport segnoself.logger.info("Scan the WhatsApp QR code with Linked Devices")diff --git a/nanobot/channels/whatsapp/tests/test_connect.py b/nanobot/channels/whatsapp/tests/test_connect.pynew file mode 100644index 000000000..c75f4c292--- /dev/null+++ b/nanobot/channels/whatsapp/tests/test_connect.py@@ -0,0 +1,226 @@+from __future__ import annotations++import asyncio+import os+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from nanobot.channels.whatsapp.connect import WhatsAppConnectStore+++class _FakeClient:+ def __init__(+ self,+ channel: "_FakeChannel",+ *,+ complete: bool,+ stop_gate: asyncio.Event | None = None,+ linger_until_stopped: bool = False,+ ) -> None:+ self.channel = channel+ self.complete = complete+ self.result: asyncio.Future[None] | None = None+ self.qr_handler: Any = None+ self.stopped = False+ self.stop_gate = stop_gate+ self.linger_until_stopped = linger_until_stopped+ self.native_stop = asyncio.Event()+ self.native_released = False+ self.connect_task: asyncio.Task[None] | None = None++ async def connect(self) -> None:+ await self.qr_handler(b"whatsapp-qr-payload")+ if self.complete:+ Path(self.channel.config.database_path).write_bytes(b"new-session")+ assert self.result is not None+ self.result.set_result(None)+ if self.linger_until_stopped:+ await self.native_stop.wait()+ self.native_released = True+ return+ await asyncio.Event().wait()++ async def stop(self) -> None:+ if self.stop_gate is not None:+ await self.stop_gate.wait()+ self.native_stop.set()+ self.stopped = True+++class _FakeChannel:+ def __init__(+ self,+ *,+ complete: bool,+ stop_gate: asyncio.Event | None = None,+ linger_until_stopped: bool = False,+ ) -> None:+ self.config = SimpleNamespace(database_path="")+ self.client = _FakeClient(+ self,+ complete=complete,+ stop_gate=stop_gate,+ linger_until_stopped=linger_until_stopped,+ )++ def connect_open_client(+ self,+ qr_handler: Any,+ ) -> tuple[_FakeClient, asyncio.Future[None]]:+ result = asyncio.get_running_loop().create_future()+ self.client.result = result+ self.client.qr_handler = qr_handler+ return self.client, result++ async def connect_start_client(+ self,+ client: _FakeClient,+ _result: asyncio.Future[None],+ ) -> asyncio.Task[None] | None:+ if client.linger_until_stopped:+ client.connect_task = asyncio.create_task(client.connect())+ await asyncio.sleep(0)+ return client.connect_task+ await client.connect()+ return None+++async def test_whatsapp_connect_commits_new_session_after_scan(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ target = tmp_path / "neonize.db"+ target.write_bytes(b"old-session")+ channel = _FakeChannel(complete=True)+ store = WhatsAppConnectStore()+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))++ started = await store.start(force=True)+ completed = await store.poll(started["session_id"])++ assert started["status"] == "pending"+ assert started["qr_url"] == "whatsapp-qr-payload"+ assert completed["status"] == "succeeded"+ assert target.read_bytes() == b"new-session"+ assert channel.client.stopped is True+++async def test_whatsapp_connect_cancel_preserves_existing_session(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ target = tmp_path / "neonize.db"+ target.write_bytes(b"working-session")+ channel = _FakeChannel(complete=False)+ store = WhatsAppConnectStore()+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))++ started = await store.start(force=True)+ pending_path = Path(channel.config.database_path)+ pending_path.write_bytes(b"partial-session")+ cancelled = await store.cancel(started["session_id"])++ assert cancelled["status"] == "cancelled"+ assert target.read_bytes() == b"working-session"+ assert not pending_path.exists()+ assert channel.client.stopped is True+++async def test_whatsapp_connect_clears_qr_while_finishing_login(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ target = tmp_path / "neonize.db"+ stop_gate = asyncio.Event()+ channel = _FakeChannel(complete=True, stop_gate=stop_gate)+ store = WhatsAppConnectStore()+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))++ started = await store.start(force=True)+ finishing = await store.poll(started["session_id"])++ assert finishing["status"] == "pending"+ assert finishing["qr_url"] == ""++ stop_gate.set()+ await asyncio.sleep(0)+ completed = await store.poll(started["session_id"])++ assert completed["status"] == "succeeded"+ assert target.read_bytes() == b"new-session"+++async def test_whatsapp_connect_waits_for_native_client_before_committing(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ target = tmp_path / "neonize.db"+ channel = _FakeChannel(complete=True, linger_until_stopped=True)+ store = WhatsAppConnectStore()+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))++ started = await store.start(force=True)+ completed: dict[str, Any] = {"status": "pending"}+ for _ in range(10):+ completed = await store.poll(started["session_id"])+ if completed["status"] != "pending":+ break+ await asyncio.sleep(0)++ assert completed["status"] == "succeeded"+ assert channel.client.native_released is True+ assert target.read_bytes() == b"new-session"+++async def test_whatsapp_connect_retries_transient_windows_database_lock(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ pending = tmp_path / ".neonize.db.connect"+ target = tmp_path / "neonize.db"+ pending.write_bytes(b"new-session")+ replace = os.replace+ attempts = 0++ def replace_after_release(source: Path, destination: Path) -> None:+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise PermissionError(32, "file is in use", str(source), str(destination))+ replace(source, destination)++ monkeypatch.setattr(os, "replace", replace_after_release)++ await WhatsAppConnectStore._commit_database(pending, target)++ assert attempts == 2+ assert target.read_bytes() == b"new-session"+++async def test_whatsapp_connect_store_closes_pending_login(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ target = tmp_path / "neonize.db"+ channel = _FakeChannel(complete=False)+ store = WhatsAppConnectStore()+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))++ started = await store.start(force=True)+ pending_path = Path(channel.config.database_path)+ pending_path.write_bytes(b"partial-session")++ await store.close()++ assert started["status"] == "pending"+ assert not pending_path.exists()+ assert channel.client.stopped is Truediff --git a/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py b/nanobot/channels/whatsapp/tests/test_whatsapp_channel.pyindex e3b80fa7a..ff3ee9063 100644--- a/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py+++ b/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py@@ -128,6 +128,36 @@ def _patch_receipt_type(monkeypatch):return ReceiptType+async def test_connect_client_normalizes_proxy_without_a_scheme(monkeypatch) -> None:+ class ProxySettings:+ def __init__(self, *, proxy_address: str) -> None:+ self.proxy_address = proxy_address++ monkeypatch.setitem(+ sys.modules,+ "neonize._binder",+ SimpleNamespace(ProxySettings=ProxySettings),+ )+ channel = _make_channel({"proxy": "127.0.0.1:23458"})+ client = SimpleNamespace(connect=AsyncMock(return_value=None))++ await channel._connect_client(client)++ settings = client.connect.await_args.args[0]+ assert settings.proxy_address == "http://127.0.0.1:23458"+++async def test_connect_client_without_proxy_uses_default_connection() -> None:+ channel = _make_channel({"proxy": ""})+ client = SimpleNamespace(connect=AsyncMock(return_value=None))++ await channel._connect_client(client)++ client.connect.assert_awaited_once_with()++class _FakeLoginClient:def __init__(self) -> None:self.handlers = {}diff --git a/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsx b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsxnew file mode 100644index 000000000..c4ba7d895--- /dev/null+++ b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsx@@ -0,0 +1,45 @@+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";+import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";++export function WhatsAppConnectFlow({+ token,+ idleLabel,+ connectRequestId,+ onFeaturesUpdate,+}: ChannelPluginConnectFlowProps) {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "whatsapp");++ return (+ <ChannelQrConnectFlow+ token={token}+ channelName="whatsapp"+ idleLabel={idleLabel}+ connectRequestId={connectRequestId}+ autoStart+ minimalPending+ forceOnRepeat+ labels={{+ qrAlt: tx("custom.qrAlt", "WhatsApp linking QR code"),+ scanTitle: tx("custom.scanTitle", "Link WhatsApp"),+ scanDescription: tx(+ "custom.scanDescription",+ "In WhatsApp, open Linked devices, choose Link a device, then scan this code.",+ ),+ waiting: tx("custom.waiting", "Waiting for WhatsApp…"),+ connected: tx("custom.connected", "WhatsApp is connected."),+ stopped: tx(+ "custom.stopped",+ "The WhatsApp connection attempt stopped. Start again to get a new code.",+ ),+ connecting: tx("custom.connecting", "Connecting…"),+ scanAgain: tx("custom.scanAgain", "Link another account"),+ connect: tx("custom.connect", "Link WhatsApp"),+ }}+ onFeaturesUpdate={onFeaturesUpdate}+ />+ );+}diff --git a/nanobot/channels/whatsapp/webui/index.ts b/nanobot/channels/whatsapp/webui/index.tsdeleted file mode 100644index fd5ccfc8d..000000000--- a/nanobot/channels/whatsapp/webui/index.ts+++ /dev/null@@ -1,20 +0,0 @@-import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";--export default {- presentation: {- displayName: "WhatsApp",- initials: "WA",- color: "#25D366",- logoUrl: "https://www.whatsapp.com/favicon.ico",- setup: {- mode: "connect",- command: "nanobot channels login whatsapp",- docsUrl: chatAppGuideUrl("whatsapp"),- manualFields: [- { key: "channels.whatsapp.allowFrom" },- { key: "channels.whatsapp.groupPolicy" },- ],- },- },-} satisfies ChannelUiContribution;diff --git a/nanobot/channels/whatsapp/webui/index.tsx b/nanobot/channels/whatsapp/webui/index.tsxnew file mode 100644index 000000000..fe18712b1--- /dev/null+++ b/nanobot/channels/whatsapp/webui/index.tsx@@ -0,0 +1,27 @@+import { MessageCircle } from "lucide-react";++import type { ChannelUiContribution } from "@/channel-plugins/types";+import { chatAppGuideUrl } from "@/components/settings/channels/catalog";++import { WhatsAppConnectFlow } from "./WhatsAppConnectFlow";++export default {+ presentation: {+ logoUrl: "https://static.whatsapp.net/rsrc.php/y1/r/FJbTMJqMap7.svg",+ displayName: "WhatsApp",+ initials: "WA",+ color: "#25D366",+ icon: MessageCircle,+ setup: {+ mode: "connect",+ docsUrl: chatAppGuideUrl("whatsapp"),+ manualFields: [+ { key: "channels.whatsapp.proxy", section: "connection" },+ { key: "channels.whatsapp.allowFrom", section: "access" },+ { key: "channels.whatsapp.groupPolicy", section: "behavior" },+ ],+ },+ },+ ConnectFlow: WhatsAppConnectFlow,+ canConnectBeforeConfigured: true,+} satisfies ChannelUiContribution;diff --git a/nanobot/channels/whatsapp/webui/locales/en.json b/nanobot/channels/whatsapp/webui/locales/en.jsonindex 34fbf56a9..d480464e1 100644--- a/nanobot/channels/whatsapp/webui/locales/en.json+++ b/nanobot/channels/whatsapp/webui/locales/en.json@@ -1,17 +1,8 @@{- "description": "Use nanobot from WhatsApp conversations.",- "requirements": "WhatsApp connection setup and gateway","setup": {"primaryAction": "Connect WhatsApp","docsLabel": "Open WhatsApp setup","officialLabel": "Open WhatsApp help",- "tryIt": "After terminal login finishes, send a WhatsApp DM to the connected account.",- "summary": "WhatsApp is connected by scanning a QR code from the account that should run the bot.",- "steps": [- "Run the WhatsApp login command shown below.",- "Scan the QR code in the terminal with WhatsApp on your phone.",- "Return here after login, enable WhatsApp, then send a direct test message."- ],"fields": {"allowFrom": {"label": "Allowed contacts",@@ -24,7 +15,22 @@"open": "All messages","allowlist": "Allowlist"}+ },+ "proxy": {+ "label": "Network proxy",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "WhatsApp linking QR code",+ "scanTitle": "Link WhatsApp",+ "scanDescription": "In WhatsApp, open Linked devices, choose Link a device, then scan this code.",+ "waiting": "Waiting for WhatsApp…",+ "connected": "WhatsApp is connected.",+ "stopped": "The WhatsApp connection attempt stopped. Start again to get a new code.",+ "connecting": "Connecting…",+ "scanAgain": "Link another account",+ "connect": "Link WhatsApp"}}diff --git a/nanobot/channels/whatsapp/webui/locales/es.json b/nanobot/channels/whatsapp/webui/locales/es.jsonindex 7719f9d50..a89e7cfe4 100644--- a/nanobot/channels/whatsapp/webui/locales/es.json+++ b/nanobot/channels/whatsapp/webui/locales/es.json@@ -1,17 +1,8 @@{- "description": "Usa nanobot desde conversaciones de WhatsApp.",- "requirements": "Configuración de conexión de WhatsApp y pasarela","setup": {"primaryAction": "Conectar WhatsApp","docsLabel": "Abrir guía de WhatsApp","officialLabel": "Abrir la ayuda de WhatsApp",- "tryIt": "Tras iniciar sesión en la terminal, envía un DM a la cuenta conectada.",- "summary": "WhatsApp se conecta escaneando un QR con la cuenta que ejecutará el bot.",- "steps": [- "Ejecuta el comando de inicio de WhatsApp mostrado abajo.",- "Escanea el QR de la terminal con WhatsApp en tu teléfono.",- "Vuelve aquí tras iniciar sesión, activa WhatsApp y envía un mensaje directo de prueba."- ],"fields": {"allowFrom": {"label": "Contactos permitidos",@@ -24,7 +15,22 @@"open": "Todos los mensajes","allowlist": "Lista de permitidos"}+ },+ "proxy": {+ "label": "Proxy de red",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "Código QR para vincular WhatsApp",+ "scanTitle": "Vincular WhatsApp",+ "scanDescription": "En WhatsApp, abre Dispositivos vinculados, elige Vincular un dispositivo y escanea este código.",+ "waiting": "Esperando a WhatsApp…",+ "connected": "WhatsApp está conectado.",+ "stopped": "El intento de conexión se detuvo. Inicia de nuevo para obtener otro código.",+ "connecting": "Conectando…",+ "scanAgain": "Vincular otra cuenta",+ "connect": "Vincular WhatsApp"}}diff --git a/nanobot/channels/whatsapp/webui/locales/fr.json b/nanobot/channels/whatsapp/webui/locales/fr.jsonindex d6c20e100..75bfe0c7c 100644--- a/nanobot/channels/whatsapp/webui/locales/fr.json+++ b/nanobot/channels/whatsapp/webui/locales/fr.json@@ -1,17 +1,8 @@{- "description": "Utilisez nanobot depuis les conversations WhatsApp.",- "requirements": "Configuration de la connexion WhatsApp et passerelle","setup": {"primaryAction": "Connecter WhatsApp","docsLabel": "Ouvrir le guide WhatsApp","officialLabel": "Ouvrir l’aide WhatsApp",- "tryIt": "Après la connexion dans le terminal, envoyez un message privé au compte connecté.",- "summary": "WhatsApp se connecte en scannant un QR code avec le compte qui exécutera le bot.",- "steps": [- "Exécutez la commande de connexion WhatsApp ci-dessous.",- "Scannez le QR code du terminal avec WhatsApp sur votre téléphone.",- "Revenez ici après la connexion, activez WhatsApp et envoyez un message privé test."- ],"fields": {"allowFrom": {"label": "Contacts autorisés",@@ -24,7 +15,22 @@"open": "Tous les messages","allowlist": "Liste d’autorisation"}+ },+ "proxy": {+ "label": "Proxy réseau",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "QR code d’association WhatsApp",+ "scanTitle": "Associer WhatsApp",+ "scanDescription": "Dans WhatsApp, ouvrez Appareils connectés, choisissez Connecter un appareil, puis scannez ce code.",+ "waiting": "En attente de WhatsApp…",+ "connected": "WhatsApp est connecté.",+ "stopped": "La tentative de connexion s’est arrêtée. Recommencez pour obtenir un nouveau code.",+ "connecting": "Connexion…",+ "scanAgain": "Associer un autre compte",+ "connect": "Associer WhatsApp"}}diff --git a/nanobot/channels/whatsapp/webui/locales/id.json b/nanobot/channels/whatsapp/webui/locales/id.jsonindex a5f1ebd3f..014f74650 100644--- a/nanobot/channels/whatsapp/webui/locales/id.json+++ b/nanobot/channels/whatsapp/webui/locales/id.json@@ -1,17 +1,8 @@{- "description": "Gunakan nanobot dari percakapan WhatsApp.",- "requirements": "Pengaturan koneksi WhatsApp dan gateway","setup": {"primaryAction": "Hubungkan WhatsApp","docsLabel": "Buka panduan WhatsApp","officialLabel": "Buka bantuan WhatsApp",- "tryIt": "Setelah login terminal selesai, kirim DM ke akun yang terhubung.",- "summary": "WhatsApp terhubung dengan memindai kode QR dari akun yang akan menjalankan bot.",- "steps": [- "Jalankan perintah login WhatsApp yang ditampilkan di bawah.",- "Pindai kode QR di terminal dengan WhatsApp di ponsel.",- "Kembali ke sini setelah login, aktifkan WhatsApp, lalu kirim pesan langsung uji."- ],"fields": {"allowFrom": {"label": "Kontak yang diizinkan",@@ -24,7 +15,22 @@"open": "Semua pesan","allowlist": "Daftar izin"}+ },+ "proxy": {+ "label": "Proxy jaringan",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "Kode QR penautan WhatsApp",+ "scanTitle": "Tautkan WhatsApp",+ "scanDescription": "Di WhatsApp, buka Perangkat tertaut, pilih Tautkan perangkat, lalu pindai kode ini.",+ "waiting": "Menunggu WhatsApp…",+ "connected": "WhatsApp terhubung.",+ "stopped": "Upaya koneksi berhenti. Mulai lagi untuk mendapatkan kode baru.",+ "connecting": "Menghubungkan…",+ "scanAgain": "Tautkan akun lain",+ "connect": "Tautkan WhatsApp"}}diff --git a/nanobot/channels/whatsapp/webui/locales/ja.json b/nanobot/channels/whatsapp/webui/locales/ja.jsonindex 7c04b3eaa..111500951 100644--- a/nanobot/channels/whatsapp/webui/locales/ja.json+++ b/nanobot/channels/whatsapp/webui/locales/ja.json@@ -1,17 +1,8 @@{- "description": "WhatsApp の会話から nanobot を利用します。",- "requirements": "WhatsApp 接続設定とゲートウェイ","setup": {"primaryAction": "WhatsApp に接続","docsLabel": "WhatsApp 設定ガイドを開く","officialLabel": "WhatsApp ヘルプを開く",- "tryIt": "ターミナルでのログイン後、接続したアカウントに WhatsApp の DM を送信します。",- "summary": "ボットを動かす WhatsApp アカウントで QR コードを読み取って接続します。",- "steps": [- "下に表示された WhatsApp ログインコマンドを実行します。",- "スマートフォンの WhatsApp でターミナルの QR コードを読み取ります。",- "ログイン後に戻り、WhatsApp を有効にして DM でテストします。"- ],"fields": {"allowFrom": {"label": "許可する連絡先",@@ -24,7 +15,22 @@"open": "すべてのメッセージ","allowlist": "許可リスト"}+ },+ "proxy": {+ "label": "ネットワークプロキシ",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "WhatsApp リンク用 QR コード",+ "scanTitle": "WhatsApp をリンク",+ "scanDescription": "WhatsApp でリンク済みデバイスを開き、デバイスをリンクを選んでこのコードを読み取ります。",+ "waiting": "WhatsApp を待機中…",+ "connected": "WhatsApp に接続しました。",+ "stopped": "接続が停止しました。新しいコードを取得するには再開してください。",+ "connecting": "接続中…",+ "scanAgain": "別のアカウントをリンク",+ "connect": "WhatsApp をリンク"}}diff --git a/nanobot/channels/whatsapp/webui/locales/ko.json b/nanobot/channels/whatsapp/webui/locales/ko.jsonindex 431dbc395..3e449cca8 100644--- a/nanobot/channels/whatsapp/webui/locales/ko.json+++ b/nanobot/channels/whatsapp/webui/locales/ko.json@@ -1,17 +1,8 @@{- "description": "WhatsApp 대화에서 nanobot을 사용합니다.",- "requirements": "WhatsApp 연결 설정 및 게이트웨이","setup": {"primaryAction": "WhatsApp 연결","docsLabel": "WhatsApp 설정 가이드 열기","officialLabel": "WhatsApp 도움말 열기",- "tryIt": "터미널 로그인이 끝나면 연결된 계정으로 WhatsApp DM을 보내세요.",- "summary": "봇을 실행할 WhatsApp 계정으로 QR 코드를 스캔해 연결합니다.",- "steps": [- "아래 표시된 WhatsApp 로그인 명령을 실행하세요.",- "휴대폰 WhatsApp으로 터미널의 QR 코드를 스캔하세요.",- "로그인 후 여기로 돌아와 WhatsApp을 활성화하고 DM으로 테스트하세요."- ],"fields": {"allowFrom": {"label": "허용된 연락처",@@ -24,7 +15,22 @@"open": "모든 메시지","allowlist": "허용 목록"}+ },+ "proxy": {+ "label": "네트워크 프록시",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "WhatsApp 연결 QR 코드",+ "scanTitle": "WhatsApp 연결",+ "scanDescription": "WhatsApp에서 연결된 기기를 열고 기기 연결을 선택한 다음 이 코드를 스캔하세요.",+ "waiting": "WhatsApp 대기 중…",+ "connected": "WhatsApp이 연결되었습니다.",+ "stopped": "연결 시도가 중지되었습니다. 새 코드를 받으려면 다시 시작하세요.",+ "connecting": "연결 중…",+ "scanAgain": "다른 계정 연결",+ "connect": "WhatsApp 연결"}}diff --git a/nanobot/channels/whatsapp/webui/locales/pt-BR.json b/nanobot/channels/whatsapp/webui/locales/pt-BR.jsonindex cde9c5da2..157f2ed48 100644--- a/nanobot/channels/whatsapp/webui/locales/pt-BR.json+++ b/nanobot/channels/whatsapp/webui/locales/pt-BR.json@@ -1,17 +1,8 @@{- "description": "Use o nanobot em conversas do WhatsApp.",- "requirements": "Configuração da conexão do WhatsApp e gateway","setup": {"primaryAction": "Conectar WhatsApp","docsLabel": "Abrir guia do WhatsApp","officialLabel": "Abrir ajuda do WhatsApp",- "tryIt": "Após o login no terminal, envie uma DM à conta conectada.",- "summary": "O WhatsApp conecta ao escanear um QR code com a conta que executará o bot.",- "steps": [- "Execute o comando de login do WhatsApp mostrado abaixo.",- "Escaneie o QR code do terminal com o WhatsApp no celular.",- "Volte aqui após o login, ative o WhatsApp e envie uma mensagem direta de teste."- ],"fields": {"allowFrom": {"label": "Contatos permitidos",@@ -24,7 +15,22 @@"open": "Todas as mensagens","allowlist": "Lista de permissão"}+ },+ "proxy": {+ "label": "Proxy de rede",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "QR code para vincular o WhatsApp",+ "scanTitle": "Vincular WhatsApp",+ "scanDescription": "No WhatsApp, abra Aparelhos conectados, escolha Conectar um aparelho e escaneie este código.",+ "waiting": "Aguardando o WhatsApp…",+ "connected": "O WhatsApp está conectado.",+ "stopped": "A tentativa de conexão parou. Inicie novamente para obter outro código.",+ "connecting": "Conectando…",+ "scanAgain": "Vincular outra conta",+ "connect": "Vincular WhatsApp"}}diff --git a/nanobot/channels/whatsapp/webui/locales/vi.json b/nanobot/channels/whatsapp/webui/locales/vi.jsonindex 1018123d5..0cd7fd947 100644--- a/nanobot/channels/whatsapp/webui/locales/vi.json+++ b/nanobot/channels/whatsapp/webui/locales/vi.json@@ -1,17 +1,8 @@{- "description": "Sử dụng nanobot từ các cuộc trò chuyện WhatsApp.",- "requirements": "Cài đặt kết nối WhatsApp và gateway","setup": {"primaryAction": "Kết nối WhatsApp","docsLabel": "Mở hướng dẫn WhatsApp","officialLabel": "Mở trợ giúp WhatsApp",- "tryIt": "Sau khi đăng nhập terminal, gửi tin nhắn riêng đến tài khoản đã kết nối.",- "summary": "WhatsApp kết nối bằng cách quét mã QR từ tài khoản sẽ chạy bot.",- "steps": [- "Chạy lệnh đăng nhập WhatsApp hiển thị bên dưới.",- "Quét mã QR trong terminal bằng WhatsApp trên điện thoại.",- "Sau khi đăng nhập, quay lại đây, bật WhatsApp và gửi tin nhắn riêng thử."- ],"fields": {"allowFrom": {"label": "Liên hệ được phép",@@ -24,7 +15,22 @@"open": "Mọi tin nhắn","allowlist": "Danh sách cho phép"}+ },+ "proxy": {+ "label": "Proxy mạng",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "Mã QR liên kết WhatsApp",+ "scanTitle": "Liên kết WhatsApp",+ "scanDescription": "Trong WhatsApp, mở Thiết bị đã liên kết, chọn Liên kết thiết bị rồi quét mã này.",+ "waiting": "Đang chờ WhatsApp…",+ "connected": "WhatsApp đã kết nối.",+ "stopped": "Kết nối đã dừng. Hãy bắt đầu lại để nhận mã mới.",+ "connecting": "Đang kết nối…",+ "scanAgain": "Liên kết tài khoản khác",+ "connect": "Liên kết WhatsApp"}}diff --git a/nanobot/channels/whatsapp/webui/locales/zh-CN.json b/nanobot/channels/whatsapp/webui/locales/zh-CN.jsonindex 7883c9311..9295f2622 100644--- a/nanobot/channels/whatsapp/webui/locales/zh-CN.json+++ b/nanobot/channels/whatsapp/webui/locales/zh-CN.json@@ -1,17 +1,8 @@{- "description": "在 WhatsApp 会话中使用 nanobot。",- "requirements": "WhatsApp 连接配置和网关","setup": {"primaryAction": "连接 WhatsApp","docsLabel": "打开 WhatsApp 配置指南","officialLabel": "打开 WhatsApp 帮助",- "tryIt": "终端登录完成后,向已连接的账户发送一条 WhatsApp 私信。",- "summary": "使用要运行机器人的 WhatsApp 账户扫描二维码即可完成连接。",- "steps": [- "运行下方显示的 WhatsApp 登录命令。",- "用手机 WhatsApp 扫描终端中的二维码。",- "登录后返回这里,启用 WhatsApp,然后发送一条私信测试。"- ],"fields": {"allowFrom": {"label": "允许的联系人",@@ -24,7 +15,22 @@"open": "所有消息","allowlist": "白名单"}+ },+ "proxy": {+ "label": "网络代理",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "WhatsApp 关联二维码",+ "scanTitle": "关联 WhatsApp",+ "scanDescription": "在 WhatsApp 中打开“已关联的设备”,选择“关联设备”,然后扫描此二维码。",+ "waiting": "正在等待 WhatsApp 扫码…",+ "connected": "WhatsApp 已连接。",+ "stopped": "WhatsApp 连接已停止。请重新开始以获取新二维码。",+ "connecting": "正在连接…",+ "scanAgain": "关联其他账户",+ "connect": "关联 WhatsApp"}}diff --git a/nanobot/channels/whatsapp/webui/locales/zh-TW.json b/nanobot/channels/whatsapp/webui/locales/zh-TW.jsonindex 3eed6f4b6..7757227d5 100644--- a/nanobot/channels/whatsapp/webui/locales/zh-TW.json+++ b/nanobot/channels/whatsapp/webui/locales/zh-TW.json@@ -1,17 +1,8 @@{- "description": "在 WhatsApp 對話中使用 nanobot。",- "requirements": "WhatsApp 連接設定和閘道","setup": {"primaryAction": "連接 WhatsApp","docsLabel": "開啟 WhatsApp 設定指南","officialLabel": "開啟 WhatsApp 說明",- "tryIt": "終端機登入完成後,向已連接的帳戶傳送一則 WhatsApp 私訊。",- "summary": "使用要執行機器人的 WhatsApp 帳戶掃描QR Code即可完成連接。",- "steps": [- "執行下方顯示的 WhatsApp 登入指令。",- "用手機 WhatsApp 掃描終端機中的QR Code。",- "登入後返回這裡,啟用 WhatsApp,然後傳送一則私訊測試。"- ],"fields": {"allowFrom": {"label": "允許的聯絡人",@@ -24,7 +15,22 @@"open": "所有訊息","allowlist": "允許清單"}+ },+ "proxy": {+ "label": "網路代理",+ "placeholder": "http://127.0.0.1:7890"}}+ },+ "custom": {+ "qrAlt": "WhatsApp 連結QR Code",+ "scanTitle": "連結 WhatsApp",+ "scanDescription": "在 WhatsApp 中開啟「已連結裝置」,選擇「連結裝置」,然後掃描此QR Code。",+ "waiting": "正在等待 WhatsApp 掃描…",+ "connected": "WhatsApp 已連接。",+ "stopped": "WhatsApp 連接已停止。請重新開始以取得新的QR Code。",+ "connecting": "正在連接…",+ "scanAgain": "連結其他帳戶",+ "connect": "連結 WhatsApp"}}diff --git a/nanobot/optional_features.py b/nanobot/optional_features.pyindex c3dac6f89..0724763c2 100644--- a/nanobot/optional_features.py+++ b/nanobot/optional_features.py@@ -451,6 +451,7 @@ def optional_features_payload(),"type": "channel" if is_channel else "feature","installed": installed,+ "requires_dependencies": has_dependencies,"install_supported": has_dependencies or is_channel,"requires_restart": _feature_requires_restart(name, is_channel=is_channel),}@@ -639,6 +640,104 @@ def _combined_channel_runtime_state(return "stopped"+def _install_feature_dependencies(+ name: str,+ dependencies: list[str] | None,+ *,+ allow_install: bool,+ runner: Any,+) -> bool:+ """Ensure one feature's declared dependencies are present.++ Returns ``True`` only when this call ran an installer. Package-install+ authorization belongs here so every WebUI action gets the same policy.+ """+ if not dependencies or extra_installed(name, dependencies):+ return False+ if not allow_install:+ raise OptionalFeatureError(+ "Installing optional features from a remote WebUI is disabled. "+ "Run this action from localhost or set tools.webuiAllowRemotePackageInstall to true.",+ status=403,+ )+ result = install_extra(+ name,+ dependencies,+ runner=runner,+ )+ if not result.ok:+ failed = command_text(result.failed_cmd or result.pip_cmd)+ detail = f": {result.output}" if result.output else ""+ raise OptionalFeatureError(f"Failed: {failed}{detail}", status=500)+ return True+++def install_optional_feature_support(+ name: str,+ *,+ config_path: Path | None = None,+ allow_install: bool = True,+ runner: Any = run_install_command,+) -> dict[str, Any]:+ """Install channel dependencies without enabling or changing configuration."""+ from nanobot.channels.registry import discover_plugins+ from nanobot.config.loader import get_config_path, load_config++ config_path = config_path or get_config_path()+ extras = optional_dependency_groups()+ channel_plugins = discover_plugins()+ known = set(channel_plugins) | set(extras)+ if name not in known:+ available = ", ".join(sorted(known))+ raise OptionalFeatureError(f"Unknown feature: {name}. Available: {available}", status=404)++ channel_plugin = channel_plugins.get(name)+ if channel_plugin is None:+ raise OptionalFeatureError(+ "Install-only actions are supported for channel features only.",+ status=400,+ )+ dependencies = _feature_dependencies(name, channel_plugin, extras)+ installed_now = _install_feature_dependencies(+ name,+ dependencies,+ allow_install=allow_install,+ runner=runner,+ )+ if dependencies and not extra_installed(name, dependencies):+ raise OptionalFeatureError(+ f"Installed support for channel '{name}', but its dependencies are still unavailable.",+ status=500,+ )++ payload = optional_features_payload(config=load_config(config_path))+ feature = next(+ (item for item in payload["features"] if item.get("name") == name),+ None,+ )+ if feature is None or not feature.get("installed"):+ raise OptionalFeatureError(+ f"Channel '{name}' dependencies are still unavailable after installation.",+ status=500,+ )+ message = (+ f"Installed support for channel '{name}'"+ if installed_now+ else f"Support for channel '{name}' is already installed"+ )+ payload["last_action"] = {+ "ok": True,+ "message": message,+ "enabled": bool(feature.get("enabled")),+ "installed": True,+ }+ # A dependency can replace a module that is already imported by the+ # gateway (for example neonize during WhatsApp setup). Keep the gateway+ # running, but require a restart before the channel can use the new code.+ payload["requires_restart"] = installed_now+ return payload++def enable_optional_feature(name: str,*,@@ -671,22 +770,12 @@ def enable_optional_feature(channel_plugin = channel_plugins.get(name)dependencies = _feature_dependencies(name, channel_plugin, extras)- if dependencies and not extra_installed(name, dependencies):- if not allow_install:- raise OptionalFeatureError(- "Installing optional features from a remote WebUI is disabled. "- "Run this action from localhost or set tools.webuiAllowRemotePackageInstall to true.",- status=403,- )- result = install_extra(- name,- dependencies,- runner=runner,- )- if not result.ok:- failed = command_text(result.failed_cmd or result.pip_cmd)- detail = f": {result.output}" if result.output else ""- raise OptionalFeatureError(f"Failed: {failed}{detail}", status=500)+ _install_feature_dependencies(+ name,+ dependencies,+ allow_install=allow_install,+ runner=runner,+ )channel_cls: Any | None = Nonetarget_instance_id: str | None = Nonediff --git a/nanobot/pairing/store.py b/nanobot/pairing/store.pyindex 260b2cb0f..9affe2588 100644--- a/nanobot/pairing/store.py+++ b/nanobot/pairing/store.py@@ -285,10 +285,11 @@ def get_approved(channel: str) -> list[str]:def format_pairing_reply(code: str) -> str:"""Return the pairing-code message sent to unrecognised DM senders."""return (- "Hi there! This assistant only responds to approved users.\n\n"+ "Hi! This is your private nanobot.\n\n"f"Your pairing code is: `{code}`\n\n"- "To get access, ask the owner to approve this request in the nanobot WebUI.\n"- f"If the WebUI is not available, the owner can also send `/pairing approve {code}`."+ "Open the nanobot WebUI and enter this code to pair your chat account.\n"+ f"Without the WebUI, approve it from an already paired chat with "+ f"`/pairing approve {code}`.")diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.pyindex 8416f3c4f..ae5541f37 100644--- a/nanobot/webui/inbound_commands.py+++ b/nanobot/webui/inbound_commands.py@@ -973,6 +973,7 @@ class WebUICommandRouter:self.request_tasks.clear()self.request_locks.clear()self.request_operations.clear()+ await self._http_router.settings_routes.close()self.gateway.tokens.clear()self.gateway.endpoint.clear()self._temporary_chats.close()diff --git a/nanobot/webui/nanobot_features_api.py b/nanobot/webui/nanobot_features_api.pyindex 3dc430b9d..2ad76f8f6 100644--- a/nanobot/webui/nanobot_features_api.py+++ b/nanobot/webui/nanobot_features_api.py@@ -9,6 +9,7 @@ from nanobot.optional_features import (OptionalFeatureError,disable_optional_feature,enable_optional_feature,+ install_optional_feature_support,optional_features_payload,)from nanobot.webui.http_utils import query_first@@ -42,9 +43,24 @@ def nanobot_features_action() -> dict[str, Any]:name = (query_first(query, "name") or "").strip()instance_id = nanobot_feature_instance_target(query)+ raw_install_only = query_first(query, "install_only")+ install_only = False+ if raw_install_only is not None:+ normalized = raw_install_only.strip().lower()+ if normalized not in {"1", "0", "true", "false", "yes", "no"}:+ raise OptionalFeatureError("install_only must be boolean")+ install_only = normalized in {"1", "true", "yes"}+ if action != "enable":+ raise OptionalFeatureError("install_only is only supported for enable actions")if not name:raise OptionalFeatureError("missing feature name")if action == "enable":+ if install_only:+ return install_optional_feature_support(+ name,+ config_path=config_path,+ allow_install=allow_install,+ )return enable_optional_feature(name,config_path=config_path,diff --git a/nanobot/webui/settings_routes.py b/nanobot/webui/settings_routes.pyindex 5b38494db..3512756e6 100644--- a/nanobot/webui/settings_routes.py+++ b/nanobot/webui/settings_routes.py@@ -258,6 +258,10 @@ class WebUISettingsRouter:)self._system = system_domain.SystemSettingsHandler(settings, logger)+ async def close(self) -> None:+ """Release state owned by settings domains."""+ await self._system.close()+async def dispatch(self,connection: Any,diff --git a/nanobot/webui/settings_system.py b/nanobot/webui/settings_system.pyindex 8588bd483..02f9ab119 100644--- a/nanobot/webui/settings_system.py+++ b/nanobot/webui/settings_system.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport inspect+import jsonimport reimport timefrom collections.abc import Callable, Iterable, Mapping@@ -265,6 +266,8 @@ def coerce_channel_value(allowed = Noneif kind in {"string", "secret"}:+ if kind == "secret" and raw_value is None:+ return ""value = raw_value.strip() if isinstance(raw_value, str) else str(raw_value)if kind == "secret" and not value:return _SKIP_FIELD@@ -291,6 +294,25 @@ def coerce_channel_value(except (TypeError, ValueError) as exc:raise WebUISettingsError(f"'{raw_key}' must be a number") from exc+ if kind == "float":+ if raw_value in (None, ""):+ return _SKIP_FIELD+ try:+ return float(raw_value)+ except (TypeError, ValueError) as exc:+ raise WebUISettingsError(f"'{raw_key}' must be a number") from exc++ if kind == "json":+ if raw_value in (None, ""):+ return _SKIP_FIELD+ try:+ value = json.loads(raw_value) if isinstance(raw_value, str) else raw_value+ except (TypeError, ValueError) as exc:+ raise WebUISettingsError(f"'{raw_key}' must be valid JSON") from exc+ if not isinstance(value, dict):+ raise WebUISettingsError(f"'{raw_key}' must be a JSON object")+ return cast(dict[str, Any], value)+if kind == "bool":if isinstance(raw_value, bool):return raw_value@@ -366,6 +388,24 @@ class SystemSettingsHandler:self.logger = loggerself._channel_connectors: dict[str, Any] = {}+ async def close(self) -> None:+ """Release channel-owned setup sessions during gateway shutdown."""+ connectors = tuple(self._channel_connectors.items())+ self._channel_connectors.clear()+ for channel_name, connector in connectors:+ close = getattr(connector, "close", None)+ if not callable(close):+ continue+ try:+ result = close()+ if inspect.isawaitable(result):+ await result+ except Exception:+ self.logger.exception(+ "failed to close {} WebUI connector",+ channel_name,+ )+async def handle(self,action: str,@@ -524,6 +564,11 @@ class SystemSettingsHandler:action: str,operations: SystemSettingsOperations,) -> SettingsRouteResult:+ install_only = (+ action == "enable"+ and (query_first(request.query, "install_only") or "").strip().lower()+ in {"1", "true", "yes"}+ )try:payload = await asyncio.to_thread(self._nanobot_features_action,@@ -546,12 +591,13 @@ class SystemSettingsHandler:action,)return SettingsRouteResult.failure(status, message)- payload = await self._apply_feature_runtime_change(- action,- request.query,- payload,- operations,- )+ if not install_only:+ payload = await self._apply_feature_runtime_change(+ action,+ request.query,+ payload,+ operations,+ )payload = self._with_channel_runtime_status(payload, operations)return SettingsRouteResult.success(payload,diff --git a/tests/channels/test_channel_contracts.py b/tests/channels/test_channel_contracts.pyindex a726c0e1d..bb0909d7a 100644--- a/tests/channels/test_channel_contracts.py+++ b/tests/channels/test_channel_contracts.py@@ -572,4 +572,7 @@ def test_channel_setup_contract_owns_fields_and_validation() -> None:"choices": [],"required": True,}],+ "requirements": [+ {"alternatives": [["channels.setup_contract.token"]]},+ ],}diff --git a/tests/channels/test_channel_plugins.py b/tests/channels/test_channel_plugins.pyindex edef3a1d4..aadce9c44 100644--- a/tests/channels/test_channel_plugins.py+++ b/tests/channels/test_channel_plugins.py@@ -292,7 +292,7 @@ def test_special_setup_validation_is_owned_by_channel_package(name: str):assert plugin.setup.validator.__module__ == f"nanobot.channels.{name}.validation"[email protected]("name", ["feishu", "weixin"])[email protected]("name", ["feishu", "weixin", "whatsapp"])def test_interactive_connector_is_owned_by_channel_package(name: str):plugin = load_channel_package(name)@@ -582,6 +582,9 @@ def test_plugin_setup_contract_drives_feature_payload(monkeypatch: pytest.Monkey"required": False,},],+ "requirements": [+ {"alternatives": [["channels.setupplugin.token"]]},+ ],"official_url": "https://plugin.example/setup",}assert feature["configured_fields"] == [@@ -630,10 +633,11 @@ def test_plugin_contract_error_is_isolated_in_feature_payload(monkeypatch):"type": "channel","capabilities": [],"settings_visible": True,- "setup": {"fields": []},+ "setup": {"fields": [], "requirements": []},"enabled": False,"configured": False,"installed": True,+ "requires_dependencies": False,"ready": False,"status": "invalid_config","install_supported": True,@@ -842,10 +846,7 @@ def test_discover_plugins_excludes_internal_helpers():names = discover_plugins()- assert "_feishu_ws" not in namesassert "_setup" not in names- assert "setup" not in names- assert "_feishu_instances" not in namesdef test_discover_enabled_imports_only_enabled_packages():@@ -1880,6 +1881,47 @@ def test_enable_optional_feature_reports_install_failure(monkeypatch, tmp_path):assert not config_path.exists()+def test_install_only_adds_channel_support_without_enabling_it(monkeypatch, tmp_path):+ from nanobot.optional_features import InstallResult+ from nanobot.webui.nanobot_features_api import nanobot_features_action++ config_path = tmp_path / "config.json"+ config_path.write_text(+ json.dumps({"channels": {"fakeplugin": {"enabled": False, "marker": "keep"}}}),+ encoding="utf-8",+ )+ before = config_path.read_bytes()+ _stub_channel_registry(+ monkeypatch,+ _channel_plugin(_FakePlugin, dependencies=("fake-sdk>=1",)),+ )+ monkeypatch.setattr("nanobot.optional_features.optional_dependency_groups", lambda: {})+ installed = False++ def extra_installed(_name: str, _dependencies: list[str] | None) -> bool:+ return installed++ def install_extra(name: str, dependencies: list[str], *, runner) -> InstallResult:+ nonlocal installed+ installed = True+ return InstallResult(True, f"{name} support", ["pip", *dependencies])++ monkeypatch.setattr("nanobot.optional_features.extra_installed", extra_installed)+ monkeypatch.setattr("nanobot.optional_features.install_extra", install_extra)++ payload = nanobot_features_action(+ "enable",+ {"name": ["fakeplugin"], "install_only": ["true"]},+ config_path=config_path,+ )++ feature = payload["features"][0]+ assert config_path.read_bytes() == before+ assert feature["installed"] is True+ assert feature["enabled"] is False+ assert payload["requires_restart"] is True++def test_disable_optional_feature_rejects_unknown_features_and_non_channels(monkeypatch,tmp_path,@@ -2022,6 +2064,7 @@ def test_optional_features_payload_counts_enabled_channel_with_missing_dependencassert matrix["name"] == "matrix"assert matrix["enabled"] is Trueassert matrix["installed"] is False+ assert matrix["requires_dependencies"] is Trueassert matrix["ready"] is Falseassert payload["enabled_count"] == 1@@ -2303,50 +2346,21 @@ def test_optional_features_payload_lists_feishu_instances(monkeypatch):assert feishu["enabled"] is Trueassert feishu["configured"] is Trueassert payload["enabled_count"] == 1- assert feishu["instances"] == [- {- "id": "default",- "name": "nanobot",- "display_name": "Voraflare Bot",- "avatar_url": "https://example.com/bot.png",- "enabled": True,- "configured": True,- "config_values": {- "channels.feishu.appId": "cli_default",- "channels.feishu.domain": "feishu",- "channels.feishu.groupPolicy": "mention",- "channels.feishu.topicIsolation": "true",- },- "configured_fields": [- "channels.feishu.appId",- "channels.feishu.appSecret",- "channels.feishu.domain",- "channels.feishu.groupPolicy",- "channels.feishu.topicIsolation",- ],- },- {- "id": "product",- "name": "Product bot",- "display_name": "Product bot",- "avatar_url": "",- "enabled": False,- "configured": True,- "config_values": {- "channels.feishu.appId": "cli_product",- "channels.feishu.domain": "feishu",- "channels.feishu.groupPolicy": "mention",- "channels.feishu.topicIsolation": "true",- },- "configured_fields": [- "channels.feishu.appId",- "channels.feishu.appSecret",- "channels.feishu.domain",- "channels.feishu.groupPolicy",- "channels.feishu.topicIsolation",- ],- },+ instances = feishu["instances"]+ assert [+ (item["id"], item["name"], item["display_name"], item["avatar_url"], item["enabled"])+ for item in instances+ ] == [+ ("default", "nanobot", "Voraflare Bot", "https://example.com/bot.png", True),+ ("product", "Product bot", "Product bot", "", False),]+ assert [item["configured"] for item in instances] == [True, True]+ assert instances[0]["config_values"]["channels.feishu.appId"] == "cli_default"+ assert instances[1]["config_values"]["channels.feishu.appId"] == "cli_product"+ assert all(+ "channels.feishu.appSecret" in item["configured_fields"]+ for item in instances+ )def test_optional_features_payload_does_not_refresh_saved_feishu_identity(monkeypatch, tmp_path):@@ -2699,7 +2713,7 @@ def test_optional_dependency_metadata_for_enable():"wecom": ("wecom-aibot-sdk-python>=0.1.7,<0.2.0",),"weixin": ("qrcode[pil]>=8.0", "pycryptodome>=3.20.0"),"whatsapp": (- "neonize>=0.3.18.post0,<0.4.0",+ "neonize>=0.4.3.post0,<0.5.0","segno>=1.6.1,<2.0.0",),}diff --git a/tests/channels/test_channel_setup.py b/tests/channels/test_channel_setup.pyindex 39c89d5fb..2cbb2277c 100644--- a/tests/channels/test_channel_setup.py+++ b/tests/channels/test_channel_setup.py@@ -33,17 +33,58 @@ EXPECTED_CHANNELS = {"whatsapp",}+INTERNAL_CHANNEL_FIELDS = {+ "feishu": {"instanceId", "identityKey"},+ "signal": {"allowFrom"},+ "weixin": {"token"},+ "whatsapp": {"databasePath", "lidMappings"},+ # nanobot WebUI owns this transport and intentionally has no channel dialog.+ "websocket": {+ "allowFrom",+ "host",+ "maxMessageBytes",+ "path",+ "pingIntervalS",+ "pingTimeoutS",+ "port",+ "publicWsUrl",+ "sslCertfile",+ "sslKeyfile",+ "streaming",+ "token",+ "tokenIssuePath",+ "tokenIssueSecret",+ "tokenTtlS",+ "trustedProxyAuth",+ "unixSocketPath",+ "websocketRequiresToken",+ },+}+++def _flatten_channel_fields(value: object, prefix: str = "") -> set[str]:+ if not isinstance(value, dict):+ return {prefix} if prefix else set()+ if not value:+ return {prefix} if prefix else set()+ fields: set[str] = set()+ for key, nested in value.items():+ path = f"{prefix}.{key}" if prefix else key+ fields.update(_flatten_channel_fields(nested, path))+ return fields+def test_channel_setup_spec_derives_route_and_secret_metadata() -> None:slack = channel_setup_spec("slack")assert slack is not Noneassert slack.secrets == {"appToken", "botToken"}- assert slack.route_field_types == {- "appToken": "secret",- "botToken": "secret",- "groupPolicy": ("enum", {"mention", "open", "allowlist"}),- }+ assert slack.route_field_types["appToken"] == "secret"+ assert slack.route_field_types["botToken"] == "secret"+ assert slack.route_field_types["groupPolicy"] == (+ "enum",+ {"mention", "open", "allowlist"},+ )assert slack.simple_required_fields == ("appToken", "botToken")assert slack.fields["groupPolicy"].default == "mention"group_policy = next(@@ -73,7 +114,7 @@ def test_channel_setup_spec_separates_writable_and_snapshot_fields() -> None:assert matrix is not Noneassert discord is not None- assert "allowFrom" not in matrix.route_field_types+ assert "allowFrom" in matrix.route_field_typesassert "allowFrom" in matrix.snapshot_fieldsassert "allowFrom" in discord.route_field_typesassert "allowFrom" not in discord.snapshot_fields@@ -87,6 +128,7 @@ def test_webui_forms_have_writable_mattermost_and_whatsapp_contracts() -> None:assert whatsapp is not Noneassert mattermost.route_field_types["serverUrl"] == "string"assert mattermost.route_field_types["token"] == "secret"+ assert whatsapp.route_field_types["proxy"] == "string"assert whatsapp.route_field_types["allowFrom"] == "list"assert whatsapp.route_field_types["groupPolicy"] == ("enum",@@ -94,6 +136,19 @@ def test_webui_forms_have_writable_mattermost_and_whatsapp_contracts() -> None:)+def test_weixin_token_is_managed_only_by_qr_login() -> None:+ weixin = channel_setup_spec("weixin")++ assert weixin is not None+ assert weixin.simple_required_fields == ("token",)+ assert "token" not in weixin.route_field_types+ assert "token" not in weixin.snapshot_fields+ assert all(+ field["field"] != "token"+ for field in weixin.to_public_dict("weixin")["fields"]+ )++def test_every_channel_is_a_self_contained_package() -> None:channel_dir = Path(channel_setup_module.__file__).parentpackage_names = {path.parent.name for path in channel_dir.glob("*/manifest.py")}@@ -127,6 +182,13 @@ def test_channel_locales_cover_authoritative_setup_contracts() -> None:)setup_messages = english["setup"]field_messages = setup_messages.get("fields", {})+ contract_message_keys = {+ re.sub(r"[^A-Za-z0-9_-]+", "_", field_name)+ for field_name in plugin.setup.fields+ }+ assert not set(field_messages) - contract_message_keys, (+ f"{name} has locale copy for fields outside its setup contract"+ )for field_name, field in plugin.setup.fields.items():if not field.writable:continue@@ -136,6 +198,26 @@ def test_channel_locales_cover_authoritative_setup_contracts() -> None:assert setup_messages.get("officialLabel"), f"{name} has no localized official label"+def test_every_runtime_channel_field_has_a_webui_contract() -> None:+ for name, plugin in discover_plugins().items():+ runtime_fields = _flatten_channel_fields(plugin.load_channel_class().default_config())+ runtime_fields.discard("enabled")+ setup = plugin.setup+ assert setup is not None+ contract_fields = set(setup.fields)+ internal_fields = INTERNAL_CHANNEL_FIELDS.get(name, set())++ assert not runtime_fields - contract_fields - internal_fields, (+ f"{name} runtime fields missing from WebUI contract: "+ f"{sorted(runtime_fields - contract_fields - internal_fields)}"+ )+ assert not {+ field_name+ for field_name in runtime_fields - internal_fields+ if field_name not in setup.route_field_types+ }, f"{name} has user-configurable runtime fields that WebUI cannot save"++def test_channel_manifests_only_import_contract_modules() -> None:channel_dir = Path(channel_setup_module.__file__).parentallowed_imports = {@@ -184,6 +266,24 @@ def test_weixin_package_manifest_owns_runtime_and_webui_metadata() -> None:assert plugin.webui == "webui/index.tsx"+def test_whatsapp_package_manifest_owns_browser_connector() -> None:+ plugin = load_channel_package("whatsapp")++ assert plugin is not None+ assert plugin.connector == "nanobot.channels.whatsapp.connect:WhatsAppConnectStore"+ assert plugin.webui == "webui/index.tsx"+++def test_mochat_package_manifest_exposes_required_setup() -> None:+ plugin = load_channel_package("mochat")++ assert plugin is not None+ assert plugin.webui == "webui/index.ts"+ assert plugin.settings_visible is True+ assert plugin.setup is not None+ assert plugin.setup.simple_required_fields == ("clawToken",)++def test_package_manifests_do_not_import_runtimes() -> None:code = f"""import sysdiff --git a/tests/pairing/test_store.py b/tests/pairing/test_store.pyindex 0f681bd9b..cb9e8fd77 100644--- a/tests/pairing/test_store.py+++ b/tests/pairing/test_store.py@@ -64,6 +64,8 @@ class TestFormatPairingReply:assert "nanobot WebUI" in replyassert "ABCD-EFGH" in replyassert "/pairing approve ABCD-EFGH" in reply+ assert "private nanobot" in reply+ assert "approved users" not in replyclass TestApproveDeny:diff --git a/tests/webui/test_settings_routes.py b/tests/webui/test_settings_routes.pyindex 3fd98c94e..b655bebf9 100644--- a/tests/webui/test_settings_routes.py+++ b/tests/webui/test_settings_routes.py@@ -59,6 +59,24 @@ def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace:return request+async def test_close_releases_channel_connectors() -> None:+ router = _router()+ closed = False++ class Connector:+ async def close(self) -> None:+ nonlocal closed+ closed = True++ router._system._channel_connectors["whatsapp"] = Connector()++ await router.close()++ assert closed is True+ assert router._system._channel_connectors == {}++@pytest.mark.asyncioasync def test_mcp_list_serializes_local_runtime_failure_snapshot(tmp_path) -> None:config_path = tmp_path / "config.json"diff --git a/tests/webui/test_settings_system.py b/tests/webui/test_settings_system.pyindex 79af2ca4f..353e92765 100644--- a/tests/webui/test_settings_system.py+++ b/tests/webui/test_settings_system.py@@ -1,8 +1,10 @@from __future__ import annotations+from nanobot.channels.registry import load_channel_pluginfrom nanobot.config.schema import Configfrom nanobot.webui.settings_system import (coerce_channel_value,+ save_channel_config_values,system_settings_payload,update_agent_system_settings,)@@ -42,3 +44,24 @@ def test_system_domain_validates_channel_field_values() -> None:]assert coerce_channel_value("enabled", "yes", "bool") is Trueassert coerce_channel_value("port", "8765", "int") == 8765+ assert coerce_channel_value("delay", "0.6", "float") == 0.6+ assert coerce_channel_value("overrides", '{"123": "open"}', "json") == {+ "123": "open"+ }+ assert coerce_channel_value("token", None, "secret") == ""+++def test_channel_secret_is_cleared_only_by_explicit_null() -> None:+ config = Config.model_validate({+ "channels": {"matrix": {"password": "saved-password"}},+ })++ saved = save_channel_config_values(+ config,+ "matrix",+ {"channels.matrix.password": None},+ load_channel_plugin=load_channel_plugin,+ )++ assert saved == ["channels.matrix.password"]+ assert config.channels.matrix["password"] == ""diff --git a/webui/src/channel-plugins/i18n.ts b/webui/src/channel-plugins/i18n.tsindex 10984e1da..e686eb490 100644--- a/webui/src/channel-plugins/i18n.ts+++ b/webui/src/channel-plugins/i18n.ts@@ -3,21 +3,17 @@ import type { TFunction } from "i18next";type ChannelFieldMessages = {label: string;placeholder?: string;- help?: string;choices?: Record<string, string>;};export type ChannelMessages = {displayName?: string;- description: string;- requirements: string;setup: {primaryAction?: string;docsLabel?: string;officialLabel?: string;- summary?: string;- tryIt?: string;- steps: string[];+ presetLabel?: string;+ sections?: Record<string, string>;fields?: Record<string, ChannelFieldMessages>;actions?: Record<string, string>;presets?: Record<string, string>;diff --git a/webui/src/channel-plugins/types.ts b/webui/src/channel-plugins/types.tsindex af6977f5a..e97fe7281 100644--- a/webui/src/channel-plugins/types.ts+++ b/webui/src/channel-plugins/types.ts@@ -6,14 +6,24 @@ import type {NanobotFeaturesPayload,} from "@/lib/types";+export type ChannelFeatureActionOptions = {+ confirmed?: boolean;+ installOnly?: boolean;+};++export type ChannelFeatureAction = (+ action: "enable" | "disable",+ name: string,+ options?: ChannelFeatureActionOptions,+) => void;+export type ChannelPluginPanelProps = {connectRequestId?: number;token: string;feature: NanobotFeatureInfo;actionKey: string | null;- chatAppsDocsUrl?: string;showBrandLogos: boolean;- onAction: (action: "enable" | "disable", name: string) => void;+ onAction: ChannelFeatureAction;onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;};diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsxindex 8b4ab8a32..c4ea93646 100644--- a/webui/src/components/settings/SettingsPage.tsx+++ b/webui/src/components/settings/SettingsPage.tsx@@ -680,12 +680,16 @@ export function SettingsPage({/><NanobotFeatureInstallDialog- feature={nanobotFeatureConfirm}- installing={nanobotFeatureAction === `enable:${nanobotFeatureConfirm?.name ?? ""}`}+ feature={nanobotFeatureConfirm?.feature ?? null}+ installOnly={nanobotFeatureConfirm?.installOnly ?? false}+ installing={nanobotFeatureAction === `${nanobotFeatureConfirm?.installOnly ? "install" : "enable"}:${nanobotFeatureConfirm?.feature.name ?? ""}`}onOpenChange={(open) => {if (!open) setNanobotFeatureConfirm(null);}}- onConfirm={(feature) => handleNanobotFeatureAction("enable", feature.name, true)}+ onConfirm={(feature) => handleNanobotFeatureAction("enable", feature.name, {+ confirmed: true,+ installOnly: nanobotFeatureConfirm?.installOnly,+ })}/><AutomationDeleteDialogdiff --git a/webui/src/components/settings/channels/ChannelHelpMenu.tsx b/webui/src/components/settings/channels/ChannelHelpMenu.tsxnew file mode 100644index 000000000..e81994760--- /dev/null+++ b/webui/src/components/settings/channels/ChannelHelpMenu.tsx@@ -0,0 +1,48 @@+import { CircleHelp, ExternalLink } from "lucide-react";+import { useTranslation } from "react-i18next";+import { channelSetup } from "@/components/settings/channels/ChannelIdentity";+import { docsUrlWithBase } from "@/components/settings/channels/catalog";+import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";+import { Tooltip, TooltipProvider, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";+import type { NanobotFeatureInfo } from "@/lib/types";++export function ChannelHelpMenu({ feature, chatAppsDocsUrl }: {+ feature: NanobotFeatureInfo;+ chatAppsDocsUrl?: string;+}) {+ const { t, i18n } = useTranslation();+ const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);+ const links = [+ { url: setup.officialUrl, label: setup.officialLabel },+ { url: docsUrlWithBase(setup.docsUrl, chatAppsDocsUrl), label: setup.docsLabel },+ ].filter((link) => link.url);+ if (!links.length) return null;+ const label = t("settings.channels.help", { defaultValue: "Help" });+ return (+ <TooltipProvider>+ <DropdownMenu>+ <Tooltip>+ <TooltipTrigger asChild>+ <DropdownMenuTrigger asChild>+ <button type="button" aria-label={label}+ className="grid h-8 w-8 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">+ <CircleHelp className="h-4 w-4" aria-hidden />+ </button>+ </DropdownMenuTrigger>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="end">+ {links.map((link) => (+ <DropdownMenuItem key={link.url} asChild>+ <a href={link.url} target="_blank" rel="noreferrer">+ {link.label ?? label}+ <ExternalLink className="ml-2 h-3.5 w-3.5 text-muted-foreground" aria-hidden />+ </a>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </TooltipProvider>+ );+}diff --git a/webui/src/components/settings/channels/ChannelIdentity.tsx b/webui/src/components/settings/channels/ChannelIdentity.tsxindex 1afcb6f47..dfb7c8bd3 100644--- a/webui/src/components/settings/channels/ChannelIdentity.tsx+++ b/webui/src/components/settings/channels/ChannelIdentity.tsx@@ -1,5 +1,5 @@import { useMemo, type ReactNode } from "react";-import type { useTranslation } from "react-i18next";+import { useTranslation } from "react-i18next";import {channelFieldMessageKey,@@ -12,14 +12,17 @@ import {} from "@/channel-plugins/registry";import type {ChannelConfigField,+ ChannelFieldPresentation,ChannelSetupPresentation,} from "@/components/settings/channels/catalog";+import { channelValidationMessage } from "@/components/settings/channels/validationMessages";import { useLogoFallback } from "@/hooks/useLogoFallback";import { normalizeLocale } from "@/i18n/config";import { logoFallbackUrls } from "@/lib/provider-brand";import type { ChannelRuntimeStatus, NanobotFeatureInfo } from "@/lib/types";-export type ChannelFilter = "all" | "on" | "off";+export const CHANNEL_SETUP_PANEL_CLASS_NAME =+ "min-h-full rounded-panel bg-settings-surface p-6";export function channelSetup(feature: NanobotFeatureInfo,@@ -35,25 +38,23 @@ export function channelSetup(key,label: copy?.label ?? fieldLabel(key.split(".").at(-1) ?? key),placeholder: copy?.placeholder,- help: copy?.help,};};+ const localizePresentedField = (+ field: ChannelFieldPresentation,+ ): ChannelConfigField => ({+ ...localizeField(field.key),+ section: field.section,+ });const presentation: ChannelSetupPresentation = {...definition,primaryActionLabel: setupMessages?.primaryAction,docsLabel: setupMessages?.docsLabel,officialLabel: setupMessages?.officialLabel,- summary:- setupMessages?.summary- ?? "Enable turns on this channel in nanobot, but this integration still needs platform-specific setup before it can receive messages.",- tryIt: setupMessages?.tryIt,- steps: setupMessages?.steps ?? [- `Open ~/.nanobot/config.json and find channels.${feature.name}.`,- "Add the credentials required by that platform, using the channel documentation as the source of truth.",- "Restart nanobot, then send a small test message from that platform.",- ],- fields: definition?.fields?.map((field) => localizeField(field.key)),- manualFields: definition?.manualFields?.map((field) => localizeField(field.key)),+ presetLabel: setupMessages?.presetLabel,+ sectionLabels: setupMessages?.sections,+ fields: definition?.fields?.map(localizePresentedField),+ manualFields: definition?.manualFields?.map(localizePresentedField),actions: definition?.actions?.map((action) => ({...action,label: setupMessages?.actions?.[action.id] ?? fieldLabel(action.id),@@ -83,9 +84,11 @@ export function channelSetup(...copy,key: field.key,label: copy.label,+ section: copy.section ?? (field.required ? "credentials" : "advanced"),secret: field.kind === "secret",optional: !field.required,- inputType: field.kind === "int" ? "number" : undefined,+ kind: field.kind,+ inputType: channelFieldInputType(field.field, field.kind),defaultValue: field.default_value,options:field.kind === "enum" || field.kind === "bool"@@ -106,11 +109,24 @@ export function channelSetup(officialLabel:presentation.officialLabel?? (contract.official_url ? "Open official setup" : undefined),+ requirements: contract.requirements,fields: fields.length ? fields : undefined,manualFields: manual.length ? manual : undefined,};}+function channelFieldInputType(+ field: string,+ kind: string,+): ChannelConfigField["inputType"] {+ if (kind === "int" || kind === "float") return "number";+ const normalized = field.toLowerCase();+ if (normalized.includes("url")) return "url";+ if (normalized.includes("email") || normalized.includes("address")) return "email";+ if (normalized.includes("phone")) return "tel";+ return undefined;+}+function fieldLabel(value: string): string {const spaced = value.replace(/([a-z0-9])([A-Z])/g, "$1 $2")@@ -126,21 +142,14 @@ export function ChannelLogo({feature: NanobotFeatureInfo;showBrandLogos: boolean;}) {- const presentation = channelUiPresentation(feature.name, feature.webui);+ const presentation = channelUiPresentation(feature.name, feature.webui)+ ?? channelUiPresentation(feature.name);const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();const color = presentation?.color ?? "#6B7280";const Icon = presentation?.icon;const logoUrls = useMemo(() => logoFallbackUrls(presentation?.logoUrl), [presentation?.logoUrl]);const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);- if (feature.name === "websocket") {- return (- <span className="grid h-10 w-10 shrink-0 place-items-center rounded-control bg-background">- <img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6 object-contain" draggable={false} />- </span>- );- }-if (showBrandLogos && logoUrl) {return (<span@@ -194,24 +203,6 @@ export function localizedChannelDisplayName(return channelTranslator(t, channelUiOwner(feature.name))("displayName", fallback);}-export function channelDescription(feature: NanobotFeatureInfo, t: ReturnType<typeof useTranslation>["t"]): string {- const fallback =- `Use nanobot from ${channelDisplayName(feature)}.`;- return channelTranslator(t, channelUiOwner(feature.name))("description", fallback);-}--export function channelRequirements(feature: NanobotFeatureInfo, t: ReturnType<typeof useTranslation>["t"]): string {- const fallback =- "Channel credentials and gateway settings";- return channelTranslator(t, channelUiOwner(feature.name))("requirements", fallback);-}--export function channelMatchesFilter(feature: NanobotFeatureInfo, filter: ChannelFilter): boolean {- if (filter === "on") return channelIsRunning(feature);- if (filter === "off") return !channelIsRunning(feature);- return true;-}-export function channelIsRunning(feature: NanobotFeatureInfo): boolean {return feature.runtime_status === "running";}@@ -232,27 +223,11 @@ export function channelStatusLabel(}if (channelIsRunning(feature)) return tx("settings.values.on", "On");if (feature.enabled) return tx("settings.channels.runtimeStopped", "Not running");+ if (feature.configured === false) return tx("settings.channels.needsConfig", "Needs setup");+ if (feature.configured === true) return tx("settings.nanobotFeatures.ready", "Ready");return tx("settings.values.off", "Off");}-export function channelSearchText(- feature: NanobotFeatureInfo,- t?: ReturnType<typeof useTranslation>["t"],-): string {- return [- t ? localizedChannelDisplayName(feature, t) : undefined,- channelDisplayName(feature),- feature.display_name,- feature.name,- feature.status,- t ? channelDescription(feature, t) : undefined,- t ? channelRequirements(feature, t) : undefined,- ]- .join(" ")- .toLowerCase();-}--export function ChannelStatusBadge({children,status,@@ -281,10 +256,11 @@ export function ChannelRuntimeError({message?: string;className?: string;}) {+ const { t } = useTranslation();if (!message) return null;return (<div className={`${className} rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive`}>- {message}+ {channelValidationMessage(message, t)}</div>);}diff --git a/webui/src/components/settings/channels/ChannelInstancesPanel.tsx b/webui/src/components/settings/channels/ChannelInstancesPanel.tsxindex 28dd140c4..ece8fd078 100644--- a/webui/src/components/settings/channels/ChannelInstancesPanel.tsx+++ b/webui/src/components/settings/channels/ChannelInstancesPanel.tsx@@ -13,17 +13,12 @@ import {defaultChannelFieldValues,} from "@/components/settings/channels/CredentialForm";import {+ CHANNEL_SETUP_PANEL_CLASS_NAME,ChannelLogo,ChannelRuntimeError,- ChannelStatusBadge,channelSetup,- channelStatusLabel,localizedChannelDisplayName,} from "@/components/settings/channels/ChannelIdentity";-import {- ChannelGuideLink,- ChannelSetupSteps,-} from "@/components/settings/channels/ChannelSetupParts";import { Button } from "@/components/ui/button";import { useLogoFallback } from "@/hooks/useLogoFallback";import {@@ -41,7 +36,6 @@ import { cn } from "@/lib/utils";import { useClient } from "@/providers/ClientProvider";export type ChannelInstancesPanelCustomization = {- countLabel?: (runningCount: number) => string;toggleAriaLabel?: (instance: NanobotChannelInstanceInfo) => string;configuredLabel?: string;needsSetupLabel?: string;@@ -53,14 +47,12 @@ export type ChannelInstancesPanelCustomization = {export function ChannelInstancesPanel({feature,showBrandLogos,- chatAppsDocsUrl,instances: providedInstances,onFeaturesUpdate,customization = {},}: {feature: NanobotFeatureInfo;showBrandLogos: boolean;- chatAppsDocsUrl?: string;instances?: NanobotChannelInstanceInfo[];onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;customization?: ChannelInstancesPanelCustomization;@@ -70,8 +62,9 @@ export function ChannelInstancesPanel({const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });const displayName = localizedChannelDisplayName(feature, t);const instances = providedInstances ?? feature.instances ?? [];- const [selectedId, setSelectedId] = useState<string | null>(null);- const [busyInstanceId, setBusyInstanceId] = useState<string | null>(null);+ const [editor, setEditor] = useState<{ id: string; expanded: boolean } | null>(null);+ const selectedId = editor?.id;+ const [pendingToggle, setPendingToggle] = useState<{ id: string; checked: boolean } | null>(null);const [notice, setNotice] = useState<string | null>(null);const selected = selectedId ? instances.find((instance) => instance.id === selectedId) : undefined;const setup = useMemo(@@ -87,9 +80,9 @@ export function ChannelInstancesPanel({);const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});const [savingFields, setSavingFields] = useState(false);- const configuredCount = instances.filter((instance) => instance.configured).length;- const runningCount = instances.filter((instance) => instance.runtime_status === "running").length;- const selectedValuesKey = JSON.stringify(selected?.config_values ?? {});+ const selectedValuesKey = JSON.stringify(+ defaultChannelFieldValues(instanceFields, selected?.config_values),+ );const selectedConfiguredFields = useMemo(() => new Set(selected?.configured_fields ?? []),[selected?.configured_fields],@@ -97,17 +90,18 @@ export function ChannelInstancesPanel({useEffect(() => {if (selectedId && !instances.some((instance) => instance.id === selectedId)) {- setSelectedId(null);+ setEditor(null);}}, [instances, selectedId]);useEffect(() => {setFieldValues(defaultChannelFieldValues(instanceFields, selected?.config_values));setVisibleSecrets({});- }, [instanceFields, selected?.id, selectedValuesKey]);+ }, [selected?.id, selectedValuesKey]);const toggleInstance = async (instance: NanobotChannelInstanceInfo, checked: boolean) => {- setBusyInstanceId(instance.id);+ if (pendingToggle || savingFields) return;+ setPendingToggle({ id: instance.id, checked });setNotice(null);try {const payload = checked@@ -117,12 +111,12 @@ export function ChannelInstancesPanel({} catch (err) {setNotice((err as Error).message);} finally {- setBusyInstanceId(null);+ setPendingToggle(null);}};const saveSelectedInstanceSettings = async () => {- if (!selected) return;+ if (!selected || pendingToggle || savingFields) return;setSavingFields(true);setNotice(null);try {@@ -144,35 +138,24 @@ export function ChannelInstancesPanel({};return (- <aside className="min-h-full rounded-panel bg-settings-surface p-5">- <div className="flex items-start justify-between gap-3">- <div className="flex min-w-0 items-start gap-3">- <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />- <div className="min-w-0 flex-1">- <h3 className="truncate text-[18px] font-semibold leading-6 text-foreground">- {displayName}- </h3>- <p className="mt-1 text-[13px] leading-5 text-muted-foreground">- {customization.countLabel?.(runningCount)- ?? t("settings.channels.configuredInstances", {- count: configuredCount,- defaultValue: `${configuredCount} instances configured`,- })}- </p>- </div>- </div>- <div className="flex shrink-0 items-center gap-2">- <ChannelStatusBadge status={feature.runtime_status}>- {channelStatusLabel(feature, tx)}- </ChannelStatusBadge>- </div>+ <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>+ <div className="pe-20">+ <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />+ <h3 className="sr-only">{displayName}</h3></div><ChannelRuntimeError message={feature.runtime_error} /><div className="mt-5 space-y-3">{instances.map((instance) => {- const expanded = selected?.id === instance.id;+ const expanded = selected?.id === instance.id && editor?.expanded === true;+ const toggling = pendingToggle?.id === instance.id;+ const checked = toggling ? pendingToggle.checked : instanceToggleChecked(instance);+ const instanceSummary = customization.renderInstanceSummary+ ? customization.renderInstanceSummary(instance)+ : instance.id;+ const instanceAction = customization.renderInstanceAction?.(instance);+ const hasInstanceOverview = Boolean(instanceSummary || instanceAction);return (<articlekey={instance.id}@@ -180,18 +163,11 @@ export function ChannelInstancesPanel({"overflow-hidden rounded-floating transition-colors",expanded? "bg-background"- : "bg-background/70 settings-hover",+ : "bg-background/70",)}>- <div className="flex items-center gap-3 px-3 py-3">- <button- type="button"- className="flex min-w-0 flex-1 items-center gap-3 text-left"- onClick={() =>- setSelectedId((current) => (current === instance.id ? null : instance.id))- }- aria-expanded={expanded}- >+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-3">+ <div className="flex min-w-0 flex-[1_1_12rem] items-center gap-3"><ChannelInstanceAvatarfeature={feature}instance={instance}@@ -200,22 +176,43 @@ export function ChannelInstancesPanel({<span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground">{channelInstanceDisplayName(instance)}</span>- <ChevronDown- className={cn(- "h-4 w-4 shrink-0 text-muted-foreground transition-transform",- expanded && "rotate-180",- )}- aria-hidden+ <ChannelInstanceStatusBadge+ instance={instance}+ configuredLabel={customization.configuredLabel}+ needsSetupLabel={customization.needsSetupLabel}/>- </button>- <div className="flex shrink-0 items-center gap-2">- {busyInstanceId === instance.id ? (+ </div>+ <div className="ms-auto flex shrink-0 items-center gap-3">+ {instanceFields.length ? (+ <button+ type="button"+ className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"+ onClick={() =>+ setEditor((current) => ({+ id: instance.id,+ expanded: current?.id !== instance.id || !current.expanded,+ }))+ }+ aria-expanded={expanded}+ >+ {tx("settings.channels.advanced", "Advanced")}+ <ChevronDown+ className={cn(+ "h-3.5 w-3.5 transition-transform motion-reduce:transition-none",+ expanded && "rotate-180",+ )}+ aria-hidden+ />+ </button>+ ) : null}+ {toggling ? (<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />) : null}<ToggleButton- checked={instanceToggleChecked(instance)}+ checked={checked}disabled={- busyInstanceId === instance.id+ Boolean(pendingToggle)+ || savingFields|| !instance.configured}ariaLabel={customization.toggleAriaLabel?.(instance)@@ -223,51 +220,28 @@ export function ChannelInstancesPanel({name: channelInstanceDisplayName(instance),defaultValue: "{{name}} instance",})}- label={instanceToggleChecked(instance) ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}+ label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}onChange={(checked) => void toggleInstance(instance, checked)}/></div></div>- {expanded ? (- <div className="space-y-5 px-4 pb-4">- <section className="pt-4">- <div className="mb-3 flex items-start justify-between gap-3">+ {hasInstanceOverview || (expanded && instanceFields.length > 0) ? (+ <div className="space-y-3 px-4 pb-4 pt-1">+ {hasInstanceOverview ? <section className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ {instanceSummary ? (<p className="min-w-0 flex-1 truncate font-mono text-[11.5px] leading-6 text-muted-foreground">- {customization.renderInstanceSummary?.(instance) ?? instance.id}+ {instanceSummary}</p>- <ChannelInstanceStatusBadge- instance={instance}- configuredLabel={customization.configuredLabel}- needsSetupLabel={customization.needsSetupLabel}- />- </div>- {customization.renderInstanceAction?.(instance)}- </section>- <ChannelSetupSteps- steps={setup.steps}- action={- <ChannelGuideLink- feature={feature}- setup={setup}- chatAppsDocsUrl={chatAppsDocsUrl}- compact- />- }- />- {instanceFields.length ? (- <details className="group text-[12px] leading-5 text-muted-foreground">- <summary className="cursor-pointer list-none text-[12px] font-semibold text-foreground">- <span className="inline-flex items-center gap-1.5">- {tx("settings.channels.advanced", "Advanced")}- <ChevronDown- className="h-3.5 w-3.5 transition-transform group-open:rotate-180"- aria-hidden- />- </span>- </summary>+ ) : <span className="flex-1" />}+ {instanceAction}+ </section> : null}+ {expanded && instanceFields.length > 0 ? (+ <div className={cn(+ "text-[12px] leading-5 text-muted-foreground",+ hasInstanceOverview && "border-t border-border/50 pt-3",+ )}><form- className="mt-3"onSubmit={(event) => {event.preventDefault();void saveSelectedInstanceSettings();@@ -292,7 +266,7 @@ export function ChannelInstancesPanel({size="sm"variant="secondary"className="h-8 rounded-full bg-muted/70 px-3 text-[12px] font-semibold settings-hover"- disabled={savingFields}+ disabled={savingFields || Boolean(pendingToggle)}>{savingFields ? (<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />@@ -301,7 +275,7 @@ export function ChannelInstancesPanel({</Button></div></form>- </details>+ </div>) : null}</div>) : null}diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsxindex 911da2729..a3edb4bfc 100644--- a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx+++ b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx@@ -1,6 +1,7 @@+import { channelValidationMessage } from "./validationMessages";import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";import QRCode from "qrcode";-import { Check, Loader2, Network, RotateCcw } from "lucide-react";+import { Check, Loader2, RotateCcw } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/components/ui/button";@@ -28,13 +29,6 @@ export type ChannelQrConnectLabels = {connect: string;};-export type ChannelConnectStartOptions = {- domain?: string;- instanceId?: string;- mode?: "replace" | "create";- force?: boolean;-};-export type ChannelQrConnectPendingContext = {connect: ChannelConnectPayload;busy: boolean;@@ -45,10 +39,12 @@ export type ChannelQrConnectPendingContext = {export function ChannelQrConnectFlow({channelName,- startOptions = {},+ startParams = {},idleLabel,connectRequestId,forceOnRepeat = false,+ autoStart = false,+ minimalPending = false,labels,onFeaturesUpdate,pausePolling,@@ -58,10 +54,12 @@ export function ChannelQrConnectFlow({}: {token: string;channelName: string;- startOptions?: ChannelConnectStartOptions;+ startParams?: Readonly<Record<string, string | boolean>>;idleLabel?: string;connectRequestId?: number;forceOnRepeat?: boolean;+ autoStart?: boolean;+ minimalPending?: boolean;labels: ChannelQrConnectLabels;onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;pausePolling?: (payload: ChannelConnectPayload) => boolean;@@ -77,19 +75,16 @@ export function ChannelQrConnectFlow({const [qrDataUrl, setQrDataUrl] = useState("");const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);- const [handledRequestId, setHandledRequestId] = useState(0);+ const handledRequestId = useRef(0);+ const autoStarted = useRef(false);const pollInFlight = useRef(false);- const startDomain = startOptions.domain;- const startInstanceId = startOptions.instanceId;- const startMode = startOptions.mode;- const startForce = startOptions.force;const pending = connect?.status === "pending";const succeeded = connect?.status === "succeeded";const canStart = !pending && !busy;const pollingPaused = Boolean(connect && pausePolling?.(connect));const displayMessage = connect- ? resolveMessage?.(connect) ?? connect.message+ ? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined): undefined;useEffect(() => {@@ -176,10 +171,8 @@ export function ChannelQrConnectFlow({setError(null);try {const payload = await startChannelConnect(client, channelName, {- domain: startDomain,- instanceId: startInstanceId,- mode: startMode,- force: force || startForce,+ ...startParams,+ ...(force ? { force: true } : {}),});setConnect(payload);} catch (err) {@@ -187,13 +180,15 @@ export function ChannelQrConnectFlow({} finally {setBusy(false);}- }, [channelName, client, startDomain, startForce, startInstanceId, startMode]);+ }, [channelName, client, startParams]);useEffect(() => {- if (!connectRequestId || connectRequestId === handledRequestId) return;- setHandledRequestId(connectRequestId);+ const requested = Boolean(connectRequestId && connectRequestId !== handledRequestId.current);+ if (!requested && !(autoStart && !autoStarted.current)) return;+ handledRequestId.current = connectRequestId ?? 0;+ autoStarted.current = true;void start();- }, [connectRequestId, handledRequestId, start]);+ }, [autoStart, connectRequestId, start]);const cancel = async () => {if (!connect?.session_id) {@@ -250,7 +245,28 @@ export function ChannelQrConnectFlow({return (<div className="mt-3 space-y-3">- {pending ? (+ {autoStart && busy && !connect ? (+ <div role="status" className="grid min-h-[228px] place-items-center">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />+ <span className="sr-only">{labels.connecting}</span>+ </div>+ ) : null}+ {pending && minimalPending ? (+ <div className="flex min-h-[228px] flex-col items-center justify-center gap-4 py-4">+ <div className="grid h-[196px] w-[196px] place-items-center rounded-control bg-background shadow-[inset_0_0_0_1px_oklch(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_oklch(1_0_0/0.1)]">+ {qrDataUrl ? (+ <img+ src={qrDataUrl}+ alt={labels.qrAlt}+ className="h-[184px] w-[184px]"+ />+ ) : (+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />+ )}+ </div>+ {renderPending?.({ connect, busy, poll: submitPoll })}+ </div>+ ) : pending ? (<div className="grid gap-4 rounded-control border border-border/70 p-4 sm:grid-cols-[auto_minmax(0,1fr)]"><div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">{qrDataUrl ? (@@ -268,12 +284,12 @@ export function ChannelQrConnectFlow({{labels.scanTitle}</div><p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">- {labels.scanDescription}+ {qrDataUrl ? labels.scanDescription : null}</p>{renderPending?.({ connect, busy, poll: submitPoll }) ?? (<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground"><Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />- {labels.waiting}+ {qrDataUrl ? labels.waiting : labels.connecting}</div>)}<div className="mt-4 flex flex-wrap justify-end gap-2">@@ -311,7 +327,7 @@ export function ChannelQrConnectFlow({</div>) : null}- <div className="flex flex-wrap justify-end gap-2">+ {!pending && !(autoStart && busy && !connect) ? <div className="flex flex-wrap justify-end gap-2"><Buttontype="button"size="sm"@@ -324,16 +340,14 @@ export function ChannelQrConnectFlow({<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />) : succeeded ? (<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />- ) : (- <Network className="mr-1.5 h-3.5 w-3.5" aria-hidden />- )}+ ) : null}{pending? labels.connecting: succeeded? labels.scanAgain: idleLabel ?? labels.connect}</Button>- </div>+ </div> : null}</div>);}diff --git a/webui/src/components/settings/channels/ChannelSetupPanel.tsx b/webui/src/components/settings/channels/ChannelSetupPanel.tsxindex 34bbb33bc..92d6c65be 100644--- a/webui/src/components/settings/channels/ChannelSetupPanel.tsx+++ b/webui/src/components/settings/channels/ChannelSetupPanel.tsx@@ -1,25 +1,38 @@+import { channelValidationMessage } from "./validationMessages";import {Suspense,+ useCallback,useEffect,+ useId,useMemo,+ useRef,useState,type ComponentType,+ type ReactNode,} from "react";import {Check,ChevronDown,Clipboard,+ Download,Loader2,Plus,} from "lucide-react";import { useTranslation } from "react-i18next";import { channelUiContribution } from "@/channel-plugins/registry";-import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";+import type {+ ChannelFeatureAction,+ ChannelPluginConnectFlowProps,+} from "@/channel-plugins/types";import { ToggleButton } from "@/components/settings/ToggleButton";+import { useAutoSave } from "@/components/settings/shared/useAutoSave";import {+ type ChannelConfigField,+ type ChannelFieldSection,type ChannelProviderPreset,type ChannelSetupPresentation,+ type ChannelSetupRequirement,} from "@/components/settings/channels/catalog";import {CredentialForm,@@ -29,8 +42,8 @@ import {import {ChannelLogo,ChannelRuntimeError,+ CHANNEL_SETUP_PANEL_CLASS_NAME,ChannelStatusBadge,- channelRequirements,channelSetup,channelStatusLabel,channelToggleChecked,@@ -39,16 +52,13 @@ import {import {ChannelProviderPresets,ChannelSetupActions,- ChannelSetupLinks,- ChannelSetupSteps,- ChannelValidationBadge,- ChannelValidationChecks,- ChannelValidationDetails,+ ChannelValidationProgress,} from "@/components/settings/channels/ChannelSetupParts";import { ChannelInstancesPanel } from "@/components/settings/channels/ChannelInstancesPanel";import { Button } from "@/components/ui/button";import {configureChannel,+ disableNanobotFeature,validateChannel,} from "@/lib/api";import { copyTextToClipboard } from "@/lib/clipboard";@@ -65,56 +75,108 @@ export function ChannelCatalogRow({showBrandLogos,onSelect,actionKey,+ actionsDisabled = false,onAction,}: {feature: NanobotFeatureInfo;showBrandLogos: boolean;onSelect: (connect?: boolean) => void;actionKey: string | null;- onAction: (action: "enable" | "disable", name: string) => void;+ actionsDisabled?: boolean;+ onAction: ChannelFeatureAction;}) {const { t } = useTranslation();const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });const displayName = localizedChannelDisplayName(feature, t);const alwaysEnabled = feature.capabilities?.includes("always_enabled") ?? false;- const checked = alwaysEnabled || channelToggleChecked(feature);- const busy = actionKey === `enable:${feature.name}` || actionKey === `disable:${feature.name}`;+ const pendingChecked = actionKey === `enable:${feature.name}` ? true+ : actionKey === `disable:${feature.name}` ? false : null;+ const ownActionBusy = pendingChecked !== null || actionKey === `install:${feature.name}`;+ const checked = alwaysEnabled || (pendingChecked ?? channelToggleChecked(feature));+ const anyActionBusy = Boolean(actionKey);+ const installButtonRef = useRef<HTMLButtonElement | null>(null);+ const [installHint, setInstallHint] = useState(false);- return (- <div className="settings-list-row flex items-center gap-3 py-2.5 transition-colors settings-hover">- <button- type="button"- aria-label={t("settings.channels.selectChannel", {- name: displayName,- defaultValue: "View {{name}} settings",- })}- aria-haspopup="dialog"- onClick={() => onSelect()}- className={cn(- "group flex min-w-0 flex-1 select-none items-center gap-3 rounded-control text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border/80",- )}- >+ useEffect(() => {+ if (!installHint) return;+ const timeout = window.setTimeout(() => setInstallHint(false), 1400);+ return () => window.clearTimeout(timeout);+ }, [installHint]);++ const pointToInstall = () => {+ setInstallHint(true);+ installButtonRef.current?.focus();+ };+ const channelIdentity = (+ <><ChannelLogo feature={feature} showBrandLogos={showBrandLogos} /><div className="min-w-0 flex-1"><h3 className="truncate text-[14px] font-semibold leading-5 text-foreground">{displayName}</h3></div>- </button>- <div className="flex shrink-0 items-center gap-2">- {feature.runtime_status === "failed" ? (+ </>+ );++ return (+ <div className={cn(+ "settings-list-row flex min-w-0 items-center gap-3 py-2.5 transition-colors",+ !alwaysEnabled && "settings-hover",+ )}>+ {alwaysEnabled ? (+ <div className="flex min-w-0 flex-1 select-none items-center gap-3">+ {channelIdentity}+ </div>+ ) : (+ <button+ type="button"+ aria-label={t("settings.channels.selectChannel", {+ name: displayName,+ defaultValue: "View {{name}} settings",+ })}+ aria-haspopup="dialog"+ disabled={actionsDisabled}+ onClick={() => feature.installed ? onSelect() : pointToInstall()}+ className="group flex min-w-0 flex-1 select-none items-center gap-3 rounded-control text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border/80"+ >+ {channelIdentity}+ </button>+ )}+ {feature.runtime_status === "failed" ? (+ <div className="min-w-0 shrink truncate"><ChannelStatusBadge status={feature.runtime_status}>{channelStatusLabel(feature, tx)}</ChannelStatusBadge>- ) : null}- <ToggleButton checked={checked}- label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}- disabled={alwaysEnabled || busy || (!feature.install_supported && !feature.installed && !feature.enabled)}- ariaLabel={t("settings.channels.toggleChannel", { name: displayName, defaultValue: "{{name}} channel" })}- onChange={(enabled) => {- if (enabled && feature.configured === false) onSelect(true);- else onAction(enabled ? "enable" : "disable", feature.name);- }} />+ </div>+ ) : null}+ <div className="flex w-16 shrink-0 items-center justify-center">+ {!feature.installed ? (+ <Button ref={installButtonRef} type="button" variant="outline" size="icon"+ className={cn(+ "h-[22px] w-[38px] min-w-0 shrink-0 rounded-full border-border/70 bg-background p-0 shadow-sm settings-hover active:scale-[0.96]",+ installHint && "border-[#2997FF]/60 bg-[#2997FF]/10 text-[#087FE7] ring-2 ring-[#2997FF]/25 ring-offset-2",+ )}+ disabled={actionsDisabled || anyActionBusy || !feature.install_supported}+ aria-label={t("settings.channels.installChannel", { name: displayName })}+ onClick={() => {+ setInstallHint(false);+ onAction("enable", feature.name, { installOnly: true, confirmed: true });+ }}>+ {ownActionBusy+ ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ : <Download className="h-3.5 w-3.5" aria-hidden />}+ <span className="sr-only">{tx("settings.channels.install", "Install")}</span>+ </Button>+ ) : (+ <ToggleButton checked={checked}+ label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}+ disabled={alwaysEnabled || actionsDisabled || anyActionBusy}+ ariaLabel={t("settings.channels.toggleChannel", { name: displayName, defaultValue: "{{name}} channel" })}+ onChange={(enabled) => {+ if (enabled && feature.configured === false) onSelect(true);+ else onAction(enabled ? "enable" : "disable", feature.name);+ }} />+ )}</div></div>);@@ -124,27 +186,29 @@ export function ChannelSetupPanel({token,feature,actionKey,- chatAppsDocsUrl,showBrandLogos,onAction,onFeaturesUpdate,connectRequestId = 0,+ onBeforeCloseChange,}: {token: string;feature: NanobotFeatureInfo;actionKey: string | null;- chatAppsDocsUrl?: string;showBrandLogos: boolean;- onAction: (action: "enable" | "disable", name: string) => void;+ onAction: ChannelFeatureAction;onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;connectRequestId?: number;+ onBeforeCloseChange?: (handler: (() => Promise<boolean>) | null) => void;}) {const { t, i18n } = useTranslation();const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });const displayName = localizedChannelDisplayName(feature, t);const uiContribution = channelUiContribution(feature.name, feature.webui);const PluginPanel = uiContribution?.Panel;- if (PluginPanel) {+ const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);+ const missingSupport = !feature.installed;+ if (PluginPanel && !missingSupport) {return (<Suspense fallback={<ChannelPluginLoading />}><PluginPanel@@ -153,99 +217,106 @@ export function ChannelSetupPanel({feature={feature}actionKey={actionKey}showBrandLogos={showBrandLogos}- chatAppsDocsUrl={chatAppsDocsUrl}onAction={onAction}onFeaturesUpdate={onFeaturesUpdate}/></Suspense>);}- if (feature.instances !== undefined) {+ if (feature.instances !== undefined && !missingSupport) {return (<ChannelInstancesPanelfeature={feature}showBrandLogos={showBrandLogos}- chatAppsDocsUrl={chatAppsDocsUrl}onFeaturesUpdate={onFeaturesUpdate}/>);}- const enableBusy = actionKey === `enable:${feature.name}`;- const missingSupport = feature.enabled && !feature.installed;- const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);- const installSupportLabel = tx("settings.nanobotFeatures.installSupport", "Install support");+ const enableBusy = actionKey === `enable:${feature.name}` || actionKey === `install:${feature.name}`;+ const anyActionBusy = Boolean(actionKey);+ const installSupportLabel = tx("settings.channels.install", "Install");- return (- <aside className="settings-editor rounded-panel bg-settings-surface">- <div className="flex items-start justify-between gap-4 pr-8">- <div className="flex min-w-0 items-start gap-3">- <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />- <div className="min-w-0 flex-1">- <h3 className="truncate select-none text-[14px] font-semibold leading-5 text-foreground">- {displayName}- </h3>- {missingSupport && feature.install_supported ? (- <Button- type="button"- size="sm"- variant="secondary"- disabled={enableBusy}- onClick={() => onAction("enable", feature.name)}- className="mt-2 h-8 rounded-full px-3 text-[12px] font-semibold"- >- {enableBusy ? (- <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />- ) : (- <Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />- )}- {installSupportLabel}- </Button>- ) : null}- </div>- </div>- </div>-- <ChannelRuntimeError message={feature.runtime_error} className="mt-4" />+ const header = (+ <div className="flex min-w-0 items-center gap-3">+ <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />+ <h3 className="sr-only">{displayName}</h3>+ {missingSupport && feature.install_supported ? (+ <Button+ type="button"+ size="sm"+ variant="secondary"+ disabled={anyActionBusy}+ onClick={() => onAction("enable", feature.name, { installOnly: true, confirmed: true })}+ className="h-8 rounded-full px-3 text-[12px] font-semibold"+ >+ {enableBusy ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />+ )}+ {installSupportLabel}+ </Button>+ ) : null}+ </div>+ );- <ChannelSetupSurface+ return (+ <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>+ {missingSupport ? <>+ <div className="pe-20">{header}</div>+ <ChannelRuntimeError message={feature.runtime_error} className="mt-4" />+ </> : <ChannelSetupSurface+ key={feature.name}+ header={header}token={token}feature={feature}setup={setup}- chatAppsDocsUrl={chatAppsDocsUrl}connectRequestId={connectRequestId}- ConnectFlow={uiContribution?.ConnectFlow}+ ConnectFlow={feature.installed ? uiContribution?.ConnectFlow : undefined}onFeaturesUpdate={onFeaturesUpdate}- />+ onBeforeCloseChange={onBeforeCloseChange}+ />}</aside>);}function ChannelSetupSurface({+ header,token,feature,setup,- chatAppsDocsUrl,connectRequestId,ConnectFlow,onFeaturesUpdate,+ onBeforeCloseChange,}: {+ header: ReactNode;token: string;feature: NanobotFeatureInfo;setup: ChannelSetupPresentation;- chatAppsDocsUrl?: string;connectRequestId: number;ConnectFlow?: ComponentType<ChannelPluginConnectFlowProps>;onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;+ onBeforeCloseChange?: (handler: (() => Promise<boolean>) | null) => void;}) {const { client } = useClient();const { t } = useTranslation();const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });const [notice, setNotice] = useState<string | null>(null);const [saving, setSaving] = useState(false);+ const [autoSaving, setAutoSaving] = useState(false);+ const [autoSaveState, setAutoSaveState] = useState<"idle" | "saved">("idle");+ const autoSavePromiseRef = useRef<Promise<boolean> | null>(null);const [validating, setValidating] = useState(false);+ const [pendingEnabled, setPendingEnabled] = useState<boolean | null>(null);+ const actionPending = saving || autoSaving || validating || pendingEnabled !== null;const [validation, setValidation] = useState<ChannelValidationPayload | null>(null);const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());+ const [clearedSecrets, setClearedSecrets] = useState<Set<string>>(() => new Set());+ const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});+ const [advancedOpen, setAdvancedOpen] = useState(false);+ const advancedPanelId = useId();const configValuesKey = JSON.stringify(feature.config_values ?? {});const configuredFields = useMemo(() => new Set(feature.configured_fields ?? []),@@ -253,18 +324,24 @@ function ChannelSetupSurface({);const mode = setup.mode ?? "credentials";const fields = setup.fields ?? [];- const requiredFields = fields.filter((field) => !field.optional);- const primaryFields = requiredFields.length ? requiredFields : fields.slice(0, 1);- const optionalFields = fields.filter((field) => field.optional);+ const requirementKeys = new Set(+ (setup.requirements ?? []).flatMap((requirement) => requirement.alternatives.flat()),+ );+ const primaryFields = fields.filter(+ (field) => !field.optional || requirementKeys.has(field.key),+ );const manualFields = setup.manualFields ?? [];- const advancedFields = mode === "connect" ? manualFields : optionalFields;+ const advancedFields = mode === "connect"+ ? manualFields+ : fields.filter((field) => !primaryFields.includes(field));const editableFields = mode === "credentials" ? fields : mode === "connect" ? manualFields : [];- const hasAdvanced = advancedFields.length > 0;- const requirements = channelRequirements(feature, t);- const summary = setup.summary ?? tx(- "settings.channels.setupSummary",- "Enable only turns on nanobot support. Add the platform credentials, then restart nanobot.",+ const savedSecretFields = editableFields.filter(+ (field) => field.secret && configuredFields.has(field.key),);+ const availablePresets = feature.configured ? [] : setup.presets ?? [];+ const hasAdvanced = advancedFields.length > 0+ || savedSecretFields.length > 0+ || availablePresets.length > 0;const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>defaultChannelFieldValues(editableFields, feature.config_values),);@@ -276,6 +353,8 @@ function ChannelSetupSurface({setValidating(false);setValidation(null);setTouchedFields(new Set());+ setClearedSecrets(new Set());+ setFieldErrors({});setFieldValues(defaultChannelFieldValues(editableFields, feature.config_values));}, [configValuesKey, feature.name]);@@ -286,17 +365,128 @@ function ChannelSetupSurface({const setFieldValue = (key: string, value: string) => {setFieldValues((current) => ({ ...current, [key]: value }));setTouchedFields((current) => new Set(current).add(key));+ setClearedSecrets((current) => {+ if (!current.has(key)) return current;+ const next = new Set(current);+ next.delete(key);+ return next;+ });+ setFieldErrors((current) => {+ if (!current[key]) return current;+ const next = { ...current };+ delete next[key];+ return next;+ });+ setAutoSaveState("idle");+ };++ const saveConnectionSettings = async () => {+ if (mode !== "connect" || saving || !touchedFields.size) return;+ setSaving(true);+ try {+ const payload = await configureChannel(client, feature.name,+ channelValuesForSubmit(editableFields, fieldValues, touchedFields, clearedSecrets));+ setTouchedFields(new Set());+ if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);+ } catch (err) {+ setNotice((err as Error).message);+ } finally {+ setSaving(false);+ }+ };++ const setSecretCleared = (key: string, clear: boolean) => {+ setClearedSecrets((current) => {+ const next = new Set(current);+ if (clear) next.add(key);+ else next.delete(key);+ return next;+ });+ setAutoSaveState("idle");};const applyPreset = (preset: ChannelProviderPreset) => {- setFieldValues((current) => ({ ...current, ...preset.values }));+ const values = Object.fromEntries(+ Object.entries(preset.values).filter(([key]) => !(fieldValues[key] ?? "").trim()),+ );+ if (!Object.keys(values).length) return;+ setFieldValues((current) => ({ ...current, ...values }));setTouchedFields((current) => {const next = new Set(current);- for (const key of Object.keys(preset.values)) next.add(key);+ for (const key of Object.keys(values)) next.add(key);return next;});+ setAutoSaveState("idle");};+ const credentialDirty = touchedFields.size > 0 || clearedSecrets.size > 0;+ const touchedSecret = fields.some(+ (field) => field.secret && touchedFields.has(field.key),+ );+ const saveCredentialDraft = useCallback(async (): Promise<boolean> => {+ const activeSave = autoSavePromiseRef.current;+ if (activeSave) return activeSave;+ if (mode !== "credentials" || !credentialDirty) return true;+ if (saving || validating || pendingEnabled !== null) return false;++ const values = channelValuesForSubmit(fields, fieldValues, touchedFields, clearedSecrets);+ const save = (async () => {+ setAutoSaving(true);+ setAutoSaveState("idle");+ setNotice(null);+ try {+ const payload = await configureChannel(client, feature.name, values);+ setTouchedFields(new Set());+ setClearedSecrets(new Set());+ setAutoSaveState("saved");+ if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);+ return true;+ } catch (err) {+ setNotice((err as Error).message);+ return false;+ } finally {+ setAutoSaving(false);+ }+ })();+ autoSavePromiseRef.current = save;+ const saved = await save;+ if (autoSavePromiseRef.current === save) autoSavePromiseRef.current = null;+ return saved;+ }, [+ clearedSecrets,+ client,+ credentialDirty,+ feature.name,+ fieldValues,+ fields,+ mode,+ onFeaturesUpdate,+ pendingEnabled,+ saving,+ touchedFields,+ validating,+ ]);++ useAutoSave(+ { fieldValues, touchedFields: [...touchedFields], clearedSecrets: [...clearedSecrets] },+ mode === "credentials" && credentialDirty,+ actionPending,+ () => void saveCredentialDraft(),+ !touchedSecret,+ );++ useEffect(() => {+ if (autoSaveState !== "saved") return;+ const timeout = window.setTimeout(() => setAutoSaveState("idle"), 1500);+ return () => window.clearTimeout(timeout);+ }, [autoSaveState]);++ useEffect(() => {+ if (!onBeforeCloseChange) return;+ onBeforeCloseChange(credentialDirty ? saveCredentialDraft : null);+ return () => onBeforeCloseChange(null);+ }, [credentialDirty, onBeforeCloseChange, saveCredentialDraft]);+const copyCommand = () => {if (!setup.command) return;void copyTextToClipboard(setup.command).then((ok) => {@@ -309,16 +499,40 @@ function ChannelSetupSurface({};const saveCredentialSettings = async () => {+ if (actionPending) return;+ const errors = channelRequirementErrors(+ fields,+ setup.requirements ?? [],+ fieldValues,+ configuredFields,+ clearedSecrets,+ tx("settings.channels.fieldRequired", "Required to complete setup."),+ );+ if (Object.keys(errors).length) {+ setFieldErrors(errors);+ setNotice(tx("settings.channels.validationFailed", "Check the required setup before enabling."));+ focusFirstChannelFieldError(errors);+ return;+ }+ setPendingEnabled(true);setSaving(true);setValidating(true);setNotice(null);- const values = channelValuesForSubmit(fields, fieldValues, touchedFields);+ const values = channelValuesForSubmit(fields, fieldValues, touchedFields, clearedSecrets);try {const validationPayload = await validateChannel(client, feature.name, values);setValidation(validationPayload);if (!validationPayload.can_enable) {+ const errors = channelServerValidationErrors(+ fields,+ validationPayload.missing_fields,+ tx("settings.channels.fieldRequired", "Required to complete setup."),+ );+ setFieldErrors(errors);+ if (advancedFields.some((field) => errors[field.key])) setAdvancedOpen(true);+ focusFirstChannelFieldError(errors);setNotice(- validationPayload.message+ (validationPayload.message ? channelValidationMessage(validationPayload.message, t) : undefined)?? tx("settings.channels.validationFailed", "Check the required setup before enabling."),);return;@@ -338,20 +552,35 @@ function ChannelSetupSurface({} finally {setSaving(false);setValidating(false);+ setPendingEnabled(null);}};const checkCurrentSettings = async () => {+ if (actionPending) return;setValidating(true);+ setValidation(null);setNotice(null);try {const payload = await validateChannel(client,feature.name,- channelValuesForSubmit(fields, fieldValues, touchedFields),+ channelValuesForSubmit(fields, fieldValues, touchedFields, clearedSecrets),);setValidation(payload);- if (payload.message) setNotice(payload.message);+ const failedCheck = payload.checks.find((check) => check.status === "fail");+ const resultMessage = failedCheck?.message ?? payload.message;+ const localizedResult = resultMessage ? channelValidationMessage(resultMessage, t) : null;+ const localizedRuntimeError = feature.runtime_error+ ? channelValidationMessage(feature.runtime_error, t)+ : null;+ setNotice(+ payload.status !== "connected"+ && localizedResult+ && localizedResult !== localizedRuntimeError+ ? localizedResult+ : null,+ );} catch (err) {setNotice((err as Error).message);} finally {@@ -359,184 +588,425 @@ function ChannelSetupSurface({}};- const primaryActionLabel = channelToggleChecked(feature)- ? tx("settings.channels.checkConnection", "Check connection")- : tx("settings.channels.checkAndEnable", "Check and enable");+ const enabled = pendingEnabled ?? channelToggleChecked(feature);+ const toggleEnabled = async (next: boolean) => {+ if (actionPending) return;+ if (next) {+ await saveCredentialSettings();+ return;+ }+ setPendingEnabled(false);+ setSaving(true);+ setNotice(null);+ try {+ onFeaturesUpdate(await disableNanobotFeature(client, feature.name));+ } catch (err) {+ setNotice((err as Error).message);+ } finally {+ setSaving(false);+ setPendingEnabled(null);+ }+ };++ const inlineActions = mode === "credentials" && primaryFields.length === 1+ && !advancedOpen && !setup.presets?.length && !setup.actions?.length;+ const credentialActions = mode === "credentials" ? (+ <div className="ms-auto flex min-h-10 flex-wrap items-center justify-end gap-x-3 gap-y-2 sm:min-h-9">+ {feature.setup?.verifies_connection ? (+ <Button+ type="button"+ size="sm"+ variant="secondary"+ className="h-10 rounded-full px-3 text-[12px] font-semibold sm:h-9"+ onClick={() => void checkCurrentSettings()}+ disabled={actionPending}+ >+ {tx("settings.channels.checkConnection", "Check connection")}+ </Button>+ ) : null}+ <ToggleButton checked={enabled} disabled={actionPending}+ label={tx("settings.channels.enable", "Enable")}+ onChange={(next) => void toggleEnabled(next)} />+ </div>+ ) : null;return (<form- className="mt-5 space-y-5"+ className="flex flex-col gap-4"onSubmit={(event) => {event.preventDefault();if (mode === "credentials") void saveCredentialSettings();}}>- <section>- <div className="flex flex-wrap items-center justify-between gap-2">- <div className="text-[13px] font-semibold text-foreground">- {tx("settings.channels.requiredSetup", "Required setup")}+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">+ {header}+ <div className="ms-auto flex min-h-8 items-center gap-2">+ <span+ role="status"+ aria-live="polite"+ aria-atomic="true"+ className={cn(+ "inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground",+ !autoSaving && autoSaveState !== "saved" && "sr-only",+ )}+ >+ {autoSaving ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ {tx("settings.actions.saving", "Saving")}+ </>+ ) : autoSaveState === "saved" ? (+ <>+ <Check className="h-3 w-3" aria-hidden />+ {tx("settings.channels.savedSettings", "Settings saved.")}+ </>+ ) : null}+ </span>+ {hasAdvanced ? (+ <button+ type="button"+ className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"+ aria-expanded={advancedOpen}+ aria-controls={advancedPanelId}+ onClick={() => setAdvancedOpen((current) => !current)}+ >+ {tx("settings.channels.advanced", "Advanced")}+ <ChevronDown className={cn(+ "h-3.5 w-3.5 transition-transform motion-reduce:transition-none",+ advancedOpen && "rotate-180",+ )} aria-hidden />+ </button>+ ) : null}+ </div>+ </div>+ <ChannelRuntimeError message={feature.runtime_error} />+ <div className="flex flex-wrap items-center gap-4">+ <section className={cn("min-w-0", inlineActions ? "flex-[1_1_20rem]" : "w-full")}>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex max-w-full flex-wrap justify-end gap-2">+ {mode === "webui" ? (+ <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11.5px] font-medium text-emerald-700 dark:text-emerald-200">+ <Check className="h-3.5 w-3.5" aria-hidden />+ {tx("settings.channels.managedByWebui", "Managed by WebUI")}+ </span>+ ) : null}+ </div></div>- <div className="flex max-w-full flex-wrap justify-end gap-2">- {mode !== "webui" ? (- <ChannelValidationBadge- validation={validation}- validating={validating}+ <ChannelSetupActions feature={feature} setup={setup} onNotice={setNotice} />++ {mode === "connect" && !feature.installed ? null : mode === "connect" && ConnectFlow ? (+ <Suspense fallback={<ChannelPluginLoading compact />}>+ <ConnectFlow+ token={token}feature={feature}+ idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}+ connectRequestId={connectRequestId}+ onFeaturesUpdate={onFeaturesUpdate}/>- ) : null}- {mode === "webui" ? (- <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11.5px] font-medium text-emerald-700 dark:text-emerald-200">- <Check className="h-3.5 w-3.5" aria-hidden />- {tx("settings.channels.managedByWebui", "Managed by WebUI")}- </span>- ) : null}- </div>- </div>- <p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">{requirements}</p>-- <p className="mt-3 text-[12.5px] leading-5 text-muted-foreground">{summary}</p>- <ChannelValidationDetails validation={validation} />- <ChannelSetupLinks feature={feature} setup={setup} chatAppsDocsUrl={chatAppsDocsUrl} />- <ChannelSetupActions feature={feature} setup={setup} onNotice={setNotice} />-- {mode === "connect" && ConnectFlow ? (- <Suspense fallback={<ChannelPluginLoading compact />}>- <ConnectFlow- token={token}- feature={feature}- idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}- connectRequestId={connectRequestId}- onFeaturesUpdate={onFeaturesUpdate}- />- </Suspense>- ) : mode === "connect" ? (- <>- <div className="mt-3 flex flex-wrap justify-end gap-2">- <Button- type="button"- size="sm"- variant="secondary"- className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"- onClick={() =>- setNotice(- tx(- "settings.channels.connectPreview",- "Run the command below in your terminal to connect.",- ),- )- }- >- {setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}- </Button>- {setup.command ? (+ </Suspense>+ ) : mode === "connect" ? (+ <>+ <div className="mt-3 flex flex-wrap justify-end gap-2"><Buttontype="button"size="sm"variant="secondary"- className="h-8 rounded-full px-3 text-[12px] font-semibold"- onClick={copyCommand}+ className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"+ onClick={() =>+ setNotice(+ tx(+ "settings.channels.connectPreview",+ "Run the command below in your terminal to connect.",+ ),+ )+ }>- <Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />- {tx("settings.channels.copyCommand", "Copy command")}+ {setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}</Button>+ {setup.command ? (+ <Button+ type="button"+ size="sm"+ variant="secondary"+ className="h-8 rounded-full px-3 text-[12px] font-semibold"+ onClick={copyCommand}+ >+ <Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />+ {tx("settings.channels.copyCommand", "Copy command")}+ </Button>+ ) : null}+ </div>+ {setup.command ? (+ <code className="mt-3 block rounded-control border border-border/50 bg-muted/45 px-2.5 py-2 font-mono text-[11px] leading-5 text-foreground">+ {setup.command}+ </code>) : null}- </div>- {setup.command ? (- <code className="mt-3 block rounded-control border border-border/50 bg-muted/45 px-2.5 py-2 font-mono text-[11px] leading-5 text-foreground">- {setup.command}- </code>- ) : null}- </>- ) : mode === "credentials" ? (- <>- {setup.presets?.length ? (+ </>+ ) : mode === "credentials" ? (+ <>+ {primaryFields.length ? (+ <ChannelFieldGroups+ fields={primaryFields}+ values={fieldValues}+ configuredFields={configuredFields}+ visibleSecrets={visibleSecrets}+ onChange={setFieldValue}+ onFieldBlur={(key) => {+ if (fields.some((field) => field.key === key && field.secret)) {+ void saveCredentialDraft();+ }+ }}+ onToggleSecret={toggleSecret}+ errors={fieldErrors}+ clearedSecrets={clearedSecrets}+ onClearSecret={setSecretCleared}+ requirements={setup.requirements ?? []}+ sectionLabels={setup.sectionLabels}+ disabled={actionPending}+ />+ ) : null}+ </>+ ) : null}+ </section>++ {hasAdvanced ? (+ <div id={advancedPanelId} hidden={!advancedOpen} className="min-w-0 w-full space-y-3 text-[12px] leading-5 text-muted-foreground">+ {availablePresets.length ? (<ChannelProviderPresets- presets={setup.presets}+ presets={availablePresets}onApply={applyPreset}+ label={setup.presetLabel}+ disabled={actionPending}/>) : null}- {primaryFields.length ? (- <CredentialForm- fields={primaryFields}- values={fieldValues}- configuredFields={configuredFields}- visibleSecrets={visibleSecrets}- onChange={setFieldValue}- onToggleSecret={toggleSecret}- />- ) : null}- <div className="mt-3 flex flex-wrap justify-end gap-2">- <Button- type="submit"- size="sm"- variant="secondary"- className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"- disabled={saving}- >- {saving || validating ? (- <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />- ) : null}- {primaryActionLabel}- </Button>- {feature.configured || validation ? (- <Button- type="button"- size="sm"- variant="ghost"- className="h-8 rounded-full px-3 text-[12px] font-semibold"- onClick={() => void checkCurrentSettings()}- disabled={saving || validating}- >- {tx("settings.channels.checkOnly", "Check only")}- </Button>- ) : null}+ <div className="space-y-2">+ {savedSecretFields.filter((field) => !(fieldValues[field.key] ?? "").trim()).map((field) => (+ <div key={field.key} className="flex min-h-9 flex-wrap items-center justify-between gap-x-4 gap-y-1">+ <span>{field.label}</span>+ <button type="button" className="min-h-8 text-[12px] hover:text-foreground"+ onClick={() => setSecretCleared(field.key, !clearedSecrets.has(field.key))}>+ {clearedSecrets.has(field.key)+ ? tx("settings.channels.keepSavedSecret", "Keep saved credential")+ : tx("settings.channels.removeSavedSecret", "Remove saved credential")}+ </button>+ </div>+ ))}</div>- </>+ {advancedFields.length ? (+ <div onBlur={() => void saveConnectionSettings()}>+ <CredentialForm+ fields={advancedFields}+ values={fieldValues}+ configuredFields={configuredFields}+ visibleSecrets={visibleSecrets}+ onChange={setFieldValue}+ onFieldBlur={(key) => {+ if (fields.some((field) => field.key === key && field.secret)) {+ void saveCredentialDraft();+ }+ }}+ onToggleSecret={toggleSecret}+ errors={fieldErrors}+ clearedSecrets={clearedSecrets}+ onClearSecret={setSecretCleared}+ compact+ disabled={actionPending}+ />+ </div>+ ) : null}+ </div>) : null}- </section>+ {credentialActions}+ </div>+ {mode === "credentials" && feature.setup?.verifies_connection+ && (validation || validating) ? (+ <div>+ <ChannelValidationProgress+ validation={validation}+ validating={validating}+ feature={feature}+ />+ </div>+ ) : null}+ <div+ role="status"+ aria-live="polite"+ className={cn(+ "rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground",+ !notice && "sr-only",+ )}+ >+ {notice ?? ""}+ </div>+ </form>+ );+}++const CHANNEL_FIELD_SECTION_ORDER: ChannelFieldSection[] = [+ "account",+ "credentials",+ "connection",+ "access",+ "behavior",+ "security",+];++function ChannelFieldGroups({+ fields,+ requirements,+ sectionLabels,+ ...formProps+}: {+ fields: ChannelConfigField[];+ requirements: ChannelSetupRequirement[];+ sectionLabels?: Record<string, string>;+ values: Record<string, string>;+ configuredFields: Set<string>;+ visibleSecrets: Record<string, boolean>;+ onChange: (key: string, value: string) => void;+ onFieldBlur?: (key: string) => void;+ onToggleSecret: (key: string) => void;+ errors: Record<string, string>;+ clearedSecrets: Set<string>;+ onClearSecret: (key: string, clear: boolean) => void;+ disabled?: boolean;+}) {+ const { t } = useTranslation();+ const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });+ const labels = new Map(fields.map((field) => [field.key, field.label]));+ const compositeRequirements = requirements.filter(+ (requirement) => requirement.alternatives.length > 1,+ );+ const groups = new Map<string, ChannelConfigField[]>();+ for (const field of fields) {+ const section = field.section ?? "credentials";+ const current = groups.get(section) ?? [];+ current.push(field);+ groups.set(section, current);+ }+ const orderedSections = [+ ...CHANNEL_FIELD_SECTION_ORDER,+ ...[...groups.keys()].filter(+ (section) => !CHANNEL_FIELD_SECTION_ORDER.includes(section as ChannelFieldSection),+ ),+ ];- {notice ? (+ return (+ <div className="space-y-5">+ {compositeRequirements.map((requirement, index) => (<div- role="status"- className="rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground"+ key={index}+ className="rounded-control border border-border/60 bg-background/55 px-3 py-2.5">- {notice}+ <div className="text-[11px] font-semibold text-foreground">+ {tx("settings.channels.chooseCredentialMethod", "Choose one credential method")}+ </div>+ <div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground">+ {requirement.alternatives.map((alternative, alternativeIndex) => (+ <span key={alternative.join("|")} className="contents">+ {alternativeIndex ? <span aria-hidden>{tx("settings.channels.or", "or")}</span> : null}+ <span className="rounded-full bg-muted px-2 py-0.5 text-foreground/85">+ {alternative.map((key) => labels.get(key) ?? key.split(".").at(-1)).join(" + ")}+ </span>+ </span>+ ))}+ </div></div>- ) : null}+ ))}+ {orderedSections.map((section) => {+ const sectionFields = groups.get(section);+ if (!sectionFields?.length) return null;+ return (+ <fieldset key={section} className="min-w-0">+ <legend className={groups.size === 1 ? "sr-only" : "mb-2 text-[12px] font-medium text-muted-foreground"}>+ {channelFieldSectionLabel(section, tx, sectionLabels)}+ </legend>+ <div>+ <CredentialForm fields={sectionFields} {...formProps} compact />+ </div>+ </fieldset>+ );+ })}+ </div>+ );+}- {setup.steps.length ? (- <ChannelSetupSteps steps={setup.steps} tryIt={setup.tryIt} />- ) : null}+function channelFieldSectionLabel(+ section: string,+ tx: (key: string, fallback: string) => string,+ sectionLabels?: Record<string, string>,+): string {+ const customLabel = sectionLabels?.[section];+ if (customLabel) return customLabel;- {validation?.checks.length ? <ChannelValidationChecks validation={validation} /> : null}-- {hasAdvanced ? (- <details className="group text-[12px] leading-5 text-muted-foreground">- <summary className="cursor-pointer list-none text-[12px] font-semibold text-foreground">- <span className="inline-flex items-center gap-1.5">- {tx("settings.channels.advanced", "Advanced")}- <ChevronDown className="h-3.5 w-3.5 transition-transform group-open:rotate-180" aria-hidden />- </span>- </summary>- {advancedFields.length ? (- <div className="mt-3">- <CredentialForm- fields={advancedFields}- values={fieldValues}- configuredFields={configuredFields}- visibleSecrets={visibleSecrets}- onChange={setFieldValue}- onToggleSecret={toggleSecret}- compact- />- </div>- ) : null}- </details>- ) : null}- </form>+ const fallbacks: Record<ChannelFieldSection, string> = {+ account: "Account",+ credentials: "Credentials",+ connection: "Connection",+ access: "Access",+ behavior: "Behavior",+ security: "Security",+ advanced: "Advanced",+ };+ const fallback = fallbacks[section as ChannelFieldSection];+ if (fallback) return tx(`settings.channels.sections.${section}`, fallback);+ return section+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .replace(/[_-]+/g, " ")+ .replace(/\b\w/g, (letter) => letter.toUpperCase());+}++function channelRequirementErrors(+ fields: ChannelConfigField[],+ requirements: ChannelSetupRequirement[],+ values: Record<string, string>,+ configuredFields: Set<string>,+ clearedSecrets: Set<string>,+ message: string,+): Record<string, string> {+ const fieldByKey = new Map(fields.map((field) => [field.key, field]));+ const present = (key: string) => {+ const field = fieldByKey.get(key);+ if (!field || clearedSecrets.has(key)) return false;+ const value = (values[key] ?? "").trim();+ if (field.kind === "bool") return value === "true";+ if (value) return true;+ return Boolean(field.secret && configuredFields.has(key));+ };+ const errors: Record<string, string> = {};+ for (const requirement of requirements) {+ if (requirement.alternatives.some((alternative) => alternative.every(present))) continue;+ const closest = [...requirement.alternatives].sort(+ (left, right) => left.filter((key) => !present(key)).length - right.filter((key) => !present(key)).length,+ )[0] ?? [];+ for (const key of closest) {+ if (!present(key) && fieldByKey.has(key)) errors[key] = message;+ }+ }+ return errors;+}++function channelServerValidationErrors(+ fields: ChannelConfigField[],+ missingFields: string[],+ message: string,+): Record<string, string> {+ const missing = new Set(missingFields);+ return Object.fromEntries(+ fields+ .filter((field) => missing.has(field.key) || missing.has(field.key.split(".").at(-1) ?? ""))+ .map((field) => [field.key, message]),);}+function focusFirstChannelFieldError(errors: Record<string, string>) {+ const key = Object.keys(errors)[0];+ if (!key) return;+ window.requestAnimationFrame(() => {+ document.getElementById(`channel-field-${key.replace(/[^a-zA-Z0-9_-]/g, "-")}`)?.focus();+ });+}+function ChannelPluginLoading({ compact = false }: { compact?: boolean }) {const { t } = useTranslation();return (@@ -544,7 +1014,9 @@ function ChannelPluginLoading({ compact = false }: { compact?: boolean }) {role="status"className={cn("flex items-center justify-center gap-2 text-sm text-muted-foreground",- compact ? "min-h-12" : "min-h-48",+ compact+ ? "min-h-12"+ : `${CHANNEL_SETUP_PANEL_CLASS_NAME} min-h-48`,)}><Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />diff --git a/webui/src/components/settings/channels/ChannelSetupParts.tsx b/webui/src/components/settings/channels/ChannelSetupParts.tsxindex 000fb5fd5..b3d27928b 100644--- a/webui/src/components/settings/channels/ChannelSetupParts.tsx+++ b/webui/src/components/settings/channels/ChannelSetupParts.tsx@@ -1,11 +1,11 @@-import { useMemo, useState, type ReactNode } from "react";+import { channelValidationMessage } from "./validationMessages";+import { useEffect, useMemo, useState } from "react";import { Clipboard, ExternalLink, Loader2 } from "lucide-react";import { useTranslation } from "react-i18next";import { channelUiPresentation } from "@/channel-plugins/registry";import { Button } from "@/components/ui/button";import {- docsUrlWithBase,type ChannelProviderPreset,type ChannelSetupPresentation,} from "@/components/settings/channels/catalog";@@ -16,154 +16,13 @@ import {channelValidationStatusIcon,channelValidationStatusLabel,} from "@/components/settings/channels/CredentialForm";-import { useLogoFallback } from "@/hooks/useLogoFallback";import { copyTextToClipboard } from "@/lib/clipboard";-import { logoFallbackUrls } from "@/lib/provider-brand";import type {ChannelValidationPayload,NanobotFeatureInfo,} from "@/lib/types";import { cn } from "@/lib/utils";-export function ChannelGuideLink({- feature,- setup,- chatAppsDocsUrl,- compact = false,-}: {- feature: NanobotFeatureInfo;- setup: ChannelSetupPresentation;- chatAppsDocsUrl?: string;- compact?: boolean;-}) {- const { t } = useTranslation();- const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });- const presentation = channelUiPresentation(feature.name, feature.webui);- const logoUrls = useMemo(- () => logoFallbackUrls(setup.docsLogoUrl ?? presentation?.logoUrl),- [presentation?.logoUrl, setup.docsLogoUrl],- );- const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);- const Icon = presentation?.icon;- const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();- const color = presentation?.color ?? "#6B7280";- const docsUrl = docsUrlWithBase(setup.docsUrl, chatAppsDocsUrl);-- if (!docsUrl) return null;-- return (- <a- href={docsUrl}- target="_blank"- rel="noreferrer"- className={cn(- "inline-flex max-w-full items-center gap-2 bg-background/80 font-semibold text-foreground transition-colors settings-hover",- compact- ? "shrink-0 rounded-full py-1 pl-1 pr-2.5 text-[11.5px]"- : "mt-3 rounded-control py-1.5 pl-1.5 pr-3 text-[12px]",- )}- >- <span- className={cn(- "grid shrink-0 place-items-center overflow-hidden bg-muted/70 font-bold",- compact ? "h-5 w-5 rounded-full text-[9px]" : "h-6 w-6 rounded-compact text-[10px]",- )}- style={{ color }}- aria-hidden- >- {logoUrl ? (- <img- src={logoUrl}- alt=""- decoding="async"- loading="lazy"- className={cn("object-contain", compact ? "h-3.5 w-3.5" : "h-4 w-4")}- onLoad={onLogoLoad}- onError={onLogoError}- />- ) : Icon ? (- <Icon className={compact ? "h-3 w-3" : "h-3.5 w-3.5"} strokeWidth={2.25} />- ) : (- initials- )}- </span>- <span className="truncate">- {setup.docsLabel ?? tx("settings.channels.officialGuide", "Official guide")}- </span>- <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />- </a>- );-}--export function ChannelSetupLinks({- feature,- setup,- chatAppsDocsUrl,-}: {- feature: NanobotFeatureInfo;- setup: ChannelSetupPresentation;- chatAppsDocsUrl?: string;-}) {- return (- <div className="mt-3 flex flex-wrap items-center gap-2">- <ChannelOfficialLink feature={feature} setup={setup} />- <ChannelGuideLink feature={feature} setup={setup} chatAppsDocsUrl={chatAppsDocsUrl} compact />- </div>- );-}--function ChannelOfficialLink({- feature,- setup,-}: {- feature: NanobotFeatureInfo;- setup: ChannelSetupPresentation;-}) {- const presentation = channelUiPresentation(feature.name, feature.webui);- const logoUrls = useMemo(- () => logoFallbackUrls(setup.docsLogoUrl ?? presentation?.logoUrl),- [presentation?.logoUrl, setup.docsLogoUrl],- );- const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);- const Icon = presentation?.icon;- const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();- const color = presentation?.color ?? "#6B7280";- const label = setup.officialLabel;- if (!setup.officialUrl || !label) return null;- return (- <a- href={setup.officialUrl}- target="_blank"- rel="noreferrer"- className="inline-flex max-w-full shrink-0 items-center gap-2 rounded-full bg-background/80 py-1 pl-1 pr-2.5 text-[11.5px] font-semibold text-foreground transition-colors settings-hover"- >- <span- className="grid h-5 w-5 shrink-0 place-items-center overflow-hidden rounded-full bg-muted/70"- style={{ color }}- aria-hidden- >- {logoUrl ? (- <img- src={logoUrl}- alt=""- decoding="async"- loading="lazy"- className="h-3.5 w-3.5 object-contain"- onLoad={onLogoLoad}- onError={onLogoError}- />- ) : Icon ? (- <Icon className="h-3 w-3" strokeWidth={2.25} />- ) : (- <span className="text-[8px] font-bold">{initials}</span>- )}- </span>- <span className="truncate">{label}</span>- <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />- </a>- );-}-export function ChannelSetupActions({feature,setup,@@ -216,48 +75,48 @@ export function ChannelSetupActions({export function ChannelProviderPresets({presets,onApply,+ label,+ disabled = false,}: {presets: ChannelProviderPreset[];onApply: (preset: ChannelProviderPreset) => void;+ label?: string;+ disabled?: boolean;}) {const { t } = useTranslation();- const [selected, setSelected] = useState("");if (!presets.length) return null;return (- <div className="mt-3">- <div className="mb-1 text-[11px] font-medium text-foreground/85">- {t("settings.channels.providerPreset", { defaultValue: "Provider" })}- </div>- <div- role="radiogroup"- aria-label={t("settings.channels.providerPreset", { defaultValue: "Provider" })}- className="grid rounded-control bg-muted p-0.5 text-[12px] font-medium text-muted-foreground"- style={{ gridTemplateColumns: `repeat(${presets.length}, minmax(0, 1fr))` }}- >+ <fieldset>+ <legend className="mb-1 text-[11px] font-medium text-foreground/85">+ {label ?? t("settings.channels.providerPreset", { defaultValue: "Provider" })}+ </legend>+ <div className="flex flex-wrap gap-2">{presets.map((preset) => (- <button+ <Buttonkey={preset.id}type="button"- role="radio"- aria-checked={selected === preset.id}- onClick={() => {- setSelected(preset.id);- onApply(preset);- }}- className={cn(- "min-h-8 rounded-compact px-2 py-1.5 transition-colors hover:text-foreground",- selected === preset.id && "bg-background text-foreground",- )}+ size="sm"+ variant="outline"+ disabled={disabled}+ className="h-8 rounded-full px-3 text-[12px] font-medium"+ onClick={() => onApply(preset)}>{preset.label}- </button>+ </Button>))}</div>- </div>+ </fieldset>);}-export function ChannelValidationBadge({+function visibleValidationChecks(validation: ChannelValidationPayload | null) {+ return (validation?.checks ?? []).filter(+ (check) => check.id !== "manual_review"+ && !(check.id.startsWith("field:") && check.status === "pass"),+ ).slice(0, 6);+}++export function ChannelValidationProgress({validation,validating,feature,@@ -267,118 +126,108 @@ export function ChannelValidationBadge({feature: NanobotFeatureInfo;}) {const { t } = useTranslation();- const status = validation?.status ?? (feature.configured ? "configured" : "needs_setup");- const label = validating- ? t("settings.channels.checking", { defaultValue: "Checking..." })- : channelValidationStatusLabel(status, t);- return (- <span- className={cn(- "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] font-medium",- channelValidationStatusClass(status),- )}- >- {validating ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />- ) : (- channelValidationStatusIcon(status)- )}- {label}- </span>- );-}+ const checks = useMemo(() => visibleValidationChecks(validation), [validation]);+ const [reveal, setReveal] = useState<{+ validation: ChannelValidationPayload | null;+ settledCheckCount: number;+ }>({ validation: null, settledCheckCount: 0 });+ const settledCheckCount = reveal.validation === validation ? reveal.settledCheckCount : 0;-export function ChannelValidationDetails({ validation }: { validation: ChannelValidationPayload | null }) {- const message = validation?.message;- if (!validation?.identity?.name && !message) return null;- return (- <div className="mt-2 truncate text-[11.5px] text-muted-foreground">- {validation?.identity?.name- ? validation.identity.workspace- ? `${validation.identity.name} · ${validation.identity.workspace}`- : validation.identity.name- : message}- </div>- );-}+ useEffect(() => {+ if (validating || !validation) {+ setReveal({ validation: null, settledCheckCount: 0 });+ return;+ }+ setReveal({ validation, settledCheckCount: 0 });+ const timers = checks.map((_, index) => window.setTimeout(+ () => setReveal((current) => (+ current.validation === validation+ ? { validation, settledCheckCount: index + 1 }+ : current+ )),+ (index + 1) * 260,+ ));+ return () => timers.forEach((timer) => window.clearTimeout(timer));+ }, [checks, validating, validation]);++ if (!validating && !validation) return null;++ const finished = Boolean(validation) && !validating && settledCheckCount >= checks.length;+ const shownChecks = finished ? checks : checks.slice(0, settledCheckCount + 1);+ const status = validation?.status ?? (feature.configured ? "configured" : "needs_setup");+ const presentation = channelUiPresentation(feature.name, feature.webui);+ const identity = validation?.identity?.name+ ? validation.identity.workspace+ ? `${validation.identity.name} · ${validation.identity.workspace}`+ : validation.identity.name+ : presentation?.displayName ?? feature.display_name;-export function ChannelValidationChecks({ validation }: { validation: ChannelValidationPayload }) {- const { t } = useTranslation();- if (!validation.checks.length) return null;return (- <div>- <div className="mb-2 text-[12px] font-semibold text-foreground">- {t("settings.channels.connectionChecks")}- </div>- <div className="space-y-2">- {validation.checks.slice(0, 6).map((check) => (- <div key={check.id} className="flex gap-2 text-[12px] leading-5">- <span className={cn("mt-0.5", channelValidationCheckIconClass(check.status))}>- {channelValidationCheckIcon(check.status)}- </span>- <div className="min-w-0 flex-1">- <div className="font-medium text-foreground/85">{check.label}</div>- {check.message ? (- <div className="text-muted-foreground">{check.message}</div>- ) : null}- {check.action_url ? (- <a- href={check.action_url}- target="_blank"- rel="noreferrer"- className="inline-flex items-center gap-1 text-foreground underline decoration-border underline-offset-4"- >- {t("settings.channels.open")}- <ExternalLink className="h-3 w-3" aria-hidden />- </a>- ) : null}+ <div+ role="status"+ aria-live="polite"+ aria-atomic="true"+ className="rounded-control border border-border/60 bg-muted/25 px-3 py-3"+ >+ <div className="space-y-2.5">+ {validating ? (+ <div className="flex items-center gap-2 px-2.5 text-[12px] font-medium text-foreground/85">+ <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />+ {t("settings.channels.checking", { defaultValue: "Checking..." })}+ </div>+ ) : null}+ {!validating ? shownChecks.map((check, index) => {+ const pending = !finished && index === settledCheckCount;+ return (+ <div+ key={check.id}+ className="flex animate-in gap-2 px-2.5 fade-in-0 slide-in-from-top-1 text-[12px] leading-5 duration-200 motion-reduce:animate-none"+ >+ <span className={cn(+ "mt-0.5",+ pending ? "text-muted-foreground" : channelValidationCheckIconClass(check.status),+ )}>+ {pending+ ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ : channelValidationCheckIcon(check.status)}+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-x-2 font-medium text-foreground/85">+ <span className="min-w-0 truncate">{channelValidationMessage(check.label, t)}</span>+ {!pending && check.action_url ? (+ <a+ href={check.action_url}+ target="_blank"+ rel="noreferrer"+ className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap text-foreground underline decoration-border underline-offset-4"+ >+ {t("settings.channels.open")}+ <ExternalLink className="h-3 w-3" aria-hidden />+ </a>+ ) : null}+ </div>+ {!pending && check.status !== "pass" && check.message ? (+ <div className="text-muted-foreground">+ {channelValidationMessage(check.message, t)}+ </div>+ ) : null}+ </div></div>+ );+ }) : null}+ {finished ? (+ <div+ className={cn(+ "flex animate-in items-center gap-2 rounded-control px-2.5 py-2 text-[12px] font-medium fade-in-0 duration-200 motion-reduce:animate-none",+ channelValidationStatusClass(status),+ )}+ >+ {channelValidationStatusIcon(status)}+ <span className="min-w-0 truncate font-semibold">{identity}</span>+ <span className="lowercase">{channelValidationStatusLabel(status, t)}</span></div>- ))}+ ) : null}</div></div>);}--export function ChannelSetupSteps({- steps,- action,- tryIt,-}: {- steps: string[];- action?: ReactNode;- tryIt?: string;-}) {- const { t } = useTranslation();- const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });- return (- <div className="text-[12.5px] leading-5 text-muted-foreground">- <div className="mb-2 flex items-center justify-between gap-3">- <div className="text-[12px] font-semibold text-foreground">- {tx("settings.channels.setupSteps", "Next steps")}- </div>- {action}- </div>- <ol className="space-y-1.5">- {steps.map((step, index) => (- <li key={step} className="flex gap-2">- <span className="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-muted text-[10px] font-semibold text-muted-foreground">- {index + 1}- </span>- <span>{step}</span>- </li>- ))}- </ol>- {tryIt ? (- <div className="mt-3 rounded-control bg-background/75 px-3 py-2 text-[12px] text-muted-foreground">- <span className="font-medium text-foreground">- {tx("settings.channels.tryIt", "Try it")}- </span>- <span className="ml-2">- {tryIt}- </span>- </div>- ) : null}- </div>- );-}diff --git a/webui/src/components/settings/channels/CredentialForm.tsx b/webui/src/components/settings/channels/CredentialForm.tsxindex 154672e45..9952b2991 100644--- a/webui/src/components/settings/channels/CredentialForm.tsx+++ b/webui/src/components/settings/channels/CredentialForm.tsx@@ -3,6 +3,7 @@ import { Check, CircleAlert, Eye, EyeOff, X } from "lucide-react";import { useTranslation } from "react-i18next";import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";import type { ChannelConfigField } from "@/components/settings/channels/catalog";import { cn } from "@/lib/utils";@@ -10,6 +11,10 @@ function channelFieldValue(field: ChannelConfigField, values: Record<string, strreturn values[field.key] ?? field.defaultValue ?? field.options?.[0]?.value ?? "";}+export function channelFieldInputId(key: string): string {+ return `channel-field-${key.replace(/[^a-zA-Z0-9_-]/g, "-")}`;+}+export function defaultChannelFieldValues(fields: ChannelConfigField[],configValues: Record<string, string> | undefined = undefined,@@ -39,9 +44,14 @@ export function channelValuesForSubmit(fields: ChannelConfigField[],values: Record<string, string>,touchedFields: Set<string>,-): Record<string, string> {- const payload: Record<string, string> = {};+ clearedSecrets: Set<string> = new Set(),+): Record<string, string | null> {+ const payload: Record<string, string | null> = {};for (const field of fields) {+ if (field.secret && clearedSecrets.has(field.key)) {+ payload[field.key] = null;+ continue;+ }const touched = touchedFields.has(field.key);const value = channelFieldValue(field, values);if (field.secret && !value.trim()) continue;@@ -58,7 +68,7 @@ export function channelValidationStatusLabel(): string {const labels: Record<string, string> = {connected: "Connected",- configured: "Configured manually",+ configured: "Not verified",needs_setup: "Needs setup",invalid: "Invalid",unsupported: "Manual setup",@@ -82,7 +92,7 @@ export function channelValidationStatusClass(status: string): string {}export function channelValidationStatusIcon(status: string): ReactNode {- if (status === "connected" || status === "configured") {+ if (status === "connected") {return <Check className="h-3.5 w-3.5" aria-hidden />;}if (status === "invalid") {@@ -111,34 +121,53 @@ export function CredentialForm({configuredFields,visibleSecrets,onChange,+ onFieldBlur,onToggleSecret,+ errors = {},+ clearedSecrets = new Set(),+ onClearSecret,compact = false,+ showSecretActions = false,+ disabled = false,}: {fields: ChannelConfigField[];values: Record<string, string>;configuredFields?: Set<string>;visibleSecrets: Record<string, boolean>;onChange: (key: string, value: string) => void;+ onFieldBlur?: (key: string) => void;onToggleSecret: (key: string) => void;+ errors?: Record<string, string>;+ clearedSecrets?: Set<string>;+ onClearSecret?: (key: string, clear: boolean) => void;compact?: boolean;+ showSecretActions?: boolean;+ disabled?: boolean;}) {const { t } = useTranslation();const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });return (- <div className={cn(compact ? "space-y-2.5" : "mt-3 space-y-2.5")}>+ <div className={cn("grid", compact ? "gap-y-4" : "mt-3 gap-y-2.5")}>{fields.map((field) => {+ const inputId = channelFieldInputId(field.key);+ const error = errors[field.key];+ const errorId = error ? `${inputId}-error` : undefined;+ const describedBy = errorId;const visible = Boolean(visibleSecrets[field.key]);const value = values[field.key] ?? "";- const savedSecret = Boolean(field.secret && configuredFields?.has(field.key) && !value.trim());+ const clearSecret = clearedSecrets.has(field.key);+ const savedSecret = Boolean(+ field.secret && configuredFields?.has(field.key) && !value.trim() && !clearSecret,+ );const showSecretToggle = Boolean(field.secret && value.trim());const inputType = field.secret && !visible ? "password" : field.inputType ?? "text";const selectedOption = channelFieldValue(field, values);const header = (<span className="flex items-center justify-between gap-2 text-[11px] font-medium text-foreground/85"><span>{field.label}</span>- {savedSecret ? (- <span className="font-normal text-muted-foreground">- {tx("settings.channels.savedSecret", "Saved")}+ {clearSecret ? (+ <span className="font-normal text-destructive">+ {tx("settings.channels.secretWillBeRemoved", "Will be removed")}</span>) : field.optional && !compact ? (<span className="font-normal text-muted-foreground">@@ -147,48 +176,94 @@ export function CredentialForm({) : null}</span>);- const help = field.help ? (- <span className="mt-1 block text-[11px] leading-4 text-muted-foreground">- {field.help}+ const errorMessage = error ? (+ <span id={errorId} className="mt-1 block text-[11px] leading-4 text-destructive">+ {error}</span>) : null;if (field.options?.length) {return (- <div key={field.key} className="block">- {header}+ <fieldset+ key={field.key}+ id={`${inputId}-group`}+ aria-labelledby={`${inputId}-label`}+ aria-invalid={Boolean(error)}+ aria-describedby={describedBy}+ className="block"+ >+ <div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] items-start gap-x-4">+ <span id={`${inputId}-label`} className="flex min-h-12 items-center sm:min-h-10">{header}</span>+ <div className="min-w-0"><span- role="radiogroup"- aria-label={field.label}- className="mt-1 grid rounded-control bg-muted p-0.5 text-[12px] font-medium text-muted-foreground"+ className="grid rounded-control bg-muted p-0.5 text-[12px] font-medium text-muted-foreground"style={{ gridTemplateColumns: `repeat(${field.options.length}, minmax(0, 1fr))` }}>- {field.options.map((option) => (- <button- key={option.value}- type="button"- role="radio"- aria-checked={selectedOption === option.value}- onClick={() => onChange(field.key, option.value)}- className={cn(- "min-h-8 rounded-compact px-2 py-1.5 transition-colors hover:text-foreground",- selectedOption === option.value- && "bg-background text-foreground ring-1 ring-inset ring-border/45",- )}- >- {option.label}- </button>+ {field.options.map((option, index) => (+ <label key={option.value} className="relative block">+ <input+ id={index === 0 ? inputId : `${inputId}-${index}`}+ type="radio"+ name={inputId}+ value={option.value}+ checked={selectedOption === option.value}+ disabled={disabled}+ aria-invalid={Boolean(error)}+ aria-describedby={describedBy}+ onChange={() => onChange(field.key, option.value)}+ onBlur={() => onFieldBlur?.(field.key)}+ className="peer sr-only"+ />+ <span className="grid min-h-11 cursor-pointer place-items-center rounded-compact px-2 py-1.5 transition-colors hover:text-foreground peer-checked:bg-background peer-checked:text-foreground peer-checked:ring-1 peer-checked:ring-inset peer-checked:ring-border/45 peer-focus-visible:ring-2 peer-focus-visible:ring-ring sm:min-h-9">+ {option.label}+ </span>+ </label>))}</span>- {help}+ {errorMessage}+ </div>+ </div>+ </fieldset>+ );+ }+ if (field.kind === "json") {+ return (+ <div key={field.key} className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] items-start gap-x-4">+ <label htmlFor={inputId} className="flex min-h-10 min-w-0 items-center self-start sm:min-h-9">+ {header}+ </label>+ <div className="min-w-0">+ <Textarea+ id={inputId}+ aria-label={field.label}+ aria-invalid={Boolean(error)}+ aria-describedby={describedBy}+ placeholder={field.placeholder}+ value={value}+ disabled={disabled}+ onChange={(event) => onChange(field.key, event.target.value)}+ onBlur={() => onFieldBlur?.(field.key)}+ rows={4}+ spellCheck={false}+ className={cn(+ "resize-y border-border/40 bg-background font-mono text-[12px]",+ error && "border-destructive focus-visible:ring-destructive/30",+ )}+ />+ {errorMessage}+ </div></div>);}return (- <label key={field.key} className="block">- {header}- <span className="relative mt-1 block">+ <div key={field.key} className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] items-start gap-x-4">+ <label htmlFor={inputId} className="flex min-h-10 min-w-0 items-center self-start sm:min-h-9">{header}</label>+ <div className="min-w-0">+ <span className="relative block"><Input+ id={inputId}aria-label={field.label}+ aria-invalid={Boolean(error)}+ aria-describedby={describedBy}type={inputType}autoComplete={field.secret ? "off" : undefined}inputMode={field.inputType === "number" ? "numeric" : undefined}@@ -198,9 +273,12 @@ export function CredentialForm({: field.placeholder}value={values[field.key] ?? ""}+ disabled={disabled}onChange={(event) => onChange(field.key, event.target.value)}+ onBlur={() => onFieldBlur?.(field.key)}className={cn(- "h-9 rounded-full border-border/60 bg-muted/35 text-[13px]",+ "h-10 rounded-full border-border/40 bg-background text-base sm:h-9 sm:text-[13px]",+ error && "border-destructive focus-visible:ring-destructive/30",showSecretToggle && "pr-9",)}/>@@ -213,7 +291,8 @@ export function CredentialForm({: tx("settings.channels.showSecret", "Show secret")}onClick={() => onToggleSecret(field.key)}- className="absolute right-2 top-1/2 grid h-6 w-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground settings-hover hover:text-foreground"+ disabled={disabled}+ className="absolute right-0 top-1/2 grid h-10 w-10 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-background hover:text-foreground sm:right-1 sm:h-8 sm:w-8">{visible ? (<EyeOff className="h-3.5 w-3.5" aria-hidden />@@ -223,8 +302,21 @@ export function CredentialForm({</button>) : null}</span>- {help}- </label>+ {errorMessage}+ {showSecretActions && field.secret && configuredFields?.has(field.key) && !value.trim() && onClearSecret ? (+ <button+ type="button"+ className="mt-1 min-h-8 text-[11px] font-medium text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"+ onClick={() => onClearSecret(field.key, !clearSecret)}+ disabled={disabled}+ >+ {clearSecret+ ? tx("settings.channels.keepSavedSecret", "Keep saved credential")+ : tx("settings.channels.removeSavedSecret", "Remove saved credential")}+ </button>+ ) : null}+ </div>+ </div>);})}</div>diff --git a/webui/src/components/settings/channels/catalog.ts b/webui/src/components/settings/channels/catalog.tsindex e1f63ebcf..2b8a12e86 100644--- a/webui/src/components/settings/channels/catalog.ts+++ b/webui/src/components/settings/channels/catalog.ts@@ -1,10 +1,10 @@-import type { LucideIcon } from "lucide-react";+import type { ComponentType } from "react";export type ChannelPresentation = {displayName: string;initials: string;color: string;- icon?: LucideIcon;+ icon?: ComponentType<{ className?: string; strokeWidth?: string | number }>;logoUrl?: string;setup?: ChannelCatalogSetupPresentation;};@@ -15,14 +15,13 @@ export type ChannelSetupPresentation = {command?: string;docsUrl?: string;docsLabel?: string;- docsLogoUrl?: string;officialUrl?: string;officialLabel?: string;- summary?: string;- tryIt?: string;- steps: string[];+ presetLabel?: string;+ sectionLabels?: Record<string, string>;fields?: ChannelConfigField[];manualFields?: ChannelConfigField[];+ requirements?: ChannelSetupRequirement[];actions?: ChannelSetupAction[];presets?: ChannelProviderPreset[];};@@ -31,15 +30,28 @@ type ChannelCatalogSetupPresentation = {mode?: "webui" | "credentials" | "connect";command?: string;docsUrl?: string;- docsLogoUrl?: string;fields?: ChannelFieldPresentation[];manualFields?: ChannelFieldPresentation[];actions?: ChannelSetupActionDefinition[];presets?: ChannelProviderPresetDefinition[];};-type ChannelFieldPresentation = {+export type ChannelFieldPresentation = {key: string;+ section?: string;+};++export type ChannelFieldSection =+ | "account"+ | "credentials"+ | "connection"+ | "access"+ | "behavior"+ | "security"+ | "advanced";++export type ChannelSetupRequirement = {+ alternatives: string[][];};type ChannelSetupActionDefinition = Omit<ChannelSetupAction, "label">;@@ -66,8 +78,9 @@ export type ChannelConfigField = {placeholder?: string;secret?: boolean;optional?: boolean;- help?: string;- inputType?: "text" | "number";+ inputType?: "text" | "number" | "url" | "email" | "tel";+ kind?: "string" | "secret" | "int" | "bool" | "list" | "enum" | string;+ section?: string;defaultValue?: string;options?: ChannelConfigOption[];};diff --git a/webui/src/components/settings/channels/validationMessages.ts b/webui/src/components/settings/channels/validationMessages.tsnew file mode 100644index 000000000..f12a259b9--- /dev/null+++ b/webui/src/components/settings/channels/validationMessages.ts@@ -0,0 +1,17 @@+import type { TFunction } from "i18next";++const messages: Record<string, string> = {+ "Connection verified.": "connected",+ "Configuration is present, but full verification was not possible.": "unverified",+ "Required setup is missing.": "missing",+ "Configuration was checked and looks invalid.": "invalid",+ "This channel is not supported by the WebUI setup checker.": "unsupported",+ "Configured.": "present",+ "Required.": "required",+ "This channel can be checked from saved fields, but not fully verified in-browser.": "manual",+};++export function channelValidationMessage(message: string, t: TFunction): string {+ const key = messages[message];+ return key ? t(`settings.channels.validationMessages.${key}`, { defaultValue: message }) : message;+}diff --git a/webui/src/components/settings/shared/SettingsControls.tsx b/webui/src/components/settings/shared/SettingsControls.tsxindex 211a5363c..1f6ca40cf 100644--- a/webui/src/components/settings/shared/SettingsControls.tsx+++ b/webui/src/components/settings/shared/SettingsControls.tsx@@ -48,11 +48,13 @@ export function CapabilityInstallNotice({export function NanobotFeatureInstallDialog({feature,+ installOnly = false,installing,onOpenChange,onConfirm,}: {feature: NanobotFeatureInfo | null;+ installOnly?: boolean;installing: boolean;onOpenChange: (open: boolean) => void;onConfirm: (feature: NanobotFeatureInfo) => void | Promise<void>;@@ -72,11 +74,17 @@ export function NanobotFeatureInstallDialog({{tx("settings.nanobotFeatures.installConfirmTitle", "Install support for {{name}}?", { name })}</DialogTitle><DialogDescription className="mt-3 max-w-[20rem] text-center text-[14px] leading-6 text-muted-foreground">- {tx(- "settings.nanobotFeatures.installConfirmDescription",- "nanobot will add what {{name}} needs, then turn it on. Continue?",- { name },- )}+ {installOnly+ ? tx(+ "settings.nanobotFeatures.installOnlyConfirmDescription",+ "nanobot will install what {{name}} needs. You can connect it after installation.",+ { name },+ )+ : tx(+ "settings.nanobotFeatures.installConfirmDescription",+ "nanobot will add what {{name}} needs, then turn it on. Continue?",+ { name },+ )}</DialogDescription></DialogHeader><DialogFooter className="mt-7 !grid grid-cols-1 gap-2 sm:grid-cols-2">@@ -96,7 +104,9 @@ export function NanobotFeatureInstallDialog({className="h-11 w-full min-w-0 !whitespace-normal px-5 text-center text-[15px] font-semibold">{installing ? <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden /> : null}- {tx("settings.nanobotFeatures.installConfirmAction", "Install and enable")}+ {installOnly+ ? tx("settings.nanobotFeatures.installOnlyConfirmAction", "Install support")+ : tx("settings.nanobotFeatures.installConfirmAction", "Install and enable")}</Button></DialogFooter></DialogContent>@@ -117,6 +127,8 @@ export function DismissibleStatusMessage({const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });return (<div+ role={isError ? "alert" : "status"}+ aria-atomic="true"className={cn("flex items-center justify-between gap-3 rounded-control border py-2.5 pl-4 pr-2 text-[13px]",isErrordiff --git a/webui/src/components/settings/system/AutomationsSettings.tsx b/webui/src/components/settings/system/AutomationsSettings.tsxindex 7eca86897..41008b390 100644--- a/webui/src/components/settings/system/AutomationsSettings.tsx+++ b/webui/src/components/settings/system/AutomationsSettings.tsx@@ -1,5 +1,6 @@import { useEffect, useMemo, useState } from "react";import type { FormEvent, ReactNode } from "react";+import type { TFunction } from "i18next";import {ArrowUpDown,Check,@@ -17,7 +18,8 @@ import {} from "lucide-react";import { useTranslation } from "react-i18next";-import { channelUiPresentation } from "@/channel-plugins/registry";+import { channelTranslator } from "@/channel-plugins/i18n";+import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry";import { SETTINGS_SEARCH_INPUT_CLASS } from "@/components/settings/shared/SettingsControls";import { AppsActionButton } from "@/components/settings/system/AppsSettings";import { Button } from "@/components/ui/button";@@ -302,7 +304,7 @@ function AutomationListItem({const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>t(key, { defaultValue: fallback, ...(values ?? {}) });const status = automationStatus(job, tx);- const origin = automationOriginLabel(job, tx);+ const origin = automationOriginLabel(job, t);const nextRun = formatAutomationNext(job, tx);const summary = automationSummary(job, tx);@@ -381,7 +383,7 @@ function AutomationDetailPanel({const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>t(key, { defaultValue: fallback, ...(values ?? {}) });const status = automationStatus(job, tx);- const origin = automationOriginLabel(job, tx);+ const origin = automationOriginLabel(job, t);const originHref = job.origin?.channel === "websocket" && job.origin.session_key? `#/chat/${encodeURIComponent(job.origin.session_key)}`: null;@@ -1358,23 +1360,27 @@ function automationStatus(function automationOriginLabel(job: SessionAutomationJob,- tx: (key: string, fallback: string, values?: Record<string, unknown>) => string,+ t: TFunction,): string {- if (job.protected) return tx("settings.automations.origin.system", "System");+ if (job.protected) return t("settings.automations.origin.system", { defaultValue: "System" });const origin = job.origin;- if (!origin) return tx("settings.automations.origin.unknown", "No linked chat");- if (origin.channel !== "websocket") return automationChannelLabel(origin.channel, tx);- return origin.title || origin.preview || origin.session_key || automationChannelLabel(origin.channel, tx);+ if (!origin) return t("settings.automations.origin.unknown", { defaultValue: "No linked chat" });+ if (origin.channel !== "websocket") return automationChannelLabel(origin.channel, t);+ return origin.title || origin.preview || origin.session_key || automationChannelLabel(origin.channel, t);}function automationChannelLabel(channel: string,- tx: (key: string, fallback: string, values?: Record<string, unknown>) => string,+ t: TFunction,): string {const key = channel.trim().toLowerCase();- const displayName = automationChannelDisplayName(key);+ const presentation = channelUiPresentation(key);+ if (presentation) {+ return channelTranslator(t, channelUiOwner(key))("displayName", presentation.displayName);+ }+ const displayName = HOST_AUTOMATION_CHANNEL_LABELS[key];return displayName- ? tx(`settings.automations.channels.${key}`, displayName)+ ? t(`settings.automations.channels.${key}`, { defaultValue: displayName }): channel;}diff --git a/webui/src/components/settings/system/ChannelsSettings.tsx b/webui/src/components/settings/system/ChannelsSettings.tsxindex c2a5d7099..08c0f2ab7 100644--- a/webui/src/components/settings/system/ChannelsSettings.tsx+++ b/webui/src/components/settings/system/ChannelsSettings.tsx@@ -1,12 +1,19 @@-import { useRef, useState } from "react";-import { Loader2 } from "lucide-react";+import { useCallback, useLayoutEffect, useRef, useState } from "react";+import { Loader2, Search, X } from "lucide-react";import { useTranslation } from "react-i18next";+import { Input } from "@/components/ui/input";+import { SegmentedControl } from "@/components/ui/segmented-control";+import { SETTINGS_SEARCH_INPUT_CLASS } from "@/components/settings/shared/SettingsControls";+import type { ChannelFeatureAction } from "@/channel-plugins/types";import { localizedChannelDisplayName } from "@/components/settings/channels/ChannelIdentity";+import { ChannelHelpMenu } from "@/components/settings/channels/ChannelHelpMenu";import { ChannelCatalogRow, ChannelSetupPanel } from "@/components/settings/channels/ChannelSetupPanel";import { DismissibleStatusMessage, RestartRequiredNotice, SettingsGroup } from "@/components/settings/shared/SettingsControls";import type { NanobotFeaturesPayload } from "@/lib/types";-import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";+import { Dialog, DialogClose, DialogContent, DialogTitle } from "@/components/ui/dialog";++type ChannelFilter = "all" | "enabled";export function ChannelsSettings({token, nanobotFeatures, loading, actionKey, chatAppsDocsUrl, showBrandLogos,@@ -21,7 +28,7 @@ export function ChannelsSettings({showBrandLogos: boolean;error: string | null;requiresRestartPending: boolean;- onAction: (action: "enable" | "disable", name: string) => void;+ onAction: ChannelFeatureAction;onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;onDismissStatus: () => void;onRestart?: () => void;@@ -29,19 +36,83 @@ export function ChannelsSettings({}) {const { t } = useTranslation();const [selectedChannelName, setSelectedChannelName] = useState<string | null>(null);+ const [query, setQuery] = useState("");+ const [filter, setFilter] = useState<ChannelFilter>("enabled");const [connectRequestId, setConnectRequestId] = useState(0);+ const filterInitializedRef = useRef(false);const triggerRef = useRef<HTMLElement | null>(null);const dialogRef = useRef<HTMLDivElement | null>(null);+ const beforeCloseRef = useRef<(() => Promise<boolean>) | null>(null);+ const closePendingRef = useRef(false);const channels = (nanobotFeatures?.features ?? []).filter((feature) => feature.type === "channel" && feature.settings_visible !== false).sort((left, right) => Number(!left.ready) - Number(!right.ready)|| localizedChannelDisplayName(left, t).localeCompare(localizedChannelDisplayName(right, t)));+ const hasEnabledChannels = channels.some((feature) => feature.enabled);+ const restartRequired = requiresRestartPending || Boolean(nanobotFeatures?.requires_restart);+ useLayoutEffect(() => {+ if (!nanobotFeatures || filterInitializedRef.current) return;+ filterInitializedRef.current = true;+ setFilter(hasEnabledChannels ? "enabled" : "all");+ }, [hasEnabledChannels, nanobotFeatures]);+ const visibleChannels = channels.filter((feature) =>+ (filter === "all" || feature.enabled)+ && `${feature.name} ${localizedChannelDisplayName(feature, t)}`.toLocaleLowerCase()+ .includes(query.trim().toLocaleLowerCase()));+ const channelGroups = filter === "enabled"+ ? [{ key: "enabled", label: null, channels: visibleChannels }]+ : [+ {+ key: "builtin",+ label: t("settings.channels.noInstallNeeded"),+ channels: visibleChannels.filter((feature) => !feature.requires_dependencies),+ },+ {+ key: "dependencies",+ label: t("settings.channels.installNeeded"),+ channels: visibleChannels.filter((feature) => feature.requires_dependencies),+ },+ ].filter((group) => group.channels.length);const selectedChannel = channels.find((feature) => feature.name === selectedChannelName);+ const requestChannelClose = useCallback(() => {+ if (closePendingRef.current) return;+ const beforeClose = beforeCloseRef.current;+ if (!beforeClose) {+ setSelectedChannelName(null);+ return;+ }+ closePendingRef.current = true;+ void beforeClose().then((canClose) => {+ if (canClose) setSelectedChannelName(null);+ }).finally(() => {+ closePendingRef.current = false;+ });+ }, []);+ const setBeforeChannelClose = useCallback(+ (handler: (() => Promise<boolean>) | null) => { beforeCloseRef.current = handler; },+ [],+ );return (<div className="settings-stack">- {error ? <DismissibleStatusMessage message={error} isError onDismiss={onDismissStatus} /> : null}- {requiresRestartPending ? (+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center">+ <div className="relative min-w-0 flex-1">+ <Search className="pointer-events-none absolute start-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />+ <Input type="search" value={query} onChange={(event) => setQuery(event.target.value)}+ aria-label={t("settings.channels.search")}+ placeholder={t("settings.channels.search")}+ className={`h-12 ps-11 text-[15px] ${SETTINGS_SEARCH_INPUT_CLASS}`} />+ </div>+ <SegmentedControl value={filter} onChange={(value) => {+ filterInitializedRef.current = true;+ setFilter(value);+ }} options={[+ { value: "all", label: t("settings.channels.filterAll") },+ { value: "enabled", label: t("settings.channels.filterEnabled") },+ ]} />+ </div>+ {error && !selectedChannel ? <DismissibleStatusMessage message={error} isError onDismiss={onDismissStatus} /> : null}+ {restartRequired ? (<RestartRequiredNotice message={t("settings.channels.restartRequired")}onRestart={onRestart} isRestarting={isRestarting} />) : null}@@ -50,34 +121,62 @@ export function ChannelsSettings({<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />{t("settings.channels.loading")}</div>- ) : channels.length ? (- <SettingsGroup>- {channels.map((feature) => (+ ) : visibleChannels.length ? (+ channelGroups.map((group) => (+ <section+ key={group.key}+ aria-labelledby={group.label ? `channel-group-${group.key}` : undefined}+ aria-label={group.label ? undefined : t("settings.channels.filterEnabled")}+ className={group.label ? "space-y-2" : undefined}+ >+ {group.label ? (+ <h2 id={`channel-group-${group.key}`} className="px-4 text-[12px] font-medium text-muted-foreground">{group.label}</h2>+ ) : null}+ <SettingsGroup>+ <div className="grid grid-cols-1 gap-x-4 gap-y-1 min-[640px]:grid-cols-2">+ {group.channels.map((feature) => (<ChannelCatalogRow key={feature.name} feature={feature} showBrandLogos={showBrandLogos}- actionKey={actionKey} onAction={onAction}+ actionKey={actionKey} actionsDisabled={restartRequired || Boolean(isRestarting)} onAction={onAction}onSelect={(connect = false) => {triggerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ beforeCloseRef.current = null;setConnectRequestId(connect ? 1 : 0);setSelectedChannelName(feature.name);}} />))}- </SettingsGroup>+ </div>+ </SettingsGroup>+ </section>+ ))) : (<div className="px-3 py-12 text-center text-sm text-muted-foreground">- {t("settings.channels.empty")}+ {t(channels.length ? "settings.channels.noResults" : "settings.channels.empty")}</div>)}- <Dialog open={Boolean(selectedChannel)} onOpenChange={(open) => { if (!open) setSelectedChannelName(null); }}>- <DialogContent ref={dialogRef} aria-describedby={undefined} className="max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-y-auto p-0 outline-none"+ <Dialog open={Boolean(selectedChannel)} onOpenChange={(open) => { if (!open) requestChannelClose(); }}>+ <DialogContent ref={dialogRef} showCloseButton={false} aria-describedby={undefined} className="max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-hidden p-0 outline-none"onOpenAutoFocus={(event) => {event.preventDefault();dialogRef.current?.focus({ preventScroll: true });}}onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}><DialogTitle className="sr-only">{t("settings.nav.channels")}</DialogTitle>- {selectedChannel ? <ChannelSetupPanel token={token} feature={selectedChannel} actionKey={actionKey}- chatAppsDocsUrl={chatAppsDocsUrl} showBrandLogos={showBrandLogos}- onAction={onAction} onFeaturesUpdate={onFeaturesUpdate} connectRequestId={connectRequestId} /> : null}+ <div className="max-h-[85dvh] min-h-0 overflow-y-auto overscroll-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">+ <div className="relative">+ <div className="absolute end-6 top-6 z-10 flex h-10 items-center gap-1">+ {selectedChannel ? <ChannelHelpMenu feature={selectedChannel} chatAppsDocsUrl={chatAppsDocsUrl} /> : null}+ <DialogClose className="grid h-8 w-8 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">+ <X className="h-4 w-4" aria-hidden />+ <span className="sr-only">{t("common.close")}</span>+ </DialogClose>+ </div>+ {error ? <DismissibleStatusMessage message={error} isError onDismiss={onDismissStatus} /> : null}+ {selectedChannel ? <ChannelSetupPanel token={token} feature={selectedChannel} actionKey={actionKey}+ showBrandLogos={showBrandLogos}+ onAction={onAction} onFeaturesUpdate={onFeaturesUpdate} connectRequestId={connectRequestId}+ onBeforeCloseChange={setBeforeChannelClose} /> : null}+ </div>+ </div></DialogContent></Dialog></div>diff --git a/webui/src/components/settings/system/createSystemSettingsActions.ts b/webui/src/components/settings/system/createSystemSettingsActions.tsindex 88d58cc46..17b55ccc3 100644--- a/webui/src/components/settings/system/createSystemSettingsActions.ts+++ b/webui/src/components/settings/system/createSystemSettingsActions.ts@@ -98,6 +98,7 @@ export function createSystemSettingsActions({mcpOAuthFlowRef,mcpOAuthNavigatedUrlRef,mcpOAuthPopupRef,+ nanobotFeatureActionRef,nanobotFeatures,setApiService,setApiServiceAction,@@ -130,12 +131,26 @@ export function createSystemSettingsActions({setNanobotFeaturesError,} = state;+ const beginNanobotFeatureAction = (key: string) => {+ if (nanobotFeatureActionRef.current) return false;+ nanobotFeatureActionRef.current = key;+ setNanobotFeatureAction(key);+ return true;+ };++ const endNanobotFeatureAction = (key: string) => {+ if (nanobotFeatureActionRef.current !== key) return;+ nanobotFeatureActionRef.current = null;+ setNanobotFeatureAction(null);+ };+const installCapabilities = async (names: string[]): Promise<boolean> => {const missing = names.filter((name) => !featureCatalog.find((feature) => feature.name === name)?.installed,);if (!missing.length) return true;- setNanobotFeatureAction(`enable:${names.join("+")}`);+ const key = `enable:${names.join("+")}`;+ if (!beginNanobotFeatureAction(key)) return false;setNanobotFeaturesError(null);try {let latest = nanobotFeatures;@@ -151,7 +166,7 @@ export function createSystemSettingsActions({setNanobotFeaturesError((err as Error).message);return false;} finally {- setNanobotFeatureAction(null);+ endNanobotFeatureAction(key);}};@@ -204,30 +219,42 @@ export function createSystemSettingsActions({const handleNanobotFeatureAction = async (action: "enable" | "disable",name: string,- confirmed = false,+ options: { confirmed?: boolean; installOnly?: boolean } = {},) => {const feature = featureCatalog.find((item) => item.name === name);- if (action === "enable" && !confirmed && feature && !feature.installed && feature.install_supported) {+ if (+ action === "enable"+ && !options.confirmed+ && feature+ && !feature.installed+ && feature.install_supported+ ) {setNanobotFeaturesError(null);- setNanobotFeatureConfirm(feature);+ setNanobotFeatureConfirm({ feature, installOnly: Boolean(options.installOnly) });return;}- const key = `${action}:${name}`;- setNanobotFeatureAction(key);+ const key = `${action === "enable" && options.installOnly ? "install" : action}:${name}`;+ if (!beginNanobotFeatureAction(key)) return;setNanobotFeatureConfirm(null);setNanobotFeaturesError(null);try {const payload = action === "enable"- ? await enableNanobotFeature(client, name)+ ? await enableNanobotFeature(client, name, { installOnly: options.installOnly }): await disableNanobotFeature(client, name);setNanobotFeatures(payload);if (payload.requires_restart) {setPendingRestartSections((prev) => ({ ...prev, runtime: true }));}} catch (err) {- setNanobotFeaturesError((err as Error).message);+ console.error("nanobot feature action failed", {+ action,+ name,+ installOnly: Boolean(options.installOnly),+ error: err,+ });+ setNanobotFeaturesError(err instanceof Error ? err.message : String(err));} finally {- setNanobotFeatureAction(null);+ endNanobotFeatureAction(key);}};diff --git a/webui/src/components/settings/system/useSystemSettingsState.ts b/webui/src/components/settings/system/useSystemSettingsState.tsindex ab0efdf15..2add8f17e 100644--- a/webui/src/components/settings/system/useSystemSettingsState.ts+++ b/webui/src/components/settings/system/useSystemSettingsState.ts@@ -20,6 +20,11 @@ import type {SessionAutomationJob,} from "@/lib/types";+export type NanobotFeatureInstallRequest = {+ feature: NanobotFeatureInfo;+ installOnly: boolean;+};+export function useSystemSettingsState() {const [cliApps, setCliApps] = useState<CliAppsPayload | null>(null);const [nanobotFeatures, setNanobotFeatures] = useState<NanobotFeaturesPayload | null>(null);@@ -31,7 +36,9 @@ export function useSystemSettingsState() {const [automationsLoading, setAutomationsLoading] = useState(false);const [cliAppsAction, setCliAppsAction] = useState<string | null>(null);const [nanobotFeatureAction, setNanobotFeatureAction] = useState<string | null>(null);- const [nanobotFeatureConfirm, setNanobotFeatureConfirm] = useState<NanobotFeatureInfo | null>(null);+ const nanobotFeatureActionRef = useRef<string | null>(null);+ const [nanobotFeatureConfirm, setNanobotFeatureConfirm] =+ useState<NanobotFeatureInstallRequest | null>(null);const [mcpPresetAction, setMcpPresetAction] = useState<string | null>(null);const [mcpOAuthFlow, setMcpOAuthFlow] = useState<McpOAuthFlowPayload | null>(null);const mcpOAuthFlowRef = useRef<McpOAuthFlowPayload | null>(null);@@ -105,6 +112,7 @@ export function useSystemSettingsState() {mcpPresets,mcpPresetsLoading,nanobotFeatureAction,+ nanobotFeatureActionRef,nanobotFeatureConfirm,nanobotFeatures,nanobotFeaturesError,diff --git a/webui/src/components/ui/dialog.tsx b/webui/src/components/ui/dialog.tsxindex 645923ea1..0a57888cb 100644--- a/webui/src/components/ui/dialog.tsx+++ b/webui/src/components/ui/dialog.tsx@@ -12,6 +12,7 @@ import { FloatingPortalContext } from "@/components/ui/floating-portal";const Dialog = DialogPrimitive.Root;const DialogTrigger = DialogPrimitive.Trigger;+const DialogClose = DialogPrimitive.Close;const DialogPortal = DialogPrimitive.Portal;export const DialogLayoutContext = React.createContext<HTMLElement | null>(null);@@ -95,7 +96,7 @@ const DialogContent = React.forwardRef<{children}</FloatingPortalContext.Provider>{showCloseButton ? (- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none">+ <DialogPrimitive.Close className="absolute right-2.5 top-2.5 grid h-7 w-7 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground active:bg-muted/80 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none"><X className="h-4 w-4" /><span className="sr-only">{t("common.close")}</span></DialogPrimitive.Close>@@ -165,6 +166,7 @@ DialogDescription.displayName = DialogPrimitive.Description.displayName;export {Dialog,DialogTrigger,+ DialogClose,DialogContent,DialogDescription,DialogFooter,diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex 2a244519d..a18f8421a 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -42,8 +42,8 @@"description": "nanobot web UI — chat with your nanobot workspace."},"pairing": {- "title": "Pair a chat user",- "description": "Enter the pairing code shown in the chat.",+ "title": "Pair your chat account",+ "description": "Enter the pairing code you received in chat.","code": "Pairing code","matched": "Matched {{channel}}. Connecting...","expiresInline": "Code expires {{expires}}.",@@ -983,7 +983,6 @@"requires": "Requires: {{requirements}}","setUp": "Set up","setupGuide": "Setup guide",- "setupSummary": "Enable only turns on nanobot support. Add the platform credentials, then restart nanobot.","configKeys": "Config keys","enable": "Enable channel","disable": "Disable channel",@@ -997,7 +996,8 @@"open": "Open","checkedAndEnabled": "Checked and enabled.","checking": "Checking...",- "checkOnly": "Check only",+ "help": "Help",+ "checkOnly": "Check","commandCopied": "Command copied.","commandCopyFailed": "Could not copy command.","configuredInstances": "{{count}} instances configured",@@ -1015,7 +1015,6 @@"runtimeStarting": "Starting","runtimeStopped": "Not running","managedByWebui": "Managed by WebUI",- "officialGuide": "Official guide","optional": "Optional","providerPreset": "Provider","requiredSetup": "Required setup",@@ -1024,21 +1023,51 @@"savedSettings": "Settings saved.","saveSettings": "Save settings","selectChannel": "View {{name}} settings",- "setupSteps": "Next steps","showSecret": "Show secret","toggleChannel": "{{name}} channel","toggleInstance": "{{name}} instance",- "tryIt": "Try it","validationFailed": "Check the required setup before enabling.",+ "completeSetupToEnable": "Complete the required setup below, then nanobot can enable this channel.",+ "chooseCredentialMethod": "Choose one credential method",+ "or": "or",+ "fieldRequired": "Required to complete setup.",+ "secretWillBeRemoved": "Will be removed",+ "keepSavedSecret": "Keep saved credential",+ "removeSavedSecret": "Remove saved credential",+ "sections": {+ "account": "Account",+ "credentials": "Credentials",+ "connection": "Connection",+ "access": "Access",+ "behavior": "Behavior",+ "security": "Security"+ },"validation": {"connected": "Connected",- "configured": "Configured manually",+ "configured": "Not verified","needs_setup": "Needs setup",- "invalid": "Invalid",+ "invalid": "Connection failed","unsupported": "Manual setup"},"configuredInstances_one": "{{count}} instance configured",- "configuredInstances_other": "{{count}} instances configured"+ "configuredInstances_other": "{{count}} instances configured",+ "validationMessages": {+ "connected": "Connection verified.",+ "unverified": "Connection not verified.",+ "missing": "Complete the required fields.",+ "invalid": "Connection check failed.",+ "unsupported": "Connection testing is not supported for this channel yet.",+ "present": "Filled in",+ "required": "Required",+ "manual": "Connection testing is not supported for this channel yet."+ },+ "search": "Search channels",+ "filterEnabled": "Enabled",+ "noResults": "No matching channels",+ "install": "Install",+ "installChannel": "Install {{name}}",+ "noInstallNeeded": "No installation needed",+ "installNeeded": "Requires dependencies"},"nanobotFeatures": {"enabled": "Enabled",@@ -1049,7 +1078,9 @@"installSupport": "Install support","installConfirmTitle": "Install support for {{name}}?","installConfirmDescription": "nanobot will add what {{name}} needs, then turn it on. Continue?",+ "installOnlyConfirmDescription": "nanobot will install what {{name}} needs. You can connect it after installation.","installConfirmAction": "Install and enable",+ "installOnlyConfirmAction": "Install support","websocketRequired": "Required for WebUI","channelDisabled": "Channel is disabled","notEnabled": "Not enabled"@@ -1114,20 +1145,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "DingTalk",- "discord": "Discord",- "email": "Email",- "feishu": "Feishu",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "WeChat",- "wecom": "WeCom",- "weixin": "WeChat",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "At {{time}}",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 33d6b551f..9fe46338a 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -42,8 +42,8 @@"description": "Interfaz web de nanobot: conversa con tu espacio de trabajo de nanobot."},"pairing": {- "title": "Vincular a un usuario del chat",- "description": "Introduce el código de vinculación que aparece en el chat.",+ "title": "Vincular tu cuenta de chat",+ "description": "Introduce el código de vinculación que recibiste en el chat.","code": "Código de vinculación","matched": "Coincidencia: {{channel}}. Conectando...","expiresInline": "El código caduca {{expires}}.",@@ -778,13 +778,13 @@"searchPlaceholder": "Buscar canales","backToChannels": "Todos los canales","catalog": "Canales",+ "help": "Ayuda","loading": "Cargando canales...","empty": "Ningún canal coincide con este filtro.","restartRequired": "Reinicia nanobot para aplicar el soporte de canales actualizado.","requires": "Requiere: {{requirements}}","setUp": "Configurar","setupGuide": "Guía de configuración",- "setupSummary": "Activa el canal, añade las credenciales de la plataforma y reinicia nanobot.","configKeys": "Claves de configuración","enable": "Activar canal","disable": "Desactivar canal",@@ -818,7 +818,6 @@"runtimeStarting": "Iniciando","runtimeStopped": "No está en ejecución","managedByWebui": "Gestionado por WebUI",- "officialGuide": "Guía oficial","optional": "Opcional","providerPreset": "Proveedor","requiredSetup": "Configuración requerida",@@ -827,19 +826,49 @@"savedSettings": "Configuración guardada.","saveSettings": "Guardar configuración","selectChannel": "Ver la configuración de {{name}}",- "setupSteps": "Siguientes pasos","showSecret": "Mostrar secreto","toggleChannel": "Activar {{name}}","toggleInstance": "Activar la instancia {{name}}",- "tryIt": "Pruébalo","validationFailed": "Comprueba la configuración requerida antes de activar.",+ "completeSetupToEnable": "Completa la configuración requerida para activar este canal.",+ "chooseCredentialMethod": "Elige un método de credenciales",+ "or": "o",+ "fieldRequired": "Obligatorio para completar la configuración.",+ "secretWillBeRemoved": "Se eliminará",+ "keepSavedSecret": "Conservar credencial guardada",+ "removeSavedSecret": "Eliminar credencial guardada",+ "sections": {+ "account": "Cuenta",+ "credentials": "Credenciales",+ "connection": "Conexión",+ "access": "Acceso",+ "behavior": "Comportamiento",+ "security": "Seguridad"+ },"validation": {"connected": "Conectado","configured": "Configurado manualmente","needs_setup": "Requiere configuración",- "invalid": "No válido",+ "invalid": "Error de conexión","unsupported": "Configuración manual"- }+ },+ "validationMessages": {+ "connected": "Conexión verificada.",+ "unverified": "Conexión sin verificar.",+ "missing": "Completa los campos obligatorios.",+ "invalid": "Falló la comprobación de la conexión.",+ "unsupported": "Este canal todavía no permite comprobar la conexión.",+ "present": "Completado",+ "required": "Obligatorio",+ "manual": "Este canal todavía no permite comprobar la conexión."+ },+ "search": "Buscar canales",+ "filterEnabled": "Activados",+ "noResults": "No hay canales coincidentes",+ "install": "Instalar",+ "installChannel": "Instalar {{name}}",+ "noInstallNeeded": "No requiere instalación",+ "installNeeded": "Requiere dependencias"},"nanobotFeatures": {"enabled": "Activado",@@ -850,7 +879,9 @@"installSupport": "Instalar dependencias","installConfirmTitle": "¿Instalar las dependencias de {{name}}?","installConfirmDescription": "nanobot instalará las dependencias necesarias y activará {{name}}.",+ "installOnlyConfirmDescription": "nanobot instalará lo que {{name}} necesita. Podrás conectarlo después de la instalación.","installConfirmAction": "Instalar y activar",+ "installOnlyConfirmAction": "Instalar soporte","websocketRequired": "Requerido para WebUI","channelDisabled": "El canal está desactivado","notEnabled": "No activado"@@ -915,20 +946,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "DingTalk",- "discord": "Discord",- "email": "Email",- "feishu": "Feishu",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "WeChat",- "wecom": "WeCom",- "weixin": "WeChat",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "A las {{time}}",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex ee004ba8c..f9fa09949 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -42,8 +42,8 @@"description": "Interface web nanobot — discutez avec votre espace de travail nanobot."},"pairing": {- "title": "Associer un utilisateur du chat",- "description": "Saisissez le code d’association affiché dans le chat.",+ "title": "Associer votre compte de messagerie",+ "description": "Saisissez le code d’association reçu dans la messagerie.","code": "Code d’association","matched": "Correspondance {{channel}}. Connexion...","expiresInline": "Le code expire {{expires}}.",@@ -777,13 +777,13 @@"searchPlaceholder": "Rechercher des canaux","backToChannels": "Tous les canaux","catalog": "Canaux",+ "help": "Aide","loading": "Chargement des canaux...","empty": "Aucun canal ne correspond à ce filtre.","restartRequired": "Redémarrez nanobot pour appliquer le support de canal mis à jour.","requires": "Requiert : {{requirements}}","setUp": "Configurer","setupGuide": "Guide de configuration",- "setupSummary": "Activez le canal, renseignez les identifiants de la plateforme, puis redémarrez nanobot.","configKeys": "Clés de configuration","enable": "Activer le canal","disable": "Désactiver le canal",@@ -817,7 +817,6 @@"runtimeStarting": "Démarrage","runtimeStopped": "À l'arrêt","managedByWebui": "Géré par la WebUI",- "officialGuide": "Guide officiel","optional": "Facultatif","providerPreset": "Fournisseur","requiredSetup": "Configuration requise",@@ -826,19 +825,49 @@"savedSettings": "Paramètres enregistrés.","saveSettings": "Enregistrer les paramètres","selectChannel": "Afficher les paramètres de {{name}}",- "setupSteps": "Étapes suivantes","showSecret": "Afficher le secret","toggleChannel": "Activer {{name}}","toggleInstance": "Activer l’instance {{name}}",- "tryIt": "Essayer","validationFailed": "Vérifiez la configuration requise avant l'activation.",+ "completeSetupToEnable": "Terminez la configuration requise ci-dessous pour activer ce canal.",+ "chooseCredentialMethod": "Choisissez une méthode d'authentification",+ "or": "ou",+ "fieldRequired": "Requis pour terminer la configuration.",+ "secretWillBeRemoved": "Sera supprimé",+ "keepSavedSecret": "Conserver l'identifiant enregistré",+ "removeSavedSecret": "Supprimer l'identifiant enregistré",+ "sections": {+ "account": "Compte",+ "credentials": "Identifiants",+ "connection": "Connexion",+ "access": "Accès",+ "behavior": "Comportement",+ "security": "Sécurité"+ },"validation": {"connected": "Connecté","configured": "Configuré manuellement","needs_setup": "Configuration requise",- "invalid": "Non valide",+ "invalid": "Échec de la connexion","unsupported": "Configuration manuelle"- }+ },+ "validationMessages": {+ "connected": "Connexion vérifiée.",+ "unverified": "Connexion non vérifiée.",+ "missing": "Renseignez les champs obligatoires.",+ "invalid": "Échec de la vérification de la connexion.",+ "unsupported": "La vérification de la connexion n’est pas encore disponible pour ce canal.",+ "present": "Renseigné",+ "required": "Obligatoire",+ "manual": "La vérification de la connexion n’est pas encore disponible pour ce canal."+ },+ "search": "Rechercher des canaux",+ "filterEnabled": "Activés",+ "noResults": "Aucun canal correspondant",+ "install": "Installer",+ "installChannel": "Installer {{name}}",+ "noInstallNeeded": "Aucune installation requise",+ "installNeeded": "Dépendances requises"},"nanobotFeatures": {"enabled": "Activé",@@ -849,7 +878,9 @@"installSupport": "Installer les dépendances","installConfirmTitle": "Installer les dépendances de {{name}} ?","installConfirmDescription": "nanobot installera les dépendances nécessaires, puis activera {{name}}.",+ "installOnlyConfirmDescription": "nanobot installera les composants requis par {{name}}. Vous pourrez vous connecter après l’installation.","installConfirmAction": "Installer et activer",+ "installOnlyConfirmAction": "Installer le support","websocketRequired": "Requis pour la WebUI","channelDisabled": "Canal désactivé","notEnabled": "Non activé"@@ -914,20 +945,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "DingTalk",- "discord": "Discord",- "email": "Email",- "feishu": "Feishu",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "WeChat",- "wecom": "WeCom",- "weixin": "WeChat",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "À {{time}}",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 847eef9c8..ede38e6b9 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -42,8 +42,8 @@"description": "UI web nanobot — ngobrol dengan ruang kerja nanobot Anda."},"pairing": {- "title": "Hubungkan pengguna chat",- "description": "Masukkan kode pairing yang ditampilkan di chat.",+ "title": "Pasangkan akun chat Anda",+ "description": "Masukkan kode pemasangan yang Anda terima di chat.","code": "Kode pairing","matched": "Cocok dengan {{channel}}. Menghubungkan...","expiresInline": "Kode kedaluwarsa {{expires}}.",@@ -777,13 +777,13 @@"searchPlaceholder": "Cari kanal","backToChannels": "Semua kanal","catalog": "Kanal",+ "help": "Bantuan","loading": "Memuat kanal...","empty": "Tidak ada kanal yang cocok dengan filter ini.","restartRequired": "Mulai ulang nanobot untuk menerapkan dukungan kanal yang diperbarui.","requires": "Memerlukan: {{requirements}}","setUp": "Siapkan","setupGuide": "Panduan penyiapan",- "setupSummary": "Aktifkan kanal, tambahkan kredensial platform, lalu mulai ulang nanobot.","configKeys": "Kunci konfigurasi","enable": "Aktifkan kanal","disable": "Nonaktifkan kanal",@@ -817,7 +817,6 @@"runtimeStarting": "Memulai","runtimeStopped": "Tidak berjalan","managedByWebui": "Dikelola oleh WebUI",- "officialGuide": "Panduan resmi","optional": "Opsional","providerPreset": "Penyedia","requiredSetup": "Penyiapan wajib",@@ -826,19 +825,49 @@"savedSettings": "Pengaturan disimpan.","saveSettings": "Simpan pengaturan","selectChannel": "Lihat pengaturan {{name}}",- "setupSteps": "Langkah berikutnya","showSecret": "Tampilkan kredensial","toggleChannel": "Aktifkan {{name}}","toggleInstance": "Aktifkan instans {{name}}",- "tryIt": "Coba","validationFailed": "Periksa penyiapan wajib sebelum mengaktifkan.",+ "completeSetupToEnable": "Selesaikan penyiapan wajib di bawah untuk mengaktifkan kanal ini.",+ "chooseCredentialMethod": "Pilih satu metode kredensial",+ "or": "atau",+ "fieldRequired": "Wajib untuk menyelesaikan penyiapan.",+ "secretWillBeRemoved": "Akan dihapus",+ "keepSavedSecret": "Pertahankan kredensial tersimpan",+ "removeSavedSecret": "Hapus kredensial tersimpan",+ "sections": {+ "account": "Akun",+ "credentials": "Kredensial",+ "connection": "Koneksi",+ "access": "Akses",+ "behavior": "Perilaku",+ "security": "Keamanan"+ },"validation": {"connected": "Terhubung","configured": "Dikonfigurasi manual","needs_setup": "Perlu penyiapan",- "invalid": "Tidak valid",+ "invalid": "Koneksi gagal","unsupported": "Penyiapan manual"- }+ },+ "validationMessages": {+ "connected": "Koneksi terverifikasi.",+ "unverified": "Koneksi belum terverifikasi.",+ "missing": "Lengkapi kolom wajib.",+ "invalid": "Pemeriksaan koneksi gagal.",+ "unsupported": "Kanal ini belum mendukung pemeriksaan koneksi.",+ "present": "Terisi",+ "required": "Wajib",+ "manual": "Kanal ini belum mendukung pemeriksaan koneksi."+ },+ "search": "Cari kanal",+ "filterEnabled": "Aktif",+ "noResults": "Tidak ada kanal yang cocok",+ "install": "Pasang",+ "installChannel": "Pasang {{name}}",+ "noInstallNeeded": "Tidak perlu dipasang",+ "installNeeded": "Memerlukan dependensi"},"nanobotFeatures": {"enabled": "Aktif",@@ -849,7 +878,9 @@"installSupport": "Pasang paket yang diperlukan","installConfirmTitle": "Pasang paket yang diperlukan {{name}}?","installConfirmDescription": "nanobot akan memasang paket yang diperlukan, lalu mengaktifkan {{name}}.",+ "installOnlyConfirmDescription": "nanobot akan menginstal dukungan yang dibutuhkan {{name}}. Anda dapat menghubungkannya setelah instalasi.","installConfirmAction": "Instal dan aktifkan",+ "installOnlyConfirmAction": "Instal dukungan","websocketRequired": "Wajib untuk WebUI","channelDisabled": "Kanal dinonaktifkan","notEnabled": "Belum aktif"@@ -914,20 +945,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "DingTalk",- "discord": "Discord",- "email": "Email",- "feishu": "Feishu",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "WeChat",- "wecom": "WeCom",- "weixin": "WeChat",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "Pada {{time}}",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex 3433b38c8..dbd27d823 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -42,8 +42,8 @@"description": "nanobot Web UI — nanobot ワークスペースと会話します。"},"pairing": {- "title": "チャットユーザーをペアリング",- "description": "チャットに表示されたペアリングコードを入力してください。",+ "title": "チャットアカウントをペアリング",+ "description": "チャットで受け取ったペアリングコードを入力してください。","code": "ペアリングコード","matched": "{{channel}} と一致しました。接続中…","expiresInline": "コードの有効期限: {{expires}}。",@@ -777,13 +777,13 @@"searchPlaceholder": "チャンネルを検索","backToChannels": "すべてのチャンネル","catalog": "チャンネル",+ "help": "ヘルプ","loading": "チャンネルを読み込み中...","empty": "一致するチャンネルはありません。","restartRequired": "更新したチャンネルサポートを反映するには nanobot を再起動してください。","requires": "必要: {{requirements}}","setUp": "設定","setupGuide": "設定ガイド",- "setupSummary": "チャンネルを有効にしてプラットフォームの認証情報を設定し、nanobot を再起動してください。","configKeys": "設定キー","enable": "チャンネルを有効化","disable": "チャンネルを無効化",@@ -817,7 +817,6 @@"runtimeStarting": "起動中","runtimeStopped": "未実行","managedByWebui": "WebUI で管理",- "officialGuide": "公式ガイド","optional": "任意","providerPreset": "プロバイダー","requiredSetup": "必要な設定",@@ -826,19 +825,49 @@"savedSettings": "設定を保存しました。","saveSettings": "設定を保存","selectChannel": "{{name}} の設定を表示",- "setupSteps": "次の手順","showSecret": "シークレットを表示","toggleChannel": "{{name}} を有効にする","toggleInstance": "インスタンス {{name}} を有効にする",- "tryIt": "試してみる","validationFailed": "有効化する前に必要な設定を確認してください。",+ "completeSetupToEnable": "以下の必須設定を完了すると、このチャンネルを有効にできます。",+ "chooseCredentialMethod": "認証方法を1つ選択",+ "or": "または",+ "fieldRequired": "設定を完了するために必要です。",+ "secretWillBeRemoved": "削除されます",+ "keepSavedSecret": "保存済みの認証情報を保持",+ "removeSavedSecret": "保存済みの認証情報を削除",+ "sections": {+ "account": "アカウント",+ "credentials": "認証情報",+ "connection": "接続",+ "access": "アクセス",+ "behavior": "動作",+ "security": "セキュリティ"+ },"validation": {"connected": "接続済み","configured": "手動設定済み","needs_setup": "設定が必要",- "invalid": "無効",+ "invalid": "接続失敗","unsupported": "手動設定"- }+ },+ "validationMessages": {+ "connected": "接続を確認しました。",+ "unverified": "接続は未確認です。",+ "missing": "必須項目を入力してください。",+ "invalid": "接続確認に失敗しました。",+ "unsupported": "このチャンネルでは、まだ接続を確認できません。",+ "present": "入力済み",+ "required": "必須",+ "manual": "このチャンネルでは、まだ接続を確認できません。"+ },+ "search": "チャンネルを検索",+ "filterEnabled": "有効",+ "noResults": "一致するチャンネルはありません",+ "install": "インストール",+ "installChannel": "{{name}} をインストール",+ "noInstallNeeded": "インストール不要",+ "installNeeded": "依存関係が必要"},"nanobotFeatures": {"enabled": "有効",@@ -849,7 +878,9 @@"installSupport": "必要なパッケージをインストール","installConfirmTitle": "{{name}} に必要なパッケージをインストールしますか?","installConfirmDescription": "nanobot が必要なパッケージをインストールし、{{name}} を有効にします。",+ "installOnlyConfirmDescription": "nanobot が {{name}} に必要なサポートをインストールします。インストール後に接続できます。","installConfirmAction": "インストールして有効化",+ "installOnlyConfirmAction": "サポートをインストール","websocketRequired": "WebUI に必須","channelDisabled": "チャンネルは無効","notEnabled": "無効"@@ -914,20 +945,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "DingTalk",- "discord": "Discord",- "email": "Email",- "feishu": "Feishu",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "WeChat",- "wecom": "WeCom",- "weixin": "WeChat",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "{{time}}",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex ca99c11ee..954c8ec5c 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -42,8 +42,8 @@"description": "nanobot 웹 UI — nanobot 작업공간과 대화하세요."},"pairing": {- "title": "채팅 사용자 연결",- "description": "채팅에 표시된 연결 코드를 입력하세요.",+ "title": "내 채팅 계정 페어링",+ "description": "채팅에서 받은 페어링 코드를 입력하세요.","code": "연결 코드","matched": "{{channel}} 일치. 연결 중...","expiresInline": "코드 만료: {{expires}}.",@@ -777,13 +777,13 @@"searchPlaceholder": "채널 검색","backToChannels": "모든 채널","catalog": "채널",+ "help": "도움말","loading": "채널을 불러오는 중...","empty": "일치하는 채널이 없습니다.","restartRequired": "업데이트된 채널 지원을 적용하려면 nanobot을 다시 시작하세요.","requires": "필요: {{requirements}}","setUp": "설정","setupGuide": "설정 가이드",- "setupSummary": "채널을 활성화하고 플랫폼 인증 정보를 입력한 후 nanobot을 다시 시작하세요.","configKeys": "설정 키","enable": "채널 활성화","disable": "채널 비활성화",@@ -817,7 +817,6 @@"runtimeStarting": "시작 중","runtimeStopped": "실행 중 아님","managedByWebui": "WebUI에서 관리",- "officialGuide": "공식 가이드","optional": "선택 사항","providerPreset": "제공업체","requiredSetup": "필수 설정",@@ -826,19 +825,49 @@"savedSettings": "설정을 저장했습니다.","saveSettings": "설정 저장","selectChannel": "{{name}} 설정 보기",- "setupSteps": "다음 단계","showSecret": "비밀 값 표시","toggleChannel": "{{name}} 활성화","toggleInstance": "{{name}} 인스턴스 활성화",- "tryIt": "사용해 보기","validationFailed": "활성화하기 전에 필수 설정을 확인하세요.",+ "completeSetupToEnable": "아래 필수 설정을 완료하면 이 채널을 활성화할 수 있습니다.",+ "chooseCredentialMethod": "인증 방식 하나 선택",+ "or": "또는",+ "fieldRequired": "설정을 완료하려면 필요합니다.",+ "secretWillBeRemoved": "삭제 예정",+ "keepSavedSecret": "저장된 인증 정보 유지",+ "removeSavedSecret": "저장된 인증 정보 삭제",+ "sections": {+ "account": "계정",+ "credentials": "인증 정보",+ "connection": "연결",+ "access": "접근",+ "behavior": "동작",+ "security": "보안"+ },"validation": {"connected": "연결됨","configured": "수동 설정됨","needs_setup": "설정 필요",- "invalid": "잘못됨",+ "invalid": "연결 실패","unsupported": "수동 설정"- }+ },+ "validationMessages": {+ "connected": "연결을 확인했습니다.",+ "unverified": "연결이 확인되지 않았습니다.",+ "missing": "필수 항목을 입력하세요.",+ "invalid": "연결 확인에 실패했습니다.",+ "unsupported": "이 채널은 아직 연결 확인을 지원하지 않습니다.",+ "present": "입력됨",+ "required": "필수",+ "manual": "이 채널은 아직 연결 확인을 지원하지 않습니다."+ },+ "search": "채널 검색",+ "filterEnabled": "활성화됨",+ "noResults": "일치하는 채널 없음",+ "install": "설치",+ "installChannel": "{{name}} 설치",+ "noInstallNeeded": "설치 필요 없음",+ "installNeeded": "종속 항목 필요"},"nanobotFeatures": {"enabled": "활성화됨",@@ -849,7 +878,9 @@"installSupport": "지원 패키지 설치","installConfirmTitle": "{{name}}에 필요한 패키지를 설치할까요?","installConfirmDescription": "nanobot이 필요한 패키지를 설치한 뒤 {{name}} 기능을 활성화합니다.",+ "installOnlyConfirmDescription": "nanobot이 {{name}}에 필요한 지원 패키지를 설치합니다. 설치 후 연결할 수 있습니다.","installConfirmAction": "설치하고 활성화",+ "installOnlyConfirmAction": "지원 패키지 설치","websocketRequired": "WebUI 필수","channelDisabled": "채널이 비활성화됨","notEnabled": "비활성화됨"@@ -914,20 +945,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "DingTalk",- "discord": "Discord",- "email": "Email",- "feishu": "Feishu",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "WeChat",- "wecom": "WeCom",- "weixin": "WeChat",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "{{time}}",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 17386d237..3787225fc 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -42,8 +42,8 @@"description": "Interface web do nanobot — converse com o seu espaço de trabalho do nanobot."},"pairing": {- "title": "Vincular usuário do chat",- "description": "Digite o código de vinculação exibido no chat.",+ "title": "Parear sua conta de chat",+ "description": "Digite o código de pareamento recebido no chat.","code": "Código de vinculação","matched": "Correspondência com {{channel}}. Conectando...","expiresInline": "O código expira {{expires}}.",@@ -791,13 +791,13 @@"searchPlaceholder": "Buscar canais","backToChannels": "Todos os canais","catalog": "Canais",+ "help": "Ajuda","loading": "Carregando canais...","empty": "Nenhum canal corresponde a este filtro.","restartRequired": "Reinicie o nanobot para aplicar o suporte de canais atualizado.","requires": "Requer: {{requirements}}","setUp": "Configurar","setupGuide": "Guia de configuração",- "setupSummary": "Ative o canal, adicione as credenciais da plataforma e reinicie o nanobot.","configKeys": "Chaves de configuração","enable": "Habilitar canal","disable": "Desabilitar canal",@@ -831,7 +831,6 @@"runtimeStarting": "Iniciando","runtimeStopped": "Não está em execução","managedByWebui": "Gerenciado pela WebUI",- "officialGuide": "Guia oficial","optional": "Opcional","providerPreset": "Provedor","requiredSetup": "Configuração obrigatória",@@ -840,19 +839,49 @@"savedSettings": "Configurações salvas.","saveSettings": "Salvar configurações","selectChannel": "Ver configurações de {{name}}",- "setupSteps": "Próximas etapas","showSecret": "Mostrar segredo","toggleChannel": "Ativar {{name}}","toggleInstance": "Ativar a instância {{name}}",- "tryIt": "Experimente","validationFailed": "Verifique a configuração obrigatória antes de ativar.",+ "completeSetupToEnable": "Conclua a configuração obrigatória abaixo para ativar este canal.",+ "chooseCredentialMethod": "Escolha um método de credencial",+ "or": "ou",+ "fieldRequired": "Obrigatório para concluir a configuração.",+ "secretWillBeRemoved": "Será removida",+ "keepSavedSecret": "Manter credencial salva",+ "removeSavedSecret": "Remover credencial salva",+ "sections": {+ "account": "Conta",+ "credentials": "Credenciais",+ "connection": "Conexão",+ "access": "Acesso",+ "behavior": "Comportamento",+ "security": "Segurança"+ },"validation": {"connected": "Conectado","configured": "Configurado manualmente","needs_setup": "Requer configuração",- "invalid": "Inválido",+ "invalid": "Falha na conexão","unsupported": "Configuração manual"- }+ },+ "validationMessages": {+ "connected": "Conexão verificada.",+ "unverified": "Conexão não verificada.",+ "missing": "Preencha os campos obrigatórios.",+ "invalid": "Falha ao verificar a conexão.",+ "unsupported": "Este canal ainda não permite verificar a conexão.",+ "present": "Preenchido",+ "required": "Obrigatório",+ "manual": "Este canal ainda não permite verificar a conexão."+ },+ "search": "Buscar canais",+ "filterEnabled": "Ativados",+ "noResults": "Nenhum canal correspondente",+ "install": "Instalar",+ "installChannel": "Instalar {{name}}",+ "noInstallNeeded": "Não requer instalação",+ "installNeeded": "Requer dependências"},"nanobotFeatures": {"enabled": "Habilitado",@@ -863,7 +892,9 @@"installSupport": "Instalar dependências","installConfirmTitle": "Instalar as dependências de {{name}}?","installConfirmDescription": "O nanobot instalará as dependências necessárias e ativará {{name}}.",+ "installOnlyConfirmDescription": "O nanobot instalará o que {{name}} precisa. Você poderá conectá-lo após a instalação.","installConfirmAction": "Instalar e habilitar",+ "installOnlyConfirmAction": "Instalar suporte","websocketRequired": "Necessário para a WebUI","channelDisabled": "Canal desabilitado","notEnabled": "Não habilitado"@@ -928,20 +959,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "DingTalk",- "discord": "Discord",- "email": "E-mail",- "feishu": "Feishu",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "WeChat",- "wecom": "WeCom",- "weixin": "WeChat",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "Às {{time}}",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex eb07db563..a1aa754f2 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -42,8 +42,8 @@"description": "Giao diện web nanobot — trò chuyện với không gian làm việc nanobot của bạn."},"pairing": {- "title": "Liên kết người dùng chat",- "description": "Nhập mã liên kết hiển thị trong cuộc trò chuyện.",+ "title": "Ghép nối tài khoản trò chuyện của bạn",+ "description": "Nhập mã ghép nối bạn nhận được trong cuộc trò chuyện.","code": "Mã liên kết","matched": "Đã khớp với {{channel}}. Đang kết nối...","expiresInline": "Mã hết hạn {{expires}}.",@@ -777,13 +777,13 @@"searchPlaceholder": "Tìm kênh","backToChannels": "Tất cả kênh","catalog": "Kênh",+ "help": "Trợ giúp","loading": "Đang tải kênh...","empty": "Không có kênh nào phù hợp.","restartRequired": "Khởi động lại nanobot để áp dụng hỗ trợ kênh đã cập nhật.","requires": "Yêu cầu: {{requirements}}","setUp": "Thiết lập","setupGuide": "Hướng dẫn thiết lập",- "setupSummary": "Bật kênh, thêm thông tin xác thực của nền tảng rồi khởi động lại nanobot.","configKeys": "Khóa cấu hình","enable": "Bật kênh","disable": "Tắt kênh",@@ -817,7 +817,6 @@"runtimeStarting": "Đang khởi động","runtimeStopped": "Không chạy","managedByWebui": "Do WebUI quản lý",- "officialGuide": "Hướng dẫn chính thức","optional": "Tùy chọn","providerPreset": "Nhà cung cấp","requiredSetup": "Thiết lập bắt buộc",@@ -826,19 +825,49 @@"savedSettings": "Đã lưu cài đặt.","saveSettings": "Lưu cài đặt","selectChannel": "Xem cài đặt {{name}}",- "setupSteps": "Các bước tiếp theo","showSecret": "Hiện khóa bí mật","toggleChannel": "Bật {{name}}","toggleInstance": "Bật cấu hình {{name}}",- "tryIt": "Dùng thử","validationFailed": "Hãy kiểm tra thiết lập bắt buộc trước khi bật.",+ "completeSetupToEnable": "Hoàn tất thiết lập bắt buộc bên dưới để bật kênh này.",+ "chooseCredentialMethod": "Chọn một phương thức xác thực",+ "or": "hoặc",+ "fieldRequired": "Bắt buộc để hoàn tất thiết lập.",+ "secretWillBeRemoved": "Sẽ bị xóa",+ "keepSavedSecret": "Giữ thông tin xác thực đã lưu",+ "removeSavedSecret": "Xóa thông tin xác thực đã lưu",+ "sections": {+ "account": "Tài khoản",+ "credentials": "Thông tin xác thực",+ "connection": "Kết nối",+ "access": "Quyền truy cập",+ "behavior": "Hành vi",+ "security": "Bảo mật"+ },"validation": {"connected": "Đã kết nối","configured": "Đã cấu hình thủ công","needs_setup": "Cần thiết lập",- "invalid": "Không hợp lệ",+ "invalid": "Kết nối thất bại","unsupported": "Thiết lập thủ công"- }+ },+ "validationMessages": {+ "connected": "Đã xác minh kết nối.",+ "unverified": "Chưa xác minh kết nối.",+ "missing": "Hãy điền các trường bắt buộc.",+ "invalid": "Không thể xác minh kết nối.",+ "unsupported": "Kênh này chưa hỗ trợ kiểm tra kết nối.",+ "present": "Đã điền",+ "required": "Bắt buộc",+ "manual": "Kênh này chưa hỗ trợ kiểm tra kết nối."+ },+ "search": "Tìm kênh",+ "filterEnabled": "Đã bật",+ "noResults": "Không có kênh phù hợp",+ "install": "Cài đặt",+ "installChannel": "Cài đặt {{name}}",+ "noInstallNeeded": "Không cần cài đặt",+ "installNeeded": "Cần phần phụ thuộc"},"nanobotFeatures": {"enabled": "Đã bật",@@ -849,7 +878,9 @@"installSupport": "Cài gói hỗ trợ","installConfirmTitle": "Cài các gói cần thiết cho {{name}}?","installConfirmDescription": "nanobot sẽ cài các gói cần thiết rồi bật {{name}}.",+ "installOnlyConfirmDescription": "nanobot sẽ cài đặt gói hỗ trợ mà {{name}} cần. Bạn có thể kết nối sau khi cài đặt.","installConfirmAction": "Cài và bật",+ "installOnlyConfirmAction": "Cài gói hỗ trợ","websocketRequired": "Bắt buộc cho WebUI","channelDisabled": "Kênh đang tắt","notEnabled": "Chưa bật"@@ -914,20 +945,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "DingTalk",- "discord": "Discord",- "email": "Email",- "feishu": "Feishu",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "WeChat",- "wecom": "WeCom",- "weixin": "WeChat",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "Vào {{time}}",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 477bb0895..f98599da1 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -42,8 +42,8 @@"description": "nanobot Web UI —— 与你的 nanobot 工作区对话。"},"pairing": {- "title": "配对聊天用户",- "description": "输入聊天中显示的配对码。",+ "title": "配对你的聊天账号",+ "description": "输入你在聊天平台中收到的配对码。","code": "配对码","matched": "已匹配 {{channel}},正在连接…","expiresInline": "配对码将于 {{expires}} 过期。",@@ -983,7 +983,6 @@"requires": "需要:{{requirements}}","setUp": "设置","setupGuide": "配置指南",- "setupSummary": "启用后,请填写此平台的连接信息,然后重启 nanobot。","configKeys": "配置字段","enable": "启用","disable": "停用",@@ -997,7 +996,8 @@"open": "打开","checkedAndEnabled": "已检查并启用。","checking": "正在检查...",- "checkOnly": "仅检查",+ "help": "帮助",+ "checkOnly": "检测","commandCopied": "命令已复制。","commandCopyFailed": "无法复制命令。","configuredInstances_one": "已配置 {{count}} 个实例",@@ -1017,7 +1017,6 @@"runtimeStarting": "正在启动","runtimeStopped": "未运行","managedByWebui": "由 WebUI 管理",- "officialGuide": "官方指南","optional": "可选","providerPreset": "提供商","requiredSetup": "必需配置",@@ -1026,19 +1025,49 @@"savedSettings": "设置已保存。","saveSettings": "保存设置","selectChannel": "查看 {{name}} 设置",- "setupSteps": "后续步骤","showSecret": "显示密钥","toggleChannel": "启用 {{name}}","toggleInstance": "启用 {{name}}",- "tryIt": "试一试","validationFailed": "启用前请检查必需配置。",+ "completeSetupToEnable": "请先完成下方必需配置,然后即可启用此渠道。",+ "chooseCredentialMethod": "选择一种凭据方式",+ "or": "或",+ "fieldRequired": "完成配置需要此字段。",+ "secretWillBeRemoved": "将被删除",+ "keepSavedSecret": "保留已保存的凭据",+ "removeSavedSecret": "删除已保存的凭据",+ "sections": {+ "account": "账户",+ "credentials": "凭据",+ "connection": "连接",+ "access": "访问权限",+ "behavior": "行为",+ "security": "安全"+ },"validation": {"connected": "已连接",- "configured": "手动配置",+ "configured": "未验证","needs_setup": "需要配置",- "invalid": "配置无效",+ "invalid": "连接失败","unsupported": "手动配置"- }+ },+ "validationMessages": {+ "connected": "连接正常",+ "unverified": "尚未验证连接是否可用",+ "missing": "请填写必填项",+ "invalid": "检测失败",+ "unsupported": "此渠道暂不支持连接检测",+ "present": "已填写",+ "required": "必填",+ "manual": "此渠道暂不支持连接检测"+ },+ "search": "搜索聊天平台",+ "filterEnabled": "已启用",+ "noResults": "没有匹配的渠道",+ "install": "安装",+ "installChannel": "安装 {{name}}",+ "noInstallNeeded": "无需安装",+ "installNeeded": "需要额外依赖"},"nanobotFeatures": {"enabled": "已启用",@@ -1049,7 +1078,9 @@"installSupport": "安装支持包","installConfirmTitle": "安装 {{name}} 所需的软件包?","installConfirmDescription": "安装所需软件包后,将启用 {{name}}。",+ "installOnlyConfirmDescription": "将安装 {{name}} 所需的支持包。安装完成后即可连接。","installConfirmAction": "安装并启用",+ "installOnlyConfirmAction": "安装支持包","websocketRequired": "WebUI 必需","channelDisabled": "此平台已停用","notEnabled": "未启用"@@ -1114,20 +1145,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "钉钉",- "discord": "Discord",- "email": "邮件",- "feishu": "飞书",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "微信",- "wecom": "企业微信",- "weixin": "微信",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "在 {{time}}",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 4700b1aa2..3f654a85b 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -42,8 +42,8 @@"description": "nanobot Web UI —— 與你的 nanobot 工作區對話。"},"pairing": {- "title": "配對聊天使用者",- "description": "輸入聊天中顯示的配對碼。",+ "title": "配對你的聊天帳號",+ "description": "輸入你在聊天平台收到的配對碼。","code": "配對碼","matched": "已符合 {{channel}},正在連線…","expiresInline": "配對碼將於 {{expires}} 到期。",@@ -783,7 +783,6 @@"requires": "需要:{{requirements}}","setUp": "設定","setupGuide": "設定指南",- "setupSummary": "啟用此通訊管道只會開啟 nanobot 的支援功能。請新增平台憑證,然後重新啟動 nanobot。","configKeys": "設定欄位","enable": "啟用通訊管道","disable": "停用通訊管道",@@ -797,7 +796,8 @@"open": "開啟","checkedAndEnabled": "已檢查並啟用。","checking": "正在檢查...",- "checkOnly": "僅檢查",+ "help": "說明",+ "checkOnly": "檢測","commandCopied": "指令已複製。","commandCopyFailed": "無法複製指令。","configuredInstances_one": "已設定 {{count}} 個執行個體",@@ -817,7 +817,6 @@"runtimeStarting": "正在啟動","runtimeStopped": "未執行","managedByWebui": "由 WebUI 管理",- "officialGuide": "官方指南","optional": "選填","providerPreset": "服務供應商","requiredSetup": "必要設定",@@ -826,19 +825,49 @@"savedSettings": "設定已儲存。","saveSettings": "儲存設定","selectChannel": "檢視 {{name}} 設定",- "setupSteps": "後續步驟","showSecret": "顯示金鑰","toggleChannel": "啟用 {{name}}","toggleInstance": "{{name}} 執行個體",- "tryIt": "試試看","validationFailed": "啟用前請檢查必要設定。",+ "completeSetupToEnable": "請先完成下方必要設定,然後即可啟用此頻道。",+ "chooseCredentialMethod": "選擇一種憑證方式",+ "or": "或",+ "fieldRequired": "完成設定需要此欄位。",+ "secretWillBeRemoved": "將被移除",+ "keepSavedSecret": "保留已儲存的憑證",+ "removeSavedSecret": "移除已儲存的憑證",+ "sections": {+ "account": "帳戶",+ "credentials": "憑證",+ "connection": "連線",+ "access": "存取權限",+ "behavior": "行為",+ "security": "安全性"+ },"validation": {"connected": "已連線",- "configured": "手動設定",+ "configured": "未驗證","needs_setup": "需要設定",- "invalid": "無效",+ "invalid": "連線失敗","unsupported": "手動設定"- }+ },+ "validationMessages": {+ "connected": "連線正常",+ "unverified": "尚未驗證連線是否可用",+ "missing": "請填寫必填欄位",+ "invalid": "檢測失敗",+ "unsupported": "此渠道暫不支援連線檢測",+ "present": "已填寫",+ "required": "必填",+ "manual": "此渠道暫不支援連線檢測"+ },+ "search": "搜尋聊天平台",+ "filterEnabled": "已啟用",+ "noResults": "沒有符合的渠道",+ "install": "安裝",+ "installChannel": "安裝 {{name}}",+ "noInstallNeeded": "無需安裝",+ "installNeeded": "需要額外依賴"},"nanobotFeatures": {"enabled": "已啟用",@@ -849,7 +878,9 @@"installSupport": "安裝支援套件","installConfirmTitle": "安裝 {{name}} 的支援套件?","installConfirmDescription": "nanobot 將安裝 {{name}} 所需的元件並啟用支援。要繼續嗎?",+ "installOnlyConfirmDescription": "將安裝 {{name}} 所需的支援套件。安裝完成後即可連線。","installConfirmAction": "安裝並啟用",+ "installOnlyConfirmAction": "安裝支援套件","websocketRequired": "WebUI 需要此功能","channelDisabled": "通訊管道已停用","notEnabled": "未啟用"@@ -914,20 +945,7 @@},"channels": {"api": "API",- "cli": "CLI",- "dingtalk": "釘釘",- "discord": "Discord",- "email": "電子郵件",- "feishu": "飛書",- "matrix": "Matrix",- "msteams": "Microsoft Teams",- "qq": "QQ",- "slack": "Slack",- "telegram": "Telegram",- "wechat": "微信",- "wecom": "企業微信",- "weixin": "微信",- "whatsapp": "WhatsApp"+ "cli": "CLI"},"schedule": {"at": "於 {{time}}",@@ -1187,7 +1205,7 @@"compaction": {"cancelled": "上下文壓縮已取消","empty": "無需壓縮上下文",- "started": "正在壓縮上下文",+ "started": "正在壓縮上下文…","failed": "上下文壓縮失敗","succeeded": "上下文已壓縮"},diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.tsindex 592bf5e7c..8434f5688 100644--- a/webui/src/lib/api.ts+++ b/webui/src/lib/api.ts@@ -566,12 +566,16 @@ export async function stopApiService(export async function enableNanobotFeature(transport: WebUIMutationTransport,name: string,- options: { instanceId?: string } = {},+ options: { instanceId?: string; installOnly?: boolean } = {},): Promise<NanobotFeaturesPayload> {return mutation<NanobotFeaturesPayload>(transport,"settings.feature.enable",- { name, ...(options.instanceId ? { instance_id: options.instanceId } : {}) },+ {+ name,+ ...(options.instanceId ? { instance_id: options.instanceId } : {}),+ ...(options.installOnly ? { install_only: true } : {}),+ },PACKAGE_MUTATION_TIMEOUT_MS,);}@@ -611,22 +615,14 @@ export async function runPairingAction(export async function startChannelConnect(transport: WebUIMutationTransport,channel: string,- options: {- domain?: string;- instanceId?: string;- mode?: "replace" | "create";- force?: boolean;- } = {},+ params: Readonly<Record<string, string | boolean>> = {},): Promise<ChannelConnectPayload> {return mutation<ChannelConnectPayload>(transport,"settings.channel.connect.start",{+ ...params,channel,- ...(options.domain ? { domain: options.domain } : {}),- ...(options.instanceId ? { instance_id: options.instanceId } : {}),- ...(options.mode ? { mode: options.mode } : {}),- ...(options.force ? { force: true } : {}),},PACKAGE_MUTATION_TIMEOUT_MS,);@@ -664,7 +660,7 @@ export async function cancelChannelConnect(export async function configureChannel(transport: WebUIMutationTransport,name: string,- values: Record<string, string>,+ values: Record<string, string | null>,options: { enable?: boolean; instanceId?: string } = {},): Promise<ChannelConfigurePayload> {return mutation<ChannelConfigurePayload>(@@ -683,7 +679,7 @@ export async function configureChannel(export async function validateChannel(transport: WebUIMutationTransport,name: string,- values: Record<string, string> = {},+ values: Record<string, string | null> = {},options: { instanceId?: string } = {},): Promise<ChannelValidationPayload> {return mutation<ChannelValidationPayload>(diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex 76934c2c5..6754cdea8 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -984,8 +984,9 @@ export interface NanobotFeatureInfo {configured_fields?: string[];setup?: ChannelSetupContract;instances?: NanobotChannelInstanceInfo[];- installed: boolean;- ready: boolean;+ installed: boolean;+ requires_dependencies?: boolean;+ ready: boolean;status: "enabled" | "missing_dependency" | "not_enabled" | string;install_supported: boolean;requires_restart: boolean;@@ -1002,7 +1003,13 @@ export interface ChannelSetupContractField {export interface ChannelSetupContract {fields: ChannelSetupContractField[];+ requirements?: ChannelSetupContractRequirement[];official_url?: string;+ verifies_connection?: boolean;+}++export interface ChannelSetupContractRequirement {+ alternatives: string[][];}export interface NanobotChannelInstanceInfo {@@ -1194,11 +1201,8 @@ export interface ChannelConnectPayload {status: ChannelConnectStatus;message?: string;qr_url?: string;- domain?: string;interval_ms?: number;expires_at_ms?: number;- app_id?: string;- account?: string;nanobot_features?: NanobotFeaturesPayload;}diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.tsindex 65d810786..75cf166f3 100644--- a/webui/src/tests/api.test.ts+++ b/webui/src/tests/api.test.ts@@ -259,6 +259,20 @@ describe("webui API helpers", () => {);});+ it("forwards channel-owned connect parameters without overriding the channel", async () => {+ await startChannelConnect(mutationTransport, "plugin-chat", {+ region: "eu",+ interactive: false,+ channel: "another-channel",+ });++ expect(requestMutation).toHaveBeenLastCalledWith(+ "settings.channel.connect.start",+ { channel: "plugin-chat", region: "eu", interactive: false },+ 150_000,+ );+ });+it("serializes workspace automation actions", async () => {await runAutomationAction(mutationTransport, "disable", "job 1/2");@@ -810,6 +824,13 @@ describe("webui API helpers", () => {150_000,);+ await enableNanobotFeature(mutationTransport, "whatsapp", { installOnly: true });+ expect(requestMutation).toHaveBeenLastCalledWith(+ "settings.feature.enable",+ { name: "whatsapp", install_only: true },+ 150_000,+ );+await disableNanobotFeature(mutationTransport, "matrix");expect(requestMutation).toHaveBeenLastCalledWith("settings.feature.disable",diff --git a/webui/src/tests/channel-credential-form.test.tsx b/webui/src/tests/channel-credential-form.test.tsxnew file mode 100644index 000000000..1904b3a91--- /dev/null+++ b/webui/src/tests/channel-credential-form.test.tsx@@ -0,0 +1,111 @@+import { fireEvent, render, screen, within } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import {+ CredentialForm,+ channelValuesForSubmit,+} from "@/components/settings/channels/CredentialForm";+import type { ChannelConfigField } from "@/components/settings/channels/catalog";++const fields: ChannelConfigField[] = [+ {+ key: "channels.matrix.password",+ label: "Password",+ secret: true,+ },+ {+ key: "channels.matrix.groupPolicy",+ label: "Group behavior",+ options: [+ { value: "mention", label: "Mention only" },+ { value: "open", label: "All messages" },+ ],+ },+];++describe("CredentialForm", () => {+ it("uses native radio semantics for option fields", () => {+ const onChange = vi.fn();+ render(+ <CredentialForm+ fields={[fields[1]!]}+ values={{ "channels.matrix.groupPolicy": "mention" }}+ visibleSecrets={{}}+ onChange={onChange}+ onToggleSecret={vi.fn()}+ />,+ );++ const group = screen.getByRole("group", { name: "Group behavior" });+ expect(within(group).getByRole("radio", { name: "Mention only" })).toBeChecked();+ fireEvent.click(within(group).getByRole("radio", { name: "All messages" }));+ expect(onChange).toHaveBeenCalledWith("channels.matrix.groupPolicy", "open");+ });++ it("associates option errors and exposes a stable focus target", () => {+ render(+ <CredentialForm+ fields={[fields[1]!]}+ values={{ "channels.matrix.groupPolicy": "mention" }}+ visibleSecrets={{}}+ onChange={vi.fn()}+ onToggleSecret={vi.fn()}+ errors={{ "channels.matrix.groupPolicy": "Required to complete setup." }}+ />,+ );++ const group = screen.getByRole("group", { name: "Group behavior" });+ const firstRadio = within(group).getByRole("radio", { name: "Mention only" });+ const secondRadio = within(group).getByRole("radio", { name: "All messages" });++ expect(group).toHaveAttribute("id", "channel-field-channels-matrix-groupPolicy-group");+ expect(group).toHaveAttribute("aria-invalid", "true");+ expect(group).toHaveAccessibleDescription(+ "Required to complete setup.",+ );+ expect(firstRadio).toHaveAttribute("id", "channel-field-channels-matrix-groupPolicy");+ expect(secondRadio).toHaveAttribute("id", "channel-field-channels-matrix-groupPolicy-1");+ expect(firstRadio).toHaveAttribute("aria-invalid", "true");+ expect(firstRadio).toHaveAccessibleDescription(+ "Required to complete setup.",+ );++ document.getElementById("channel-field-channels-matrix-groupPolicy")?.focus();+ expect(firstRadio).toHaveFocus();+ });++ it("associates field errors and saved-secret removal actions", () => {+ const onClearSecret = vi.fn();+ render(+ <CredentialForm+ fields={[fields[0]!]}+ values={{}}+ configuredFields={new Set(["channels.matrix.password"])}+ visibleSecrets={{}}+ onChange={vi.fn()}+ onToggleSecret={vi.fn()}+ errors={{ "channels.matrix.password": "Required to complete setup." }}+ onClearSecret={onClearSecret}+ showSecretActions+ />,+ );++ const password = screen.getByLabelText("Password");+ expect(password).toHaveAttribute("aria-invalid", "true");+ expect(password).toHaveAccessibleDescription("Required to complete setup.");+ fireEvent.click(screen.getByRole("button", { name: "Remove saved credential" }));+ expect(onClearSecret).toHaveBeenCalledWith("channels.matrix.password", true);+ });++ it("uses null only for an explicitly cleared secret", () => {+ expect(+ channelValuesForSubmit(+ fields,+ { "channels.matrix.password": "" },+ new Set(),+ new Set(["channels.matrix.password"]),+ ),+ ).toEqual({ "channels.matrix.password": null });+ expect(channelValuesForSubmit(fields, {}, new Set())).toEqual({});+ });+});diff --git a/webui/src/tests/channel-identity.test.ts b/webui/src/tests/channel-identity.test.tsindex 03c1ed40d..80267811d 100644--- a/webui/src/tests/channel-identity.test.ts+++ b/webui/src/tests/channel-identity.test.ts@@ -120,13 +120,26 @@ describe("channelSetup", () => {webui: "webui/index.ts",}), "zh-CN");- expect(setup.summary).toBe("钉钉需要 Stream 模式的应用凭据。");- expect(setup.steps[0]).toBe("创建或选择一个已启用 Stream 模式的钉钉应用。");+ expect(setup.docsLabel).toBe("打开钉钉配置指南");+ expect(setup.officialLabel).toBe("打开钉钉开发者后台");expect(setup.fields).toContainEqual(expect.objectContaining({key: "channels.dingtalk.allowFrom",label: "允许的用户",}));});++ it("loads custom setup section labels from the channel-owned locale", () => {+ const setup = channelSetup(feature({+ name: "email",+ display_name: "Email",+ webui: "webui/index.ts",+ }));++ expect(setup.sectionLabels).toEqual({+ receiving: "Receiving mail",+ sending: "Sending mail",+ });+ });});describe("channel runtime state", () => {diff --git a/webui/src/tests/channel-locale-registry.test.ts b/webui/src/tests/channel-locale-registry.test.tsindex 21073be17..c1a47e4c7 100644--- a/webui/src/tests/channel-locale-registry.test.ts+++ b/webui/src/tests/channel-locale-registry.test.ts@@ -1,6 +1,3 @@-import { readFileSync } from "node:fs";-import { resolve } from "node:path";-import { describe, expect, it, vi } from "vitest";import { channelFieldMessageKey } from "@/channel-plugins/i18n";@@ -15,6 +12,7 @@ const expectedChannels = ["feishu","matrix","mattermost",+ "mochat","msteams","napcat","qq",@@ -96,22 +94,6 @@ describe("channel locale registry", () => {}}});-- it("keeps i18n initialization independent from channel React modules", () => {- const localeRegistry = readFileSync(- resolve(process.cwd(), "src/channel-plugins/locale-registry.ts"),- "utf8",- );- const i18nEntry = readFileSync(resolve(process.cwd(), "src/i18n/index.ts"), "utf8");-- expect(localeRegistry).toContain("webui/locales/*.json");- expect(localeRegistry).not.toContain("eager: true");- expect(localeRegistry).not.toMatch(/channel-plugins\/registry|\.tsx|\breact\b/i);- expect(i18nEntry).toContain("channel-plugins/locale-registry");- expect(i18nEntry).toContain("import.meta.glob");- expect(i18nEntry).not.toMatch(/import\s+\w+Common\s+from/);- expect(i18nEntry).not.toContain("channel-plugins/registry");- });});describe("channel locale registry concurrency", () => {diff --git a/webui/src/tests/channel-qr-connect.test.tsx b/webui/src/tests/channel-qr-connect.test.tsxnew file mode 100644index 000000000..20ba07688--- /dev/null+++ b/webui/src/tests/channel-qr-connect.test.tsx@@ -0,0 +1,81 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";+import { FeishuConnectFlow } from "../../../nanobot/channels/feishu/webui/FeishuConnectFlow";++const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));++vi.mock("@/providers/ClientProvider", () => {+ const client = { requestMutation };+ return { useClient: () => ({ client }) };+});++const labels = {+ qrAlt: "Connection QR code",+ scanTitle: "Scan to connect",+ scanDescription: "Scan with your app",+ waiting: "Waiting",+ connected: "Connected",+ stopped: "Stopped",+ connecting: "Connecting",+ scanAgain: "Scan again",+ connect: "Connect",+};++beforeEach(() => {+ requestMutation.mockReset().mockResolvedValue({+ session_id: "link-1",+ status: "succeeded",+ });+});++afterEach(cleanup);++describe("channel QR connect parameters", () => {+ it("forwards current channel parameters without restarting on rerender and preserves forced retries", async () => {+ const props = {+ token: "tok",+ channelName: "plugin-chat",+ autoStart: true,+ forceOnRepeat: true,+ labels,+ onFeaturesUpdate: vi.fn(),+ };+ const view = render(<ChannelQrConnectFlow {...props} startParams={{ region: "eu" }} />);+ await waitFor(() => expect(requestMutation).toHaveBeenCalledTimes(1));+ expect(requestMutation).toHaveBeenLastCalledWith(+ "settings.channel.connect.start",+ { channel: "plugin-chat", region: "eu" },+ 150_000,+ );+ await screen.findByText("Connected");++ view.rerender(<ChannelQrConnectFlow {...props} startParams={{ region: "us" }} />);+ expect(requestMutation).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: "Scan again" }));+ await waitFor(() => expect(requestMutation).toHaveBeenCalledTimes(2));+ expect(requestMutation).toHaveBeenLastCalledWith(+ "settings.channel.connect.start",+ { channel: "plugin-chat", region: "us", force: true },+ 150_000,+ );+ });++ it("preserves the Feishu-owned registration domain and instance creation mode", async () => {+ render(+ <FeishuConnectFlow+ token="tok"+ instanceId="support"+ mode="create"+ connectRequestId={1}+ onFeaturesUpdate={vi.fn()}+ />,+ );+ await waitFor(() => expect(requestMutation).toHaveBeenCalledWith(+ "settings.channel.connect.start",+ { channel: "feishu", domain: "feishu", instance_id: "support", mode: "create" },+ 150_000,+ ));+ });+});diff --git a/webui/src/tests/channel-toggles.test.tsx b/webui/src/tests/channel-toggles.test.tsxnew file mode 100644index 000000000..a8f8e0670--- /dev/null+++ b/webui/src/tests/channel-toggles.test.tsx@@ -0,0 +1,189 @@+import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { NanobotFeatureInfo, NanobotFeaturesPayload } from "@/lib/types";+import {+ installSettingsViewTestHooks,+ jsonResponse,+ renderSettingsView,+ requestMutationMock,+ settingsPayload,+} from "@/tests/settings-test-utils";++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });+ return { promise, resolve, reject };+}++function feature(enabled: boolean, instances = false): NanobotFeatureInfo {+ return {+ name: "test-chat",+ display_name: "Test Chat",+ type: "channel",+ installed: true,+ configured: true,+ enabled,+ running: enabled,+ runtime_status: enabled ? "running" : "stopped",+ ready: true,+ status: enabled ? "enabled" : "not_enabled",+ install_supported: true,+ requires_restart: false,+ setup: { fields: [], requirements: [] },+ ...(instances ? { instances: [{+ id: "first",+ name: "First",+ configured: true,+ enabled,+ runtime_status: enabled ? "running" : "stopped",+ config_values: {},+ configured_fields: [],+ }, {+ id: "second",+ name: "Second",+ configured: true,+ enabled: false,+ runtime_status: "stopped",+ config_values: {},+ configured_fields: [],+ }] } : {}),+ };+}++function payload(channel: NanobotFeatureInfo): NanobotFeaturesPayload {+ return { features: [channel], enabled_count: Number(channel.enabled) };+}++function renderChannel(channel: NanobotFeatureInfo) {+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/nanobot-features") return jsonResponse(payload(channel));+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }));+ renderSettingsView({ initialSection: "channels" });+}++describe("optimistic channel switches", () => {+ installSettingsViewTestHooks();+ afterEach(() => vi.restoreAllMocks());++ for (const surface of ["catalog", "setup", "instance"] as const) {+ it.each([+ [false, true],+ [true, true],+ [false, false],+ [true, false],+ ])(`${surface}: updates immediately from %s and settles with success=%s`, async (initial, succeeds) => {+ const mutation = deferred<unknown>();+ const validation = deferred<unknown>();+ requestMutationMock.mockImplementation((action: string) =>+ action === "settings.channel.validate" ? validation.promise : mutation.promise);+ vi.spyOn(console, "error").mockImplementation(() => {});+ renderChannel(feature(initial, surface === "instance"));++ const catalogSwitch = await screen.findByRole("switch", { name: "Test Chat channel" });+ if (surface !== "catalog") {+ fireEvent.click(screen.getByRole("button", { name: "View Test Chat settings" }));+ }+ const toggle = surface === "catalog"+ ? catalogSwitch+ : surface === "instance"+ ? await screen.findByRole("switch", { name: "First instance" })+ : within(await screen.findByRole("dialog")).getByRole("switch");++ if (!initial && succeeds) {+ toggle.focus();+ await userEvent.setup().keyboard("[Space]");+ } else {+ fireEvent.click(toggle);+ }+ expect(toggle).toHaveAttribute("aria-checked", String(!initial));+ expect(toggle).toBeDisabled();+ fireEvent.click(toggle);+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ if (surface === "instance") {+ const other = screen.getByRole("switch", { name: "Second instance" });+ expect(other).toHaveAttribute("aria-checked", "false");+ expect(other).toBeDisabled();+ fireEvent.click(other);+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ }++ await act(async () => { fireEvent(window, new Event("focus")); });+ expect(toggle).toHaveAttribute("aria-checked", String(!initial));+ expect(toggle).toBeDisabled();++ if (surface === "setup" && !initial) {+ await act(async () => validation.resolve({+ name: "test-chat", status: "connected", can_enable: true,+ checks: [], missing_fields: [], requires_restart: false,+ }));+ expect(requestMutationMock).toHaveBeenCalledTimes(2);+ expect(toggle).toHaveAttribute("aria-checked", "true");+ expect(toggle).toBeDisabled();+ }+ const result = payload(feature(!initial, surface === "instance"));+ await act(async () => {+ if (succeeds) {+ mutation.resolve(surface === "setup" && !initial ? { nanobot_features: result } : result);+ } else {+ mutation.reject(new Error("Channel update failed"));+ }+ });+ if (surface === "catalog" && initial && succeeds) {+ await waitFor(() => expect(toggle).not.toBeInTheDocument());+ } else {+ await waitFor(() => expect(toggle).toBeEnabled());+ expect(toggle).toHaveAttribute("aria-checked", String(succeeds ? !initial : initial));+ }+ if (!succeeds) expect(screen.getByText("Channel update failed")).toBeVisible();+ if (surface === "instance") {+ expect(screen.getByRole("switch", { name: "Second instance" })).toBeEnabled();+ }+ });+ }++ it("rolls back when server validation rejects activation without saving", async () => {+ const validation = deferred<unknown>();+ requestMutationMock.mockReturnValue(validation.promise);+ renderChannel(feature(false));+ fireEvent.click(await screen.findByRole("button", { name: "View Test Chat settings" }));+ const toggle = within(await screen.findByRole("dialog")).getByRole("switch");+ fireEvent.click(toggle);+ expect(toggle).toHaveAttribute("aria-checked", "true");++ await act(async () => validation.resolve({+ name: "test-chat", status: "invalid", can_enable: false, message: "Credentials rejected",+ checks: [], missing_fields: [], requires_restart: false,+ }));+ expect(toggle).toHaveAttribute("aria-checked", "false");+ expect(toggle).toBeEnabled();+ expect(screen.getByText("Credentials rejected")).toBeVisible();+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ expect(requestMutationMock.mock.calls[0][0]).toBe("settings.channel.validate");+ });++ it("does not show installation-only requests as optimistic activation", async () => {+ const installation = deferred<unknown>();+ requestMutationMock.mockReturnValue(installation.promise);+ const channel = { ...feature(false), installed: false, requires_dependencies: true };+ renderChannel(channel);+ fireEvent.click(await screen.findByRole("button", { name: "Install Test Chat" }));+ expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.feature.enable", { name: "test-chat", install_only: true }, 150_000,+ );++ channel.installed = true;+ await act(async () => { fireEvent(window, new Event("focus")); });+ const toggle = await screen.findByRole("switch", { name: "Test Chat channel" });+ expect(toggle).toHaveAttribute("aria-checked", "false");+ expect(toggle).toBeDisabled();+ await act(async () => installation.resolve(payload(channel)));+ expect(toggle).toHaveAttribute("aria-checked", "false");+ expect(toggle).toBeEnabled();+ });+});diff --git a/webui/src/tests/channel-ui-registry.test.ts b/webui/src/tests/channel-ui-registry.test.tsindex 82e894a5f..1d6b1d669 100644--- a/webui/src/tests/channel-ui-registry.test.ts+++ b/webui/src/tests/channel-ui-registry.test.ts@@ -33,44 +33,6 @@ describe("channel UI contributions", () => {expect(channelUiOwner("wechat")).toBe("weixin");});- it("uses the DingTalk Open Platform brand mark", () => {- expect(channelUiPresentation("dingtalk")?.logoUrl).toBe(- "https://img.alicdn.com/imgextra/i3/O1CN01WMvMRG1ks3Ixc9x1v_!!6000000004738-55-tps-32-32.svg",- );- });-- it("keeps the core setup panel independent of concrete channel plugins", () => {- const source = readFileSync(- resolve(process.cwd(), "src/components/settings/channels/ChannelSetupPanel.tsx"),- "utf8",- );-- expect(source).not.toMatch(/feature\.name\s*===\s*["'](?:feishu|weixin)["']/);- expect(source).not.toMatch(/channel-plugins\/(?:feishu|weixin)/);- expect(source).not.toMatch(/(?:Feishu|Weixin)(?:AssistantsPanel|ConnectFlow)/);- });-- it("discovers UI contributions only from channel-owned packages", () => {- const source = readFileSync(- resolve(process.cwd(), "src/channel-plugins/registry.ts"),- "utf8",- );-- expect(source).toContain("../../../nanobot/channels/*/webui/index.{ts,tsx}");- expect(source).not.toContain("webui/**/*.{ts,tsx}");- expect(source).not.toContain('"./*/index.tsx"');- });-- it("derives channel identity from the package directory", () => {- for (const channel of ["feishu", "weixin"]) {- const source = readFileSync(- resolve(process.cwd(), `../nanobot/channels/${channel}/webui/index.tsx`),- "utf8",- );- expect(source).not.toMatch(/\bchannel\s*:/);- }- });-it("includes channel-owned UI in Tailwind's production scan", () => {const source = readFileSync(resolve(process.cwd(), "tailwind.config.js"), "utf8");diff --git a/webui/src/tests/i18n.test.tsx b/webui/src/tests/i18n.test.tsxindex 5af41a342..757315e08 100644--- a/webui/src/tests/i18n.test.tsx+++ b/webui/src/tests/i18n.test.tsx@@ -228,7 +228,6 @@ const LOCALIZED_CHANNEL_SHELL_KEYS = ["settings.channels.instanceConfigured","settings.channels.instanceNeedsSetup","settings.channels.managedByWebui",- "settings.channels.officialGuide","settings.channels.optional","settings.channels.providerPreset","settings.channels.requiredSetup",@@ -237,11 +236,9 @@ const LOCALIZED_CHANNEL_SHELL_KEYS = ["settings.channels.savedSettings","settings.channels.saveSettings","settings.channels.selectChannel",- "settings.channels.setupSteps","settings.channels.showSecret","settings.channels.toggleChannel","settings.channels.toggleInstance",- "settings.channels.tryIt","settings.channels.validation.connected","settings.channels.validation.configured","settings.channels.validation.invalid",diff --git a/webui/src/tests/settings-automations.test.tsx b/webui/src/tests/settings-automations.test.tsxnew file mode 100644index 000000000..8f2558214--- /dev/null+++ b/webui/src/tests/settings-automations.test.tsx@@ -0,0 +1,68 @@+import { act, cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { AutomationsSettings } from "@/components/settings/system/AutomationsSettings";+import i18n from "@/i18n";++afterEach(cleanup);++function renderAutomations(channel: string) {+ return render(+ <AutomationsSettings+ payload={{ jobs: [{+ id: "task-1",+ name: "Scheduled task",+ enabled: true,+ schedule: { kind: "every", every_ms: 60_000 },+ payload: { message: "Summarize updates" },+ state: {},+ origin: { channel },+ }] }}+ loading={false}+ query=""+ filter="all"+ sort="name"+ actionKey={null}+ error={null}+ onQueryChange={vi.fn()}+ onFilterChange={vi.fn()}+ onSortChange={vi.fn()}+ onAction={vi.fn()}+ onRequestEdit={vi.fn()}+ onRequestDelete={vi.fn()}+ onBackToChat={vi.fn()}+ />,+ );+}++describe("automation channel identity", () => {+ it("uses channel-owned names in the list and details when the language changes", async () => {+ renderAutomations("email");+ expect(screen.getAllByText("Email")).toHaveLength(2);++ for (const [locale, name] of [+ ["zh-CN", "电子邮件"],+ ["ja", "メール"],+ ["es", "Correo electrónico"],+ ]) {+ await act(() => i18n.changeLanguage(locale));+ expect(screen.getAllByText(name)).toHaveLength(2);+ expect(screen.queryByText("Email")).not.toBeInTheDocument();+ }+ });++ it("resolves aliases through the owning channel namespace", async () => {+ await i18n.changeLanguage("zh-CN");+ renderAutomations("wechat");+ expect(screen.getAllByText("微信")).toHaveLength(2);+ });++ it.each([+ ["api", "API"],+ ["cli", "CLI"],+ ["extension-chat", "extension-chat"],+ ])("preserves the label for %s", (channel, label) => {+ renderAutomations(channel);+ expect(screen.getAllByText(label)).toHaveLength(2);+ });+});diff --git a/webui/src/tests/settings-channels.test.tsx b/webui/src/tests/settings-channels.test.tsxindex 3b7895354..303d02387 100644--- a/webui/src/tests/settings-channels.test.tsx+++ b/webui/src/tests/settings-channels.test.tsx@@ -1,6 +1,12 @@-import { fireEvent, screen, waitFor, within } from "@testing-library/react";+import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import { expect, it, vi } from "vitest";-import type { ChannelSetupContract, ChannelSetupContractField } from "@/lib/types";+import type {+ ChannelSetupContract,+ ChannelSetupContractField,+ NanobotFeatureInfo,+ NanobotFeaturesPayload,+} from "@/lib/types";import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";@@ -46,6 +52,9 @@ function channelSetupContract(defaultValue: "mention",}),],+ requirements: [+ { alternatives: [["channels.discord.token"]] },+ ],};case "email":return {@@ -66,6 +75,15 @@ function channelSetupContract(field("verifyDkim", "bool", { defaultValue: "true" }),field("verifySpf", "bool", { defaultValue: "true" }),],+ requirements: [+ { alternatives: [["channels.email.consentGranted"]] },+ { alternatives: [["channels.email.imapHost"]] },+ { alternatives: [["channels.email.imapUsername"]] },+ { alternatives: [["channels.email.imapPassword"]] },+ { alternatives: [["channels.email.smtpHost"]] },+ { alternatives: [["channels.email.smtpUsername"]] },+ { alternatives: [["channels.email.smtpPassword"]] },+ ],};case "feishu":return {@@ -84,6 +102,10 @@ function channelSetupContract(field("allowFrom", "list"),field("topicIsolation", "bool"),],+ requirements: [+ { alternatives: [["channels.feishu.appId"]] },+ { alternatives: [["channels.feishu.appSecret"]] },+ ],};case "matrix":return {@@ -99,6 +121,16 @@ function channelSetupContract(defaultValue: "open",}),],+ requirements: [+ { alternatives: [["channels.matrix.homeserver"]] },+ { alternatives: [["channels.matrix.userId"]] },+ {+ alternatives: [+ ["channels.matrix.password"],+ ["channels.matrix.accessToken", "channels.matrix.deviceId"],+ ],+ },+ ],};case "qq":return {@@ -112,13 +144,486 @@ function channelSetupContract(defaultValue: "plain",}),],+ requirements: [+ { alternatives: [["channels.qq.appId"]] },+ { alternatives: [["channels.qq.secret"]] },+ ],};}}+function uninstalledConnectFeature(+ name: "feishu" | "weixin" | "whatsapp",+): NanobotFeatureInfo {+ const displayNames = {+ feishu: "Feishu",+ weixin: "WeChat",+ whatsapp: "WhatsApp",+ };+ return {+ name,+ display_name: displayNames[name],+ webui: "webui/index.tsx",+ type: "channel",+ enabled: false,+ configured: false,+ installed: false,+ requires_dependencies: true,+ ready: false,+ runtime_status: "stopped",+ status: "not_enabled",+ install_supported: true,+ requires_restart: true,+ ...(name === "feishu"+ ? {+ instances: [{+ id: "default",+ name: "nanobot",+ enabled: false,+ runtime_status: "stopped",+ configured: false,+ config_values: {},+ configured_fields: [],+ }],+ }+ : {}),+ };+}++function catalogFeature(+ name: string,+ enabled: boolean,+ requiresDependencies = false,+): NanobotFeatureInfo {+ return {+ name,+ display_name: name,+ type: "channel",+ enabled,+ configured: enabled,+ installed: true,+ requires_dependencies: requiresDependencies,+ ready: enabled,+ status: enabled ? "enabled" : "not_enabled",+ install_supported: true,+ requires_restart: false,+ };+}+describe("Settings channels", () => {installSettingsViewTestHooks();+ it.each([+ {+ name: "telegram",+ displayName: "Telegram",+ identity: "nano_test0001bot",+ checks: [+ { id: "token_format", label: "Token format", status: "pass" },+ { id: "get_me", label: "Bot identity", status: "pass" },+ ],+ },+ {+ name: "discord",+ displayName: "Discord",+ identity: "nanobot-test",+ checks: [+ { id: "bot_token", label: "Bot token", status: "pass" },+ {+ id: "invite",+ label: "Server invite",+ status: "pass",+ action_url: "https://discord.com/oauth2/authorize?client_id=123",+ },+ ],+ },+ ])("reveals $displayName connection checks before confirming the identity", async ({+ name,+ displayName,+ identity,+ checks,+ }) => {+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({+ features: [{+ name,+ display_name: displayName,+ webui: "webui/index.ts",+ type: "channel",+ enabled: true,+ running: true,+ runtime_status: "running",+ configured: true,+ installed: true,+ ready: true,+ status: "enabled",+ install_supported: true,+ requires_restart: false,+ setup: {+ verifies_connection: true,+ fields: [channelSetupField(name, "token", "secret", { required: true })],+ requirements: [{ alternatives: [[`channels.${name}.token`]] }],+ },+ configured_fields: [`channels.${name}.token`],+ }],+ enabled_count: 1,+ });+ }+ return jsonResponse({});+ }));+ requestMutationMock.mockResolvedValueOnce({+ name,+ status: "connected",+ checks,+ identity: { name: identity },+ missing_fields: [],+ can_enable: true,+ requires_restart: false,+ });++ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: `View ${displayName} settings` }));++ const checkButton = screen.getByRole("button", { name: "Check connection" });+ expect(checkButton.parentElement).toBe(+ screen.getByRole("switch", { name: "Enable channel" }).parentElement,+ );+ vi.useFakeTimers();+ try {+ fireEvent.click(checkButton);+ await act(async () => {});++ const progress = screen.getAllByRole("status").find(+ (element) => element.textContent?.includes(checks[0].label),+ );+ expect(progress).toBeDefined();+ expect(within(progress!).getByText(checks[0].label)).toBeVisible();+ expect(within(progress!).queryByText(checks[1].label)).not.toBeInTheDocument();+ expect(within(progress!).queryByText(identity)).not.toBeInTheDocument();++ act(() => vi.advanceTimersByTime(260));+ expect(within(progress!).getByText(checks[1].label)).toBeVisible();+ expect(within(progress!).queryByText(identity)).not.toBeInTheDocument();++ act(() => vi.advanceTimersByTime(260));+ expect(within(progress!).getByText(identity)).toBeVisible();+ expect(within(progress!).getByText("Connected")).toBeVisible();+ if (name === "discord") {+ const checkLabel = within(progress!).getByText("Server invite");+ expect(checkLabel.parentElement).toContainElement(+ within(progress!).getByRole("link", { name: "Open" }),+ );+ }+ expect(screen.queryByText("Connection verified.")).not.toBeInTheDocument();+ } finally {+ vi.useRealTimers();+ }+ });++ it("shows enabled channels by default when any are enabled", async () => {+ const enabled = catalogFeature("Enabled channel", true);+ const enabledWithDependencies = catalogFeature("Enabled dependency channel", true, true);+ const disabled = catalogFeature("Disabled channel", false);+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({ features: [enabled, enabledWithDependencies, disabled], enabled_count: 2 });+ }+ return jsonResponse({});+ }));++ renderSettingsView({ initialSection: "channels" });++ expect(await screen.findByRole("button", { name: "View Enabled channel settings" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "View Enabled dependency channel settings" })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "View Disabled channel settings" })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Enabled" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.queryByText("No installation needed")).not.toBeInTheDocument();+ expect(screen.queryByText("Requires dependencies")).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "All" }));+ expect(screen.getByRole("button", { name: "View Disabled channel settings" })).toBeInTheDocument();+ });++ it("shows all channels by default when none are enabled", async () => {+ const first = catalogFeature("First channel", false);+ const second = catalogFeature("Second channel", false);+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({ features: [first, second], enabled_count: 0 });+ }+ return jsonResponse({});+ }));++ renderSettingsView({ initialSection: "channels" });++ expect(await screen.findByRole("button", { name: "View First channel settings" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "View Second channel settings" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "All" })).toHaveAttribute("aria-pressed", "true");+ });++ it("requires a restart before enabling newly installed channel support", async () => {+ const whatsappFeature = {+ name: "whatsapp",+ display_name: "WhatsApp",+ webui: "webui/index.tsx",+ type: "channel",+ enabled: false,+ configured: false,+ installed: false,+ requires_dependencies: true,+ ready: false,+ status: "not_enabled",+ install_supported: true,+ requires_restart: false,+ } as const;+ const weixinFeature = uninstalledConnectFeature("weixin");+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/cli-apps") return jsonResponse({ apps: [], installed_count: 0 });+ if (url === "/api/settings/mcp-presets") return jsonResponse({ presets: [], installed_count: 0 });+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({ features: [whatsappFeature, weixinFeature], enabled_count: 0 });+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }),+ );+ let finishInstall: (payload: NanobotFeaturesPayload) => void = () => {};+ requestMutationMock.mockImplementationOnce(() => new Promise((resolve) => {+ finishInstall = resolve;+ }));+ const installedPayload = {+ features: [{ ...whatsappFeature, installed: true }, weixinFeature],+ enabled_count: 0,+ requires_restart: true,+ last_action: {+ ok: true,+ message: "Installed support for channel 'whatsapp'",+ enabled: false,+ },+ };++ renderSettingsView({ initialSection: "channels" });++ requestMutationMock.mockResolvedValueOnce({ status: "pending", session_id: "test-link" });+ expect(screen.queryByRole("switch", { name: "WhatsApp channel" })).not.toBeInTheDocument();+ const installationGroup = await screen.findByRole("region", { name: "Requires dependencies" });+ fireEvent.click(within(installationGroup).getByRole("button", { name: "Install WhatsApp" }));+ const secondInstall = within(installationGroup).getByRole("button", { name: "Install WeChat" });+ expect(secondInstall).toBeDisabled();+ fireEvent.click(secondInstall);+ expect(requestMutationMock).toHaveBeenCalledTimes(1);++ await waitFor(() =>+ expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.feature.enable",+ { name: "whatsapp", install_only: true },+ 150_000,+ ),+ );+ finishInstall(installedPayload);+ expect(requestMutationMock).not.toHaveBeenCalledWith("settings.channel.connect.start", expect.anything(), expect.anything());+ expect(await screen.findByText("Restart nanobot to apply updated channel support.")).toBeInTheDocument();+ const installedGroup = await screen.findByRole("region", { name: "Requires dependencies" });+ expect(within(installedGroup).getByRole("switch", { name: "WhatsApp channel" })).toBeDisabled();+ expect(requestMutationMock.mock.calls.map(([action]) => action)).toEqual([+ "settings.feature.enable",+ ]);++ });++ it.each([+ ["feishu", "Feishu"],+ ["weixin", "WeChat"],+ ] as const)(+ "installs %s support before mounting its custom connect panel",+ async (name, displayName) => {+ const feature = uninstalledConnectFeature(name);+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/cli-apps") {+ return jsonResponse({ apps: [], installed_count: 0 });+ }+ if (url === "/api/settings/mcp-presets") {+ return jsonResponse({ presets: [], installed_count: 0 });+ }+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({ features: [feature], enabled_count: 0 });+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }),+ );+ requestMutationMock.mockResolvedValueOnce({+ features: [{ ...feature, installed: true }],+ enabled_count: 0,+ requires_restart: false,+ last_action: {+ ok: true,+ message: `Installed support for channel '${name}'`,+ enabled: false,+ },+ });++ if (name === "weixin") {+ requestMutationMock.mockResolvedValueOnce({ status: "pending", session_id: "weixin-auto", qr_url: "https://example.com/weixin-login" });+ }+ renderSettingsView({ initialSection: "channels" });++ fireEvent.click(await screen.findByRole("button", { name: `View ${displayName} settings` }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ const installButton = screen.getByRole("button", { name: `Install ${displayName}` });+ expect(installButton).toHaveFocus();+ expect(installButton).toBeEnabled();++ fireEvent.click(installButton);++ await waitFor(() =>+ expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.feature.enable",+ { name, install_only: true },+ 150_000,+ ),+ );+ await screen.findByRole("switch", { name: `${displayName} channel` });+ fireEvent.click(screen.getByRole("button", { name: `View ${displayName} settings` }));+ if (name === "weixin") {+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.channel.connect.start", { channel: "weixin" }, 150_000,+ ));+ expect(await screen.findByRole("img", { name: "WeChat login QR code" })).toBeInTheDocument();+ expect(requestMutationMock.mock.calls.filter(([action]) => action === "settings.channel.connect.start")).toHaveLength(1);+ } else {+ expect(await screen.findByRole("button", { name: "Connect" })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Create assistant" })).not.toBeInTheDocument();+ expect(requestMutationMock.mock.calls.some(([action]) => action.startsWith("settings.channel.connect"))).toBe(false);+ }+ },+ );++ it("keeps WeChat login recovery visible across transient channel refreshes", async () => {+ const expiredFeature: NanobotFeatureInfo = {+ name: "weixin",+ display_name: "WeChat",+ webui: "webui/index.tsx",+ type: "channel",+ enabled: true,+ configured: true,+ installed: true,+ requires_dependencies: true,+ ready: false,+ running: false,+ runtime_status: "failed",+ runtime_error: "WeChat login expired. Scan again to reconnect.",+ status: "failed",+ install_supported: true,+ requires_restart: false,+ };+ let currentFeature = expiredFeature;+ let featureFetches = 0;+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/cli-apps") {+ return jsonResponse({ apps: [], installed_count: 0 });+ }+ if (url === "/api/settings/mcp-presets") {+ return jsonResponse({ presets: [], installed_count: 0 });+ }+ if (url === "/api/settings/nanobot-features") {+ featureFetches += 1;+ return jsonResponse({ features: [currentFeature], enabled_count: 0 });+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }),+ );+ requestMutationMock.mockImplementation(async (action: string) => {+ if (action === "settings.channel.connect.start") {+ return {+ status: "pending",+ session_id: "weixin-recovery",+ qr_url: "https://example.com/weixin-recovery",+ };+ }+ return settingsPayload();+ });++ renderSettingsView({ initialSection: "channels" });++ fireEvent.click(await screen.findByRole("button", { name: "View WeChat settings" }));+ expect(await screen.findByRole("img", { name: "WeChat login QR code" })).toBeInTheDocument();+ const fetchesBeforeRefresh = featureFetches;+ currentFeature = {+ ...expiredFeature,+ runtime_status: "stopped",+ runtime_error: undefined,+ status: "enabled",+ };+ window.dispatchEvent(new Event("focus"));++ await waitFor(() => expect(featureFetches).toBeGreaterThan(fetchesBeforeRefresh));+ expect(screen.getByRole("img", { name: "WeChat login QR code" })).toBeInTheDocument();+ expect(screen.getByText("WeChat login expired. Scan again to reconnect.")).toBeInTheDocument();+ expect(requestMutationMock.mock.calls.filter(([action]) => (+ action === "settings.channel.connect.start"+ ))).toHaveLength(1);+ });++ it("announces an install-only failure and logs action context", async () => {+ const feature = uninstalledConnectFeature("whatsapp");+ const installError = new Error("Package install failed");+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/cli-apps") {+ return jsonResponse({ apps: [], installed_count: 0 });+ }+ if (url === "/api/settings/mcp-presets") {+ return jsonResponse({ presets: [], installed_count: 0 });+ }+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({ features: [feature], enabled_count: 0 });+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }),+ );+ requestMutationMock.mockRejectedValueOnce(installError);++ renderSettingsView({ initialSection: "channels" });++ fireEvent.click(await screen.findByRole("button", { name: "Install WhatsApp" }));++ expect(await screen.findByRole("alert")).toHaveTextContent("Package install failed");+ expect(consoleError).toHaveBeenCalledWith(+ "nanobot feature action failed",+ expect.objectContaining({+ action: "enable",+ name: "whatsapp",+ installOnly: true,+ error: installError,+ }),+ );+ } finally {+ consoleError.mockRestore();+ }+ });it("shows an enabled channel with missing support as failed", async () => {const fetchMock = vi.fn(async (input: RequestInfo | URL) => {@@ -137,6 +642,7 @@ describe("Settings channels", () => {runtime_status: "failed",runtime_error: "Channel dependencies could not be installed. Check gateway logs.",installed: false,+ requires_dependencies: true,ready: false,status: "missing_dependency",install_supported: true,@@ -155,6 +661,7 @@ describe("Settings channels", () => {type: "channel",enabled: true,installed: true,+ requires_dependencies: true,ready: true,status: "enabled",install_supported: true,@@ -166,17 +673,14 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });- fireEvent.click(await screen.findByRole("button", { name: "View Matrix settings" }));- expect(screen.getAllByText("Failed").length).toBeGreaterThan(0);-- expect(screen.getByLabelText("Matrix channel")).toHaveAttribute("aria-checked", "false");- fireEvent.click(screen.getByRole("button", { name: "Install support" }));- fireEvent.click(screen.getByRole("button", { name: "Install and enable" }));+ expect((await screen.findAllByText("Failed")).length).toBeGreaterThan(0);+ expect(screen.queryByRole("switch", { name: "Matrix channel" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Install Matrix" }));await waitFor(() =>expect(requestMutationMock).toHaveBeenCalledWith("settings.feature.enable",- { name: "matrix" },+ { name: "matrix", install_only: true },150_000,),);@@ -266,12 +770,7 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Feishu settings" }));- fireEvent.click(await screen.findByRole(- "button",- { name: "nanobot" },- { timeout: 3_000 },- ));- fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ fireEvent.click(await screen.findByRole("button", { name: "Connect" }));await waitFor(() =>expect(requestMutationMock).toHaveBeenCalledWith(@@ -281,7 +780,7 @@ describe("Settings channels", () => {),);expect(await screen.findByText("Scan with Feishu")).toBeInTheDocument();- expect(screen.getByText("Waiting for authorization...")).toBeInTheDocument();+ expect(await screen.findByText("Waiting for authorization...")).toBeInTheDocument();});it("starts Feishu connect from the default assistant action", async () => {@@ -324,12 +823,7 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Feishu settings" }));- fireEvent.click(await screen.findByRole(- "button",- { name: "nanobot" },- { timeout: 3_000 },- ));- fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ fireEvent.click(await screen.findByRole("button", { name: "Connect" }));await waitFor(() =>expect(requestMutationMock).toHaveBeenCalledWith(@@ -413,7 +907,6 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click((await screen.findAllByRole("button", { name: /^View .+ settings$/ }))[0]);- fireEvent.click(await screen.findByRole("button", { name: "nanobot" }));fireEvent.click(await screen.findByRole("switch", { name: "nanobot assistant" }));await waitFor(() =>@@ -432,7 +925,7 @@ describe("Settings channels", () => {);});- it("shows Feishu assistant instances in the channel details", async () => {+ it("opens and saves each Feishu assistant's settings directly from Advanced", async () => {vi.stubGlobal("fetch",vi.fn(async (input: RequestInfo | URL) => {@@ -507,33 +1000,108 @@ describe("Settings channels", () => {expect(screen.getAllByText("Support Bot")).toHaveLength(1);expect(document.querySelector('img[src="https://example.com/support.png"]')).toBeTruthy();- expect(screen.getByRole("button", { name: /Support Bot/ })).toHaveAttribute(- "aria-expanded",- "false",- );- expect(screen.getByRole("button", { name: /Product Helper/ })).toHaveAttribute(- "aria-expanded",- "false",- );+ const support = within(screen.getByText("Support Bot").closest("article")!);+ const product = within(screen.getByText("Product Helper").closest("article")!);+ const supportAdvanced = support.getByRole("button", { name: "Advanced" });+ const productAdvanced = product.getByRole("button", { name: "Advanced" });+ expect(supportAdvanced).toBeVisible();+ expect(productAdvanced).toBeVisible();++ supportAdvanced.focus();+ await userEvent.setup().keyboard("[Enter]");+ expect(supportAdvanced).toHaveAttribute("aria-expanded", "true");+ expect(support.getByLabelText("App ID")).toBeVisible();+ expect(support.getByLabelText("App ID")).toHaveValue("cli_default");+ expect(support.getByRole("group", { name: "Topic isolation" })).toBeVisible();++ fireEvent.click(productAdvanced);+ expect(supportAdvanced).toHaveAttribute("aria-expanded", "false");+ expect(productAdvanced).toHaveAttribute("aria-expanded", "true");+ expect(product.getByLabelText("App ID")).toHaveValue("cli_product");+ fireEvent.change(product.getByLabelText("App ID"), { target: { value: "cli_updated" } });+ const featureRequests = () => vi.mocked(fetch).mock.calls+ .filter(([input]) => String(input) === "/api/settings/nanobot-features").length;+ const beforeRefresh = featureRequests();+ await act(async () => { fireEvent(window, new Event("focus")); });+ await waitFor(() => expect(featureRequests()).toBeGreaterThan(beforeRefresh));+ expect(product.getByLabelText("App ID")).toHaveValue("cli_updated");+ fireEvent.click(productAdvanced);+ expect(productAdvanced).toHaveAttribute("aria-expanded", "false");+ fireEvent.click(productAdvanced);+ expect(product.getByLabelText("App ID")).toHaveValue("cli_updated");+ fireEvent.click(product.getByRole("button", { name: "Save settings" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.channel.configure",+ expect.objectContaining({+ name: "feishu",+ instance_id: "product",+ enable: false,+ values: expect.objectContaining({ "channels.feishu.appId": "cli_updated" }),+ }),+ 150_000,+ ));+ expect(await screen.findByText("Settings saved.")).toBeVisible();- fireEvent.click(screen.getByRole("button", { name: /Support Bot/ }));- expect(screen.getByRole("button", { name: /Support Bot/ })).toHaveAttribute(- "aria-expanded",- "true",- );- expect(screen.getAllByText("cli_def...ault").length).toBeGreaterThan(0);- expect(screen.getByText("Advanced", { selector: "summary span" })).toBeInTheDocument();- expect(screen.getByText("Topic isolation")).toBeInTheDocument();+ productAdvanced.focus();+ await userEvent.setup().keyboard("[Space]");+ expect(productAdvanced).toHaveAttribute("aria-expanded", "false");+ fireEvent.click(supportAdvanced);+ expect(support.getByLabelText("App ID")).toHaveValue("cli_default");+ });- fireEvent.click(screen.getByRole("button", { name: /Product Helper/ }));- expect(screen.getByRole("button", { name: /Support Bot/ })).toHaveAttribute(- "aria-expanded",- "false",- );- expect(screen.getByRole("button", { name: /Product Helper/ })).toHaveAttribute(- "aria-expanded",- "true",- );+ it("opens WeChat advanced settings from the header and preserves autosave", async () => {+ const feature: NanobotFeatureInfo = {+ name: "weixin",+ display_name: "WeChat",+ webui: "webui/index.tsx",+ type: "channel",+ installed: true,+ enabled: false,+ configured: true,+ ready: true,+ status: "not_enabled",+ install_supported: true,+ requires_restart: false,+ setup: { fields: [+ channelSetupField("weixin", "sendProgress", "bool"),+ channelSetupField("weixin", "baseUrl"),+ channelSetupField("weixin", "token", "secret"),+ ] },+ config_values: {+ "channels.weixin.sendProgress": "true",+ "channels.weixin.baseUrl": "https://api.example.com",+ },+ };+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ if (String(input) === "/api/settings") return jsonResponse(settingsPayload());+ if (String(input) === "/api/settings/nanobot-features") {+ return jsonResponse({ features: [feature], enabled_count: 0 });+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }));+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View WeChat settings" }));++ const advanced = await screen.findByRole("button", { name: "Advanced" });+ advanced.focus();+ await userEvent.setup().keyboard("[Enter]");+ const apiUrl = screen.getByRole("textbox", { name: "API URL" });+ expect(apiUrl).toBeVisible();+ expect(screen.queryByLabelText("Token")).not.toBeInTheDocument();+ fireEvent.change(apiUrl, { target: { value: "https://updated.example.com" } });+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.channel.configure",+ expect.objectContaining({+ name: "weixin",+ enable: false,+ values: expect.objectContaining({ "channels.weixin.baseUrl": "https://updated.example.com" }),+ }),+ 150_000,+ ));++ fireEvent.click(advanced);+ fireEvent.click(advanced);+ expect(screen.getByRole("textbox", { name: "API URL" })).toHaveValue("https://updated.example.com");});it("renders external multi-instance channels from the shared contract", async () => {@@ -608,9 +1176,9 @@ describe("Settings channels", () => {"aria-checked","true",);- fireEvent.click(screen.getByRole("button", { name: "Product worker" }));- expect(screen.getByRole("radio", { name: "Eu" })).toHaveAttribute("aria-checked", "true");- expect(screen.getByText("Saved")).toBeInTheDocument();+ fireEvent.click(within(screen.getByText("Product worker").closest("article")!)+ .getByRole("button", { name: "Advanced" }));+ expect(screen.getByRole("radio", { name: "Eu" })).toBeChecked();});it("shows a single Feishu assistant without a duplicate assistant list", async () => {@@ -665,19 +1233,12 @@ describe("Settings channels", () => {fireEvent.click((await screen.findAllByRole("button", { name: /^View .+ settings$/ }))[0]);await screen.findByText("Support Bot");expect(screen.getAllByText("Support Bot")).toHaveLength(1);- expect(screen.getByText("1 assistant connected")).toBeInTheDocument();expect(screen.getByRole("switch", { name: "Support Bot assistant" })).toHaveAttribute("aria-checked","true",);- fireEvent.click(screen.getByRole("button", { name: "Support Bot" }));- expect(screen.getByText("cli_sup...port")).toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));- await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(- "settings.feature.enable",- { name: "feishu", instance_id: "default" },- 150_000,- ));+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ expect(screen.getByLabelText("App ID")).toBeInTheDocument();expect(document.querySelector('img[src="https://example.com/support.png"]')).toBeTruthy();});@@ -732,7 +1293,6 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click((await screen.findAllByRole("button", { name: /^View .+ settings$/ }))[0]);- await screen.findByText("No assistant connected");expect(screen.getAllByText("Failed").length).toBeGreaterThan(0);expect(screen.getByText(runtimeError)).toBeInTheDocument();expect(screen.getByRole("switch", { name: "test assistant" })).toHaveAttribute(@@ -741,7 +1301,7 @@ describe("Settings channels", () => {);});- it("shows group behavior fields as options", async () => {+ it("preserves advanced field edits when collapsed and reopened with the keyboard", async () => {vi.stubGlobal("fetch",vi.fn(async (input: RequestInfo | URL) => {@@ -774,21 +1334,28 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Discord settings" }));- fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));- const behavior = screen.getByRole("radiogroup", { name: "Group behavior" });- expect(within(behavior).getByRole("radio", { name: "Mention only" })).toHaveAttribute(- "aria-checked",- "true",- );+ const advanced = screen.getByRole("button", { name: "Advanced" });+ advanced.focus();+ await userEvent.setup().keyboard("[Enter]");+ expect(advanced).toHaveAttribute("aria-expanded", "true");+ const behavior = screen.getByRole("group", { name: "Group behavior" });+ expect(behavior).toBeVisible();+ expect(within(behavior).getByRole("radio", { name: "Mention only" })).toBeChecked();expect(within(behavior).getByRole("radio", { name: "All messages" })).toBeInTheDocument();fireEvent.click(within(behavior).getByRole("radio", { name: "All messages" }));- expect(within(behavior).getByRole("radio", { name: "All messages" })).toHaveAttribute(- "aria-checked",- "true",- );+ expect(within(behavior).getByRole("radio", { name: "All messages" })).toBeChecked();++ fireEvent.click(advanced);+ expect(advanced).toHaveAttribute("aria-expanded", "false");+ expect(behavior).not.toBeVisible();+ advanced.focus();+ await userEvent.setup().keyboard("[Space]");+ expect(advanced).toHaveAttribute("aria-expanded", "true");+ expect(behavior).toBeVisible();+ expect(within(behavior).getByRole("radio", { name: "All messages" })).toBeChecked();});it("uses a list-to-detail navigation stack on compact screens", async () => {@@ -841,6 +1408,7 @@ describe("Settings channels", () => {fireEvent.click(emailRow);expect(screen.getByRole("dialog")).toHaveFocus();+ expect(within(screen.getByRole("dialog")).getByRole("heading", { name: "Email" })).toBeVisible();fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));@@ -917,23 +1485,25 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Discord settings" }));- expect(screen.getByRole("link", { name: "Open Discord setup" })).toHaveAttribute(+ fireEvent.pointerDown(screen.getByRole("button", { name: "Help", exact: true }), { button: 0, ctrlKey: false });+ expect(await screen.findByRole("menuitem", { name: "Open Discord setup" })).toHaveAttribute("href","https://nanobot.wiki/docs/0.2.2/getting-started/chat-apps#discord",);+ fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });expect(screen.getByLabelText("Discord channel")).toBeEnabled();fireEvent.change(screen.getByPlaceholderText("Discord bot token"), {target: { value: "discord-token" },});- fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));fireEvent.change(screen.getByLabelText("Allowed channels"), {target: { value: "123, 456" },});- fireEvent.click(within(screen.getByRole("radiogroup", { name: "Group behavior" })).getByRole(+ fireEvent.click(within(screen.getByRole("group", { name: "Group behavior" })).getByRole("radio",{ name: "All messages" },));- fireEvent.click(screen.getByRole("button", { name: "Check and enable" }));+ fireEvent.click(screen.getByRole("switch", { name: "Enable channel", exact: true }));await waitFor(() =>expect(@@ -962,6 +1532,221 @@ describe("Settings channels", () => {);});+ it("requires Email consent to be granted before validating or enabling", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/cli-apps") return jsonResponse({ apps: [], installed_count: 0 });+ if (url === "/api/settings/mcp-presets") return jsonResponse({ presets: [], installed_count: 0 });+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({+ features: [{+ name: "email",+ display_name: "Email",+ webui: "webui/index.ts",+ type: "channel",+ enabled: false,+ configured: false,+ installed: true,+ ready: false,+ status: "not_enabled",+ install_supported: true,+ requires_restart: false,+ setup: channelSetupContract("email"),+ }],+ enabled_count: 0,+ });+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }),+ );+ requestMutationMock.mockImplementation(async (action: string) => {+ if (action === "settings.channel.validate") {+ return {+ name: "email",+ status: "ready",+ checks: [],+ missing_fields: [],+ can_enable: true,+ requires_restart: false,+ };+ }+ if (action === "settings.channel.configure") {+ return {+ name: "email",+ saved: true,+ saved_keys: [+ "channels.email.consentGranted",+ "channels.email.imapHost",+ "channels.email.imapUsername",+ "channels.email.imapPassword",+ "channels.email.smtpHost",+ "channels.email.smtpUsername",+ "channels.email.smtpPassword",+ ],+ };+ }+ return settingsPayload();+ });++ renderSettingsView({ initialSection: "channels" });++ fireEvent.click(await screen.findByRole("button", { name: "View Email settings" }));+ expect(screen.getByText("Receiving mail")).toBeInTheDocument();+ expect(screen.getByText("Sending mail")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Gmail" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ expect(screen.getByText("Quick fill")).toBeVisible();+ fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.custom.test" } });+ fireEvent.click(screen.getByRole("button", { name: "Gmail" }));+ expect(screen.getByLabelText("IMAP host")).toHaveValue("imap.custom.test");+ expect(screen.getByLabelText("SMTP host")).toHaveValue("smtp.gmail.com");+ fireEvent.click(screen.getByRole("button", { name: "Outlook" }));+ expect(screen.getByLabelText("SMTP host")).toHaveValue("smtp.gmail.com");+ fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.example.com" } });+ fireEvent.change(screen.getByLabelText("IMAP username"), { target: { value: "[email protected]" } });+ fireEvent.change(screen.getByLabelText("IMAP password"), { target: { value: "imap-secret" } });+ fireEvent.change(screen.getByLabelText("SMTP host"), { target: { value: "smtp.example.com" } });+ fireEvent.change(screen.getByLabelText("SMTP username"), { target: { value: "[email protected]" } });+ fireEvent.change(screen.getByLabelText("SMTP password"), { target: { value: "smtp-secret" } });++ const consentGroup = screen.getByRole("group", { name: "Allow nanobot to read and send email" });+ const notGranted = within(consentGroup).getByRole("radio", { name: "Not granted" });+ const granted = within(consentGroup).getByRole("radio", { name: "Granted" });+ expect(notGranted).toBeChecked();++ fireEvent.click(screen.getByRole("switch", { name: "Enable channel", exact: true }));++ await waitFor(() => expect(granted).toHaveFocus());+ expect(consentGroup).toHaveAttribute("aria-invalid", "true");+ expect(notGranted).toHaveAttribute("aria-invalid", "true");+ expect(granted).toHaveAttribute("aria-invalid", "true");+ expect(screen.getByText("Required to complete setup.")).toBeInTheDocument();+ expect(requestMutationMock.mock.calls.some(([action]) => (+ action === "settings.channel.validate" || action === "settings.channel.configure"+ ))).toBe(false);++ fireEvent.click(granted);++ expect(consentGroup).toHaveAttribute("aria-invalid", "false");+ expect(notGranted).toHaveAttribute("aria-invalid", "false");+ expect(granted).toHaveAttribute("aria-invalid", "false");+ expect(screen.queryByText("Required to complete setup.")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("switch", { name: "Enable channel", exact: true }));++ await waitFor(() =>+ expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.channel.validate",+ expect.objectContaining({+ name: "email",+ values: expect.objectContaining({+ "channels.email.consentGranted": "true",+ }),+ }),+ 20_000,+ ),+ );+ await waitFor(() =>+ expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.channel.configure",+ expect.objectContaining({ name: "email", enable: true }),+ 150_000,+ ),+ );+ });++ it("autosaves Email edits and waits for the save before closing", async () => {+ let resolveConfigure: ((value: Record<string, unknown>) => void) | undefined;+ const configureResult = new Promise<Record<string, unknown>>((resolve) => {+ resolveConfigure = resolve;+ });+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/cli-apps") return jsonResponse({ apps: [], installed_count: 0 });+ if (url === "/api/settings/mcp-presets") return jsonResponse({ presets: [], installed_count: 0 });+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({+ features: [{+ name: "email",+ display_name: "Email",+ webui: "webui/index.ts",+ type: "channel",+ enabled: true,+ configured: true,+ installed: true,+ ready: true,+ running: true,+ runtime_status: "running",+ status: "enabled",+ install_supported: true,+ requires_restart: false,+ config_values: {+ "channels.email.consentGranted": "true",+ "channels.email.imapHost": "imap.example.com",+ "channels.email.imapUsername": "[email protected]",+ "channels.email.smtpHost": "smtp.example.com",+ "channels.email.smtpUsername": "[email protected]",+ },+ configured_fields: [+ "channels.email.consentGranted",+ "channels.email.imapHost",+ "channels.email.imapUsername",+ "channels.email.imapPassword",+ "channels.email.smtpHost",+ "channels.email.smtpUsername",+ "channels.email.smtpPassword",+ ],+ setup: channelSetupContract("email"),+ }],+ enabled_count: 1,+ });+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }),+ );+ requestMutationMock.mockImplementation((action: string) => {+ if (action === "settings.channel.configure") return configureResult;+ return Promise.resolve(settingsPayload());+ });++ renderSettingsView({ initialSection: "channels" });++ fireEvent.click(await screen.findByRole("button", { name: "View Email settings" }));+ const dialog = screen.getByRole("dialog");+ expect(within(dialog).queryByRole("button", { name: "Save", exact: true })).not.toBeInTheDocument();+ fireEvent.click(within(dialog).getByRole("button", { name: "Advanced" }));+ expect(within(dialog).queryByRole("button", { name: "Gmail" })).not.toBeInTheDocument();+ fireEvent.change(screen.getByLabelText("IMAP host"), {+ target: { value: "imap.changed.example.com" },+ });++ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.channel.configure",+ expect.objectContaining({+ name: "email",+ values: expect.objectContaining({+ "channels.email.imapHost": "imap.changed.example.com",+ }),+ }),+ 150_000,+ ));+ expect(within(dialog).getByText("Saving")).toBeVisible();++ fireEvent.click(within(dialog).getByRole("button", { name: "Close", exact: true }));+ expect(screen.getByRole("dialog")).toBeInTheDocument();++ await act(async () => {+ resolveConfigure?.({ name: "email", saved: true, saved_keys: ["channels.email.imapHost"] });+ await configureResult;+ });+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ });+it("prefills saved channel config without exposing secrets", async () => {const fetchMock = vi.fn(async (input: RequestInfo | URL) => {const url = String(input);@@ -1026,23 +1811,21 @@ describe("Settings channels", () => {"false",);expect(screen.getByLabelText("Discord channel")).toBeEnabled();- expect(screen.getByText("Configured manually")).toBeInTheDocument();- expect(screen.getByText("Saved")).toBeInTheDocument();const savedSecret = screen.getByPlaceholderText("Saved secret");expect(savedSecret).toHaveValue("");expect(savedSecret).toHaveAttribute("autocomplete", "off");expect(savedSecret.closest("form")).not.toBeNull();expect(screen.queryByDisplayValue("discord-secret-token")).not.toBeInTheDocument();- fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));expect(screen.getByLabelText("Allowed channels")).toHaveValue("123, 456");- expect(within(screen.getByRole("radiogroup", { name: "Group behavior" })).getByRole(+ expect(within(screen.getByRole("group", { name: "Group behavior" })).getByRole("radio",{ name: "All messages" },- )).toHaveAttribute("aria-checked", "true");+ )).toBeChecked();fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));- fireEvent.click(screen.getByRole("switch", { name: "Discord channel" }));+ fireEvent.click(screen.getByLabelText("Discord channel"));await waitFor(() =>expect(requestMutationMock).toHaveBeenCalledWith("settings.feature.enable",@@ -1084,15 +1867,16 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Telegram settings" }));- expect(screen.getByRole("link", { name: "Open Telegram setup" })).toHaveAttribute(+ fireEvent.pointerDown(screen.getByRole("button", { name: "Help", exact: true }), { button: 0, ctrlKey: false });+ expect(await screen.findByRole("menuitem", { name: "Open Telegram setup" })).toHaveAttribute("href","https://nanobot.wiki/docs/0.2.2/getting-started/chat-apps#telegram",);+ fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });});- it("shows branded setup guide links for supported WebUI channels", async () => {+ it("opens channel setup guides from the help menu", async () => {const channels = [- ["websocket", "WebSocket", "Open WebSocket setup"],["telegram", "Telegram", "Open Telegram setup"],["feishu", "Feishu", "Open Feishu setup"],["slack", "Slack", "Open Slack setup"],@@ -1107,8 +1891,8 @@ describe("Settings channels", () => {["signal", "Signal", "Open Signal setup"],["msteams", "Microsoft Teams", "Open Teams setup"],["napcat", "NapCat", "Open NapCat setup"],+ ["mochat", "MoChat", "Open MoChat setup guide"],] as const;- const hiddenChannels = [["mochat", "MoChat"]] as const;vi.stubGlobal("fetch",@@ -1122,7 +1906,7 @@ describe("Settings channels", () => {features: channels.map(([name, displayName]) => ({name,display_name: displayName,- webui: ["feishu", "weixin"].includes(name) ? "webui/index.tsx" : "webui/index.ts",+ webui: ["feishu", "weixin", "whatsapp"].includes(name) ? "webui/index.tsx" : "webui/index.ts",type: "channel",enabled: name === "websocket",installed: true,@@ -1130,18 +1914,7 @@ describe("Settings channels", () => {status: name === "websocket" ? "enabled" : "not_enabled",install_supported: true,requires_restart: true,- })).concat(hiddenChannels.map(([name, displayName]) => ({- name,- display_name: displayName,- settings_visible: false,- type: "channel",- enabled: false,- installed: true,- ready: false,- status: "not_enabled",- install_supported: true,- requires_restart: true,- }))),+ })),enabled_count: 1,});}@@ -1153,16 +1926,10 @@ describe("Settings channels", () => {for (const [, displayName, guideLabel] of channels) {fireEvent.click(await screen.findByRole("button", { name: `View ${displayName} settings` }));- if (displayName === "Feishu") {- fireEvent.click(await screen.findByRole(- "button",- { name: "nanobot" },- { timeout: 3_000 },- ));- }- const guide = await screen.findByRole("link", { name: guideLabel });+ fireEvent.pointerDown(screen.getByRole("button", { name: "Help", exact: true }), { button: 0, ctrlKey: false });+ const guide = await screen.findByRole("menuitem", { name: guideLabel });expect(guide).toHaveAttribute("href", expect.stringMatching(/^https:\/\//));- expect(guide.querySelector("span[aria-hidden] img, span[aria-hidden] svg")).not.toBeNull();+ fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));}});@@ -1200,46 +1967,34 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Email settings" }));- const consent = screen.getByRole("radiogroup", { name: "Allow nanobot to read and send email" });- expect(within(consent).getByRole("radio", { name: "Not granted" })).toHaveAttribute(- "aria-checked",- "true",- );+ const consent = screen.getByRole("group", { name: "Allow nanobot to read and send email" });+ expect(within(consent).getByRole("radio", { name: "Not granted" })).toBeChecked();expect(within(consent).getByRole("radio", { name: "Granted" })).toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));fireEvent.click(screen.getByRole("button", { name: "View Feishu settings" }));- fireEvent.click(screen.getByRole("button", { name: "nanobot" }));- fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));- const region = screen.getByRole("radiogroup", { name: "Region" });- expect(within(region).getByRole("radio", { name: "Feishu" })).toHaveAttribute(- "aria-checked",- "true",- );+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ const region = screen.getByRole("group", { name: "Region" });+ expect(within(region).getByRole("radio", { name: "Feishu" })).toBeChecked();expect(within(region).getByRole("radio", { name: "Lark" })).toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));fireEvent.click(screen.getByRole("button", { name: "View Matrix settings" }));- fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));- const matrixBehavior = screen.getByRole("radiogroup", { name: "Group behavior" });- expect(within(matrixBehavior).getByRole("radio", { name: "All messages" })).toHaveAttribute(- "aria-checked",- "true",- );+ expect(screen.getByText("Choose one credential method")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ const matrixBehavior = screen.getByRole("group", { name: "Group behavior" });+ expect(within(matrixBehavior).getByRole("radio", { name: "All messages" })).toBeChecked();expect(within(matrixBehavior).getByRole("radio", { name: "Allowlist" })).toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));fireEvent.click(screen.getByRole("button", { name: "View QQ settings" }));- fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));- const format = screen.getByRole("radiogroup", { name: "Message format" });- expect(within(format).getByRole("radio", { name: "Plain text" })).toHaveAttribute(- "aria-checked",- "true",- );+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ const format = screen.getByRole("group", { name: "Message format" });+ expect(within(format).getByRole("radio", { name: "Plain text" })).toBeChecked();expect(within(format).getByRole("radio", { name: "Markdown" })).toBeInTheDocument();});- it("does not offer to disable the websocket channel", async () => {+ it("keeps the WebUI websocket channel enabled without opening a setup dialog", async () => {const fetchMock = vi.fn(async (input: RequestInfo | URL) => {const url = String(input);if (url === "/api/settings") return jsonResponse(settingsPayload());@@ -1269,11 +2024,10 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });- fireEvent.click(await screen.findByRole("button", { name: "View WebSocket settings" }));- expect(screen.getByRole("heading", { name: "WebSocket", exact: true })).toBeVisible();- expect(screen.getByText("Managed by WebUI")).toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));- const websocketSwitch = screen.getByRole("switch", { name: "WebSocket channel" });+ const websocketName = await screen.findByText("nanobot WebUI");+ fireEvent.click(websocketName);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ const websocketSwitch = screen.getByRole("switch", { name: "nanobot WebUI channel" });expect(websocketSwitch).toBeDisabled();expect(websocketSwitch).toHaveAttribute("aria-checked", "true");expect(requestMutationMock).not.toHaveBeenCalled();diff --git a/webui/src/tests/settings-system.test.tsx b/webui/src/tests/settings-system.test.tsxindex 6981c4ebc..726cf66f1 100644--- a/webui/src/tests/settings-system.test.tsx+++ b/webui/src/tests/settings-system.test.tsx@@ -162,7 +162,7 @@ describe("Settings system domains", () => {expect(screen.getByTestId("settings-section-transition")).not.toHaveClass("settings-feature-page");});- it("does not show the Settings kicker on the standalone Automations surface", async () => {+ it("opens a chat from the standalone automations empty state", async () => {const onBackToChat = vi.fn();vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {const url = String(input);@@ -389,7 +389,7 @@ describe("Settings system domains", () => {expect(screen.getByRole("button", { name: "MCP" })).toBeInTheDocument();});- it("shows nanobot optional features and enables one", async () => {+ it("installs optional channel support before enabling and disabling it", async () => {const fetchMock = vi.fn(async (input: RequestInfo | URL) => {const url = String(input);if (url === "/api/settings") return jsonResponse(settingsPayload());@@ -403,6 +403,7 @@ describe("Settings system domains", () => {webui: "webui/index.ts",type: "channel",enabled: false,+ configured: true,installed: false,ready: false,status: "missing_dependency",@@ -415,25 +416,31 @@ describe("Settings system domains", () => {return { ok: false, status: 404, json: async () => ({}) } as Response;});vi.stubGlobal("fetch", fetchMock);- requestMutationMock.mockImplementation(async (action: string) => {+ requestMutationMock.mockImplementation(async (action: string, values: Record<string, unknown>) => {if (action === "settings.feature.enable") {+ const enabled = values.install_only !== true;return {features: [{name: "matrix",display_name: "Matrix",webui: "webui/index.ts",type: "channel",- enabled: true,- running: true,- runtime_status: "running",+ enabled,+ running: enabled,+ runtime_status: enabled ? "running" : "stopped",+ configured: true,installed: true,ready: true,- status: "enabled",+ status: enabled ? "enabled" : "not_enabled",install_supported: true,requires_restart: true,}],- enabled_count: 1,- last_action: { ok: true, message: "Enabled channel 'matrix'", enabled: true },+ enabled_count: enabled ? 1 : 0,+ last_action: {+ ok: true,+ message: enabled ? "Enabled channel 'matrix'" : "Installed support for channel 'matrix'",+ enabled,+ },};}if (action === "settings.feature.disable") {@@ -463,13 +470,23 @@ describe("Settings system domains", () => {const matrixRow = await screen.findByRole("button", { name: "View Matrix settings" });expect(matrixRow).toHaveAttribute("aria-haspopup", "dialog");fireEvent.click(matrixRow);- expect(screen.getByRole("heading", { name: "Matrix", exact: true })).toBeVisible();- fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));- fireEvent.click(screen.getByRole("switch", { name: "Matrix channel" }));- expect(screen.getByRole("dialog", { name: "Install support for Matrix?" })).toBeInTheDocument();- expect(screen.getByText("nanobot will add what Matrix needs, then turn it on. Continue?")).toBeInTheDocument();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.queryByRole("switch", { name: "Matrix channel" })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Install Matrix" })).toHaveFocus();expect(requestMutationMock).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole("button", { name: "Install and enable" }));+ fireEvent.click(screen.getByRole("button", { name: "Install Matrix" }));++ await waitFor(() =>+ expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.feature.enable",+ { name: "matrix", install_only: true },+ 150_000,+ ),+ );+ const matrixToggle = await screen.findByRole("switch", { name: "Matrix channel" });+ expect(matrixToggle).toHaveAttribute("aria-checked", "false");+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ fireEvent.click(matrixToggle);await waitFor(() =>expect(requestMutationMock).toHaveBeenCalledWith(