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

+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}