fix(feishu): restore assistant creation and pairing recovery

Refs NAN-239
This commit is contained in:
Xubin Ren committed 2026-10-12 17:38:43 +08:00
1 parent cfb0f51e78
commit 2aa98677c6
36 files changed
+369 -47

No files matched your search

+4
View File
@@ -43,6 +43,8 @@ nanobot channels login feishu
Open the printed URL or scan the QR code. nanobot writes the generated `appId`, `appSecret`, `domain`, and `enabled` fields into the active config.
In WebUI, open **Channels → Feishu** and choose **Connect** for the first bot, or **Add another assistant** below your existing assistants. Each new assistant has its own settings and sender approvals; adding one does not replace an existing bot. Cancel the QR flow to stop an unfinished authorization.
If QR login is unavailable, create a Feishu/Lark app manually and merge this shape into `~/.nanobot/config.json`:
```json
@@ -98,6 +100,8 @@ After approval, DM the bot again or mention it in a group chat:
- If streaming cards fail, confirm `cardkit:card:write` or set `"streaming": false`.
- If no messages arrive, check Feishu/Lark event permissions, Long Connection mode, and `nanobot gateway --verbose`.
- If a first DM returns a pairing code, approve it before testing normal replies.
- If WebUI reports that the pairing code could not be sent, the DM reached nanobot but its reply failed. Check the gateway log for the Feishu error and request ID, check that the app has permission to send messages as a bot (`im:message:send_as_bot`), and publish any permission changes. Then send another private message to retry; nanobot reuses the unexpired code. Pairing replies use plain text and do not need streaming-card permissions.
- If neither a code nor a pairing request appears, check the running gateway, the app's receive-message subscription, and which assistant you messaged. A saved App ID and App Secret mean **Configured**, not that message delivery has been tested. Do not set `allowFrom` to `*` to work around pairing failures.
## Next: memory, automations, MCP tools
+14 -7
View File
@@ -15,6 +15,7 @@ from nanobot.pairing import (
format_pairing_reply,
generate_code,
is_approved,
record_delivery,
)
@@ -284,14 +285,20 @@ class BaseChannel(ABC):
"Pairing store unavailable; dropping DM from {}", sender_id
)
return
await self.send(
OutboundMessage(
channel=self.name,
chat_id=str(chat_id),
content=format_pairing_reply(code),
metadata={PAIRING_CODE_META_KEY: code},
record_delivery(code, "sending")
try:
await self.send(
OutboundMessage(
channel=self.name,
chat_id=str(chat_id),
content=format_pairing_reply(code),
metadata={PAIRING_CODE_META_KEY: code},
)
)
)
except Exception:
record_delivery(code, "failed")
raise
record_delivery(code, "sent")
self.logger.info(
"Sent pairing code {} to sender {} in chat {}",
code, sender_id, chat_id,
+5 -2
View File
@@ -43,7 +43,7 @@ from nanobot.channels.feishu.websocket import get_feishu_ws_runner
from nanobot.command.router import normalize_command_text
from nanobot.config.paths import get_media_dir
from nanobot.events import ContextCompactionEvent
from nanobot.pairing import clear_channel
from nanobot.pairing import PAIRING_CODE_META_KEY, clear_channel
from nanobot.utils.helpers import safe_filename
from nanobot.utils.logging_bridge import redirect_lib_logging
@@ -2446,6 +2446,8 @@ class FeishuChannel(BaseChannel):
):
return
if not self._client:
if msg.metadata.get(PAIRING_CODE_META_KEY):
raise RuntimeError("Feishu client is not ready to send the pairing reply")
self.logger.warning("client not initialized")
return
@@ -2589,7 +2591,8 @@ class FeishuChannel(BaseChannel):
)
if msg.content and msg.content.strip():
fmt = self._detect_msg_format(msg.content)
# Bootstrap authorization must not depend on rich-text/card permissions.
fmt = "text" if msg.metadata.get(PAIRING_CODE_META_KEY) else self._detect_msg_format(msg.content)
if fmt == "text":
# Short plain text – send as simple text message
@@ -98,6 +98,47 @@ def test_feishu_config_reply_to_message_defaults_false() -> None:
assert FeishuConfig().reply_to_message is False
@pytest.mark.asyncio
@pytest.mark.parametrize("channel_name", ["feishu", "feishu.assistant-test"])
async def test_pairing_failed_delivery_retries_plain_text_without_approving(channel_name):
from nanobot.pairing import store
channel = _make_feishu_channel()
channel.name = channel_name
channel.config.allow_from = []
with patch.object(channel, "_send_message_sync", return_value=None) as send:
await channel._on_message(_make_feishu_event(message_id="om_first"))
[pending] = store.list_pending()
assert pending["delivery_status"] == "failed"
assert pending["channel"] == channel_name
assert send.call_args.args[:3] == ("open_id", "ou_alice", "text")
send.return_value = "om_pairing_reply"
await channel._on_message(_make_feishu_event(message_id="om_retry"))
[retried] = store.list_pending()
assert retried["code"] == pending["code"]
assert retried["delivery_status"] == "sent"
assert pending["code"] in json.loads(send.call_args.args[3])["text"]
assert not channel.is_allowed("ou_alice")
assert channel.bus.inbound_size == 0
assert store.approve_code(pending["code"]) == (channel_name, "ou_alice")
assert channel.is_allowed("ou_alice")
other_channel = "feishu.other-assistant"
assert not store.is_approved(other_channel, "ou_alice")
@pytest.mark.asyncio
async def test_pairing_without_client_is_reported_as_failed():
from nanobot.pairing import store
channel = _make_feishu_channel()
channel.config.allow_from = []
channel._client = None
await channel._on_message(_make_feishu_event())
assert store.list_pending()[0]["delivery_status"] == "failed"
def test_feishu_config_reply_to_message_can_be_enabled() -> None:
config = FeishuConfig(reply_to_message=True)
assert config.reply_to_message is True
@@ -0,0 +1,18 @@
from nanobot.channels.contracts import ChannelValidationContext
from nanobot.channels.feishu.validation import validate
def test_saved_fields_do_not_claim_a_live_connection():
result = validate(
{"appId": "cli_not_verified", "appSecret": "not_verified"},
ChannelValidationContext(),
)
assert result["status"] == "configured"
assert result["can_enable"] is True
assert "not_verified" not in str(result["checks"])
def test_missing_secret_still_needs_setup():
result = validate({"appId": "cli_test"}, ChannelValidationContext())
assert result["status"] == "needs_setup"
assert result["can_enable"] is False
+2 -1
View File
@@ -22,7 +22,8 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict
"App ID is saved, but it does not look like a standard Feishu App ID.",
)
)
status = "connected" if not missing else "needs_setup"
# Field presence is not evidence of a working event or reply connection.
status = "configured" if not missing else "needs_setup"
identity = {
"name": display_name or "Feishu assistant",
"avatar_url": avatar_url or None,
@@ -46,6 +46,15 @@ export function FeishuAssistantsPanel({
onFeaturesUpdate={onFeaturesUpdate}
/>
),
footer: instances.some((instance) => instance.configured) ? (
<FeishuConnectFlow
key={instances.map((instance) => instance.id).join(",")}
token={token}
mode="create"
idleLabel={tx("custom.addAssistant", "Add another assistant")}
onFeaturesUpdate={onFeaturesUpdate}
/>
) : null,
}}
/>
);
@@ -73,6 +73,7 @@
}
},
"custom": {
"addAssistant": "Add another assistant",
"toggleAssistant": "{{name}} assistant",
"configured": "Connected",
"needsSetup": "Needs authorization",
@@ -73,6 +73,7 @@
}
},
"custom": {
"addAssistant": "Añadir otro asistente",
"toggleAssistant": "Activar el asistente {{name}}",
"configured": "Conectado",
"needsSetup": "Necesita autorización",
@@ -73,6 +73,7 @@
}
},
"custom": {
"addAssistant": "Ajouter un autre assistant",
"toggleAssistant": "Activer l’assistant {{name}}",
"configured": "Connecté",
"needsSetup": "Autorisation requise",
@@ -73,6 +73,7 @@
}
},
"custom": {
"addAssistant": "Tambahkan asisten lain",
"toggleAssistant": "Aktifkan asisten {{name}}",
"configured": "Terhubung",
"needsSetup": "Perlu otorisasi",
@@ -73,6 +73,7 @@
}
},
"custom": {
"addAssistant": "別のアシスタントを追加",
"toggleAssistant": "アシスタント {{name}} を有効にする",
"configured": "接続済み",
"needsSetup": "認可が必要",
@@ -73,6 +73,7 @@
}
},
"custom": {
"addAssistant": "다른 어시스턴트 추가",
"toggleAssistant": "{{name}} 어시스턴트 활성화",
"configured": "연결됨",
"needsSetup": "인증 필요",
@@ -73,6 +73,7 @@
}
},
"custom": {
"addAssistant": "Adicionar outro assistente",
"toggleAssistant": "Ativar assistente {{name}}",
"configured": "Conectado",
"needsSetup": "Precisa de autorização",
@@ -73,6 +73,7 @@
}
},
"custom": {
"addAssistant": "Thêm trợ lý khác",
"toggleAssistant": "Bật trợ lý {{name}}",
"configured": "Đã kết nối",
"needsSetup": "Cần cấp quyền",
@@ -74,6 +74,7 @@
}
},
"custom": {
"addAssistant": "添加新助手",
"toggleAssistant": "{{name}} 助手",
"configured": "已连接",
"needsSetup": "需要授权",
@@ -74,6 +74,7 @@
}
},
"custom": {
"addAssistant": "新增助理",
"toggleAssistant": "{{name}} 助手",
"configured": "已連接",
"needsSetup": "需要授權",
+2
View File
@@ -11,6 +11,7 @@ from nanobot.pairing.store import (
handle_pairing_command,
is_approved,
list_pending,
record_delivery,
revoke,
revoke_channel,
)
@@ -30,6 +31,7 @@ __all__ = [
"handle_pairing_command",
"is_approved",
"list_pending",
"record_delivery",
"revoke",
"revoke_channel",
"PAIRING_CODE_META_KEY",
+21 -1
View File
@@ -13,7 +13,7 @@ import string
import threading
import time
from pathlib import Path
from typing import Any, cast
from typing import Any, Literal, cast
from loguru import logger
@@ -141,6 +141,26 @@ def generate_code(
return code
def record_delivery(code: str, status: Literal["sending", "sent", "failed"]) -> None:
"""Record a reply outcome without changing approval or reviving a stale request.
Once a code has been sent, a failed concurrent retry must not hide it.
Delivery bookkeeping is best-effort: a store error must not mask the actual
transport result or reset any approvals.
"""
try:
with _LOCK:
data = _load()
_gc_pending(data)
info = data["pending"].get(code)
if info is None or info.get("delivery_status") == "sent":
return
info["delivery_status"] = status
_save(data)
except OSError:
logger.warning("Could not persist pairing reply delivery status")
def approve_code(code: str) -> tuple[str, str] | None:
"""Approve a pending pairing code.
+7
View File
@@ -395,6 +395,7 @@ def pairing_payload(
for item in list_pending():
expires_at = float(item.get("expires_at", 0) or 0)
created_at = float(item.get("created_at", 0) or 0)
delivery_status = item.get("delivery_status")
requests.append(
{
"code": str(item.get("code", "")),
@@ -405,6 +406,12 @@ def pairing_payload(
"expires_in_seconds": (
max(0, int(expires_at - current_time)) if expires_at else None
),
**(
{"delivery_status": delivery_status}
if isinstance(delivery_status, str)
and delivery_status in {"sending", "sent", "failed"}
else {}
),
}
)
payload: dict[str, Any] = {"requests": requests}
+49
View File
@@ -57,6 +57,55 @@ class TestGenerateCode:
assert store.approve_code(code2) is None
class TestDelivery:
def test_failed_reply_can_retry_without_replacing_code_or_approving(self):
code = store.generate_code("feishu", "alice")
assert "delivery_status" not in store.list_pending()[0]
store.record_delivery(code, "sending")
assert store.list_pending()[0]["delivery_status"] == "sending"
store.record_delivery(code, "failed")
assert store.list_pending()[0]["delivery_status"] == "failed"
assert store.generate_code("feishu", "alice") == code
store.record_delivery(code, "sent")
store.record_delivery(code, "failed")
assert store.list_pending()[0]["delivery_status"] == "sent"
assert not store.is_approved("feishu", "alice")
@pytest.mark.parametrize("action", [store.approve_code, store.deny_code])
def test_late_delivery_does_not_revive_removed_request(self, action):
code = store.generate_code("feishu", "alice")
action(code)
store.record_delivery(code, "sent")
assert store.list_pending() == []
def test_expired_reply_is_not_revived(self, monkeypatch):
monkeypatch.setattr(store.time, "time", lambda: 1000)
code = store.generate_code("feishu", "alice", ttl=10)
monkeypatch.setattr(store.time, "time", lambda: 1011)
store.record_delivery(code, "sent")
assert store.list_pending() == []
assert store.approve_code(code) is None
def test_old_records_remain_usable(self):
code = store.generate_code("feishu", "alice")
data = store._load()
data["pending"][code].pop("delivery_status", None)
store._save(data)
assert "delivery_status" not in store.list_pending()[0]
store.record_delivery(code, "sent")
assert store.approve_code(code) == ("feishu", "alice")
def test_bookkeeping_failure_preserves_store(self, monkeypatch):
code = store.generate_code("feishu", "alice")
before = store._store_path().read_bytes()
with monkeypatch.context() as m:
def fail(_data):
raise OSError("disk unavailable")
m.setattr(store, "_save", fail)
store.record_delivery(code, "sent")
assert store._store_path().read_bytes() == before
class TestFormatPairingReply:
def test_points_owner_to_webui_with_command_fallback(self) -> None:
reply = store.format_pairing_reply("ABCD-EFGH")
+16
View File
@@ -13,12 +13,28 @@ from nanobot.config.loader import load_config, save_config
from nanobot.config.schema import Config
from nanobot.webui.settings_system import (
coerce_channel_value,
pairing_payload,
save_channel_config_values,
system_settings_payload,
update_agent_system_settings,
)
@pytest.mark.parametrize("status", [None, "sending", "sent", "failed", "unknown", []])
def test_pairing_payload_preserves_optional_delivery_state(status):
item = {"code": "ABCD-EFGH", "channel": "feishu", "sender_id": "alice",
"created_at": 1000, "expires_at": 1600}
if status is not None:
item["delivery_status"] = status
[request] = pairing_payload(lambda: [item], now=1100)["requests"]
assert request["code"] == "ABCD-EFGH"
assert request["expires_in_seconds"] == 500
if isinstance(status, str) and status in {"sending", "sent", "failed"}:
assert request["delivery_status"] == status
else:
assert "delivery_status" not in request
def test_system_domain_owns_runtime_dto_and_agent_updates(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.webui.settings_system.COMMIT", "a" * 40)
config = Config()
+65 -36
View File
@@ -626,9 +626,14 @@ function PairingCodePopup({
() => requests.find((request) => request.code === normalizedCode) ?? null,
[normalizedCode, requests],
);
const firstRequest = requests[0] ?? null;
// Keep delivered and legacy requests usable even when another bot cannot reply.
const firstRequest = requests.find((request) => (
!request.delivery_status || request.delivery_status === "sent"
)) ?? requests[0] ?? null;
const displayRequest = matchedRequest ?? firstRequest;
const expires = formatPairingExpiry(firstRequest?.expires_in_seconds);
const deliveryBlocked = displayRequest?.delivery_status === "failed"
|| displayRequest?.delivery_status === "sending";
const expires = formatPairingExpiry(displayRequest?.expires_in_seconds);
const isCompleteCode = normalizedCode.length === 9;
const showNoMatch = isCompleteCode && !matchedRequest && !busyCode;
@@ -643,6 +648,17 @@ function PairingCodePopup({
if (!firstRequest) return null;
const codeInput = (
<PairingCodeSlots
value={value}
disabled={Boolean(busyCode)}
matched={Boolean(matchedRequest)}
invalid={showNoMatch}
ariaLabel={t("app.pairing.code", { defaultValue: "Pairing code" })}
onChange={(next) => setValue(formatPairingCodeInput(next))}
/>
);
return (
<div
role="dialog"
@@ -664,8 +680,15 @@ function PairingCodePopup({
<p className="text-[15px] font-semibold tracking-[-0.01em]">
{t("app.pairing.title", { defaultValue: "Pair a chat user" })}
</p>
<p className="mt-1 text-[13px] leading-5 text-muted-foreground">
{t("app.pairing.description", {
<p
className="mt-1 text-pretty text-[13px] leading-5 text-muted-foreground"
role={displayRequest.delivery_status === "failed" ? "alert" : undefined}
>
{displayRequest.delivery_status === "failed" ? t("app.pairing.deliveryFailed", {
defaultValue: "Couldn't send the pairing code. Check this bot's send-message permissions and gateway logs, then send it another private message to retry.",
}) : displayRequest.delivery_status === "sending" ? t("app.pairing.deliverySending", {
defaultValue: "Sending a pairing code to your chat. If it doesn't arrive, send the bot another private message to retry.",
}) : t("app.pairing.description", {
defaultValue: "Enter the pairing code shown in the chat.",
})}
</p>
@@ -673,46 +696,52 @@ function PairingCodePopup({
<button
type="button"
aria-label={t("common.close", { defaultValue: "Close" })}
onClick={() => onDismiss(firstRequest.code)}
onClick={() => onDismiss(displayRequest.code)}
className="rounded-full p-1 text-muted-foreground transition hover:bg-muted hover:text-foreground"
>
<X className="h-4 w-4" aria-hidden />
</button>
</div>
<label className="mt-4 block text-[12.5px] font-medium text-foreground">
{t("app.pairing.code", { defaultValue: "Pairing code" })}
</label>
<PairingCodeSlots
value={value}
disabled={Boolean(busyCode)}
matched={Boolean(matchedRequest)}
invalid={showNoMatch}
ariaLabel={t("app.pairing.code", { defaultValue: "Pairing code" })}
onChange={(next) => setValue(formatPairingCodeInput(next))}
/>
{deliveryBlocked ? (
<details className="mt-3 text-[12.5px] text-muted-foreground">
<summary className="cursor-pointer">
{t("app.pairing.haveCode", { defaultValue: "Already received a code?" })}
</summary>
{codeInput}
</details>
) : (
<>
<label className="mt-4 block text-[12.5px] font-medium text-foreground">
{t("app.pairing.code", { defaultValue: "Pairing code" })}
</label>
{codeInput}
</>
)}
<div className="mt-3 flex items-center justify-between gap-3 text-[12.5px] text-muted-foreground">
<span>
{matchedRequest
? t("app.pairing.matched", {
defaultValue: "Matched {{channel}}. Connecting...",
channel: channelLabel(matchedRequest.channel),
})
: t("app.pairing.expiresInline", {
defaultValue: "Code expires {{expires}}.",
expires,
})}
</span>
{total > 1 ? (
<span className="shrink-0">
{t("app.pairing.queueCount", {
defaultValue: "{{count}} pending",
count: total,
})}
{!deliveryBlocked || total > 1 ? (
<div className="mt-3 flex items-center justify-between gap-3 text-[12.5px] text-muted-foreground">
<span>
{matchedRequest
? t("app.pairing.matched", {
defaultValue: "Matched {{channel}}. Connecting...",
channel: channelLabel(matchedRequest.channel),
})
: deliveryBlocked ? null : t("app.pairing.expiresInline", {
defaultValue: "Code expires {{expires}}.",
expires,
})}
</span>
) : null}
</div>
{total > 1 ? (
<span className="shrink-0">
{t("app.pairing.queueCount", {
defaultValue: "{{count}} pending",
count: total,
})}
</span>
) : null}
</div>
) : null}
{showNoMatch ? (
<p className="mt-2 text-[12px] leading-5 text-destructive">
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot web UI — chat with your nanobot workspace."
},
"pairing": {
"haveCode": "Already received a code?",
"deliveryFailed": "Couldn't send the pairing code. Check this bot's send-message permissions and gateway logs, then send it another private message to retry.",
"deliverySending": "Sending a pairing code to your chat. If it doesn't arrive, send the bot another private message to retry.",
"title": "Pair account",
"description": "Enter the pairing code received in chat.",
"code": "Pairing code",
+3
View File
@@ -339,6 +339,9 @@
"description": "Interfaz web de nanobot: conversa con tu espacio de trabajo de nanobot."
},
"pairing": {
"haveCode": "¿Ya recibiste un código?",
"deliveryFailed": "No se pudo enviar el código. Revisa los permisos de envío del bot y los registros de la pasarela. Después, envíale otro mensaje privado para reintentar.",
"deliverySending": "Enviando el código al chat. Si no llega, envía otro mensaje privado al bot para reintentar.",
"title": "Vincular cuenta",
"description": "Introduce el código de vinculación recibido en el chat.",
"code": "Código de vinculación",
+3
View File
@@ -339,6 +339,9 @@
"description": "Interface web nanobot — discutez avec votre espace de travail nanobot."
},
"pairing": {
"haveCode": "Vous avez déjà reçu un code ?",
"deliveryFailed": "Impossible d’envoyer le code. Vérifiez les autorisations d’envoi du bot et les journaux de la passerelle, puis envoyez-lui un autre message privé pour réessayer.",
"deliverySending": "Envoi du code dans votre conversation. Si vous ne le recevez pas, envoyez un autre message privé au bot pour réessayer.",
"title": "Associer un compte",
"description": "Saisissez le code d’association reçu dans la discussion.",
"code": "Code d’association",
+3
View File
@@ -339,6 +339,9 @@
"description": "UI web nanobot — ngobrol dengan ruang kerja nanobot Anda."
},
"pairing": {
"haveCode": "Sudah menerima kode?",
"deliveryFailed": "Kode tidak dapat dikirim. Periksa izin pengiriman pesan bot dan log gateway, lalu kirim pesan pribadi lagi untuk mencoba ulang.",
"deliverySending": "Mengirim kode ke obrolan Anda. Jika belum diterima, kirim pesan pribadi lagi ke bot untuk mencoba ulang.",
"title": "Pasangkan akun",
"description": "Masukkan kode pemasangan yang diterima di chat.",
"code": "Kode pairing",
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot Web UI — nanobot ワークスペースと会話します。"
},
"pairing": {
"haveCode": "コードを受け取りましたか?",
"deliveryFailed": "ペアリングコードを送信できませんでした。ボットのメッセージ送信権限とゲートウェイのログを確認し、もう一度ボットにダイレクトメッセージを送ってください。",
"deliverySending": "チャットにペアリングコードを送信しています。届かない場合は、もう一度ボットにダイレクトメッセージを送ってください。",
"title": "アカウント連携",
"description": "チャットで受け取った連携コードを入力します。",
"code": "ペアリングコード",
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot 웹 UI — nanobot 작업공간과 대화하세요."
},
"pairing": {
"haveCode": "이미 코드를 받으셨나요?",
"deliveryFailed": "페어링 코드를 보내지 못했습니다. 봇의 메시지 전송 권한과 게이트웨이 로그를 확인한 후, 봇에게 개인 메시지를 다시 보내세요.",
"deliverySending": "채팅으로 페어링 코드를 보내고 있습니다. 코드가 도착하지 않으면 봇에게 개인 메시지를 다시 보내세요.",
"title": "계정 연결",
"description": "채팅에서 받은 연결 코드를 입력하세요.",
"code": "연결 코드",
+3
View File
@@ -339,6 +339,9 @@
"description": "Interface web do nanobot — converse com o seu espaço de trabalho do nanobot."
},
"pairing": {
"haveCode": "Já recebeu um código?",
"deliveryFailed": "Não foi possível enviar o código. Verifique as permissões de envio do bot e os logs do gateway. Depois, envie outra mensagem privada para tentar novamente.",
"deliverySending": "Enviando o código ao chat. Se ele não chegar, envie outra mensagem privada ao bot para tentar novamente.",
"title": "Parear conta",
"description": "Digite o código de pareamento recebido na conversa.",
"code": "Código de vinculação",
+3
View File
@@ -339,6 +339,9 @@
"description": "Giao diện web nanobot — trò chuyện với không gian làm việc nanobot của bạn."
},
"pairing": {
"haveCode": "Bạn đã nhận được mã?",
"deliveryFailed": "Không thể gửi mã ghép nối. Hãy kiểm tra quyền gửi tin nhắn của bot và nhật ký gateway, rồi gửi thêm một tin nhắn riêng để thử lại.",
"deliverySending": "Đang gửi mã ghép nối đến cuộc trò chuyện. Nếu chưa nhận được, hãy gửi thêm một tin nhắn riêng cho bot để thử lại.",
"title": "Ghép tài khoản",
"description": "Nhập mã ghép nhận được trong cuộc trò chuyện.",
"code": "Mã liên kết",
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot Web UI —— 与你的 nanobot 工作区对话。"
},
"pairing": {
"haveCode": "已收到配对码?",
"deliveryFailed": "配对码发送失败。请检查此机器人的消息发送权限和网关日志,再给它发一条私聊消息重试。",
"deliverySending": "正在向聊天发送配对码。如果没有收到,请再给机器人发一条私聊消息重试。",
"title": "账号配对",
"description": "输入聊天平台收到的配对码",
"code": "配对码",
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot Web UI —— 與你的 nanobot 工作區對話。"
},
"pairing": {
"haveCode": "已收到配對碼?",
"deliveryFailed": "配對碼傳送失敗。請檢查此機器人的訊息傳送權限和閘道日誌,再傳一則私訊給它以重試。",
"deliverySending": "正在向聊天傳送配對碼。如果沒有收到,請再傳一則私訊給機器人以重試。",
"title": "賬號配對",
"description": "輸入聊天平臺收到的配對碼",
"code": "配對碼",
+1
View File
@@ -1197,6 +1197,7 @@ export interface PairingRequestInfo {
created_at_ms?: number | null;
expires_at_ms?: number | null;
expires_in_seconds?: number | null;
delivery_status?: "sending" | "sent" | "failed";
}
export interface PairingPayload {
+26
View File
@@ -4063,6 +4063,32 @@ describe("App layout", () => {
unmount();
});
it.each(["sending", "failed"])("explains an undelivered pairing reply (%s) without empty code slots", async (delivery_status) => {
mockFetchRoutes({ "/api/settings/pairing": { requests: [{
code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status,
}] } });
render(<App />);
const popup = await screen.findByRole("dialog", { name: "Pair account" });
expect(within(popup).getByText("Already received a code?").closest("details")).not.toHaveAttribute("open");
expect(within(popup).getByText(/another private message to retry/)).toBeVisible();
if (delivery_status === "failed") expect(within(popup).getByRole("alert")).toBeVisible();
fireEvent.click(within(popup).getByText("Already received a code?"));
expect(within(popup).getByRole("textbox", { name: "Pairing code" })).toBeEnabled();
expect(requestMutationSpy).not.toHaveBeenCalledWith("settings.pairing.approve", expect.anything(), expect.anything());
});
it.each([undefined, "sent"])("keeps legacy/delivered pairing usable behind a failed request (%s)", async (delivery_status) => {
mockFetchRoutes({ "/api/settings/pairing": { requests: [
{ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "failed" },
{ code: "IJKL-MNOP", channel: "feishu.second", sender_id: "bob", delivery_status },
] } });
render(<App />);
const popup = await screen.findByRole("dialog", { name: "Pair account" });
expect(within(popup).getByRole("textbox", { name: "Pairing code" })).toBeEnabled();
expect(within(popup).queryByRole("alert")).not.toBeInTheDocument();
expect(within(popup).getByText("2 pending")).toBeVisible();
});
it("reuses an in-flight pairing poll when the page becomes visible again", async () => {
let resolvePairing!: (response: Response) => void;
const pendingPairing = new Promise<Response>((resolve) => {
@@ -4,6 +4,8 @@ import QRCode from "qrcode";
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
import { FeishuConnectFlow } from "../../../nanobot/channels/feishu/webui/FeishuConnectFlow";
import { FeishuAssistantsPanel } from "../../../nanobot/channels/feishu/webui/FeishuAssistantsPanel";
import type { NanobotFeatureInfo } from "@/lib/types";
const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));
@@ -34,6 +36,53 @@ beforeEach(() => {
afterEach(() => { cleanup(); vi.restoreAllMocks(); });
describe("channel QR connect parameters", () => {
it("adds an assistant without replacing existing ones, and supports cancellation and retry", async () => {
const feature: NanobotFeatureInfo = {
name: "feishu", display_name: "Feishu", type: "channel", webui: "webui/index.tsx",
enabled: true, configured: true, installed: true, ready: true, status: "enabled",
install_supported: true, requires_restart: false,
instances: [{
id: "default", name: "First assistant", enabled: true, configured: true,
runtime_status: "running", config_values: {}, configured_fields: [],
}],
};
const onFeaturesUpdate = vi.fn();
const props = { token: "tok", feature, showBrandLogos: false, onFeaturesUpdate };
const view = render(<FeishuAssistantsPanel {...props} />);
requestMutation.mockResolvedValueOnce({
session_id: "add-1", status: "pending", qr_url: "https://example.com/authorize",
});
fireEvent.click(screen.getByRole("button", { name: "Add another assistant" }));
expect(await screen.findByText("Scan with Feishu")).toBeVisible();
expect(requestMutation).toHaveBeenCalledWith("settings.channel.connect.start", {
channel: "feishu", domain: "feishu", instance_id: "default", mode: "create",
}, 150_000);
expect(screen.getByText("First assistant")).toBeVisible();
requestMutation.mockResolvedValueOnce({ session_id: "add-1", status: "cancelled" });
fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));
await screen.findByRole("button", { name: "Add another assistant" });
expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.cancel", {
channel: "feishu", session_id: "add-1",
}, 20_000);
expect(onFeaturesUpdate).not.toHaveBeenCalled();
requestMutation.mockRejectedValueOnce(new Error("Authorization unavailable"));
fireEvent.click(screen.getByRole("button", { name: "Add another assistant" }));
expect(await screen.findByText("Authorization unavailable")).toBeVisible();
const updated = { ...feature, instances: [...feature.instances!, {
...feature.instances![0], id: "assistant-new", name: "Second assistant",
}] };
const payload = { features: [updated], enabled_count: 1 };
requestMutation.mockResolvedValueOnce({ status: "succeeded", nanobot_features: payload });
fireEvent.click(screen.getByRole("button", { name: "Add another assistant" }));
await waitFor(() => expect(onFeaturesUpdate).toHaveBeenCalledWith(payload));
view.rerender(<FeishuAssistantsPanel {...props} feature={updated} />);
expect(screen.getByText("First assistant")).toBeVisible();
expect(screen.getByText("Second assistant")).toBeVisible();
expect(screen.getByRole("button", { name: "Add another assistant" })).toBeEnabled();
expect(screen.queryByText("Authorization unavailable")).not.toBeInTheDocument();
});
it.each([false, true])("keeps QR generation enabled by default (minimal=%s)", async (minimalPending) => {
const generateQr = vi.spyOn(QRCode, "toDataURL").mockResolvedValue("data:image/png;base64,preview");
requestMutation.mockResolvedValueOnce({