feat(qq): add QR scan connection for QQ bots

Scan the official QQ Bot binding page from Channels → QQ or
`nanobot channels login qq`; the returned AppID and encrypted secret are
decrypted locally, saved to config, and the channel is enabled by the
existing post-connect flow. The WebUI keeps manual entry of AppID and
Secret in Advanced, restores every QQ setup field there, and warns that
scanning again rotates the App Secret and invalidates the previous one.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
bingqilinweimaotaiandClaude Code authored and chengyongru committed 2026-10-20 21:55:17 +08:00
1 parent 9adbcc2cef
commit 6741acb391
20 files changed
+595 -8

No files matched your search

+9 -1
View File
@@ -97,7 +97,7 @@ If `nanobot channels status` does not show the channel as enabled, the config sn
| **Slack** | Bot token + App-Level token |
| **Matrix** | Homeserver URL + Access token |
| **Email** | IMAP/SMTP credentials |
| **QQ** | App ID + App Secret |
| **QQ** | QR code scan (`nanobot channels login qq`) or App ID + App Secret |
| **Napcat (QQ)** | Napcat Forward WebSocket URL + access token |
| **Wecom** | Bot ID + Bot Secret |
| **Microsoft Teams** | App ID + App Password + public HTTPS endpoint |
@@ -609,6 +609,14 @@ nanobot plugins enable qq
**3. Configure**
Run the QR login and scan with mobile QQ to save the AppID and AppSecret automatically. Scanning again replaces the App Secret and stops the previous secret from working:
```bash
nanobot channels login qq
```
To enter them yourself, copy **AppID** and **AppSecret** from **开发设置 (Developer Settings)** into `channels.qq`:
> - `allowFrom`: Add your openid (find it in nanobot logs when you message the bot). Use `["*"]` for public access.
> - `msgFormat`: Optional. Use `"plain"` (default) for maximum compatibility with legacy QQ clients, or `"markdown"` for richer formatting on newer clients.
> - For production: submit a review in the bot console and publish. See [QQ Bot Docs](https://bot.q.qq.com/wiki/) for the full publishing flow.
+1 -1
View File
@@ -24,7 +24,7 @@ For terminal or server setup, use the manual configuration section below. Reuse
## Enable the QQ channel
Create a QQ bot application, copy its AppID and AppSecret, and add your account to the sandbox members. In **Channels → QQ**, enter those credentials, enable the channel, and save. Follow any installation or restart prompt.
In **Channels → QQ**, scan the QR code with mobile QQ. nanobot saves the AppID and Secret automatically, enables the channel, and follows any installation or restart prompt. To use credentials you already copied, open **Advanced** and enter them manually. Scanning again replaces the current App Secret, and the previous secret stops working once the new scan completes.
<details>
<summary>Manual configuration</summary>
+223
View File
@@ -0,0 +1,223 @@
"""QQ-owned interactive QR connection flow.
Scans the official QQ Bot QR binding page (``q.qq.com``) and writes the
resulting AppID/secret straight to config, so the settings form never needs
them typed by hand. The portal encrypts the secret with a key generated here,
so credentials never travel in plaintext.
"""
from __future__ import annotations
import asyncio
import base64
import secrets
import time
from dataclasses import dataclass
from typing import Any, cast
from urllib.parse import quote
import httpx
from nanobot.channels.connect import ChannelConnectError, QueryParams, query_first
PORTAL_BASE = "https://q.qq.com"
CONNECT_URL = "https://q.qq.com/qqbot/openclaw/connect.html?task_id={task_id}&_wv=2"
POLL_INTERVAL_MS = 2000
SESSION_TTL_SECONDS = 600
_REQUEST_TIMEOUT = 10.0
# q.qq.com serves a JS anti-bot challenge without a browser-like request.
_HEADERS = {"Accept": "application/json", "User-Agent": "Mozilla/5.0 (QQBot/1.0)"}
@dataclass(slots=True)
class QQConnectSession:
id: str
task_id: str
key: str
created_wall: float
deadline: float
def _decrypt_secret(encrypted: str, key: str) -> str:
"""Decrypt ``bot_encrypt_secret``: base64(iv[12] | ciphertext | tag[16])."""
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
raw = base64.b64decode(encrypted)
return AESGCM(base64.b64decode(key)).decrypt(raw[:12], raw[12:], None).decode()
async def create_bind_task() -> tuple[str, str]:
"""Return ``(task_id, base64 AES key)`` for one QR binding."""
key = base64.b64encode(secrets.token_bytes(32)).decode()
data = await _portal_post("/lite/create_bind_task", {"key": key})
task_id = str(data.get("task_id") or "")
if not task_id:
raise RuntimeError("QQ did not return a QR task id")
return task_id, key
async def poll_bind_task(task_id: str) -> dict[str, Any]:
return await _portal_post("/lite/poll_bind_result", {"task_id": task_id})
async def _portal_post(path: str, body: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(timeout=_REQUEST_TIMEOUT) as client:
response = await client.post(f"{PORTAL_BASE}{path}", json=body, headers=_HEADERS)
response.raise_for_status()
payload = cast(dict[str, Any], response.json())
if payload.get("retcode") != 0:
raise RuntimeError(payload.get("msg") or f"QQ portal error for {path}")
data = payload.get("data")
return cast(dict[str, Any], data) if isinstance(data, dict) else {}
def save_credentials(app_id: str, secret: str) -> None:
"""Persist credentials before the post-connect enable step reads config."""
from nanobot.config.loader import get_config_path, load_config, save_config
config = load_config()
raw = getattr(config.channels, "qq", None)
values: dict[str, Any] = dict(cast(dict[str, Any], raw)) if isinstance(raw, dict) else {}
values.update(appId=app_id, secret=secret)
setattr(config.channels, "qq", values)
save_config(config, get_config_path())
class QQConnectStore:
"""In-memory QQ QR binding sessions for the WebUI and CLI login."""
def __init__(self) -> None:
self._sessions: dict[str, QQConnectSession] = {}
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
if action == "start":
return await self.start()
session_id = (query_first(query, "session_id") or "").strip()
if not session_id:
raise ChannelConnectError("missing QQ connect session")
if action == "poll":
return await self.poll(session_id)
if action == "cancel":
return await self.cancel(session_id)
raise ChannelConnectError(f"unsupported QQ connect action: {action}", status=404)
async def start(self) -> dict[str, Any]:
self._cleanup()
try:
task_id, key = await create_bind_task()
except Exception as exc:
raise ChannelConnectError(f"Unable to start QQ QR login: {exc}", status=502) from exc
session = self._new_session(task_id, key)
return {
"session_id": session.id,
"status": "pending",
"qr_url": CONNECT_URL.format(task_id=quote(task_id)),
"interval_ms": POLL_INTERVAL_MS,
"expires_at_ms": int((session.created_wall + SESSION_TTL_SECONDS) * 1000),
"message": "Scan with mobile QQ to connect.",
}
async def poll(self, session_id: str) -> dict[str, Any]:
self._cleanup()
session = self._sessions.get(session_id)
if session is None:
return _payload(session_id, "expired", "This QQ login has expired. Start again.")
try:
result = await poll_bind_task(session.task_id)
except Exception:
# A transient portal error is not proof the scan failed; keep waiting.
return _pending(session, "Waiting for QQ scan...")
status = result.get("status")
if status == 3:
self._sessions.pop(session_id, None)
return _payload(session_id, "expired", "This QQ QR code expired. Start again.")
if status != 2:
return _pending(session, "Waiting for QQ scan...")
app_id = str(result.get("bot_appid") or "")
encrypted = str(result.get("bot_encrypt_secret") or "")
self._sessions.pop(session_id, None)
try:
secret = _decrypt_secret(encrypted, session.key)
except Exception as exc:
return _payload(session_id, "failed", f"QQ secret could not be decrypted: {exc}")
if not app_id or not secret:
return _payload(session_id, "failed", "QQ confirmed the scan but returned no credentials.")
await asyncio.to_thread(save_credentials, app_id, secret)
return {
"session_id": session_id,
"status": "succeeded",
"message": "QQ is connected.",
}
async def cancel(self, session_id: str) -> dict[str, Any]:
self._sessions.pop(session_id, None)
return _payload(session_id, "cancelled", "QQ login cancelled.")
async def login(self) -> bool:
"""Blocking CLI login: print the QR and poll until scanned."""
try:
task_id, key = await create_bind_task()
except Exception as exc:
raise ChannelConnectError(f"Unable to start QQ QR login: {exc}", status=502) from exc
session = self._new_session(task_id, key)
try:
_print_qr(CONNECT_URL.format(task_id=quote(task_id)))
while True:
payload = await self.poll(session.id)
if payload["status"] != "pending":
return payload["status"] == "succeeded"
await asyncio.sleep(POLL_INTERVAL_MS / 1000)
finally:
self._sessions.pop(session.id, None)
def _new_session(self, task_id: str, key: str) -> QQConnectSession:
session = QQConnectSession(
id=secrets.token_urlsafe(18),
task_id=task_id,
key=key,
created_wall=time.time(),
deadline=time.monotonic() + SESSION_TTL_SECONDS,
)
self._sessions[session.id] = session
return session
def _cleanup(self) -> None:
now = time.monotonic()
for session_id in [sid for sid, s in self._sessions.items() if now >= s.deadline]:
self._sessions.pop(session_id, None)
def _print_qr(url: str) -> None:
import qrcode
qr = qrcode.QRCode(border=1)
qr.add_data(url)
qr.make(fit=True)
qr.print_ascii(invert=True)
def _payload(session_id: str, status: str, message: str) -> dict[str, Any]:
return {"session_id": session_id, "status": status, "message": message}
def _pending(session: QQConnectSession, message: str) -> dict[str, Any]:
return {
"session_id": session.id,
"status": "pending",
"qr_url": CONNECT_URL.format(task_id=quote(session.task_id)),
"interval_ms": POLL_INTERVAL_MS,
"expires_at_ms": int((session.created_wall + SESSION_TTL_SECONDS) * 1000),
"message": message,
}
__all__ = [
"QQConnectStore",
"create_bind_task",
"poll_bind_task",
"save_credentials",
]
+3 -1
View File
@@ -6,6 +6,7 @@ from nanobot.channels.plugin import ChannelPlugin
SETUP_SPEC = ChannelSetupSpec(
fields={
# Written by QR binding; manual entry stays available in the WebUI.
"appId": field(),
"secret": field("secret"),
"allowFrom": field("list"),
@@ -24,10 +25,11 @@ PLUGIN = ChannelPlugin(
name="qq",
display_name="QQ",
runtime=f"{__package__}.runtime:QQChannel",
connector=f"{__package__}.connect:QQConnectStore",
setup=SETUP_SPEC,
dependencies=(
"aiohttp>=3.9.0,<4.0.0",
"qq-botpy>=1.2.0,<2.0.0",
),
webui="webui/index.ts",
webui="webui/index.tsx",
)
+8
View File
@@ -365,6 +365,14 @@ class QQChannel(BaseChannel):
self.logger.info("media directory: {}", str(root))
return root
async def login(self, force: bool = False) -> bool:
"""Scan a QQ Bot QR code and save the AppID/secret it returns."""
from nanobot.channels.qq.connect import QQConnectStore
if not force and self.config.app_id and self.config.secret:
return True
return await QQConnectStore().login()
async def start(self) -> None:
"""Start the QQ bot with auto-reconnect loop."""
redirect_lib_logging("botpy", level="WARNING")
+117
View File
@@ -0,0 +1,117 @@
from __future__ import annotations
import asyncio
import base64
import json
from typing import Any
import pytest
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from nanobot.channels.qq import connect
from nanobot.channels.qq.connect import QQConnectStore, _decrypt_secret
from nanobot.config.loader import save_config
from nanobot.config.schema import Config
def _encrypt(secret: str, key: str) -> str:
iv = b"\x01" * 12
raw = iv + AESGCM(base64.b64decode(key)).encrypt(iv, secret.encode(), None)
return base64.b64encode(raw).decode()
@pytest.fixture(autouse=True)
def _isolated_config(tmp_path, monkeypatch: pytest.MonkeyPatch):
config_path = tmp_path / "config.json"
save_config(Config.model_validate({"channels": {"qq": {"allowFrom": ["42"]}}}), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
monkeypatch.setattr(connect, "POLL_INTERVAL_MS", 0)
return config_path
@pytest.mark.asyncio
async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pytest.MonkeyPatch, _isolated_config):
async def fake_create() -> tuple[str, str]:
return "task-1", base64.b64encode(b"k" * 32).decode()
async def fake_poll(task_id: str) -> dict[str, Any]:
assert task_id == "task-1"
key = base64.b64encode(b"k" * 32).decode()
return {"status": 2, "bot_appid": "1024", "bot_encrypt_secret": _encrypt("s3cret", key)}
monkeypatch.setattr(connect, "create_bind_task", fake_create)
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
store = QQConnectStore()
started = await store.start()
assert started["status"] == "pending"
assert started["qr_url"].endswith("task_id=task-1&_wv=2")
polled = await store.poll(started["session_id"])
assert polled["status"] == "succeeded"
assert await store.poll(started["session_id"]) == {
"session_id": started["session_id"],
"status": "expired",
"message": "This QQ login has expired. Start again.",
}
saved = json.loads(_isolated_config.read_text(encoding="utf-8"))
qq = saved["channels"]["qq"]
assert qq["appId"] == "1024"
assert qq["secret"] == "s3cret"
assert qq["allowFrom"] == ["42"]
@pytest.mark.asyncio
async def test_qq_connect_keeps_waiting_on_transient_portal_errors(monkeypatch: pytest.MonkeyPatch):
async def fake_create() -> tuple[str, str]:
return "task-2", base64.b64encode(b"k" * 32).decode()
async def fake_poll(_task_id: str) -> dict[str, Any]:
raise RuntimeError("portal hiccup")
monkeypatch.setattr(connect, "create_bind_task", fake_create)
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
store = QQConnectStore()
started = await store.start()
assert (await store.poll(started["session_id"]))["status"] == "pending"
@pytest.mark.asyncio
async def test_qq_login_scans_and_persists(monkeypatch: pytest.MonkeyPatch, _isolated_config):
key = base64.b64encode(b"k" * 32).decode()
async def fake_create() -> tuple[str, str]:
return "task-3", key
async def fake_poll(_task_id: str) -> dict[str, Any]:
return {"status": 2, "bot_appid": "2048", "bot_encrypt_secret": _encrypt("new", key)}
monkeypatch.setattr(connect, "create_bind_task", fake_create)
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
monkeypatch.setattr(connect, "_print_qr", lambda _url: None)
assert await asyncio.wait_for(QQConnectStore().login(), timeout=5) is True
saved = json.loads(_isolated_config.read_text(encoding="utf-8"))["channels"]["qq"]
assert (saved["appId"], saved["secret"]) == ("2048", "new")
@pytest.mark.asyncio
async def test_qq_login_skips_scan_when_credentials_configured(monkeypatch: pytest.MonkeyPatch):
from nanobot.bus.queue import MessageBus
from nanobot.channels.qq.runtime import QQChannel
async def fail_scan(*_args, **_kwargs):
raise AssertionError("scan should not start")
monkeypatch.setattr(connect, "create_bind_task", fail_scan)
channel = QQChannel({"appId": "1024", "secret": "s3cret"}, MessageBus())
assert await channel.login() is True
def test_decrypt_secret_rejects_wrong_key():
key = base64.b64encode(b"k" * 32).decode()
encrypted = _encrypt("s3cret", key)
with pytest.raises(Exception):
_decrypt_secret(encrypted, base64.b64encode(b"x" * 32).decode())
@@ -0,0 +1,52 @@
import { useTranslation } from "react-i18next";
import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";
import { channelTranslator } from "@/channel-plugins/i18n";
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
export function QQConnectFlow({
token,
feature,
idleLabel,
connectRequestId,
onFeaturesUpdate,
}: ChannelPluginConnectFlowProps) {
const { t } = useTranslation();
const tx = channelTranslator(t, "qq");
// Every scan rotates the App Secret, so warn before the user scans again.
const rescanWarning = feature.configured
? tx("custom.scanAgainWarning", "")
: "";
return (
<ChannelQrConnectFlow
token={token}
channelName="qq"
idleLabel={idleLabel}
connectRequestId={connectRequestId}
autoStart={!feature.configured}
forceOnRepeat
renderActions={(connectButton) => (
<div className="flex flex-wrap items-center justify-end gap-2">
{rescanWarning ? (
<p className="max-w-[22rem] text-[11.5px] leading-5 text-muted-foreground">
{rescanWarning}
</p>
) : null}
{connectButton}
</div>
)}
labels={{
qrAlt: tx("custom.qrAlt", "QQ login QR code"),
scanTitle: tx("custom.scanTitle", "Scan with mobile QQ"),
scanDescription: "",
waiting: tx("custom.waiting", "Waiting for QQ scan..."),
connected: tx("custom.connected", "QQ is connected."),
stopped: tx("custom.stopped", "QQ login stopped."),
connecting: tx("custom.connecting", "Connecting..."),
scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),
connect: t("settings.channels.connect", { defaultValue: "Connect" }),
}}
onFeaturesUpdate={onFeaturesUpdate}
/>
);
}
@@ -1,7 +1,15 @@
import { lazy } from "react";
import type { ChannelUiContribution } from "@/channel-plugins/types";
import { chatAppGuideUrl } from "@/channel-plugins/catalog";
const QQConnectFlow = lazy(() =>
import("./QQConnectFlow").then(({ QQConnectFlow: component }) => ({ default: component })),
);
export default {
ConnectFlow: QQConnectFlow,
canConnectBeforeConfigured: true,
presentation: {
logoUrl: "https://static-res.qq.com/static-res/imqq/qq-logo.png",
logoFallbackUrl: "https://im.qq.com/favicon.ico",
@@ -9,13 +17,19 @@ export default {
initials: "QQ",
color: "#12B7F5",
setup: {
mode: "credentials",
mode: "connect",
command: "nanobot channels login qq",
docsUrl: chatAppGuideUrl("qq"),
fields: [
manualFields: [
{ key: "channels.qq.appId", section: "credentials" },
{ key: "channels.qq.secret", section: "credentials" },
{ key: "channels.qq.allowFrom", section: "access" },
{ key: "channels.qq.msgFormat", section: "behavior" },
{ key: "channels.qq.ackMessage", section: "behavior" },
{ key: "channels.qq.showCompactionNotices", section: "behavior" },
{ key: "channels.qq.mediaDir", section: "behavior" },
{ key: "channels.qq.downloadChunkSize", section: "behavior" },
{ key: "channels.qq.downloadMaxBytes", section: "behavior" },
],
},
},
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"qrAlt": "QQ login QR code",
"scanTitle": "Scan with mobile QQ",
"waiting": "Waiting for QQ scan…",
"connected": "QQ is connected.",
"stopped": "QQ login stopped.",
"connecting": "Connecting...",
"scanAgainWarning": "Scanning again replaces the current App Secret. The previous App Secret stops working once the new scan completes."
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "Escanea con QQ móvil",
"waiting": "Esperando el escaneo de QQ…",
"connected": "QQ está conectado.",
"stopped": "El inicio de sesión de QQ se detuvo.",
"connecting": "Conectando…",
"qrAlt": "Código QR de inicio de sesión de QQ",
"scanAgainWarning": "Escanear de nuevo reemplaza el App Secret actual. El App Secret anterior deja de funcionar cuando termina el nuevo escaneo."
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "Scannez avec QQ mobile",
"waiting": "En attente du scan QQ…",
"connected": "QQ est connecté.",
"stopped": "La connexion QQ s'est arrêtée.",
"connecting": "Connexion…",
"qrAlt": "QR code de connexion QQ",
"scanAgainWarning": "Un nouveau scan remplace l'App Secret actuel. L'ancien App Secret cesse de fonctionner dès la fin du nouveau scan."
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "Pindai dengan QQ seluler",
"waiting": "Menunggu pindaian QQ…",
"connected": "QQ terhubung.",
"stopped": "Login QQ dihentikan.",
"connecting": "Menghubungkan…",
"qrAlt": "Kode QR login QQ",
"scanAgainWarning": "Memindai ulang menggantikan App Secret saat ini. App Secret lama tidak lagi berfungsi setelah pemindaian baru selesai."
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "モバイル QQ でスキャン",
"waiting": "QQ のスキャンを待っています…",
"connected": "QQ に接続しました。",
"stopped": "QQ ログインを停止しました。",
"connecting": "接続中…",
"qrAlt": "QQ ログイン QR コード",
"scanAgainWarning": "再スキャンすると現在の App Secret が置き換わります。新しいスキャンが完了すると、以前の App Secret は無効になります。"
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "모바일 QQ로 스캔",
"waiting": "QQ 스캔을 기다리는 중…",
"connected": "QQ가 연결되었습니다.",
"stopped": "QQ 로그인이 중지되었습니다.",
"connecting": "연결 중…",
"qrAlt": "QQ 로그인 QR 코드",
"scanAgainWarning": "다시 스캔하면 현재 App Secret이 교체됩니다. 새 스캔이 완료되면 이전 App Secret은 더 이상 작동하지 않습니다."
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "Escaneie com o QQ móvel",
"waiting": "Aguardando leitura do QQ…",
"connected": "QQ está conectado.",
"stopped": "O login do QQ foi interrompido.",
"connecting": "Conectando…",
"qrAlt": "QR code de login do QQ",
"scanAgainWarning": "Escanear novamente substitui o App Secret atual. O App Secret anterior deixa de funcionar quando a nova leitura termina."
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "Quét bằng QQ di động",
"waiting": "Đang chờ quét QQ…",
"connected": "QQ đã được kết nối.",
"stopped": "Đăng nhập QQ đã dừng.",
"connecting": "Đang kết nối…",
"qrAlt": "Mã QR đăng nhập QQ",
"scanAgainWarning": "Quét lại sẽ thay thế App Secret hiện tại. App Secret cũ sẽ ngừng hoạt động khi lần quét mới hoàn tất."
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "用手机 QQ 扫码登录",
"waiting": "等待 QQ 扫码…",
"connected": "QQ 已连接。",
"stopped": "QQ 登录已停止。",
"connecting": "连接中…",
"qrAlt": "QQ 登录二维码",
"scanAgainWarning": "重新扫码会替换当前的 App Secret,新扫码完成后旧 Secret 将失效。"
}
}
@@ -42,5 +42,14 @@
}
}
}
},
"custom": {
"scanTitle": "用手機 QQ 掃碼登入",
"waiting": "等待 QQ 掃碼…",
"connected": "QQ 已連線。",
"stopped": "QQ 登入已停止。",
"connecting": "連線中…",
"qrAlt": "QQ 登入 QR code",
"scanAgainWarning": "重新掃碼會取代目前的 App Secret,新掃碼完成後舊 Secret 將失效。"
}
}
+1 -1
View File
@@ -304,7 +304,7 @@ def test_special_setup_validation_is_owned_by_channel_package(name: str):
assert plugin.setup.validator.__module__ == f"nanobot.channels.{name}.validation"
@pytest.mark.parametrize("name", ["feishu", "linear", "weixin", "whatsapp"])
@pytest.mark.parametrize("name", ["feishu", "linear", "qq", "weixin", "whatsapp"])
def test_interactive_connector_is_owned_by_channel_package(name: str):
plugin = load_channel_package(name)
+75 -2
View File
@@ -144,6 +144,11 @@ function channelSetupContract(
choices: ["markdown", "plain"],
defaultValue: "plain",
}),
field("ackMessage", "string", { defaultValue: "⏳ Processing..." }),
field("showCompactionNotices", "bool", { choices: ["true", "false"] }),
field("mediaDir", "string"),
field("downloadChunkSize", "int", { defaultValue: "262144" }),
field("downloadMaxBytes", "int", { defaultValue: "209715200" }),
],
requirements: [
{ alternatives: [["channels.qq.appId"]] },
@@ -1967,7 +1972,7 @@ describe("Settings channels", () => {
features: channels.map(([name, displayName]) => ({
name,
display_name: displayName,
webui: ["feishu", "weixin", "whatsapp"].includes(name) ? "webui/index.tsx" : "webui/index.ts",
webui: ["feishu", "qq", "weixin", "whatsapp"].includes(name) ? "webui/index.tsx" : "webui/index.ts",
type: "channel",
enabled: false,
installed: true,
@@ -2008,7 +2013,7 @@ describe("Settings channels", () => {
features: ["email", "feishu", "matrix", "qq"].map((name) => ({
name,
display_name: name === "qq" ? "QQ" : name[0].toUpperCase() + name.slice(1),
webui: name === "feishu" ? "webui/index.tsx" : "webui/index.ts",
webui: name === "feishu" || name === "qq" ? "webui/index.tsx" : "webui/index.ts",
type: "channel",
enabled: true,
installed: true,
@@ -2055,6 +2060,74 @@ describe("Settings channels", () => {
expect(within(format).getByRole("radio", { name: "Markdown" })).toBeInTheDocument();
});
it("connects QQ by QR scan and fills AppID from saved credentials", async () => {
const qqFeature: NanobotFeatureInfo = {
name: "qq",
display_name: "QQ",
webui: "webui/index.tsx",
type: "channel",
enabled: false,
configured: false,
installed: true,
ready: false,
status: "not_enabled",
install_supported: true,
requires_restart: false,
setup: channelSetupContract("qq"),
};
let currentFeature = qqFeature;
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: [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: "qq-1", qr_url: "https://example.com/qq-login" };
}
if (action === "settings.channel.connect.poll") {
currentFeature = {
...qqFeature,
enabled: true,
configured: true,
config_values: { "channels.qq.appId": "1024" },
configured_fields: ["channels.qq.appId", "channels.qq.secret"],
};
return {
status: "succeeded",
session_id: "qq-1",
message: "QQ is connected.",
nanobot_features: { features: [currentFeature], enabled_count: 1 },
};
}
return settingsPayload();
});
renderSettingsView({ initialSection: "channels" });
fireEvent.click(await screen.findByRole("button", { name: "View QQ settings" }));
expect(await screen.findByRole("img", { name: "QQ login QR code" })).toBeInTheDocument();
expect(requestMutationMock).toHaveBeenCalledWith(
"settings.channel.connect.start", { channel: "qq" }, 150_000,
);
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.channel.connect.poll", { channel: "qq", session_id: "qq-1" }, 150_000,
));
expect(await screen.findByText("QQ is connected.")).toBeInTheDocument();
expect(screen.getByText(/previous App Secret stops working/)).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Advanced" }));
expect(screen.getByLabelText("App ID")).toHaveValue("1024");
expect(screen.getByLabelText("Acknowledgement message")).toHaveValue("⏳ Processing...");
});
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);