refactor: remove redundant comments and docstrings (#6527)
* refactor: remove redundant comments and docstrings * fix(signal): annotate async context manager as a generator
This commit is contained in:
1 parent
cb3ba45317
commit
a4d2430140
922 files changed
+406
-7738
No files matched your search
@@ -1,5 +1,3 @@
|
||||
"""Shared contracts for chat channels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Small constructors shared by declarative channel manifests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Resolve channel-owned setup contracts for settings consumers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Base channel interface for chat platforms."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Small contract shared by channel-owned interactive connection flows."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Stable contracts shared by channel runtimes and management surfaces."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""DingTalk channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""DingTalk management contract."""
|
||||
|
||||
from nanobot.channels._manifest import field, required_fields
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
# pyright: reportConstantRedefinition=false, reportMissingTypeStubs=false, reportPrivateUsage=false
|
||||
"""DingTalk/DingDing channel implementation using Stream Mode."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
@@ -32,7 +31,6 @@ _DINGTALK_SENDER_NAME_MAX_CHARS = 80
|
||||
|
||||
|
||||
def _escape_markdown_sender_name(value: str) -> str:
|
||||
"""Render an untrusted display name as one bounded Markdown-safe line."""
|
||||
normalized = " ".join(value.split())[:_DINGTALK_SENDER_NAME_MAX_CHARS]
|
||||
return "".join(
|
||||
f"\\{char}" if char in _DINGTALK_MARKDOWN_INLINE_SPECIALS else char
|
||||
@@ -76,11 +74,9 @@ class NanobotDingTalkHandler(_CallbackHandlerBase):
|
||||
async def process(self, message: Any) -> tuple[Any, str]:
|
||||
"""Process incoming stream message."""
|
||||
try:
|
||||
# Parse using SDK's ChatbotMessage for robust handling
|
||||
chatbot_msg: Any = ChatbotMessage.from_dict(message.data)
|
||||
message_data = cast(dict[str, Any], message.data)
|
||||
|
||||
# Extract text content; fall back to raw dict if SDK object is empty
|
||||
content = ""
|
||||
if chatbot_msg.text:
|
||||
content = cast(str, chatbot_msg.text.content).strip()
|
||||
@@ -90,7 +86,6 @@ class NanobotDingTalkHandler(_CallbackHandlerBase):
|
||||
text_data = cast(dict[str, Any], message_data.get("text", {}))
|
||||
content = cast(str, text_data.get("content", "")).strip()
|
||||
|
||||
# Handle file/image messages
|
||||
file_paths: list[str] = []
|
||||
if chatbot_msg.message_type == "picture" and chatbot_msg.image_content:
|
||||
download_code = chatbot_msg.image_content.download_code
|
||||
@@ -194,7 +189,6 @@ class NanobotDingTalkHandler(_CallbackHandlerBase):
|
||||
"Received DingTalk message from {} ({})", sender_name, sender_id
|
||||
)
|
||||
|
||||
# Forward to Nanobot via _on_message (non-blocking).
|
||||
# Store reference to prevent GC before task completes.
|
||||
task = asyncio.create_task(
|
||||
self.channel._on_message(
|
||||
@@ -260,7 +254,6 @@ class DingTalkChannel(BaseChannel):
|
||||
self._http: httpx.AsyncClient | None = None
|
||||
self._start_task: asyncio.Task[Any] | None = None
|
||||
|
||||
# Access Token management for sending messages
|
||||
self._access_token: str | None = None
|
||||
self._token_expiry: float = 0
|
||||
|
||||
@@ -306,13 +299,11 @@ class DingTalkChannel(BaseChannel):
|
||||
credential = Credential(self.config.client_id, self.config.client_secret)
|
||||
self._client = DingTalkStreamClient(credential)
|
||||
|
||||
# Register standard handler
|
||||
handler = NanobotDingTalkHandler(self)
|
||||
self._client.register_callback_handler(ChatbotMessage.TOPIC, handler)
|
||||
|
||||
self.logger.info("bot started with Stream Mode")
|
||||
|
||||
# Reconnect loop: restart stream if SDK exits or crashes
|
||||
while self._running:
|
||||
try:
|
||||
await self._client.start()
|
||||
@@ -344,11 +335,9 @@ class DingTalkChannel(BaseChannel):
|
||||
await start_task
|
||||
self._client = None
|
||||
|
||||
# Close the shared HTTP client
|
||||
if self._http:
|
||||
await self._http.aclose()
|
||||
self._http = None
|
||||
# Cancel outstanding background tasks
|
||||
background_tasks = tuple(self._background_tasks)
|
||||
for task in background_tasks:
|
||||
task.cancel()
|
||||
@@ -374,7 +363,6 @@ class DingTalkChannel(BaseChannel):
|
||||
self.logger.opt(exception=True).debug("DingTalk stream client close failed")
|
||||
|
||||
async def _get_access_token(self) -> str | None:
|
||||
"""Get or refresh Access Token."""
|
||||
if self._access_token and time.time() < self._token_expiry:
|
||||
return self._access_token
|
||||
|
||||
@@ -483,7 +471,6 @@ class DingTalkChannel(BaseChannel):
|
||||
self,
|
||||
media_ref: str,
|
||||
) -> tuple[bytes | None, str | None]:
|
||||
"""Fetch a remote media URL with SSRF, redirect, and size checks."""
|
||||
if not self._http:
|
||||
return None, None
|
||||
|
||||
@@ -626,16 +613,14 @@ class DingTalkChannel(BaseChannel):
|
||||
|
||||
headers = {"x-acs-dingtalk-access-token": token}
|
||||
if chat_id.startswith("group:"):
|
||||
# Group chat
|
||||
url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
|
||||
payload = {
|
||||
"robotCode": self.config.client_id,
|
||||
"openConversationId": chat_id[6:], # Remove "group:" prefix,
|
||||
"openConversationId": chat_id[6:],
|
||||
"msgKey": msg_key,
|
||||
"msgParam": json.dumps(msg_param, ensure_ascii=False),
|
||||
}
|
||||
else:
|
||||
# Private chat
|
||||
url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
|
||||
payload = {
|
||||
"robotCode": self.config.client_id,
|
||||
@@ -783,11 +768,6 @@ class DingTalkChannel(BaseChannel):
|
||||
conversation_type: str | None = None,
|
||||
conversation_id: str | None = None,
|
||||
) -> None:
|
||||
"""Handle incoming message (called by NanobotDingTalkHandler).
|
||||
|
||||
Delegates to BaseChannel._handle_message() which enforces allow_from
|
||||
permission checks before publishing to the bus.
|
||||
"""
|
||||
try:
|
||||
if not sender_id:
|
||||
self.logger.warning("dropping DingTalk message without a sender ID")
|
||||
@@ -833,7 +813,6 @@ class DingTalkChannel(BaseChannel):
|
||||
filename: str,
|
||||
sender_id: str,
|
||||
) -> str | None:
|
||||
"""Download a DingTalk file to the media directory, return local path."""
|
||||
from nanobot.config.paths import get_media_dir
|
||||
|
||||
try:
|
||||
@@ -842,7 +821,6 @@ class DingTalkChannel(BaseChannel):
|
||||
self.logger.error("file download: no token or http client")
|
||||
return None
|
||||
|
||||
# Step 1: Exchange downloadCode for a temporary download URL
|
||||
api_url = "https://api.dingtalk.com/v1.0/robot/messageFiles/download"
|
||||
headers = {"x-acs-dingtalk-access-token": token, "Content-Type": "application/json"}
|
||||
payload = {"downloadCode": download_code, "robotCode": self.config.client_id}
|
||||
@@ -857,13 +835,11 @@ class DingTalkChannel(BaseChannel):
|
||||
self.logger.error("download URL not found in response: {}", result)
|
||||
return None
|
||||
|
||||
# Step 2: Download the file content
|
||||
file_resp = await self._http.get(download_url, follow_redirects=True)
|
||||
if file_resp.status_code != 200:
|
||||
self.logger.error("file download failed: status={}", file_resp.status_code)
|
||||
return None
|
||||
|
||||
# Save to media directory (accessible under workspace)
|
||||
download_dir = get_media_dir("dingtalk") / sender_id
|
||||
download_dir.mkdir(parents=True, exist_ok=True)
|
||||
file_path = download_dir / filename
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the DingTalk channel package."""
|
||||
@@ -9,7 +9,6 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
# Check optional dingtalk dependencies before running tests
|
||||
try:
|
||||
import nanobot.channels.dingtalk.runtime as dingtalk_module
|
||||
|
||||
@@ -116,7 +115,6 @@ async def test_group_message_keeps_sender_id_and_routes_chat_id() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_user_isolation_false_uses_shared_session() -> None:
|
||||
"""By default group messages share the same session_key."""
|
||||
config = DingTalkConfig(
|
||||
client_id="app", client_secret="secret", allow_from=["*"], group_user_isolation=False
|
||||
)
|
||||
@@ -140,7 +138,6 @@ async def test_group_user_isolation_false_uses_shared_session() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_user_isolation_true_separates_sessions() -> None:
|
||||
"""When group_user_isolation is True, each user gets their own session_key."""
|
||||
config = DingTalkConfig(
|
||||
client_id="app", client_secret="secret", allow_from=["*"], group_user_isolation=True
|
||||
)
|
||||
@@ -178,7 +175,7 @@ async def test_dm_rejected_when_private_chat_disabled(monkeypatch) -> None:
|
||||
config = DingTalkConfig(
|
||||
client_id="app",
|
||||
client_secret="secret",
|
||||
allow_from=["*"], # even allowlisted senders are blocked in DMs
|
||||
allow_from=["*"],
|
||||
disable_private_chat=True,
|
||||
)
|
||||
bus = MessageBus()
|
||||
@@ -197,10 +194,8 @@ async def test_dm_rejected_when_private_chat_disabled(monkeypatch) -> None:
|
||||
conversation_type="1",
|
||||
)
|
||||
|
||||
# No inbound message was published -> no session created
|
||||
assert bus.inbound.empty()
|
||||
|
||||
# A notice was sent back to the DM user via the private-chat API
|
||||
assert len(channel._http.calls) == 1
|
||||
call = channel._http.calls[0]
|
||||
assert call["url"] == "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
|
||||
@@ -211,7 +206,6 @@ async def test_dm_rejected_when_private_chat_disabled(monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dm_allowed_when_private_chat_not_disabled() -> None:
|
||||
"""By default (disable_private_chat=False), a 1:1 DM still reaches the bus."""
|
||||
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
|
||||
bus = MessageBus()
|
||||
channel = DingTalkChannel(config, bus)
|
||||
@@ -230,7 +224,6 @@ async def test_dm_allowed_when_private_chat_not_disabled() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_message_allowed_when_private_chat_disabled() -> None:
|
||||
"""Disabling private chat must not affect group messages."""
|
||||
config = DingTalkConfig(
|
||||
client_id="app", client_secret="secret", allow_from=["*"], disable_private_chat=True
|
||||
)
|
||||
@@ -271,7 +264,6 @@ async def test_group_send_uses_group_messages_api() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_send_prepends_sender_mention(monkeypatch) -> None:
|
||||
"""Group replies are prefixed with a markdown header naming the sender."""
|
||||
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
|
||||
channel = DingTalkChannel(config, MessageBus())
|
||||
channel._http = _FakeHttp()
|
||||
@@ -296,7 +288,6 @@ async def test_group_send_prepends_sender_mention(monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_send_escapes_untrusted_sender_name(monkeypatch) -> None:
|
||||
"""A sender nickname cannot inject extra Markdown blocks into the reply."""
|
||||
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
|
||||
channel = DingTalkChannel(config, MessageBus())
|
||||
channel._http = _FakeHttp()
|
||||
@@ -321,7 +312,6 @@ async def test_group_send_escapes_untrusted_sender_name(monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_private_send_does_not_prepend_mention(monkeypatch) -> None:
|
||||
"""Private replies are sent verbatim, without the sender header."""
|
||||
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
|
||||
channel = DingTalkChannel(config, MessageBus())
|
||||
channel._http = _FakeHttp()
|
||||
@@ -334,7 +324,7 @@ async def test_private_send_does_not_prepend_mention(monkeypatch) -> None:
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="dingtalk",
|
||||
chat_id="user1", # private chat: no "group:" prefix
|
||||
chat_id="user1",
|
||||
content="hello",
|
||||
metadata={"sender_name": "Alice"},
|
||||
)
|
||||
@@ -346,7 +336,6 @@ async def test_private_send_does_not_prepend_mention(monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_without_sender_id_is_dropped() -> None:
|
||||
"""Malformed inbound events must not publish or attempt an invalid reply."""
|
||||
config = DingTalkConfig(
|
||||
client_id="app",
|
||||
client_secret="secret",
|
||||
@@ -468,7 +457,6 @@ async def test_handler_retrieves_background_message_failure(monkeypatch) -> None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handler_processes_file_message(monkeypatch) -> None:
|
||||
"""Test that file messages are handled and forwarded with downloaded path."""
|
||||
bus = MessageBus()
|
||||
channel = DingTalkChannel(
|
||||
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
|
||||
@@ -705,7 +693,6 @@ async def test_start_configures_http_timeout(monkeypatch) -> None:
|
||||
pass
|
||||
|
||||
async def start(self):
|
||||
# Exit the reconnect loop after one iteration.
|
||||
channel._running = False
|
||||
|
||||
monkeypatch.setattr(dingtalk_module, "DINGTALK_AVAILABLE", True)
|
||||
@@ -817,19 +804,16 @@ async def test_stop_waits_for_background_message_tasks() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_dingtalk_file(tmp_path, monkeypatch) -> None:
|
||||
"""Test the two-step file download flow (get URL then download content)."""
|
||||
channel = DingTalkChannel(
|
||||
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
|
||||
MessageBus(),
|
||||
)
|
||||
|
||||
# Mock access token
|
||||
async def fake_get_token():
|
||||
return "test-token"
|
||||
|
||||
monkeypatch.setattr(channel, "_get_access_token", fake_get_token)
|
||||
|
||||
# Mock HTTP: first POST returns downloadUrl, then GET returns file bytes
|
||||
file_content = b"fake file content"
|
||||
channel._http = _FakeHttp(responses=[
|
||||
_FakeResponse(200, {"downloadUrl": "https://example.com/tmpfile"}),
|
||||
@@ -837,7 +821,6 @@ async def test_download_dingtalk_file(tmp_path, monkeypatch) -> None:
|
||||
])
|
||||
channel._http._responses[1].content = file_content
|
||||
|
||||
# Redirect media dir to tmp_path
|
||||
monkeypatch.setattr(
|
||||
"nanobot.config.paths.get_media_dir",
|
||||
lambda channel_name=None: tmp_path / channel_name if channel_name else tmp_path,
|
||||
@@ -849,7 +832,6 @@ async def test_download_dingtalk_file(tmp_path, monkeypatch) -> None:
|
||||
assert result.endswith("test.xlsx")
|
||||
assert (tmp_path / "dingtalk" / "user1" / "test.xlsx").read_bytes() == file_content
|
||||
|
||||
# Verify API calls
|
||||
assert channel._http.calls[0]["method"] == "POST"
|
||||
assert "messageFiles/download" in channel._http.calls[0]["url"]
|
||||
assert channel._http.calls[0]["json"]["downloadCode"] == "code123"
|
||||
@@ -858,7 +840,6 @@ async def test_download_dingtalk_file(tmp_path, monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_read_media_bytes_rejects_private_http_target_before_fetch() -> None:
|
||||
"""Remote media fetches must not reach loopback/private addresses."""
|
||||
channel = DingTalkChannel(
|
||||
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
|
||||
MessageBus(),
|
||||
@@ -882,7 +863,6 @@ async def test_read_media_bytes_rejects_private_http_target_before_fetch() -> No
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_read_media_bytes_rejects_private_redirect_result() -> None:
|
||||
"""A public-looking media URL must not be accepted after redirecting private."""
|
||||
channel = DingTalkChannel(
|
||||
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
|
||||
MessageBus(),
|
||||
@@ -906,7 +886,6 @@ async def test_read_media_bytes_rejects_private_redirect_result() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_read_media_bytes_rejects_oversized_remote_response(monkeypatch) -> None:
|
||||
"""DingTalk media downloads should enforce a byte cap before upload."""
|
||||
monkeypatch.setattr(dingtalk_module, "DINGTALK_MAX_REMOTE_MEDIA_BYTES", 8, raising=False)
|
||||
channel = DingTalkChannel(
|
||||
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
|
||||
@@ -930,7 +909,6 @@ async def test_read_media_bytes_rejects_oversized_remote_response(monkeypatch) -
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_read_media_bytes_does_not_follow_remote_redirects_by_default() -> None:
|
||||
"""Redirects are refused by default instead of followed into internal networks."""
|
||||
channel = DingTalkChannel(
|
||||
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
|
||||
MessageBus(),
|
||||
@@ -953,7 +931,6 @@ async def test_read_media_bytes_does_not_follow_remote_redirects_by_default() ->
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_read_media_bytes_follows_safe_redirect_when_explicitly_enabled() -> None:
|
||||
"""Operators can opt in to public redirects without enabling private redirects."""
|
||||
channel = DingTalkChannel(
|
||||
DingTalkConfig(
|
||||
client_id="app",
|
||||
@@ -1039,7 +1016,6 @@ async def test_read_media_bytes_blocks_untrusted_redirects(response_body, redire
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_read_media_bytes_allows_cross_host_redirect_when_allowlisted() -> None:
|
||||
"""Operators can explicitly allow a known CDN/download host for redirects."""
|
||||
channel = DingTalkChannel(
|
||||
DingTalkConfig(
|
||||
client_id="app",
|
||||
@@ -1150,12 +1126,8 @@ async def test_send_media_ref_zips_html_before_upload(tmp_path, monkeypatch) ->
|
||||
assert archive.namelist() == ["report.html"]
|
||||
|
||||
|
||||
# ── Exception handling tests ──────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_batch_message_propagates_transport_error() -> None:
|
||||
"""Network/transport errors must re-raise so callers can retry."""
|
||||
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
|
||||
channel = DingTalkChannel(config, MessageBus())
|
||||
channel._http = _NetworkErrorHttp()
|
||||
@@ -1168,32 +1140,27 @@ async def test_send_batch_message_propagates_transport_error() -> None:
|
||||
{"text": "hello", "title": "Nanobot Reply"},
|
||||
)
|
||||
|
||||
# The POST was attempted exactly once
|
||||
assert len(channel._http.calls) == 1
|
||||
assert channel._http.calls[0]["method"] == "POST"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_batch_message_returns_false_on_api_error() -> None:
|
||||
"""DingTalk API-level errors (non-200 status, errcode != 0) should return False."""
|
||||
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
|
||||
channel = DingTalkChannel(config, MessageBus())
|
||||
|
||||
# Non-200 status code → API error → return False
|
||||
channel._http = _FakeHttp(responses=[_FakeResponse(400, {"errcode": 400})])
|
||||
result = await channel._send_batch_message(
|
||||
"token", "user123", "sampleMarkdown", {"text": "hello"}
|
||||
)
|
||||
assert result is False
|
||||
|
||||
# 200 with non-zero errcode → API error → return False
|
||||
channel._http = _FakeHttp(responses=[_FakeResponse(200, {"errcode": 100})])
|
||||
result = await channel._send_batch_message(
|
||||
"token", "user123", "sampleMarkdown", {"text": "hello"}
|
||||
)
|
||||
assert result is False
|
||||
|
||||
# 200 with errcode=0 → success → return True
|
||||
channel._http = _FakeHttp(responses=[_FakeResponse(200, {"errcode": 0})])
|
||||
result = await channel._send_batch_message(
|
||||
"token", "user123", "sampleMarkdown", {"text": "hello"}
|
||||
@@ -1238,11 +1205,9 @@ async def test_send_media_ref_short_circuits_on_transport_error() -> None:
|
||||
channel = DingTalkChannel(config, MessageBus())
|
||||
channel._http = _NetworkErrorHttp()
|
||||
|
||||
# An image URL triggers the sampleImageMsg path first
|
||||
with pytest.raises(httpx.ConnectError, match="Connection refused"):
|
||||
await channel._send_media_ref("token", "user123", "https://example.com/photo.jpg")
|
||||
|
||||
# Only one POST should have been attempted — no download/upload/fallback
|
||||
assert len(channel._http.calls) == 1
|
||||
assert channel._http.calls[0]["method"] == "POST"
|
||||
|
||||
@@ -1255,14 +1220,12 @@ async def test_send_media_ref_short_circuits_on_download_transport_error() -> No
|
||||
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
|
||||
channel = DingTalkChannel(config, MessageBus())
|
||||
|
||||
# First POST (sampleImageMsg) returns API error → False, then GET (download) raises transport error
|
||||
class _MixedHttp(_FakeHttp):
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[dict] = []
|
||||
|
||||
async def post(self, url, json=None, headers=None, **kwargs):
|
||||
self.calls.append({"method": "POST", "url": url})
|
||||
# API-level failure: 200 with errcode != 0
|
||||
return _FakeResponse(200, {"errcode": 100})
|
||||
|
||||
async def get(self, url, **kwargs):
|
||||
@@ -1274,7 +1237,6 @@ async def test_send_media_ref_short_circuits_on_download_transport_error() -> No
|
||||
with pytest.raises(httpx.ConnectError, match="Connection refused"):
|
||||
await channel._send_media_ref("token", "user123", "https://example.com/photo.jpg")
|
||||
|
||||
# Should have attempted POST (image URL) and GET (download), but NOT upload
|
||||
assert len(channel._http.calls) == 2
|
||||
assert channel._http.calls[0]["method"] == "POST"
|
||||
assert channel._http.calls[1]["method"] == "GET"
|
||||
@@ -1282,11 +1244,10 @@ async def test_send_media_ref_short_circuits_on_download_transport_error() -> No
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_ref_short_circuits_on_upload_transport_error() -> None:
|
||||
"""When download succeeds but upload hits a transport error, must re-raise."""
|
||||
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
|
||||
channel = DingTalkChannel(config, MessageBus())
|
||||
|
||||
image_bytes = b"\xff\xd8\xff\xe0" + b"\x00" * 100 # minimal JPEG-ish data
|
||||
image_bytes = b"\xff\xd8\xff\xe0" + b"\x00" * 100
|
||||
|
||||
class _UploadFailsHttp(_FakeHttp):
|
||||
def __init__(self) -> None:
|
||||
@@ -1294,10 +1255,8 @@ async def test_send_media_ref_short_circuits_on_upload_transport_error() -> None
|
||||
|
||||
async def post(self, url, json=None, headers=None, files=None, **kwargs):
|
||||
self.calls.append({"method": "POST", "url": url})
|
||||
# If it's the upload endpoint, raise transport error
|
||||
if "media/upload" in url:
|
||||
raise httpx.ConnectError("Connection refused")
|
||||
# Otherwise (sampleImageMsg), return API error to trigger fallback
|
||||
return _FakeResponse(200, {"errcode": 100})
|
||||
|
||||
async def get(self, url, **kwargs):
|
||||
@@ -1312,7 +1271,6 @@ async def test_send_media_ref_short_circuits_on_upload_transport_error() -> None
|
||||
with pytest.raises(httpx.ConnectError, match="Connection refused"):
|
||||
await channel._send_media_ref("token", "user123", "https://example.com/photo.jpg")
|
||||
|
||||
# POST (image URL), GET (download), POST (upload) attempted — no further sends
|
||||
methods = [c["method"] for c in channel._http.calls]
|
||||
assert methods == ["POST", "GET", "POST"]
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Discord channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Discord management contract."""
|
||||
|
||||
from nanobot.channels._manifest import DIRECT_GROUP_POLICIES, field, required
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.discord.validation import validate
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Discord channel implementation using discord.py."""
|
||||
# pyright: reportPrivateUsage=false, reportUnusedFunction=false
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -36,7 +35,7 @@ if DISCORD_AVAILABLE:
|
||||
from discord import app_commands
|
||||
from discord.abc import Messageable
|
||||
|
||||
MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 # 20MB
|
||||
MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
|
||||
MAX_MESSAGE_LEN = 2000 # Discord message character limit
|
||||
TYPING_INTERVAL_S = 8
|
||||
|
||||
@@ -110,7 +109,6 @@ if DISCORD_AVAILABLE:
|
||||
self._channel._remember_channel(after)
|
||||
|
||||
async def _reply_ephemeral(self, interaction: discord.Interaction, text: str) -> bool:
|
||||
"""Send an ephemeral interaction response and report success."""
|
||||
try:
|
||||
await interaction.response.send_message(text, ephemeral=True)
|
||||
return True
|
||||
@@ -323,7 +321,6 @@ if DISCORD_AVAILABLE:
|
||||
)
|
||||
|
||||
async def _edit_compaction_notice(self, notice: discord.Message, content: str) -> bool:
|
||||
"""Replace a start notice's text with the outcome; False when Discord refused."""
|
||||
if not content:
|
||||
return False
|
||||
try:
|
||||
@@ -341,7 +338,6 @@ if DISCORD_AVAILABLE:
|
||||
reference: discord.MessageReference | None,
|
||||
mention_settings: discord.AllowedMentions,
|
||||
) -> bool:
|
||||
"""Send a file attachment via discord.py."""
|
||||
path = Path(file_path)
|
||||
if not path.is_file():
|
||||
self._channel.logger.warning("file not found, skipping: {}", file_path)
|
||||
@@ -415,7 +411,6 @@ class DiscordChannel(BaseChannel):
|
||||
*,
|
||||
explicit: str | None = None,
|
||||
) -> str | None:
|
||||
"""Choose an explicit reply target, or the triggering message when enabled."""
|
||||
if explicit:
|
||||
return explicit
|
||||
if not self.config.reply_to_message or not metadata:
|
||||
@@ -430,7 +425,6 @@ class DiscordChannel(BaseChannel):
|
||||
*,
|
||||
fail_if_not_exists: bool,
|
||||
) -> tuple[discord.MessageReference | None, discord.AllowedMentions]:
|
||||
"""Build a native Discord reply without pinging the replied-to user."""
|
||||
mention_settings = discord.AllowedMentions(replied_user=False)
|
||||
if not reply_to:
|
||||
return None, mention_settings
|
||||
@@ -454,7 +448,7 @@ class DiscordChannel(BaseChannel):
|
||||
self._client: DiscordBotClient | None = None
|
||||
self._typing_tasks: dict[str, asyncio.Task[None]] = {}
|
||||
self._bot_user_id: str | None = None
|
||||
self._pending_reactions: dict[str, Any] = {} # chat_id -> message object
|
||||
self._pending_reactions: dict[str, Any] = {}
|
||||
self._compaction_notices: dict[tuple[str, str], discord.Message] = {}
|
||||
self._working_emoji_tasks: dict[str, set[asyncio.Task[None]]] = {}
|
||||
self._inbound_tasks: set[asyncio.Task[Any]] = set()
|
||||
@@ -516,7 +510,6 @@ class DiscordChannel(BaseChannel):
|
||||
compaction_id: str,
|
||||
message: discord.Message,
|
||||
) -> None:
|
||||
"""Keep a start notice until its matching outcome consumes it."""
|
||||
self._compaction_notices[(chat_id, compaction_id)] = message
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
@@ -616,7 +609,6 @@ class DiscordChannel(BaseChannel):
|
||||
raise
|
||||
|
||||
async def _handle_discord_message(self, message: discord.Message) -> None:
|
||||
"""Own in-flight callbacks until they finish or runtime reset drains them."""
|
||||
task = asyncio.current_task()
|
||||
if task is not None:
|
||||
self._inbound_tasks.add(task)
|
||||
@@ -661,7 +653,6 @@ class DiscordChannel(BaseChannel):
|
||||
|
||||
await self._start_typing(message.channel)
|
||||
|
||||
# Add read receipt reaction immediately, working emoji after delay
|
||||
try:
|
||||
await message.add_reaction(self.config.read_receipt_emoji)
|
||||
self._pending_reactions[channel_id] = message
|
||||
@@ -706,7 +697,6 @@ class DiscordChannel(BaseChannel):
|
||||
await self._handle_discord_message(message)
|
||||
|
||||
async def _resolve_channel(self, chat_id: str) -> Any | None:
|
||||
"""Resolve a Discord channel from cache first, then network fetch."""
|
||||
client = self._client
|
||||
if client is None or not client.is_ready():
|
||||
return None
|
||||
@@ -729,7 +719,6 @@ class DiscordChannel(BaseChannel):
|
||||
buf: _StreamBuf,
|
||||
message: discord.Message,
|
||||
) -> None:
|
||||
"""Commit the final streamed content and flush overflow chunks."""
|
||||
chunks = DiscordBotClient._build_chunks(buf.text, [], False)
|
||||
if not chunks:
|
||||
self._stream_bufs.pop(chat_id, None)
|
||||
@@ -756,12 +745,10 @@ class DiscordChannel(BaseChannel):
|
||||
sender_id: str,
|
||||
content: str,
|
||||
) -> bool:
|
||||
"""Check if inbound Discord message should be processed."""
|
||||
# Reject unauthorized guild messages before any side effects, but let DMs
|
||||
# reach BaseChannel._handle_message so it can issue a pairing code.
|
||||
if message.guild is not None and not self.is_allowed(sender_id):
|
||||
return False
|
||||
# Channel-based filtering: only respond in allowed channels
|
||||
allow_channels = self.config.allow_channels
|
||||
if allow_channels:
|
||||
channel_ids = self._channel_allow_keys(message.channel)
|
||||
@@ -775,7 +762,6 @@ class DiscordChannel(BaseChannel):
|
||||
self,
|
||||
attachments: list[discord.Attachment],
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Download supported attachments and return paths + display markers."""
|
||||
media_paths: list[str] = []
|
||||
markers: list[str] = []
|
||||
media_dir = get_media_dir("discord")
|
||||
@@ -826,7 +812,6 @@ class DiscordChannel(BaseChannel):
|
||||
}
|
||||
|
||||
def _should_respond_in_group(self, message: discord.Message, content: str) -> bool:
|
||||
"""Check if the bot should respond in a guild channel based on policy."""
|
||||
if self.config.group_policy == "open":
|
||||
return True
|
||||
|
||||
@@ -867,7 +852,6 @@ class DiscordChannel(BaseChannel):
|
||||
return str(getattr(author, "id", "")) == bot_user_id
|
||||
|
||||
async def _start_typing(self, channel: Messageable) -> None:
|
||||
"""Start periodic typing indicator for a channel."""
|
||||
channel_id = self._channel_key(channel)
|
||||
await self._stop_typing(channel_id)
|
||||
|
||||
@@ -885,7 +869,6 @@ class DiscordChannel(BaseChannel):
|
||||
self._typing_tasks[channel_id] = asyncio.create_task(typing_loop())
|
||||
|
||||
async def _stop_typing(self, channel_id: str) -> None:
|
||||
"""Stop typing indicator for a channel."""
|
||||
task = self._typing_tasks.pop(self._channel_key(channel_id), None)
|
||||
if task is None:
|
||||
return
|
||||
@@ -894,7 +877,6 @@ class DiscordChannel(BaseChannel):
|
||||
await task
|
||||
|
||||
async def _clear_reactions(self, chat_id: str) -> None:
|
||||
"""Remove all pending reactions after bot replies."""
|
||||
# Keep tasks owned until done, so a concurrent reset can drain them too.
|
||||
tasks = tuple(self._working_emoji_tasks.get(chat_id, ()))
|
||||
# Snapshot before yielding; a newer receipt must survive this cleanup.
|
||||
@@ -912,13 +894,11 @@ class DiscordChannel(BaseChannel):
|
||||
await msg_obj.remove_reaction(emoji, bot_user)
|
||||
|
||||
async def _cancel_all_typing(self) -> None:
|
||||
"""Stop all typing tasks."""
|
||||
channel_ids = list(self._typing_tasks)
|
||||
for channel_id in channel_ids:
|
||||
await self._stop_typing(channel_id)
|
||||
|
||||
async def _cancel_all_reactions(self) -> None:
|
||||
"""Stop delayed reactions and release their retained messages."""
|
||||
tasks = tuple(task for group in self._working_emoji_tasks.values() for task in group)
|
||||
self._pending_reactions.clear()
|
||||
for task in tasks:
|
||||
@@ -928,7 +908,6 @@ class DiscordChannel(BaseChannel):
|
||||
self._working_emoji_tasks.clear()
|
||||
|
||||
async def _reset_runtime_state(self, close_client: bool) -> None:
|
||||
"""Reset client and transient runtime state."""
|
||||
self._running = False
|
||||
# Drain callbacks before clearing the state they can still create after an await.
|
||||
current = asyncio.current_task()
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the Discord channel package."""
|
||||
@@ -25,7 +25,6 @@ from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
|
||||
# Minimal Discord client test double used to control startup/readiness behavior.
|
||||
class _FakeDiscordClient:
|
||||
instances: list["_FakeDiscordClient"] = []
|
||||
start_error: Exception | None = None
|
||||
@@ -66,7 +65,6 @@ class _FakeDiscordClient:
|
||||
|
||||
|
||||
class _FakeAttachment:
|
||||
# Attachment double that can simulate successful or failing save() calls.
|
||||
def __init__(
|
||||
self, attachment_id: int, filename: str, *, size: int = 1, fail: bool = False
|
||||
) -> None:
|
||||
@@ -82,7 +80,6 @@ class _FakeAttachment:
|
||||
|
||||
|
||||
class _FakePartialMessage:
|
||||
# Lightweight stand-in for Discord partial message references used in replies.
|
||||
def __init__(self, message_id: int, channel_id: int) -> None:
|
||||
self.id = message_id
|
||||
self.channel_id = channel_id
|
||||
@@ -96,7 +93,6 @@ class _FakePartialMessage:
|
||||
|
||||
|
||||
class _FakeSentMessage:
|
||||
# Sent-message double supporting edit() for streaming tests.
|
||||
def __init__(self, channel, content: str) -> None:
|
||||
self.channel = channel
|
||||
self.content = content
|
||||
@@ -109,7 +105,6 @@ class _FakeSentMessage:
|
||||
|
||||
|
||||
class _FakeChannel:
|
||||
# Channel double that records outbound payloads and typing activity.
|
||||
def __init__(
|
||||
self,
|
||||
channel_id: int = 123,
|
||||
@@ -194,7 +189,6 @@ def _make_message(
|
||||
reply_author_id: int | None = None,
|
||||
message_type=None,
|
||||
):
|
||||
# Factory for incoming Discord message objects with optional guild/reply/attachments.
|
||||
guild = SimpleNamespace(id=guild_id) if guild_id is not None else None
|
||||
referenced_message = (
|
||||
SimpleNamespace(author=SimpleNamespace(id=reply_author_id))
|
||||
@@ -222,7 +216,6 @@ def _make_message(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_returns_when_token_missing() -> None:
|
||||
# If no token is configured, startup should no-op and leave channel stopped.
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
|
||||
await channel.start()
|
||||
@@ -247,7 +240,6 @@ async def test_start_returns_when_discord_dependency_missing(monkeypatch) -> Non
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_handles_client_construction_failure(monkeypatch) -> None:
|
||||
# Construction errors from the Discord client should be swallowed and keep state clean.
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(enabled=True, token="token", allow_from=["*"]),
|
||||
MessageBus(),
|
||||
@@ -266,7 +258,6 @@ async def test_start_handles_client_construction_failure(monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_handles_client_start_failure(monkeypatch) -> None:
|
||||
# If client.start fails, the partially created client should be closed and detached.
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(enabled=True, token="token", allow_from=["*"]),
|
||||
MessageBus(),
|
||||
@@ -288,7 +279,6 @@ async def test_start_handles_client_start_failure(monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_is_safe_after_partial_start(monkeypatch) -> None:
|
||||
# stop() should close/discard the client even when startup was only partially completed.
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(enabled=True, token="token", allow_from=["*"]),
|
||||
MessageBus(),
|
||||
@@ -383,7 +373,6 @@ async def test_stop_drains_inflight_message_before_reaction_cleanup(blocked_stag
|
||||
assert not channel._working_emoji_tasks
|
||||
assert not channel._pending_reactions
|
||||
channel._handle_message.assert_not_awaited()
|
||||
# A queued event from the closed client must not run, even after a new runtime starts.
|
||||
channel._client = DiscordBotClient(channel, intents=discord.Intents.default())
|
||||
channel._running = True
|
||||
await client.on_message(_make_message())
|
||||
@@ -554,7 +543,7 @@ async def test_stop_waits_for_reaction_already_draining(monkeypatch, cleanup_kin
|
||||
async def test_on_message_ignores_self_messages() -> None:
|
||||
# Self-loop guard: messages from this bot's own account must be dropped (#3217).
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
channel._bot_user_id = "999" # simulate bot identity populated in on_ready()
|
||||
channel._bot_user_id = "999"
|
||||
handled: list[dict] = []
|
||||
channel._handle_message = lambda **kwargs: handled.append(kwargs) # type: ignore[method-assign]
|
||||
|
||||
@@ -583,7 +572,6 @@ async def test_on_message_accepts_messages_from_other_bots() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_stops_typing_on_handle_exception() -> None:
|
||||
# If inbound handling raises, typing should be stopped for that channel.
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
|
||||
async def fail_handle(**kwargs) -> None:
|
||||
@@ -599,7 +587,6 @@ async def test_on_message_stops_typing_on_handle_exception() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_accepts_allowlisted_dm() -> None:
|
||||
# Allowed direct messages should be forwarded with normalized metadata.
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["123"]), MessageBus())
|
||||
handled: list[dict] = []
|
||||
|
||||
@@ -637,7 +624,6 @@ async def test_on_message_unauthorized_dm_sends_pairing_code(monkeypatch) -> Non
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_accepts_when_channel_in_allow_channels() -> None:
|
||||
# When allow_channels is set, messages from listed channels should be forwarded.
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(enabled=True, allow_from=["*"], allow_channels=["456"]),
|
||||
MessageBus(),
|
||||
@@ -798,7 +784,6 @@ async def test_on_message_drops_thread_when_neither_thread_nor_parent_allowed()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_drops_when_channel_not_in_allow_channels() -> None:
|
||||
# When allow_channels is set and incoming channel is not listed, drop silently.
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(enabled=True, allow_from=["*"], allow_channels=["999"]),
|
||||
MessageBus(),
|
||||
@@ -817,7 +802,6 @@ async def test_on_message_drops_when_channel_not_in_allow_channels() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_ignores_unmentioned_guild_message() -> None:
|
||||
# With mention-only group policy, guild messages without a bot mention are dropped.
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(enabled=True, allow_from=["*"], group_policy="mention"),
|
||||
MessageBus(),
|
||||
@@ -837,7 +821,6 @@ async def test_on_message_ignores_unmentioned_guild_message() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_accepts_mentioned_guild_message() -> None:
|
||||
# Mentioned guild messages should be accepted and preserve reply threading metadata.
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(enabled=True, allow_from=["*"], group_policy="mention"),
|
||||
MessageBus(),
|
||||
@@ -865,7 +848,6 @@ async def test_on_message_accepts_mentioned_guild_message() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_downloads_attachments(tmp_path, monkeypatch) -> None:
|
||||
# Attachment downloads should be saved and referenced in forwarded content/media.
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
handled: list[dict] = []
|
||||
|
||||
@@ -889,7 +871,6 @@ async def test_on_message_downloads_attachments(tmp_path, monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_marks_failed_attachment_download(tmp_path, monkeypatch) -> None:
|
||||
# Failed attachment downloads should emit a readable placeholder and no media path.
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
handled: list[dict] = []
|
||||
|
||||
@@ -913,7 +894,6 @@ async def test_on_message_marks_failed_attachment_download(tmp_path, monkeypatch
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_raises_when_client_not_ready() -> None:
|
||||
# The manager must be able to retry while Discord is still connecting.
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
|
||||
with pytest.raises(RuntimeError, match="client is not ready"):
|
||||
@@ -924,7 +904,6 @@ async def test_send_raises_when_client_not_ready() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_raises_when_channel_cannot_be_resolved() -> None:
|
||||
# The manager must be able to retry transient channel-resolution failures.
|
||||
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = DiscordBotClient(owner, intents=discord.Intents.none())
|
||||
fetch_calls: list[int] = []
|
||||
@@ -1339,7 +1318,6 @@ async def test_thread_delete_and_archive_remove_known_channel() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_send_outbound_chunks_text_replies_and_uploads_files(tmp_path) -> None:
|
||||
# Outbound payloads should upload files, attach reply references, and chunk long text.
|
||||
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = DiscordBotClient(owner, intents=discord.Intents.none())
|
||||
target = _FakeChannel(channel_id=123)
|
||||
@@ -1444,7 +1422,6 @@ async def test_client_send_outbound_replies_on_first_successful_attachment(tmp_p
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_send_outbound_reports_failed_attachments_when_no_text(tmp_path) -> None:
|
||||
# If all attachment sends fail and no text exists, emit a failure placeholder message.
|
||||
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = DiscordBotClient(owner, intents=discord.Intents.none())
|
||||
target = _FakeChannel(channel_id=123)
|
||||
@@ -1466,7 +1443,6 @@ async def test_client_send_outbound_reports_failed_attachments_when_no_text(tmp_
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_stops_typing_after_send() -> None:
|
||||
# Active typing indicators should be cancelled/cleared after a successful send.
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = _FakeDiscordClient(channel, intents=None)
|
||||
channel._client = client
|
||||
@@ -1491,7 +1467,6 @@ async def test_send_stops_typing_after_send() -> None:
|
||||
|
||||
assert channel._typing_tasks == {}
|
||||
|
||||
# Progress messages should keep typing active until a final (non-progress) send.
|
||||
start = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
@@ -1546,7 +1521,6 @@ async def test_start_typing_uses_typing_context_when_trigger_typing_missing() ->
|
||||
async def _waiter():
|
||||
await release.wait()
|
||||
|
||||
# Hold the loop so task remains active until explicitly stopped.
|
||||
class _Ctx(_TypingCtx):
|
||||
async def __aenter__(self):
|
||||
await super().__aenter__()
|
||||
@@ -1670,13 +1644,8 @@ def test_proxy_opt_in_without_shared_address_fails_before_start() -> None:
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests for the send() exception propagation fix
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_re_raises_network_error() -> None:
|
||||
"""Network errors during send must propagate so ChannelManager can retry."""
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = _FakeDiscordClient(channel, intents=None)
|
||||
channel._client = client
|
||||
@@ -1693,7 +1662,6 @@ async def test_send_re_raises_network_error() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_re_raises_generic_exception() -> None:
|
||||
"""Any exception from send_outbound must propagate, not be swallowed."""
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = _FakeDiscordClient(channel, intents=None)
|
||||
channel._client = client
|
||||
@@ -1710,13 +1678,11 @@ async def test_send_re_raises_generic_exception() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_still_stops_typing_on_error() -> None:
|
||||
"""Typing cleanup must still run in the finally block even when send raises."""
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = _FakeDiscordClient(channel, intents=None)
|
||||
channel._client = client
|
||||
channel._running = True
|
||||
|
||||
# Start a typing task so we can verify it gets cleaned up
|
||||
start = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
@@ -1740,13 +1706,11 @@ async def test_send_still_stops_typing_on_error() -> None:
|
||||
release.set()
|
||||
await asyncio.sleep(0)
|
||||
|
||||
# Typing should have been cleaned up by the finally block
|
||||
assert channel._typing_tasks == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_succeeds_normally() -> None:
|
||||
"""Successful sends should work without raising."""
|
||||
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = _FakeDiscordClient(channel, intents=None)
|
||||
channel._client = client
|
||||
@@ -1829,7 +1793,6 @@ async def test_automatic_compaction_is_received_but_not_sent() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compaction_outcome_without_a_start_notice_is_sent() -> None:
|
||||
# After a restart (or when the edit is refused) the outcome still arrives.
|
||||
target = _FakeChannel(channel_id=123)
|
||||
owner, client = _client_with_channel(target)
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Discord setup validation owned by the channel package."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Email channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Email management contract."""
|
||||
|
||||
from nanobot.channels._manifest import field, required_fields
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.email.validation import validate
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Email channel implementation using IMAP polling + SMTP replies."""
|
||||
|
||||
import asyncio
|
||||
import html
|
||||
import imaplib
|
||||
@@ -66,7 +64,6 @@ class EmailConfig(Base):
|
||||
subject_prefix: str = "Re: "
|
||||
allow_from: list[str] = Field(default_factory=list)
|
||||
|
||||
# Email authentication verification (anti-spoofing)
|
||||
verify_dkim: bool = True # Require Authentication-Results with dkim=pass
|
||||
verify_spf: bool = True # Require Authentication-Results with spf=pass
|
||||
trusted_authserv_ids: list[str] = Field(default_factory=list)
|
||||
@@ -85,7 +82,7 @@ class EmailConfig(Base):
|
||||
|
||||
# Attachment handling — set allowed types to enable (e.g. ["application/pdf", "image/*"], or ["*"] for all)
|
||||
allowed_attachment_types: list[str] = Field(default_factory=list)
|
||||
max_attachment_size: int = 2_000_000 # 2MB per attachment
|
||||
max_attachment_size: int = 2_000_000
|
||||
max_attachments_per_email: int = 5
|
||||
|
||||
|
||||
@@ -165,7 +162,7 @@ class EmailChannel(BaseChannel):
|
||||
self._self_addresses = self._collect_self_addresses()
|
||||
self._last_subject_by_chat: dict[str, str] = {}
|
||||
self._last_message_id_by_chat: dict[str, str] = {}
|
||||
self._processed_uids: set[str] = set() # Capped to prevent unbounded growth
|
||||
self._processed_uids: set[str] = set()
|
||||
self._MAX_PROCESSED_UIDS = 100000
|
||||
|
||||
async def start(self) -> None:
|
||||
@@ -260,7 +257,6 @@ class EmailChannel(BaseChannel):
|
||||
if not to_addr:
|
||||
raise DeliveryRejectedError("Missing email recipient address")
|
||||
|
||||
# Determine if this is a reply (recipient has sent us an email before)
|
||||
is_reply = to_addr in self._last_subject_by_chat
|
||||
force_send = bool((msg.metadata or {}).get("force_send"))
|
||||
|
||||
@@ -387,7 +383,6 @@ class EmailChannel(BaseChannel):
|
||||
smtp.send_message(msg)
|
||||
|
||||
def _fetch_new_messages(self) -> tuple[list[dict[str, Any]], set[str]]:
|
||||
"""Poll IMAP and return parsed unread messages plus skipped message UIDs."""
|
||||
return self._fetch_messages(
|
||||
search_criteria=("UNSEEN",),
|
||||
mark_seen=self.config.mark_seen,
|
||||
@@ -462,13 +457,6 @@ class EmailChannel(BaseChannel):
|
||||
skipped_uids: set[str],
|
||||
cycle_uids: set[str],
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""Fetch messages by arbitrary IMAP search criteria.
|
||||
|
||||
Uses UID SEARCH so already-processed UIDs are recognized before any
|
||||
FETCH at all, then fetches headers only to evaluate every filter — the
|
||||
full body (and any attachments) is downloaded only for messages that
|
||||
pass every check and are actually going to be delivered.
|
||||
"""
|
||||
mailbox = self.config.imap_mailbox or "INBOX"
|
||||
|
||||
client = self._open_imap_client(mailbox=mailbox, missing_mailbox_ok=True)
|
||||
@@ -511,7 +499,6 @@ class EmailChannel(BaseChannel):
|
||||
skipped_uids.add(uid)
|
||||
continue
|
||||
|
||||
# --- Anti-spoofing: verify Authentication-Results ---
|
||||
spf_pass, dkim_pass = self._check_authentication_results(parsed, sender)
|
||||
if self.config.verify_spf and not spf_pass:
|
||||
self.logger.warning(
|
||||
@@ -566,7 +553,6 @@ class EmailChannel(BaseChannel):
|
||||
f"{body}"
|
||||
)
|
||||
|
||||
# --- Attachment extraction ---
|
||||
attachment_paths: list[str] = []
|
||||
if self.config.allowed_attachment_types:
|
||||
saved = self._extract_attachments(
|
||||
@@ -608,7 +594,6 @@ class EmailChannel(BaseChannel):
|
||||
def _mark_seen_uid(
|
||||
self, client: Any, uid: str, features: _ServerFeatures | None
|
||||
) -> _ServerFeatures:
|
||||
"""Mark a single UID \\Seen, reusing session-learned STORE support."""
|
||||
if features is None:
|
||||
features = self._server_features(client)
|
||||
self._uid_store_flag(client, uid, "\\Seen", features)
|
||||
@@ -647,7 +632,6 @@ class EmailChannel(BaseChannel):
|
||||
client.logout()
|
||||
|
||||
def _collect_self_addresses(self) -> set[str]:
|
||||
"""Return normalized email addresses owned by this channel instance."""
|
||||
candidates = (
|
||||
self.config.from_address,
|
||||
self.config.smtp_username,
|
||||
@@ -674,12 +658,10 @@ class EmailChannel(BaseChannel):
|
||||
return ""
|
||||
|
||||
def _is_self_address(self, sender: str) -> bool:
|
||||
"""Return True when an inbound sender belongs to the bot itself."""
|
||||
normalized_sender = self._normalize_address(sender)
|
||||
return bool(normalized_sender) and normalized_sender in self._self_addresses
|
||||
|
||||
def _remember_processed_uid(self, uid: str, dedupe: bool, cycle_uids: set[str]) -> None:
|
||||
"""Track a fetched UID so skipped messages are not reprocessed forever."""
|
||||
if not uid:
|
||||
return
|
||||
cycle_uids.add(uid)
|
||||
@@ -687,7 +669,6 @@ class EmailChannel(BaseChannel):
|
||||
self._processed_uids.add(uid)
|
||||
# mark_seen is the primary dedup; this set is a safety net
|
||||
if len(self._processed_uids) > self._MAX_PROCESSED_UIDS:
|
||||
# Evict a random half to cap memory; mark_seen is the primary dedup
|
||||
self._processed_uids = set(list(self._processed_uids)[len(self._processed_uids) // 2:])
|
||||
|
||||
def _should_apply_post_action(self) -> bool:
|
||||
@@ -891,7 +872,6 @@ class EmailChannel(BaseChannel):
|
||||
return payload.strip()
|
||||
|
||||
def _check_authentication_results(self, parsed_msg: Any, sender: str) -> tuple[bool, bool]:
|
||||
"""Return aligned SPF/DKIM verdicts from one trusted producer header."""
|
||||
from_headers: list[Any] = parsed_msg.get_all("From") or []
|
||||
if (
|
||||
len(from_headers) != 1
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the email channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Inbound attachment names must not cause another attachment to be overwritten."""
|
||||
|
||||
from email.message import EmailMessage
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Ingress regressions for the receiving-service authentication boundary."""
|
||||
|
||||
import base64
|
||||
from datetime import date
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ def _make_config(**overrides) -> EmailConfig:
|
||||
smtp_password="secret",
|
||||
mark_seen=True,
|
||||
allow_from=["*"],
|
||||
# Disable auth verification by default so existing tests are unaffected
|
||||
verify_dkim=False,
|
||||
verify_spf=False,
|
||||
)
|
||||
@@ -115,7 +114,6 @@ def test_fetch_new_messages_parses_unseen_and_marks_seen(monkeypatch) -> None:
|
||||
]
|
||||
assert skipped_uids == set()
|
||||
|
||||
# Same UID should be deduped in-process.
|
||||
items_again, skipped_again = channel._fetch_new_messages()
|
||||
assert items_again == []
|
||||
assert skipped_again == set()
|
||||
@@ -364,16 +362,13 @@ def test_apply_post_actions_batch_fallback_caches_uid_store_failure(monkeypatch)
|
||||
channel = EmailChannel(_make_config(post_action="delete"), MessageBus())
|
||||
channel._apply_post_actions_batch(["123", "124"])
|
||||
|
||||
# UID STORE should be attempted only once, then cached as unsupported.
|
||||
assert [call for call in fake.uid_calls if call[0] == "STORE"] == [("STORE", "123", "+FLAGS", "(\\Deleted)")]
|
||||
assert fake.search_calls == [(None, "UID", "123"), (None, "UID", "124")]
|
||||
assert fake.store_calls == [(b"1", "+FLAGS", "\\Deleted"), (b"2", "+FLAGS", "\\Deleted")]
|
||||
# With post_action_expunge=False (default), no broad expunge is called
|
||||
assert fake.expunge_calls == 0
|
||||
|
||||
|
||||
def test_apply_post_actions_batch_delete_with_post_action_expunge_true_no_uidplus(monkeypatch) -> None:
|
||||
"""When post_action_expunge=True and UIDPLUS is unsupported, broad expunge IS called."""
|
||||
class FakeIMAP:
|
||||
def __init__(self) -> None:
|
||||
self.uid_calls: list[tuple] = []
|
||||
@@ -419,7 +414,6 @@ def test_apply_post_actions_batch_delete_with_post_action_expunge_true_no_uidplu
|
||||
channel._apply_post_actions_batch(["123", "124"])
|
||||
|
||||
assert fake.store_calls == [(b"1", "+FLAGS", "\\Deleted"), (b"2", "+FLAGS", "\\Deleted")]
|
||||
# Broad expunge called because post_action_expunge=True
|
||||
assert fake.expunge_calls == 2
|
||||
|
||||
|
||||
@@ -548,7 +542,6 @@ def test_fetch_new_messages_skips_self_sent_email_and_marks_seen(monkeypatch) ->
|
||||
assert skipped_uids == {"123"}
|
||||
assert ("STORE", "123", "+FLAGS", "(\\Seen)") in fake.uid_calls
|
||||
|
||||
# Same UID should still be deduped after being ignored.
|
||||
items_again, skipped_again = channel._fetch_new_messages()
|
||||
assert items_again == []
|
||||
assert skipped_again == set()
|
||||
@@ -569,7 +562,6 @@ def test_fetch_new_messages_skips_self_sent_email_and_marks_seen(monkeypatch) ->
|
||||
{"from_address": "", "smtp_username": "other@smtp.com", "imap_username": "bot@example.com"},
|
||||
"bot@example.com",
|
||||
),
|
||||
# Case-insensitive: inbound From arrives upper-cased.
|
||||
(
|
||||
{"from_address": "bot@example.com", "smtp_username": "other@smtp.com", "imap_username": "other@imap.com"},
|
||||
"BOT@EXAMPLE.COM",
|
||||
@@ -844,7 +836,6 @@ async def test_send_skips_progress_messages_before_smtp(monkeypatch, event) -> N
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_skips_reply_when_auto_reply_disabled(monkeypatch) -> None:
|
||||
"""When auto_reply_enabled=False, replies should be skipped but proactive sends allowed."""
|
||||
class FakeSMTP:
|
||||
def __init__(self, _host: str, _port: int, timeout: int = 30) -> None:
|
||||
self.sent_messages: list[EmailMessage] = []
|
||||
@@ -877,10 +868,8 @@ async def test_send_skips_reply_when_auto_reply_disabled(monkeypatch) -> None:
|
||||
cfg.auto_reply_enabled = False
|
||||
channel = EmailChannel(cfg, MessageBus())
|
||||
|
||||
# Mark alice as someone who sent us an email (making this a "reply")
|
||||
channel._last_subject_by_chat["alice@example.com"] = "Previous email"
|
||||
|
||||
# A policy rejection must not look like successful delivery to the manager.
|
||||
with pytest.raises(DeliveryRejectedError, match="auto_reply_enabled"):
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
@@ -891,7 +880,6 @@ async def test_send_skips_reply_when_auto_reply_disabled(monkeypatch) -> None:
|
||||
)
|
||||
assert fake_instances == []
|
||||
|
||||
# Reply with force_send=True should be sent
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="email",
|
||||
@@ -906,7 +894,6 @@ async def test_send_skips_reply_when_auto_reply_disabled(monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_proactive_email_when_auto_reply_disabled(monkeypatch) -> None:
|
||||
"""Proactive emails (not replies) should be sent even when auto_reply_enabled=False."""
|
||||
class FakeSMTP:
|
||||
def __init__(self, _host: str, _port: int, timeout: int = 30) -> None:
|
||||
self.sent_messages: list[EmailMessage] = []
|
||||
@@ -939,8 +926,6 @@ async def test_send_proactive_email_when_auto_reply_disabled(monkeypatch) -> Non
|
||||
cfg.auto_reply_enabled = False
|
||||
channel = EmailChannel(cfg, MessageBus())
|
||||
|
||||
# bob@example.com has never sent us an email (proactive send)
|
||||
# This should be sent even with auto_reply_enabled=False
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="email",
|
||||
@@ -1039,16 +1024,11 @@ def test_fetch_messages_between_dates_uses_imap_since_before_without_mark_seen(m
|
||||
|
||||
assert len(items) == 1
|
||||
assert items[0]["subject"] == "Status"
|
||||
# uid("SEARCH", None, "SINCE", "06-Feb-2026", "BEFORE", "07-Feb-2026")
|
||||
assert fake.search_args is not None
|
||||
assert fake.search_args[1:] == ("SINCE", "06-Feb-2026", "BEFORE", "07-Feb-2026")
|
||||
assert fake.store_calls == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Security: Anti-spoofing tests for Authentication-Results verification
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_fake_imap(raw: bytes, uid: bytes = b"500"):
|
||||
"""Return a FakeIMAP class pre-loaded with the given raw email."""
|
||||
class FakeIMAP:
|
||||
@@ -1084,7 +1064,6 @@ def _make_fake_imap(raw: bytes, uid: bytes = b"500"):
|
||||
|
||||
|
||||
def test_spoofed_email_rejected_when_verify_enabled(monkeypatch) -> None:
|
||||
"""An email without Authentication-Results should be rejected when verify_dkim=True."""
|
||||
raw = _make_raw_email(subject="Spoofed", body="Malicious payload")
|
||||
fake = _make_fake_imap(raw)
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||
@@ -1101,7 +1080,6 @@ def test_spoofed_email_rejected_when_verify_enabled(monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_email_with_valid_auth_results_accepted(monkeypatch) -> None:
|
||||
"""An email with spf=pass and dkim=pass should be accepted."""
|
||||
raw = _make_raw_email(
|
||||
subject="Legit",
|
||||
body="Hello from verified sender",
|
||||
@@ -1124,7 +1102,6 @@ def test_email_with_valid_auth_results_accepted(monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_email_with_partial_auth_rejected(monkeypatch) -> None:
|
||||
"""An email with only spf=pass but no dkim=pass should be rejected when verify_dkim=True."""
|
||||
raw = _make_raw_email(
|
||||
subject="Partial",
|
||||
body="Only SPF passes",
|
||||
@@ -1263,7 +1240,6 @@ def test_trusted_relaxed_domain_alignment_accepts_legitimate_subdomain_auth(monk
|
||||
|
||||
|
||||
def test_backward_compat_verify_disabled(monkeypatch) -> None:
|
||||
"""When verify_dkim=False and verify_spf=False, emails without auth headers are accepted."""
|
||||
raw = _make_raw_email(subject="NoAuth", body="No auth headers present")
|
||||
fake = _make_fake_imap(raw)
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||
@@ -1276,7 +1252,6 @@ def test_backward_compat_verify_disabled(monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_email_content_tagged_with_email_context(monkeypatch) -> None:
|
||||
"""Email content should be prefixed with [EMAIL-CONTEXT] for LLM isolation."""
|
||||
raw = _make_raw_email(subject="Tagged", body="Check the tag")
|
||||
fake = _make_fake_imap(raw)
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||
@@ -1292,11 +1267,9 @@ def test_email_content_tagged_with_email_context(monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_check_authentication_results_method() -> None:
|
||||
"""Unit test for trusted, aligned Authentication-Results parsing."""
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
|
||||
# No Authentication-Results header
|
||||
msg_no_auth = EmailMessage()
|
||||
msg_no_auth["From"] = "alice@example.com"
|
||||
msg_no_auth.set_content("test")
|
||||
@@ -1309,7 +1282,6 @@ def test_check_authentication_results_method() -> None:
|
||||
assert spf is False
|
||||
assert dkim is False
|
||||
|
||||
# Both pass
|
||||
msg_both = EmailMessage()
|
||||
msg_both["From"] = "alice@example.com"
|
||||
msg_both["Authentication-Results"] = (
|
||||
@@ -1321,7 +1293,6 @@ def test_check_authentication_results_method() -> None:
|
||||
assert spf is True
|
||||
assert dkim is True
|
||||
|
||||
# SPF pass, DKIM fail
|
||||
msg_spf_only = EmailMessage()
|
||||
msg_spf_only["From"] = "alice@example.com"
|
||||
msg_spf_only["Authentication-Results"] = (
|
||||
@@ -1333,7 +1304,6 @@ def test_check_authentication_results_method() -> None:
|
||||
assert spf is True
|
||||
assert dkim is False
|
||||
|
||||
# DKIM pass, SPF fail
|
||||
msg_dkim_only = EmailMessage()
|
||||
msg_dkim_only["From"] = "alice@example.com"
|
||||
msg_dkim_only["Authentication-Results"] = (
|
||||
@@ -1346,11 +1316,6 @@ def test_check_authentication_results_method() -> None:
|
||||
assert dkim is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Attachment extraction tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_raw_email_with_attachment(
|
||||
from_addr: str = "alice@example.com",
|
||||
subject: str = "With attachment",
|
||||
@@ -1408,7 +1373,6 @@ def test_fetch_new_messages_ignores_unauthorized_sender_before_attachments(monke
|
||||
|
||||
|
||||
def test_extract_attachments_saves_pdf(tmp_path, monkeypatch) -> None:
|
||||
"""PDF attachment is saved to media dir and path returned in media list."""
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.get_media_dir", lambda ch: tmp_path)
|
||||
|
||||
raw = _make_raw_email_with_attachment()
|
||||
@@ -1429,7 +1393,6 @@ def test_extract_attachments_saves_pdf(tmp_path, monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_extract_attachments_disabled_by_default(monkeypatch) -> None:
|
||||
"""With no allowed_attachment_types (default), no attachments are extracted."""
|
||||
raw = _make_raw_email_with_attachment()
|
||||
fake = _make_fake_imap(raw)
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||
@@ -1445,7 +1408,6 @@ def test_extract_attachments_disabled_by_default(monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_extract_attachments_mime_type_filter(tmp_path, monkeypatch) -> None:
|
||||
"""Non-allowed MIME types are skipped."""
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.get_media_dir", lambda ch: tmp_path)
|
||||
|
||||
raw = _make_raw_email_with_attachment(
|
||||
@@ -1469,7 +1431,6 @@ def test_extract_attachments_mime_type_filter(tmp_path, monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_extract_attachments_empty_allowed_types_rejects_all(tmp_path, monkeypatch) -> None:
|
||||
"""Empty allowed_attachment_types means no types are accepted."""
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.get_media_dir", lambda ch: tmp_path)
|
||||
|
||||
raw = _make_raw_email_with_attachment(
|
||||
@@ -1493,7 +1454,6 @@ def test_extract_attachments_empty_allowed_types_rejects_all(tmp_path, monkeypat
|
||||
|
||||
|
||||
def test_extract_attachments_wildcard_pattern(tmp_path, monkeypatch) -> None:
|
||||
"""Glob patterns like 'image/*' match attachment MIME types."""
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.get_media_dir", lambda ch: tmp_path)
|
||||
|
||||
raw = _make_raw_email_with_attachment(
|
||||
@@ -1517,7 +1477,6 @@ def test_extract_attachments_wildcard_pattern(tmp_path, monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_extract_attachments_size_limit(tmp_path, monkeypatch) -> None:
|
||||
"""Attachments exceeding max_attachment_size are skipped."""
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.get_media_dir", lambda ch: tmp_path)
|
||||
|
||||
raw = _make_raw_email_with_attachment(
|
||||
@@ -1540,10 +1499,8 @@ def test_extract_attachments_size_limit(tmp_path, monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_extract_attachments_max_count(tmp_path, monkeypatch) -> None:
|
||||
"""Only max_attachments_per_email are saved."""
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.get_media_dir", lambda ch: tmp_path)
|
||||
|
||||
# Build email with 3 attachments
|
||||
msg = EmailMessage()
|
||||
msg["From"] = "alice@example.com"
|
||||
msg["To"] = "bot@example.com"
|
||||
@@ -1576,7 +1533,6 @@ def test_extract_attachments_max_count(tmp_path, monkeypatch) -> None:
|
||||
|
||||
|
||||
def test_extract_attachments_sanitizes_filename(tmp_path, monkeypatch) -> None:
|
||||
"""Path traversal in filenames is neutralized."""
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.get_media_dir", lambda ch: tmp_path)
|
||||
|
||||
raw = _make_raw_email_with_attachment(
|
||||
@@ -1592,18 +1548,11 @@ def test_extract_attachments_sanitizes_filename(tmp_path, monkeypatch) -> None:
|
||||
assert len(items) == 1
|
||||
assert len(items[0]["media"]) == 1
|
||||
saved_path = Path(items[0]["media"][0])
|
||||
# File must be inside the media dir, not escaped via path traversal
|
||||
assert saved_path.parent == tmp_path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Agent-initiated file attachment tests (send with media)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_single_file_attachment(tmp_path, monkeypatch) -> None:
|
||||
"""Agent sends an email with a single file attached."""
|
||||
sent_messages: list[EmailMessage] = []
|
||||
|
||||
class FakeSMTP:
|
||||
@@ -1627,7 +1576,6 @@ async def test_send_with_single_file_attachment(tmp_path, monkeypatch) -> None:
|
||||
|
||||
monkeypatch.setattr("nanobot.channels.email.runtime.smtplib.SMTP", lambda h, p, timeout=30: FakeSMTP(h, p, timeout=timeout))
|
||||
|
||||
# Create a real temp file to attach
|
||||
attachment = tmp_path / "report.pdf"
|
||||
attachment.write_bytes(b"%PDF-1.4 fake pdf content")
|
||||
|
||||
@@ -1646,7 +1594,6 @@ async def test_send_with_single_file_attachment(tmp_path, monkeypatch) -> None:
|
||||
assert sent["To"] == "alice@example.com"
|
||||
assert sent.is_multipart(), "Email with attachment should be multipart"
|
||||
|
||||
# Walk parts to find the attachment
|
||||
attachment_parts = []
|
||||
for part in sent.walk():
|
||||
if part.get_content_disposition() == "attachment":
|
||||
@@ -1660,7 +1607,6 @@ async def test_send_with_single_file_attachment(tmp_path, monkeypatch) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_multiple_file_attachments(tmp_path, monkeypatch) -> None:
|
||||
"""Agent sends an email with multiple files attached."""
|
||||
sent_messages: list[EmailMessage] = []
|
||||
|
||||
class FakeSMTP:
|
||||
@@ -1717,7 +1663,6 @@ async def test_send_with_multiple_file_attachments(tmp_path, monkeypatch) -> Non
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_skips_missing_attachment_file(tmp_path, monkeypatch) -> None:
|
||||
"""Non-existent attachment file is skipped without breaking the send."""
|
||||
sent_messages: list[EmailMessage] = []
|
||||
|
||||
class FakeSMTP:
|
||||
@@ -1765,7 +1710,6 @@ async def test_send_skips_missing_attachment_file(tmp_path, monkeypatch) -> None
|
||||
for part in sent.walk():
|
||||
if part.get_content_disposition() == "attachment":
|
||||
attachment_parts.append(part)
|
||||
# Only the existing file should be attached
|
||||
assert len(attachment_parts) == 1
|
||||
assert attachment_parts[0].get_filename() == "real.txt"
|
||||
body = sent.get_body(preferencelist=("plain",))
|
||||
@@ -1775,7 +1719,6 @@ async def test_send_skips_missing_attachment_file(tmp_path, monkeypatch) -> None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_skips_oversized_attachment_file(tmp_path, monkeypatch) -> None:
|
||||
"""Attachment exceeding max_attachment_size is skipped with a visible note."""
|
||||
sent_messages: list[EmailMessage] = []
|
||||
|
||||
class FakeSMTP:
|
||||
@@ -1820,7 +1763,6 @@ async def test_send_skips_oversized_attachment_file(tmp_path, monkeypatch) -> No
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_limits_outbound_attachment_count(tmp_path, monkeypatch) -> None:
|
||||
"""Only max_attachments_per_email outbound attachments are included."""
|
||||
sent_messages: list[EmailMessage] = []
|
||||
|
||||
class FakeSMTP:
|
||||
@@ -1874,7 +1816,6 @@ async def test_send_limits_outbound_attachment_count(tmp_path, monkeypatch) -> N
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_unknown_mime_type_attachment(tmp_path, monkeypatch) -> None:
|
||||
"""File with unknown extension gets application/octet-stream MIME type."""
|
||||
sent_messages: list[EmailMessage] = []
|
||||
|
||||
class FakeSMTP:
|
||||
@@ -1927,7 +1868,6 @@ async def test_send_with_unknown_mime_type_attachment(tmp_path, monkeypatch) ->
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_media_and_reply_subject_and_in_reply_to(tmp_path, monkeypatch) -> None:
|
||||
"""Attachments work together with reply subject and In-Reply-To headers."""
|
||||
sent_messages: list[EmailMessage] = []
|
||||
|
||||
class FakeSMTP:
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Email setup validation owned by the channel package."""
|
||||
|
||||
import imaplib
|
||||
import smtplib
|
||||
import ssl
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Feishu/Lark channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Dependency-free Feishu configuration model shared by management and runtime."""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Short-lived WebUI channel connection sessions."""
|
||||
|
||||
# pyright: reportPrivateUsage=false
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Feishu-owned helpers for its persisted multi-instance configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Dependency-free Feishu/Lark management contract."""
|
||||
|
||||
from nanobot.channels._manifest import DIRECT_GROUP_POLICIES, field, required_fields
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.feishu.instances import FEISHU_MANAGEMENT
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection."""
|
||||
# pyright: reportMissingModuleSource=false, reportMissingTypeStubs=false
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -49,7 +48,7 @@ from nanobot.utils.helpers import safe_filename
|
||||
from nanobot.utils.logging_bridge import redirect_lib_logging
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from lark_oapi.api.im.v1.model import ( # pyright: ignore[reportMissingTypeStubs]
|
||||
from lark_oapi.api.im.v1.model import (
|
||||
MentionEvent,
|
||||
P2ImMessageReceiveV1,
|
||||
)
|
||||
@@ -64,12 +63,10 @@ def _identity_timestamp() -> str:
|
||||
|
||||
|
||||
def _as_json_object(value: Any) -> dict[str, Any] | None:
|
||||
"""Narrow untyped SDK/JSON objects at the channel boundary."""
|
||||
return cast(dict[str, Any], value) if isinstance(value, dict) else None
|
||||
|
||||
|
||||
def _as_json_list(value: Any) -> list[Any] | None:
|
||||
"""Narrow untyped SDK/JSON arrays at the channel boundary."""
|
||||
return cast(list[Any], value) if isinstance(value, list) else None
|
||||
|
||||
|
||||
@@ -91,9 +88,9 @@ def _load_lark_runtime() -> tuple[Any, str, str]:
|
||||
# close the same loop.
|
||||
with _LARK_RUNTIME_LOCK:
|
||||
ws_client_already_imported = "lark_oapi.ws.client" in sys.modules
|
||||
import lark_oapi as lark # pyright: ignore[reportMissingTypeStubs]
|
||||
import lark_oapi.ws.client as lark_ws_client # pyright: ignore[reportMissingTypeStubs]
|
||||
from lark_oapi.core.const import ( # pyright: ignore[reportMissingTypeStubs]
|
||||
import lark_oapi as lark
|
||||
import lark_oapi.ws.client as lark_ws_client
|
||||
from lark_oapi.core.const import (
|
||||
FEISHU_DOMAIN,
|
||||
LARK_DOMAIN,
|
||||
)
|
||||
@@ -131,7 +128,7 @@ def fetch_feishu_app_identity(
|
||||
|
||||
try:
|
||||
lark, feishu_domain, lark_domain = _load_lark_runtime()
|
||||
from lark_oapi.api.application.v6.model.get_application_request import ( # pyright: ignore[reportMissingTypeStubs]
|
||||
from lark_oapi.api.application.v6.model.get_application_request import (
|
||||
GetApplicationRequest,
|
||||
)
|
||||
|
||||
@@ -167,7 +164,6 @@ def fetch_feishu_app_identity(
|
||||
return {}
|
||||
|
||||
|
||||
# Message type display mapping
|
||||
MSG_TYPE_MAP = {
|
||||
"image": "[image]",
|
||||
"audio": "[audio]",
|
||||
@@ -177,7 +173,6 @@ MSG_TYPE_MAP = {
|
||||
|
||||
|
||||
def _extract_share_card_content(content_json: dict[str, Any], msg_type: str) -> str:
|
||||
"""Extract text representation from share cards and interactive messages."""
|
||||
parts: list[str] = []
|
||||
|
||||
if msg_type == "share_chat":
|
||||
@@ -197,7 +192,6 @@ def _extract_share_card_content(content_json: dict[str, Any], msg_type: str) ->
|
||||
|
||||
|
||||
def _extract_interactive_content(content: str | dict[str, Any]) -> list[str]:
|
||||
"""Recursively extract text and links from interactive card content."""
|
||||
parts: list[str] = []
|
||||
|
||||
if isinstance(content, str):
|
||||
@@ -232,19 +226,16 @@ def _extract_interactive_content(content: str | dict[str, Any]) -> list[str]:
|
||||
elif isinstance(title, str):
|
||||
parts.append(f"title: {title}")
|
||||
|
||||
# Top-level elements: flat list or nested list format
|
||||
elements = content.get("elements")
|
||||
elements_list = _as_json_list(elements)
|
||||
if elements_list is not None:
|
||||
if elements_list and isinstance(elements_list[0], list):
|
||||
# Nested list: [[{tag:"text",text:"..."}], ...]
|
||||
for row in elements_list:
|
||||
row_list = _as_json_list(row)
|
||||
if row_list is not None:
|
||||
for element in row_list:
|
||||
parts.extend(_extract_element_content(element))
|
||||
else:
|
||||
# Flat list: [{tag:"markdown",content:"..."}, ...]
|
||||
for element in elements_list:
|
||||
parts.extend(_extract_element_content(element))
|
||||
|
||||
@@ -275,7 +266,6 @@ def _extract_interactive_content(content: str | dict[str, Any]) -> list[str]:
|
||||
|
||||
|
||||
def _extract_element_content(element: Any) -> list[str]:
|
||||
"""Extract content from a single card element."""
|
||||
parts: list[str] = []
|
||||
|
||||
element_object = _as_json_object(element)
|
||||
@@ -397,13 +387,6 @@ def _extract_element_content(element: Any) -> list[str]:
|
||||
|
||||
|
||||
def _extract_post_content(content_json: dict[str, Any]) -> tuple[str, list[str]]:
|
||||
"""Extract text and image keys from Feishu post (rich text) message.
|
||||
|
||||
Handles three payload shapes:
|
||||
- Direct: {"title": "...", "content": [[...]]}
|
||||
- Localized: {"zh_cn": {"title": "...", "content": [...]}}
|
||||
- Wrapped: {"post": {"zh_cn": {"title": "...", "content": [...]}}}
|
||||
"""
|
||||
|
||||
def _parse_block(block: dict[str, Any]) -> tuple[str | None, list[str]]:
|
||||
content = _as_json_list(block.get("content"))
|
||||
@@ -442,19 +425,16 @@ def _extract_post_content(content_json: dict[str, Any]) -> tuple[str, list[str]]
|
||||
images.append(key)
|
||||
return (" ".join(texts).strip() or None), images
|
||||
|
||||
# Unwrap optional {"post": ...} envelope
|
||||
root = content_json
|
||||
post = _as_json_object(root.get("post"))
|
||||
if post is not None:
|
||||
root = post
|
||||
|
||||
# Direct format
|
||||
if "content" in root:
|
||||
text, imgs = _parse_block(root)
|
||||
if text or imgs:
|
||||
return text or "", imgs
|
||||
|
||||
# Localized: prefer known locales, then fall back to any dict child
|
||||
for key in ("zh_cn", "en_us", "ja_jp"):
|
||||
if key in root:
|
||||
block = _as_json_object(root[key])
|
||||
@@ -473,13 +453,6 @@ def _extract_post_content(content_json: dict[str, Any]) -> tuple[str, list[str]]
|
||||
return "", []
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# QR scan-to-create onboarding
|
||||
#
|
||||
# Device-code flow: user scans a QR code with the Feishu/Lark mobile app and
|
||||
# the platform creates a fully configured bot application automatically.
|
||||
# =============================================================================
|
||||
|
||||
_ONBOARD_ACCOUNTS_URLS = {
|
||||
"feishu": "https://accounts.feishu.cn",
|
||||
"lark": "https://accounts.larksuite.com",
|
||||
@@ -523,7 +496,6 @@ def _post_registration(base_url: str, body: dict[str, str]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _init_registration(domain: str = "feishu") -> None:
|
||||
"""Verify the environment supports client_secret auth. Raises RuntimeError if not."""
|
||||
base_url = _accounts_base_url(domain)
|
||||
res = _post_registration(base_url, {"action": "init"})
|
||||
methods = _as_json_list(res.get("supported_auth_methods")) or []
|
||||
@@ -535,7 +507,6 @@ def _init_registration(domain: str = "feishu") -> None:
|
||||
|
||||
|
||||
def _begin_registration(domain: str = "feishu") -> _RegistrationStart:
|
||||
"""Start the device-code flow. Returns device_code, qr_url, interval, expire_in."""
|
||||
base_url = _accounts_base_url(domain)
|
||||
res = _post_registration(base_url, {
|
||||
"action": "begin",
|
||||
@@ -575,10 +546,6 @@ def _poll_registration(
|
||||
expire_in: int,
|
||||
domain: str = "feishu",
|
||||
) -> dict[str, Any] | None:
|
||||
"""Poll until the user scans the QR code, or timeout/denial.
|
||||
|
||||
Returns dict with app_id, app_secret, domain on success, None on failure.
|
||||
"""
|
||||
deadline = time.monotonic() + expire_in
|
||||
current_domain = domain
|
||||
|
||||
@@ -602,7 +569,6 @@ def _poll_registration(
|
||||
_LOGIN_CONSOLE.print("[yellow]Authorization was cancelled or expired.[/yellow]")
|
||||
return None
|
||||
|
||||
# authorization_pending or unknown — keep polling
|
||||
time.sleep(interval)
|
||||
|
||||
_LOGIN_CONSOLE.print("[yellow]Authorization timed out.[/yellow]")
|
||||
@@ -895,7 +861,6 @@ def qr_register(
|
||||
|
||||
|
||||
def _print_qr_code(url: str) -> None:
|
||||
"""Print QR code as ASCII art if qrcode package is available, otherwise print URL."""
|
||||
try:
|
||||
import qrcode as qr_lib
|
||||
|
||||
@@ -915,7 +880,6 @@ def _qr_register_inner(
|
||||
*,
|
||||
initial_domain: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Run init → begin → poll. Raises on network/protocol errors."""
|
||||
_LOGIN_CONSOLE.print("[cyan]Preparing Feishu/Lark login...[/cyan]")
|
||||
_init_registration(initial_domain)
|
||||
begin = _begin_registration(initial_domain)
|
||||
@@ -963,7 +927,7 @@ class FeishuChannel(BaseChannel):
|
||||
name = "feishu"
|
||||
display_name = "Feishu"
|
||||
|
||||
_STREAM_EDIT_INTERVAL = 0.5 # throttle between CardKit streaming updates
|
||||
_STREAM_EDIT_INTERVAL = 0.5
|
||||
|
||||
@classmethod
|
||||
def default_config(cls) -> dict[str, Any]:
|
||||
@@ -992,16 +956,13 @@ class FeishuChannel(BaseChannel):
|
||||
self._client: Any = None
|
||||
self._ws_client: Any = None
|
||||
self._ws_runner = get_feishu_ws_runner()
|
||||
self._processed_message_ids: OrderedDict[str, None] = OrderedDict() # Ordered dedup cache
|
||||
self._processed_message_ids: OrderedDict[str, None] = OrderedDict()
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._stream_bufs: dict[str, _FeishuStreamBuf] = {}
|
||||
self._bot_open_id: str | None = None
|
||||
self._background_tasks: set[asyncio.Task[Any]] = set()
|
||||
self._reaction_ids: dict[str, str] = {} # message_id → reaction_id
|
||||
self._reaction_ids: dict[str, str] = {}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# QR login — writes credentials directly to config.json
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def login(self, force: bool = False) -> bool:
|
||||
"""Perform QR code scan-to-create login for Feishu/Lark.
|
||||
@@ -1090,7 +1051,6 @@ class FeishuChannel(BaseChannel):
|
||||
self._running = True
|
||||
self._loop = asyncio.get_running_loop()
|
||||
|
||||
# Create Lark client for sending messages
|
||||
domain = lark_domain if self.config.domain == "lark" else feishu_domain
|
||||
self._client = (
|
||||
lark.Client.builder()
|
||||
@@ -1132,7 +1092,6 @@ class FeishuChannel(BaseChannel):
|
||||
)
|
||||
event_handler = builder.build()
|
||||
|
||||
# Create WebSocket client for long connection
|
||||
self._ws_client = lark.ws.Client(
|
||||
self.config.app_id,
|
||||
self.config.app_secret,
|
||||
@@ -1143,7 +1102,6 @@ class FeishuChannel(BaseChannel):
|
||||
|
||||
await self._ws_runner.start_client(self.name, self._ws_client)
|
||||
|
||||
# Fetch bot's own open_id for accurate @mention matching
|
||||
self._bot_open_id = await asyncio.get_running_loop().run_in_executor(
|
||||
None, self._fetch_bot_open_id
|
||||
)
|
||||
@@ -1155,7 +1113,6 @@ class FeishuChannel(BaseChannel):
|
||||
self.logger.info("bot started with WebSocket long connection")
|
||||
self.logger.info("No public IP required - using WebSocket to receive events")
|
||||
|
||||
# Keep running until stopped
|
||||
while self._running:
|
||||
await asyncio.sleep(1)
|
||||
|
||||
@@ -1172,7 +1129,6 @@ class FeishuChannel(BaseChannel):
|
||||
self.logger.info("bot stopped")
|
||||
|
||||
def _fetch_bot_open_id(self) -> str | None:
|
||||
"""Fetch the bot's own open_id via GET /open-apis/bot/v3/info."""
|
||||
try:
|
||||
import lark_oapi as lark
|
||||
|
||||
@@ -1230,7 +1186,6 @@ class FeishuChannel(BaseChannel):
|
||||
user_id = user_id_obj.user_id
|
||||
name = mention.name or key
|
||||
|
||||
# Format: @姓名 (open_id, user_id: xxx)
|
||||
if open_id and user_id:
|
||||
replacement = f"@{name} ({open_id}, user id: {user_id})"
|
||||
elif open_id:
|
||||
@@ -1252,13 +1207,11 @@ class FeishuChannel(BaseChannel):
|
||||
if bot_open_id:
|
||||
return mention_open_id == bot_open_id
|
||||
|
||||
# Fallback heuristic when bot open_id is unavailable.
|
||||
return not getattr(mid, "user_id", None) and mention_open_id.startswith("ou_")
|
||||
|
||||
def _strip_leading_bot_mention(
|
||||
self, text: str, mentions: list[MentionEvent] | None
|
||||
) -> str:
|
||||
"""Remove a required leading bot mention before slash command routing."""
|
||||
if not mentions or not text:
|
||||
return text
|
||||
|
||||
@@ -1276,7 +1229,6 @@ class FeishuChannel(BaseChannel):
|
||||
return text
|
||||
|
||||
def _is_bot_mentioned(self, message: Any) -> bool:
|
||||
"""Check if the bot is @mentioned in the message."""
|
||||
raw_content = message.content or ""
|
||||
if "@_all" in raw_content:
|
||||
return True
|
||||
@@ -1287,13 +1239,11 @@ class FeishuChannel(BaseChannel):
|
||||
return False
|
||||
|
||||
def _is_group_message_for_bot(self, message: Any) -> bool:
|
||||
"""Allow group messages when policy is open or bot is @mentioned."""
|
||||
if self.config.group_policy == "open":
|
||||
return True
|
||||
return self._is_bot_mentioned(message)
|
||||
|
||||
def _add_reaction_sync(self, message_id: str, emoji_type: str) -> str | None:
|
||||
"""Sync helper for adding reaction (runs in thread pool)."""
|
||||
from lark_oapi.api.im.v1 import (
|
||||
CreateMessageReactionRequest,
|
||||
CreateMessageReactionRequestBody,
|
||||
@@ -1327,14 +1277,6 @@ class FeishuChannel(BaseChannel):
|
||||
return None
|
||||
|
||||
async def _add_reaction(self, message_id: str, emoji_type: str = "THUMBSUP") -> str | None:
|
||||
"""Add a reaction emoji to a message.
|
||||
|
||||
Returns the reaction_id on success, None on failure.
|
||||
When called via a tracked background task, the returned reaction_id
|
||||
is stored in ``_reaction_ids`` for later cleanup by ``send_delta``.
|
||||
|
||||
Common emoji types: THUMBSUP, OK, EYES, DONE, OnIt, HEART
|
||||
"""
|
||||
if not self._client:
|
||||
return None
|
||||
|
||||
@@ -1342,7 +1284,6 @@ class FeishuChannel(BaseChannel):
|
||||
return await loop.run_in_executor(None, self._add_reaction_sync, message_id, emoji_type)
|
||||
|
||||
def _remove_reaction_sync(self, message_id: str, reaction_id: str) -> None:
|
||||
"""Sync helper for removing reaction (runs in thread pool)."""
|
||||
from lark_oapi.api.im.v1 import DeleteMessageReactionRequest
|
||||
|
||||
try:
|
||||
@@ -1364,11 +1305,6 @@ class FeishuChannel(BaseChannel):
|
||||
self.logger.debug("Error removing reaction: {}", e)
|
||||
|
||||
async def _remove_reaction(self, message_id: str, reaction_id: str) -> None:
|
||||
"""
|
||||
Remove a reaction emoji from a message (non-blocking).
|
||||
|
||||
Used to clear the "processing" indicator after bot replies.
|
||||
"""
|
||||
if not self._client or not reaction_id:
|
||||
return
|
||||
|
||||
@@ -1376,7 +1312,6 @@ class FeishuChannel(BaseChannel):
|
||||
await loop.run_in_executor(None, self._remove_reaction_sync, message_id, reaction_id)
|
||||
|
||||
def _on_background_task_done(self, task: asyncio.Task[Any]) -> None:
|
||||
"""Callback: remove from tracking set and log unhandled exceptions."""
|
||||
self._background_tasks.discard(task)
|
||||
if task.cancelled():
|
||||
return
|
||||
@@ -1386,7 +1321,6 @@ class FeishuChannel(BaseChannel):
|
||||
self.logger.warning("Background task failed: {}", exc)
|
||||
|
||||
def _on_reaction_added(self, message_id: str, task: asyncio.Task[Any]) -> None:
|
||||
"""Callback: store reaction_id after background add-reaction completes."""
|
||||
if task.cancelled():
|
||||
return
|
||||
# Failures already logged by _on_background_task_done.
|
||||
@@ -1394,7 +1328,6 @@ class FeishuChannel(BaseChannel):
|
||||
reaction_id = task.result()
|
||||
if reaction_id:
|
||||
self._reaction_ids[message_id] = reaction_id
|
||||
# Trim cache to prevent unbounded growth
|
||||
if len(self._reaction_ids) > 500:
|
||||
self._reaction_ids.pop(next(iter(self._reaction_ids)))
|
||||
|
||||
@@ -1404,7 +1337,6 @@ class FeishuChannel(BaseChannel):
|
||||
meta = metadata or {}
|
||||
return meta.get("message_id") or chat_id
|
||||
|
||||
# Regex to match markdown tables (header + separator + data rows)
|
||||
_TABLE_RE = re.compile(
|
||||
r"((?:^[ \t]*\|.+\|[ \t]*\n)(?:^[ \t]*\|[-:\s|]+\|[ \t]*\n)(?:^[ \t]*\|.+\|[ \t]*\n?)+)",
|
||||
re.MULTILINE,
|
||||
@@ -1414,8 +1346,6 @@ class FeishuChannel(BaseChannel):
|
||||
|
||||
_CODE_BLOCK_RE = re.compile(r"(```[\s\S]*?```)", re.MULTILINE)
|
||||
|
||||
# Markdown formatting patterns that should be stripped from plain-text
|
||||
# surfaces like table cells and heading text.
|
||||
_MD_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
|
||||
_MD_BOLD_UNDERSCORE_RE = re.compile(r"__(.+?)__")
|
||||
_MD_ITALIC_RE = re.compile(r"(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)")
|
||||
@@ -1428,12 +1358,9 @@ class FeishuChannel(BaseChannel):
|
||||
Feishu table cells do not support markdown rendering, so we remove
|
||||
the formatting markers to keep the text readable.
|
||||
"""
|
||||
# Remove bold markers
|
||||
text = cls._MD_BOLD_RE.sub(r"\1", text)
|
||||
text = cls._MD_BOLD_UNDERSCORE_RE.sub(r"\1", text)
|
||||
# Remove italic markers
|
||||
text = cls._MD_ITALIC_RE.sub(r"\1", text)
|
||||
# Remove strikethrough markers
|
||||
text = cls._MD_STRIKE_RE.sub(r"\1", text)
|
||||
return text
|
||||
|
||||
@@ -1463,7 +1390,6 @@ class FeishuChannel(BaseChannel):
|
||||
}
|
||||
|
||||
def _build_card_elements(self, content: str) -> list[dict[str, Any]]:
|
||||
"""Split content into div/markdown + table elements for Feishu card."""
|
||||
protected = content
|
||||
code_blocks: list[str] = []
|
||||
for m in self._CODE_BLOCK_RE.finditer(content):
|
||||
@@ -1522,7 +1448,6 @@ class FeishuChannel(BaseChannel):
|
||||
return groups or [[]]
|
||||
|
||||
def _split_headings(self, content: str) -> list[dict[str, Any]]:
|
||||
"""Split content by headings, converting headings to div elements."""
|
||||
protected = content
|
||||
code_blocks: list[str] = []
|
||||
for m in self._CODE_BLOCK_RE.finditer(content):
|
||||
@@ -1558,37 +1483,29 @@ class FeishuChannel(BaseChannel):
|
||||
|
||||
return elements or [{"tag": "markdown", "content": content}]
|
||||
|
||||
# ── Smart format detection ──────────────────────────────────────────
|
||||
# Patterns that indicate "complex" markdown needing card rendering
|
||||
_COMPLEX_MD_RE = re.compile(
|
||||
r"```" # fenced code block
|
||||
r"|^\|.+\|.*\n\s*\|[-:\s|]+\|" # markdown table (header + separator)
|
||||
r"|^#{1,6}\s+", # headings
|
||||
r"```"
|
||||
r"|^\|.+\|.*\n\s*\|[-:\s|]+\|"
|
||||
r"|^#{1,6}\s+",
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
# Simple markdown patterns (bold, italic, strikethrough)
|
||||
_SIMPLE_MD_RE = re.compile(
|
||||
r"\*\*.+?\*\*" # **bold**
|
||||
r"|__.+?__" # __bold__
|
||||
r"|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)" # *italic* (single *)
|
||||
r"|~~.+?~~", # ~~strikethrough~~
|
||||
r"\*\*.+?\*\*"
|
||||
r"|__.+?__"
|
||||
r"|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)"
|
||||
r"|~~.+?~~",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
# Markdown link: [text](url)
|
||||
_MD_LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\)]+)\)")
|
||||
|
||||
# Unordered list items
|
||||
_LIST_RE = re.compile(r"^[\s]*[-*+]\s+", re.MULTILINE)
|
||||
|
||||
# Ordered list items
|
||||
_OLIST_RE = re.compile(r"^[\s]*\d+\.\s+", re.MULTILINE)
|
||||
|
||||
# Max length for plain text format
|
||||
_TEXT_MAX_LEN = 200
|
||||
|
||||
# Max length for post (rich text) format; beyond this, use card
|
||||
_POST_MAX_LEN = 2000
|
||||
|
||||
@classmethod
|
||||
@@ -1602,11 +1519,9 @@ class FeishuChannel(BaseChannel):
|
||||
"""
|
||||
stripped = content.strip()
|
||||
|
||||
# Complex markdown (code blocks, tables, headings) → always card
|
||||
if cls._COMPLEX_MD_RE.search(stripped):
|
||||
return "interactive"
|
||||
|
||||
# Long content → card (better readability with card layout)
|
||||
if len(stripped) > cls._POST_MAX_LEN:
|
||||
return "interactive"
|
||||
|
||||
@@ -1622,11 +1537,9 @@ class FeishuChannel(BaseChannel):
|
||||
if cls._MD_LINK_RE.search(stripped):
|
||||
return "post"
|
||||
|
||||
# Short plain text → text format
|
||||
if len(stripped) <= cls._TEXT_MAX_LEN:
|
||||
return "text"
|
||||
|
||||
# Medium plain text without any formatting → post format
|
||||
return "post"
|
||||
|
||||
@classmethod
|
||||
@@ -1644,7 +1557,6 @@ class FeishuChannel(BaseChannel):
|
||||
last_end = 0
|
||||
|
||||
for m in cls._MD_LINK_RE.finditer(line):
|
||||
# Text before this link
|
||||
before = line[last_end : m.start()]
|
||||
if before:
|
||||
elements.append({"tag": "text", "text": before})
|
||||
@@ -1657,12 +1569,10 @@ class FeishuChannel(BaseChannel):
|
||||
)
|
||||
last_end = m.end()
|
||||
|
||||
# Remaining text after last link
|
||||
remaining = line[last_end:]
|
||||
if remaining:
|
||||
elements.append({"tag": "text", "text": remaining})
|
||||
|
||||
# Empty line → empty paragraph for spacing
|
||||
if not elements:
|
||||
elements.append({"tag": "text", "text": ""})
|
||||
|
||||
@@ -1691,7 +1601,6 @@ class FeishuChannel(BaseChannel):
|
||||
}
|
||||
|
||||
def _upload_image_sync(self, file_path: str) -> str | None:
|
||||
"""Upload an image to Feishu and return the image_key."""
|
||||
from lark_oapi.api.im.v1 import CreateImageRequest, CreateImageRequestBody
|
||||
|
||||
try:
|
||||
@@ -1718,7 +1627,6 @@ class FeishuChannel(BaseChannel):
|
||||
return None
|
||||
|
||||
def _upload_file_sync(self, file_path: str) -> str | None:
|
||||
"""Upload a file to Feishu and return the file_key."""
|
||||
from lark_oapi.api.im.v1 import CreateFileRequest, CreateFileRequestBody
|
||||
|
||||
ext = os.path.splitext(file_path)[1].lower()
|
||||
@@ -1754,7 +1662,6 @@ class FeishuChannel(BaseChannel):
|
||||
def _download_image_sync(
|
||||
self, message_id: str, image_key: str
|
||||
) -> tuple[bytes | None, str | None]:
|
||||
"""Download an image from Feishu message by message_id and image_key."""
|
||||
from lark_oapi.api.im.v1 import GetMessageResourceRequest
|
||||
|
||||
try:
|
||||
@@ -1784,7 +1691,6 @@ class FeishuChannel(BaseChannel):
|
||||
def _download_file_sync(
|
||||
self, message_id: str, file_key: str, resource_type: str = "file"
|
||||
) -> tuple[bytes | None, str | None]:
|
||||
"""Download a file/audio/media from a Feishu message by message_id and file_key."""
|
||||
from lark_oapi.api.im.v1 import GetMessageResourceRequest
|
||||
|
||||
# Feishu resource download API only accepts 'image' or 'file' as type.
|
||||
@@ -1834,12 +1740,6 @@ class FeishuChannel(BaseChannel):
|
||||
async def _download_and_save_media(
|
||||
self, msg_type: str, content_json: dict[str, Any], message_id: str | None = None
|
||||
) -> tuple[str | None, str]:
|
||||
"""
|
||||
Download media from Feishu and save to local disk.
|
||||
|
||||
Returns:
|
||||
(file_path, content_text) - file_path is None if download failed
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
media_dir = get_media_dir("feishu")
|
||||
|
||||
@@ -1896,10 +1796,6 @@ class FeishuChannel(BaseChannel):
|
||||
_REPLY_CONTEXT_MAX_LEN = 200
|
||||
|
||||
def _get_message_content_sync(self, message_id: str) -> str | None:
|
||||
"""Fetch the text content of a Feishu message by ID (synchronous).
|
||||
|
||||
Returns a "[Reply to: ...]" context string, or None on failure.
|
||||
"""
|
||||
from lark_oapi.api.im.v1 import GetMessageRequest
|
||||
|
||||
try:
|
||||
@@ -1943,12 +1839,6 @@ class FeishuChannel(BaseChannel):
|
||||
return None
|
||||
|
||||
def _reply_message_sync(self, parent_message_id: str, msg_type: str, content: str, *, reply_in_thread: bool = False) -> bool:
|
||||
"""Reply to an existing Feishu message using the Reply API (synchronous).
|
||||
|
||||
Args:
|
||||
reply_in_thread: If True, reply as a thread/topic message
|
||||
in the Feishu client.
|
||||
"""
|
||||
from lark_oapi.api.im.v1 import ReplyMessageRequest, ReplyMessageRequestBody
|
||||
|
||||
try:
|
||||
@@ -2060,11 +1950,9 @@ class FeishuChannel(BaseChannel):
|
||||
return last_message_id
|
||||
|
||||
def _should_use_reply_in_thread(self, metadata: dict[str, Any]) -> bool:
|
||||
"""Return whether a group reply should create a Feishu thread/topic."""
|
||||
return metadata.get("chat_type", "group") == "group" and self.config.reply_to_message
|
||||
|
||||
def _thread_reply_target(self, metadata: dict[str, Any]) -> str | None:
|
||||
"""Return the message_id that should receive a Reply API response."""
|
||||
if metadata.get("chat_type", "group") != "group":
|
||||
return None
|
||||
message_id = metadata.get("message_id")
|
||||
@@ -2077,7 +1965,6 @@ class FeishuChannel(BaseChannel):
|
||||
def _send_message_sync(
|
||||
self, receive_id_type: str, receive_id: str, msg_type: str, content: str
|
||||
) -> str | None:
|
||||
"""Send a single message and return the message_id on success."""
|
||||
from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody
|
||||
|
||||
try:
|
||||
@@ -2124,13 +2011,6 @@ class FeishuChannel(BaseChannel):
|
||||
*,
|
||||
reply_in_thread: bool = False,
|
||||
) -> str | None:
|
||||
"""Create a CardKit streaming card, send it to chat, return card_id.
|
||||
|
||||
When *reply_message_id* is provided the card is delivered via the
|
||||
reply API. *reply_in_thread* controls whether Feishu creates a
|
||||
thread/topic for that reply. Otherwise the plain create-message API is
|
||||
used.
|
||||
"""
|
||||
from lark_oapi.api.cardkit.v1 import CreateCardRequest, CreateCardRequestBody
|
||||
|
||||
card_json = {
|
||||
@@ -2182,7 +2062,6 @@ class FeishuChannel(BaseChannel):
|
||||
return None
|
||||
|
||||
def _stream_update_text_sync(self, card_id: str, content: str, sequence: int) -> bool:
|
||||
"""Stream-update the markdown element on a CardKit card (typewriter effect)."""
|
||||
from lark_oapi.api.cardkit.v1 import (
|
||||
ContentCardElementRequest,
|
||||
ContentCardElementRequestBody,
|
||||
@@ -2295,7 +2174,6 @@ class FeishuChannel(BaseChannel):
|
||||
loop = asyncio.get_running_loop()
|
||||
rid_type = "chat_id" if chat_id.startswith("oc_") else "open_id"
|
||||
|
||||
# --- stream end: final update or fallback ---
|
||||
if stream_end and merge_next:
|
||||
if not delta:
|
||||
return
|
||||
@@ -2311,7 +2189,6 @@ class FeishuChannel(BaseChannel):
|
||||
reaction_id = self._reaction_ids.pop(message_id, None)
|
||||
if reaction_id:
|
||||
await self._remove_reaction(message_id, reaction_id)
|
||||
# Add completion emoji if configured
|
||||
if self.config.done_emoji:
|
||||
await self._add_reaction(message_id, self.config.done_emoji)
|
||||
|
||||
@@ -2384,7 +2261,6 @@ class FeishuChannel(BaseChannel):
|
||||
)
|
||||
return
|
||||
|
||||
# --- accumulate delta ---
|
||||
buf = self._stream_bufs.get(stream_key)
|
||||
if buf is None:
|
||||
buf = _FeishuStreamBuf()
|
||||
@@ -2395,8 +2271,6 @@ class FeishuChannel(BaseChannel):
|
||||
|
||||
now = time.monotonic()
|
||||
if buf.card_id is None:
|
||||
# Use the Reply API for existing topics, and only create new topics
|
||||
# when reply-to-message is enabled.
|
||||
use_reply_in_thread = self._should_use_reply_in_thread(meta)
|
||||
reply_msg_id = self._thread_reply_target(meta)
|
||||
card_id = await loop.run_in_executor(
|
||||
@@ -2453,9 +2327,6 @@ class FeishuChannel(BaseChannel):
|
||||
receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
# Handle tool hint messages. When a streaming card is active for
|
||||
# this chat, inline the hint into the card instead of sending a
|
||||
# separate message so the user experience stays cohesive.
|
||||
progress_event = msg.event if isinstance(msg.event, ProgressEvent) else None
|
||||
|
||||
if progress_event and progress_event.tool_hint:
|
||||
@@ -2472,9 +2343,6 @@ class FeishuChannel(BaseChannel):
|
||||
metadata=msg.metadata,
|
||||
)
|
||||
return
|
||||
# No active streaming card — send as a regular interactive card
|
||||
# with the same 🔧 prefix style. Existing topics stay threaded;
|
||||
# new topics are created only when reply-to-message is enabled.
|
||||
card = json.dumps(
|
||||
{"config": {"wide_screen_mode": True}, "elements": [
|
||||
{"tag": "markdown", "content": self._format_tool_hint_delta(hint)},
|
||||
@@ -2513,11 +2381,10 @@ class FeishuChannel(BaseChannel):
|
||||
has_thread_id = msg.metadata.get("thread_id")
|
||||
if self.config.reply_to_message and progress_event is None:
|
||||
reply_message_id = _msg_id
|
||||
# For topic group messages, always reply to keep context in thread
|
||||
elif has_thread_id:
|
||||
reply_message_id = _msg_id
|
||||
|
||||
first_send = True # tracks whether the reply has already been used
|
||||
first_send = True
|
||||
|
||||
def _do_send(m_type: str, content: str) -> None:
|
||||
"""Send via reply (first message) or create (subsequent).
|
||||
@@ -2528,7 +2395,6 @@ class FeishuChannel(BaseChannel):
|
||||
"""
|
||||
nonlocal first_send
|
||||
if reply_message_id:
|
||||
# If we're in a topic, always use reply to stay in the topic
|
||||
if has_thread_id:
|
||||
ok = self._reply_message_sync(
|
||||
reply_message_id, m_type, content,
|
||||
@@ -2537,7 +2403,6 @@ class FeishuChannel(BaseChannel):
|
||||
if ok:
|
||||
return
|
||||
elif first_send:
|
||||
# If we're not in a topic but replying to message, only first uses reply
|
||||
first_send = False
|
||||
ok = self._reply_message_sync(
|
||||
reply_message_id, m_type, content,
|
||||
@@ -2545,7 +2410,6 @@ class FeishuChannel(BaseChannel):
|
||||
)
|
||||
if ok:
|
||||
return
|
||||
# Fall back to regular send if reply fails
|
||||
message_id = self._send_message_sync(
|
||||
receive_id_type,
|
||||
msg.chat_id,
|
||||
@@ -2593,17 +2457,14 @@ class FeishuChannel(BaseChannel):
|
||||
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
|
||||
text_body = json.dumps({"text": msg.content.strip()}, ensure_ascii=False)
|
||||
await loop.run_in_executor(None, _do_send, "text", text_body)
|
||||
|
||||
elif fmt == "post":
|
||||
# Medium content with links – send as rich-text post
|
||||
post_body = self._markdown_to_post(msg.content)
|
||||
await loop.run_in_executor(None, _do_send, "post", post_body)
|
||||
|
||||
else:
|
||||
# Complex / long content – send as interactive card
|
||||
elements = self._build_card_elements(msg.content)
|
||||
for chunk in self._split_elements_by_table_limit(elements):
|
||||
card = {"config": {"wide_screen_mode": True}, "elements": chunk}
|
||||
@@ -2619,17 +2480,12 @@ class FeishuChannel(BaseChannel):
|
||||
raise
|
||||
|
||||
def _on_message_sync(self, data: Any) -> None:
|
||||
"""
|
||||
Sync handler for incoming messages (called from WebSocket thread).
|
||||
Schedules async handling in the main event loop.
|
||||
"""
|
||||
if not self._running:
|
||||
return
|
||||
if self._loop and self._loop.is_running():
|
||||
asyncio.run_coroutine_threadsafe(self._on_message(data), self._loop)
|
||||
|
||||
async def _on_message(self, data: P2ImMessageReceiveV1) -> None:
|
||||
"""Handle incoming message from Feishu."""
|
||||
if not self._running:
|
||||
return
|
||||
try:
|
||||
@@ -2645,7 +2501,6 @@ class FeishuChannel(BaseChannel):
|
||||
|
||||
message_id = message.message_id
|
||||
|
||||
# Skip bot messages
|
||||
if sender.sender_type == "bot":
|
||||
return
|
||||
|
||||
@@ -2672,12 +2527,10 @@ class FeishuChannel(BaseChannel):
|
||||
self.logger.debug("skipping group message (not mentioned)")
|
||||
return
|
||||
|
||||
# Deduplication check
|
||||
if message_id in self._processed_message_ids:
|
||||
return
|
||||
self._processed_message_ids[message_id] = None
|
||||
|
||||
# Trim cache
|
||||
while len(self._processed_message_ids) > 1000:
|
||||
self._processed_message_ids.popitem(last=False)
|
||||
|
||||
@@ -2695,7 +2548,6 @@ class FeishuChannel(BaseChannel):
|
||||
)
|
||||
return
|
||||
|
||||
# Add reaction (non-blocking — tracked background task)
|
||||
task = asyncio.create_task(
|
||||
self._add_reaction(message_id, self.config.react_emoji)
|
||||
)
|
||||
@@ -2703,7 +2555,6 @@ class FeishuChannel(BaseChannel):
|
||||
task.add_done_callback(self._on_background_task_done)
|
||||
task.add_done_callback(lambda t: self._on_reaction_added(message_id, t))
|
||||
|
||||
# Parse content
|
||||
content_parts: list[str] = []
|
||||
media_paths: list[str] = []
|
||||
|
||||
@@ -2726,7 +2577,6 @@ class FeishuChannel(BaseChannel):
|
||||
text, image_keys = _extract_post_content(content_json)
|
||||
if text:
|
||||
content_parts.append(text)
|
||||
# Download images embedded in post
|
||||
for img_key in image_keys:
|
||||
file_path, content_text = await self._download_and_save_media(
|
||||
"image", {"image_key": img_key}, message_id
|
||||
@@ -2757,7 +2607,6 @@ class FeishuChannel(BaseChannel):
|
||||
"system",
|
||||
"merge_forward",
|
||||
):
|
||||
# Handle share cards and interactive messages
|
||||
text = _extract_share_card_content(content_json, msg_type)
|
||||
if text:
|
||||
content_parts.append(text)
|
||||
@@ -2765,7 +2614,6 @@ class FeishuChannel(BaseChannel):
|
||||
else:
|
||||
content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]"))
|
||||
|
||||
# Extract reply context (parent/root message IDs)
|
||||
parent_id = getattr(message, "parent_id", None)
|
||||
root_id = getattr(message, "root_id", None)
|
||||
thread_id = getattr(message, "thread_id", None)
|
||||
@@ -2773,7 +2621,6 @@ class FeishuChannel(BaseChannel):
|
||||
root_id = root_id if isinstance(root_id, str) else None
|
||||
thread_id = thread_id if isinstance(thread_id, str) else None
|
||||
|
||||
# Prepend quoted message text when the user replied to another message
|
||||
if parent_id and self._client:
|
||||
loop = asyncio.get_running_loop()
|
||||
reply_ctx = await loop.run_in_executor(
|
||||
@@ -2810,7 +2657,6 @@ class FeishuChannel(BaseChannel):
|
||||
else:
|
||||
session_key = None
|
||||
|
||||
# Forward to message bus
|
||||
reply_to = chat_id if chat_type == "group" else sender_id
|
||||
await self._handle_message(
|
||||
sender_id=sender_id,
|
||||
@@ -2833,19 +2679,15 @@ class FeishuChannel(BaseChannel):
|
||||
self.logger.exception("Error processing message")
|
||||
|
||||
def _on_reaction_created(self, data: Any) -> None:
|
||||
"""Ignore reaction events so they do not generate SDK noise."""
|
||||
pass
|
||||
|
||||
def _on_reaction_deleted(self, data: Any) -> None:
|
||||
"""Ignore reaction deleted events so they do not generate SDK noise."""
|
||||
pass
|
||||
|
||||
def _on_message_read(self, data: Any) -> None:
|
||||
"""Ignore read events so they do not generate SDK noise."""
|
||||
pass
|
||||
|
||||
def _on_bot_p2p_chat_entered(self, data: Any) -> None:
|
||||
"""Ignore p2p-enter events when a user opens a bot chat."""
|
||||
self.logger.debug("Bot entered p2p chat (user opened chat window)")
|
||||
pass
|
||||
|
||||
@@ -2896,7 +2738,6 @@ class FeishuChannel(BaseChannel):
|
||||
return "\n".join(part for part in parts if part)
|
||||
|
||||
def _format_tool_hint_delta(self, tool_hint: str) -> str:
|
||||
"""Format a tool hint string with the 🔧 prefix for each line."""
|
||||
lines = self.__class__._format_tool_hint_lines(tool_hint).split("\n")
|
||||
return "\n".join(
|
||||
f"{self.config.tool_hint_prefix} {ln}" for ln in lines if ln.strip()
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the Feishu channel package."""
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Tests for Feishu/Lark domain configuration."""
|
||||
from unittest.mock import ANY, AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# Check optional Feishu dependencies before running tests
|
||||
try:
|
||||
from nanobot.channels.feishu.runtime import FEISHU_AVAILABLE
|
||||
except ImportError:
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for Feishu _is_bot_mentioned logic."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from nanobot.channels.feishu.runtime import FeishuChannel
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for FeishuChannel._resolve_mentions."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from nanobot.channels.feishu.runtime import FeishuChannel
|
||||
@@ -26,7 +24,6 @@ class TestResolveMentions:
|
||||
assert "@Bob (ou_abc, user id: uid_456)" in result
|
||||
|
||||
def test_mention_no_id_skipped(self):
|
||||
"""When mention has no id object, the placeholder is left unchanged."""
|
||||
text = "@_user_1 said hi"
|
||||
mentions = [SimpleNamespace(key="@_user_1", name="Charlie", id=None)]
|
||||
result = FeishuChannel._resolve_mentions(text, mentions)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# Check optional Feishu dependencies before running tests
|
||||
try:
|
||||
from nanobot.channels.feishu import runtime as feishu
|
||||
FEISHU_AVAILABLE = getattr(feishu, "FEISHU_AVAILABLE", False)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
# ruff: noqa: E402
|
||||
|
||||
"""Tests for Feishu reaction add/remove and auto-cleanup on stream end."""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
@@ -37,9 +36,6 @@ def _mock_reaction_create_response(reaction_id: str = "reaction_001", success: b
|
||||
return resp
|
||||
|
||||
|
||||
# ── _add_reaction_sync ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAddReactionSync:
|
||||
def test_returns_reaction_id_on_success(self):
|
||||
ch = _make_channel()
|
||||
@@ -66,9 +62,6 @@ class TestAddReactionSync:
|
||||
assert ch._add_reaction_sync("om_001", "THUMBSUP") is None
|
||||
|
||||
|
||||
# ── _add_reaction (async) ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAddReactionAsync:
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_reaction_id(self):
|
||||
@@ -85,9 +78,6 @@ class TestAddReactionAsync:
|
||||
assert result is None
|
||||
|
||||
|
||||
# ── _remove_reaction_sync ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRemoveReactionSync:
|
||||
def test_calls_delete_on_success(self):
|
||||
ch = _make_channel()
|
||||
@@ -107,7 +97,6 @@ class TestRemoveReactionSync:
|
||||
resp.msg = "not found"
|
||||
ch._client.im.v1.message_reaction.delete.return_value = resp
|
||||
|
||||
# Should not raise
|
||||
ch._remove_reaction_sync("om_001", "rx_42")
|
||||
ch._client.im.v1.message_reaction.delete.assert_called_once()
|
||||
|
||||
@@ -115,14 +104,10 @@ class TestRemoveReactionSync:
|
||||
ch = _make_channel()
|
||||
ch._client.im.v1.message_reaction.delete.side_effect = RuntimeError("network error")
|
||||
|
||||
# Should not raise
|
||||
ch._remove_reaction_sync("om_001", "rx_42")
|
||||
ch._client.im.v1.message_reaction.delete.assert_called_once()
|
||||
|
||||
|
||||
# ── _remove_reaction (async) ────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRemoveReactionAsync:
|
||||
@pytest.mark.asyncio
|
||||
async def test_calls_sync_helper(self):
|
||||
@@ -144,9 +129,6 @@ class TestRemoveReactionAsync:
|
||||
ch._remove_reaction_sync.assert_not_called()
|
||||
|
||||
|
||||
# ── send_delta stream end: reaction auto-cleanup ────────────────────────────
|
||||
|
||||
|
||||
class TestStreamEndReactionCleanup:
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_buffers_are_scoped_by_message_id(self):
|
||||
@@ -227,7 +209,6 @@ class TestStreamEndReactionCleanup:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_removal_when_resuming(self):
|
||||
"""resuming=True means more tool-call rounds follow; reaction must persist."""
|
||||
ch = _make_channel()
|
||||
ch.config.done_emoji = "DONE"
|
||||
ch._reaction_ids["om_001"] = "rx_42"
|
||||
@@ -243,19 +224,16 @@ class TestStreamEndReactionCleanup:
|
||||
|
||||
ch._remove_reaction.assert_not_called()
|
||||
ch._add_reaction.assert_not_called()
|
||||
# OnIt reaction id is still tracked for the eventual final stream end
|
||||
assert ch._reaction_ids.get("om_001") == "rx_42"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_done_emoji_only_on_final_stream_end(self):
|
||||
"""Across resuming rounds, done_emoji is added only on the final round."""
|
||||
ch = _make_channel()
|
||||
ch.config.done_emoji = "DONE"
|
||||
ch._reaction_ids.update({"om_001": "rx_42", "om_other": "rx_other"})
|
||||
ch._remove_reaction = AsyncMock()
|
||||
ch._add_reaction = AsyncMock()
|
||||
|
||||
# Intermediate stream end (more tool calls coming).
|
||||
await ch.send_delta(
|
||||
"oc_chat1", "",
|
||||
metadata={"message_id": "om_001"},
|
||||
@@ -267,7 +245,6 @@ class TestStreamEndReactionCleanup:
|
||||
|
||||
assert ch._reaction_ids == {"om_001": "rx_42", "om_other": "rx_other"}
|
||||
|
||||
# Final stream end (resuming=False): OnIt removed, done_emoji added.
|
||||
await ch.send_delta(
|
||||
"oc_chat1", "",
|
||||
metadata={"message_id": "om_001"},
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Tests for Feishu message reply (quote) feature."""
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -7,7 +6,6 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# Check optional Feishu dependencies before running tests
|
||||
try:
|
||||
from nanobot.channels.feishu import runtime as feishu
|
||||
FEISHU_AVAILABLE = getattr(feishu, "FEISHU_AVAILABLE", False)
|
||||
@@ -22,9 +20,6 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_feishu_channel(
|
||||
reply_to_message: bool = False,
|
||||
@@ -42,7 +37,6 @@ def _make_feishu_channel(
|
||||
)
|
||||
channel = FeishuChannel(config, MessageBus())
|
||||
channel._client = MagicMock()
|
||||
# _loop is only used by the WebSocket thread bridge; not needed for unit tests
|
||||
channel._loop = None
|
||||
channel._running = True
|
||||
return channel
|
||||
@@ -90,10 +84,6 @@ def _make_get_message_response(text: str, msg_type: str = "text", success: bool
|
||||
return resp
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_feishu_config_reply_to_message_defaults_false() -> None:
|
||||
assert FeishuConfig().reply_to_message is False
|
||||
|
||||
@@ -158,10 +148,6 @@ def test_feishu_config_topic_isolation_accepts_camel_case() -> None:
|
||||
assert config.topic_isolation is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _get_message_content_sync tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_get_message_content_sync_returns_reply_prefix() -> None:
|
||||
channel = _make_feishu_channel()
|
||||
channel._client.im.v1.message.get.return_value = _make_get_message_response("what time is it?")
|
||||
@@ -221,10 +207,6 @@ def test_get_message_content_sync_returns_none_when_empty_text() -> None:
|
||||
assert result is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _reply_message_sync tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_reply_message_sync_returns_true_on_success() -> None:
|
||||
channel = _make_feishu_channel()
|
||||
resp = MagicMock()
|
||||
@@ -332,10 +314,6 @@ async def test_send_uses_expected_feishu_msg_type_for_uploaded_files(
|
||||
assert json.loads(content) == {"file_key": "file-key"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# send() — reply routing tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_uses_reply_api_when_configured() -> None:
|
||||
channel = _make_feishu_channel(reply_to_message=True)
|
||||
@@ -435,7 +413,6 @@ async def test_send_fallback_to_create_when_reply_fails() -> None:
|
||||
metadata={"message_id": "om_001"},
|
||||
))
|
||||
|
||||
# reply attempted first, then falls back to create
|
||||
channel._client.im.v1.message.reply.assert_called_once()
|
||||
channel._client.im.v1.message.create.assert_called_once()
|
||||
|
||||
@@ -489,7 +466,6 @@ def test_send_message_sync_falls_back_to_text_for_interactive_error() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_multiple_messages_all_use_reply_when_in_topic(tmp_path: Path) -> None:
|
||||
"""When in a topic (has thread_id), all messages use reply API to stay in topic."""
|
||||
channel = _make_feishu_channel(reply_to_message=False)
|
||||
|
||||
file1 = tmp_path / "file1.png"
|
||||
@@ -524,14 +500,12 @@ async def test_send_multiple_messages_all_use_reply_when_in_topic(tmp_path: Path
|
||||
},
|
||||
))
|
||||
|
||||
# All 3 sends (text + 2 images) should use reply
|
||||
assert len(reply_calls) == 3
|
||||
assert len(create_calls) == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_multiple_messages_only_first_uses_reply_when_reply_to_message(tmp_path: Path) -> None:
|
||||
"""When reply_to_message is enabled but not in topic, only first message uses reply."""
|
||||
channel = _make_feishu_channel(reply_to_message=True)
|
||||
|
||||
file1 = tmp_path / "file1.png"
|
||||
@@ -565,15 +539,10 @@ async def test_send_multiple_messages_only_first_uses_reply_when_reply_to_messag
|
||||
},
|
||||
))
|
||||
|
||||
# Only first send uses reply, rest use create
|
||||
assert len(reply_calls) == 1
|
||||
assert len(create_calls) == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _on_message — parent_id / root_id metadata tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_captures_parent_and_root_id_in_metadata() -> None:
|
||||
channel = _make_feishu_channel()
|
||||
@@ -792,11 +761,6 @@ async def test_on_message_keeps_longer_mention_key_that_shares_bot_prefix() -> N
|
||||
assert captured[0]["content"] == "@Alice (ou_alice) /new @nanobot (ou_bot)"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Inbound media tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_audio_publishes_downloaded_path_and_transcription() -> None:
|
||||
channel = _make_feishu_channel()
|
||||
@@ -844,14 +808,8 @@ async def test_download_and_save_media_returns_absolute_path_in_content(monkeypa
|
||||
assert content_text == f"[audio: {file_path}]"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Session key derivation tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_key_group_with_root_id_is_thread_scoped() -> None:
|
||||
"""Group message with root_id gets a thread-scoped session key."""
|
||||
channel = _make_feishu_channel(group_policy="open")
|
||||
bus_spy = []
|
||||
original_publish = channel.bus.publish_inbound
|
||||
@@ -879,7 +837,6 @@ async def test_session_key_group_with_root_id_is_thread_scoped() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_key_group_no_root_id_uses_message_id() -> None:
|
||||
"""Group message without root_id gets session keyed by message_id (per-message session)."""
|
||||
channel = _make_feishu_channel(group_policy="open")
|
||||
bus_spy = []
|
||||
original_publish = channel.bus.publish_inbound
|
||||
@@ -907,7 +864,6 @@ async def test_session_key_group_no_root_id_uses_message_id() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_key_named_instance_uses_runtime_channel_namespace() -> None:
|
||||
"""Named Feishu assistant instances keep group sessions separate."""
|
||||
channel = _make_feishu_channel(group_policy="open")
|
||||
channel.name = "feishu.product"
|
||||
bus_spy = []
|
||||
@@ -937,7 +893,6 @@ async def test_session_key_named_instance_uses_runtime_channel_namespace() -> No
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_key_private_chat_no_override() -> None:
|
||||
"""Private chat never overrides session key (consistent with Telegram/Slack)."""
|
||||
channel = _make_feishu_channel()
|
||||
bus_spy = []
|
||||
original_publish = channel.bus.publish_inbound
|
||||
@@ -963,14 +918,8 @@ async def test_session_key_private_chat_no_override() -> None:
|
||||
assert bus_spy[0].session_key_override is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# reply_in_thread tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reply_uses_reply_in_thread_when_enabled() -> None:
|
||||
"""When reply_to_message is True, reply includes reply_in_thread=True."""
|
||||
channel = _make_feishu_channel(reply_to_message=True)
|
||||
|
||||
reply_resp = MagicMock()
|
||||
@@ -992,7 +941,6 @@ async def test_reply_uses_reply_in_thread_when_enabled() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reply_without_reply_in_thread_when_disabled() -> None:
|
||||
"""When reply_to_message is False, reply does NOT use reply_in_thread."""
|
||||
channel = _make_feishu_channel(reply_to_message=False)
|
||||
|
||||
create_resp = MagicMock()
|
||||
@@ -1005,13 +953,11 @@ async def test_reply_without_reply_in_thread_when_disabled() -> None:
|
||||
content="hello",
|
||||
))
|
||||
|
||||
# No message_id in metadata → no reply attempt, direct create
|
||||
channel._client.im.v1.message.create.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_topic_reply_does_not_force_reply_in_thread_when_disabled() -> None:
|
||||
"""Topic replies must not create new Feishu topics when reply_to_message is False."""
|
||||
channel = _make_feishu_channel(reply_to_message=False)
|
||||
|
||||
reply_resp = MagicMock()
|
||||
@@ -1037,7 +983,6 @@ async def test_topic_reply_does_not_force_reply_in_thread_when_disabled() -> Non
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reply_keeps_fallback_when_reply_fails() -> None:
|
||||
"""Even with reply_to_message=True, fallback to create on reply failure."""
|
||||
channel = _make_feishu_channel(reply_to_message=True)
|
||||
|
||||
reply_resp = MagicMock()
|
||||
@@ -1063,7 +1008,6 @@ async def test_reply_keeps_fallback_when_reply_fails() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reply_no_reply_in_thread_for_p2p_chat() -> None:
|
||||
"""reply_in_thread should NOT be set for p2p chats (identified by chat_type)."""
|
||||
channel = _make_feishu_channel(reply_to_message=True)
|
||||
|
||||
reply_resp = MagicMock()
|
||||
@@ -1085,7 +1029,6 @@ async def test_reply_no_reply_in_thread_for_p2p_chat() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reply_uses_reply_in_thread_for_group_chat() -> None:
|
||||
"""reply_in_thread should be True for group chats (identified by chat_type)."""
|
||||
channel = _make_feishu_channel(reply_to_message=True)
|
||||
|
||||
reply_resp = MagicMock()
|
||||
@@ -1131,13 +1074,11 @@ async def test_reply_targets_message_id_when_in_topic() -> None:
|
||||
channel._client.im.v1.message.reply.assert_called_once()
|
||||
call_args = channel._client.im.v1.message.reply.call_args
|
||||
request = call_args[0][0]
|
||||
# Should reply to the inbound message_id, not the root
|
||||
assert request.message_id == "om_child456"
|
||||
assert request.request_body.reply_in_thread is True
|
||||
|
||||
|
||||
def test_on_reaction_added_stores_reaction_id() -> None:
|
||||
"""_on_reaction_added stores the returned reaction_id in _reaction_ids."""
|
||||
channel = _make_feishu_channel()
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
@@ -1151,7 +1092,6 @@ def test_on_reaction_added_stores_reaction_id() -> None:
|
||||
|
||||
|
||||
def test_on_reaction_added_skips_none_result() -> None:
|
||||
"""_on_reaction_added does not store None results."""
|
||||
channel = _make_feishu_channel()
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
@@ -1165,7 +1105,6 @@ def test_on_reaction_added_skips_none_result() -> None:
|
||||
|
||||
|
||||
def test_on_background_task_done_removes_from_set() -> None:
|
||||
"""_on_background_task_done removes task from tracking set."""
|
||||
channel = _make_feishu_channel()
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
@@ -1177,7 +1116,7 @@ def test_on_background_task_done_removes_from_set() -> None:
|
||||
try:
|
||||
loop.run_until_complete(task)
|
||||
except RuntimeError:
|
||||
pass # expected
|
||||
pass
|
||||
channel._on_background_task_done(task)
|
||||
finally:
|
||||
loop.close()
|
||||
@@ -1186,7 +1125,6 @@ def test_on_background_task_done_removes_from_set() -> None:
|
||||
|
||||
|
||||
def test_on_message_sync_ignores_events_after_channel_stops() -> None:
|
||||
"""Late WebSocket callbacks should not schedule work after the assistant is off."""
|
||||
channel = _make_feishu_channel()
|
||||
channel._running = False
|
||||
channel._loop = MagicMock()
|
||||
@@ -1200,7 +1138,6 @@ def test_on_message_sync_ignores_events_after_channel_stops() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_ignores_events_after_channel_stops() -> None:
|
||||
"""Stopped assistants must not react, pair, or publish stale Feishu events."""
|
||||
channel = _make_feishu_channel(group_policy="open")
|
||||
channel._running = False
|
||||
channel._add_reaction = AsyncMock()
|
||||
@@ -1214,7 +1151,6 @@ async def test_on_message_ignores_events_after_channel_stops() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_unauthorized_dm_sends_pairing_code_without_side_effects() -> None:
|
||||
"""Unauthorized DM sender gets a pairing code but no media side effects."""
|
||||
channel = _make_feishu_channel(group_policy="open")
|
||||
channel.config.allow_from = ["ou_allowed"]
|
||||
channel._add_reaction = AsyncMock()
|
||||
@@ -1233,13 +1169,11 @@ async def test_on_message_unauthorized_dm_sends_pairing_code_without_side_effect
|
||||
channel._add_reaction.assert_not_awaited()
|
||||
channel._download_and_save_media.assert_not_awaited()
|
||||
channel.transcribe_audio.assert_not_awaited()
|
||||
# _handle_message is called to issue the pairing code in DMs
|
||||
channel._handle_message.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_unauthorized_group_ignored_before_side_effects() -> None:
|
||||
"""Unauthorized group chat sender is silently ignored before any side effects."""
|
||||
channel = _make_feishu_channel(group_policy="open")
|
||||
channel.config.allow_from = ["ou_allowed"]
|
||||
channel._add_reaction = AsyncMock()
|
||||
@@ -1264,7 +1198,6 @@ async def test_on_message_unauthorized_group_ignored_before_side_effects() -> No
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_key_with_topic_isolation_true_uses_thread_scoped() -> None:
|
||||
"""When topic_isolation is True (default), group messages use thread-scoped session keys."""
|
||||
channel = _make_feishu_channel(group_policy="open", topic_isolation=True)
|
||||
bus_spy = []
|
||||
original_publish = channel.bus.publish_inbound
|
||||
@@ -1278,7 +1211,6 @@ async def test_session_key_with_topic_isolation_true_uses_thread_scoped() -> Non
|
||||
channel.transcribe_audio = AsyncMock(return_value="")
|
||||
channel._add_reaction = AsyncMock(return_value=None)
|
||||
|
||||
# Test with root_id
|
||||
event1 = _make_feishu_event(
|
||||
chat_type="group",
|
||||
content='{"text": "hello"}',
|
||||
@@ -1287,7 +1219,6 @@ async def test_session_key_with_topic_isolation_true_uses_thread_scoped() -> Non
|
||||
)
|
||||
await channel._on_message(event1)
|
||||
|
||||
# Test without root_id
|
||||
event2 = _make_feishu_event(
|
||||
chat_type="group",
|
||||
content='{"text": "another"}',
|
||||
@@ -1303,7 +1234,6 @@ async def test_session_key_with_topic_isolation_true_uses_thread_scoped() -> Non
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_key_with_topic_isolation_false_uses_group_scoped() -> None:
|
||||
"""When topic_isolation is False, all group messages share the same session key (no isolation)."""
|
||||
channel = _make_feishu_channel(group_policy="open", topic_isolation=False)
|
||||
bus_spy = []
|
||||
original_publish = channel.bus.publish_inbound
|
||||
@@ -1317,7 +1247,6 @@ async def test_session_key_with_topic_isolation_false_uses_group_scoped() -> Non
|
||||
channel.transcribe_audio = AsyncMock(return_value="")
|
||||
channel._add_reaction = AsyncMock(return_value=None)
|
||||
|
||||
# Test with root_id
|
||||
event1 = _make_feishu_event(
|
||||
chat_type="group",
|
||||
content='{"text": "hello"}',
|
||||
@@ -1326,7 +1255,6 @@ async def test_session_key_with_topic_isolation_false_uses_group_scoped() -> Non
|
||||
)
|
||||
await channel._on_message(event1)
|
||||
|
||||
# Test without root_id
|
||||
event2 = _make_feishu_event(
|
||||
chat_type="group",
|
||||
content='{"text": "another"}',
|
||||
@@ -1335,7 +1263,6 @@ async def test_session_key_with_topic_isolation_false_uses_group_scoped() -> Non
|
||||
)
|
||||
await channel._on_message(event2)
|
||||
|
||||
# Private chat still works
|
||||
event3 = _make_feishu_event(
|
||||
chat_type="p2p",
|
||||
content='{"text": "private"}',
|
||||
@@ -1345,8 +1272,6 @@ async def test_session_key_with_topic_isolation_false_uses_group_scoped() -> Non
|
||||
await channel._on_message(event3)
|
||||
|
||||
assert len(bus_spy) == 3
|
||||
# Group messages all share the same key
|
||||
assert bus_spy[0].session_key_override == "feishu:oc_abc"
|
||||
assert bus_spy[1].session_key_override == "feishu:oc_abc"
|
||||
# Private chat has no session key override
|
||||
assert bus_spy[2].session_key_override is None
|
||||
@@ -1,6 +1,5 @@
|
||||
# ruff: noqa: E402
|
||||
|
||||
"""Tests for Feishu streaming (send_delta) via CardKit streaming API."""
|
||||
import json
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
@@ -285,7 +284,7 @@ class TestSendDelta:
|
||||
ch._client.cardkit.v1.card_element.content.assert_called_once()
|
||||
ch._client.cardkit.v1.card.settings.assert_called_once()
|
||||
settings_call = ch._client.cardkit.v1.card.settings.call_args[0][0]
|
||||
assert settings_call.body.sequence == 5 # after final content seq 4
|
||||
assert settings_call.body.sequence == 5
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_end_merge_next_preserves_buffer(self):
|
||||
@@ -310,7 +309,6 @@ class TestSendDelta:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_end_fallback_when_no_card_id(self):
|
||||
"""If card creation failed, stream_end falls back to a plain card message."""
|
||||
ch = _make_channel()
|
||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
||||
text="Fallback content", card_id=None, sequence=0, last_edit=0.0,
|
||||
@@ -391,7 +389,6 @@ class TestSendDelta:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_end_fallback_when_final_update_fails(self):
|
||||
"""If streaming mode was closed (e.g. Feishu timeout), fall back to a regular card."""
|
||||
ch = _make_channel()
|
||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
||||
text="Lost content", card_id="card_1", sequence=3, last_edit=0.0,
|
||||
@@ -403,7 +400,6 @@ class TestSendDelta:
|
||||
|
||||
assert "oc_chat1" not in ch._stream_bufs
|
||||
assert ch._client.cardkit.v1.card.settings.call_count == 2
|
||||
# Should fall back to sending a regular interactive card
|
||||
ch._client.im.v1.message.create.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -456,17 +452,15 @@ class TestSendDelta:
|
||||
await ch.send_delta("oc_chat1", "b")
|
||||
assert buf.sequence == 6
|
||||
|
||||
buf.last_edit = 0.0 # reset to bypass throttle
|
||||
buf.last_edit = 0.0
|
||||
await ch.send_delta("oc_chat1", "c")
|
||||
assert buf.sequence == 7
|
||||
|
||||
|
||||
class TestToolHintInlineStreaming:
|
||||
"""Tool hint messages should be inlined into active streaming cards."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_hint_inlined_when_stream_active(self):
|
||||
"""With an active streaming buffer, tool hint appends to the card."""
|
||||
ch = _make_channel()
|
||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
||||
text="Partial answer", card_id="card_1", sequence=2, last_edit=0.0,
|
||||
@@ -488,7 +482,6 @@ class TestToolHintInlineStreaming:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_hint_preserved_on_next_delta(self):
|
||||
"""When new delta arrives, the tool hint is kept as permanent content and delta appends after it."""
|
||||
ch = _make_channel()
|
||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
||||
text="Partial answer\n\n🔧 web_fetch(\"url\")\n\n",
|
||||
@@ -505,7 +498,6 @@ class TestToolHintInlineStreaming:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_hint_fallback_when_no_stream(self):
|
||||
"""Without an active buffer, tool hint falls back to a standalone card."""
|
||||
ch = _make_channel()
|
||||
ch._client.im.v1.message.create.return_value = _mock_send_response("om_hint")
|
||||
|
||||
@@ -590,7 +582,6 @@ class TestToolHintInlineStreaming:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_consecutive_tool_hints_append(self):
|
||||
"""When multiple tool hints arrive consecutively, each appends to the card."""
|
||||
ch = _make_channel()
|
||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
||||
text="Partial answer", card_id="card_1", sequence=2, last_edit=0.0,
|
||||
@@ -620,7 +611,6 @@ class TestToolHintInlineStreaming:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_hint_preserved_on_final_stream_end(self):
|
||||
"""When stream end closes the card, tool hint is kept in the final text."""
|
||||
ch = _make_channel()
|
||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
||||
text="Final content\n\n🔧 web_fetch(\"url\")\n\n",
|
||||
@@ -637,7 +627,6 @@ class TestToolHintInlineStreaming:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_tool_hint_is_noop(self):
|
||||
"""Empty or whitespace-only tool hint content is silently ignored."""
|
||||
ch = _make_channel()
|
||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
||||
text="Partial answer", card_id="card_1", sequence=2, last_edit=0.0,
|
||||
|
||||
@@ -6,7 +6,6 @@ list of card elements into groups so that each group contains at most one
|
||||
table, allowing nanobot to send multiple cards instead of failing.
|
||||
"""
|
||||
|
||||
# Check optional Feishu dependencies before running tests
|
||||
try:
|
||||
from nanobot.channels import feishu
|
||||
FEISHU_AVAILABLE = getattr(feishu, "FEISHU_AVAILABLE", False)
|
||||
@@ -54,7 +53,6 @@ def test_single_table_stays_in_one_group() -> None:
|
||||
|
||||
|
||||
def test_two_tables_split_into_two_groups() -> None:
|
||||
# Use different row values so the two tables are not equal
|
||||
t1 = {
|
||||
"tag": "table",
|
||||
"columns": [{"tag": "column", "name": "c0", "display_name": "A", "width": "auto"}],
|
||||
@@ -70,10 +68,8 @@ def test_two_tables_split_into_two_groups() -> None:
|
||||
els = [_md("before"), t1, _md("between"), t2, _md("after")]
|
||||
result = split(els)
|
||||
assert len(result) == 2
|
||||
# First group: text before table-1 + table-1
|
||||
assert t1 in result[0]
|
||||
assert t2 not in result[0]
|
||||
# Second group: text between tables + table-2 + text after
|
||||
assert t2 in result[1]
|
||||
assert t1 not in result[1]
|
||||
|
||||
@@ -110,6 +106,5 @@ def test_non_table_elements_before_first_table_kept_in_first_group() -> None:
|
||||
head = _md("head")
|
||||
t1, t2 = _table(), _table()
|
||||
result = split([head, t1, t2])
|
||||
# head + t1 in group 0; t2 in group 1
|
||||
assert result[0] == [head, t1]
|
||||
assert result[1] == [t2]
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Tests for FeishuChannel tool hint formatting."""
|
||||
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from pytest import mark
|
||||
|
||||
# Check optional Feishu dependencies before running tests
|
||||
try:
|
||||
from nanobot.channels import feishu
|
||||
FEISHU_AVAILABLE = getattr(feishu, "FEISHU_AVAILABLE", False)
|
||||
@@ -29,7 +26,7 @@ def mock_feishu_channel():
|
||||
config.app_secret = "test_app_secret"
|
||||
config.encrypt_key = None
|
||||
config.verification_token = None
|
||||
config.tool_hint_prefix = "\U0001f527" # 🔧
|
||||
config.tool_hint_prefix = "\U0001f527"
|
||||
bus = MagicMock()
|
||||
channel = FeishuChannel(config, bus)
|
||||
channel._client = MagicMock()
|
||||
@@ -46,7 +43,6 @@ def _get_tool_hint_card(mock_send):
|
||||
|
||||
@mark.asyncio
|
||||
async def test_tool_hint_sends_interactive_card(mock_feishu_channel):
|
||||
"""Tool hint without active buffer sends an interactive card with 🔧 style."""
|
||||
msg = OutboundMessage(
|
||||
channel="feishu",
|
||||
chat_id="oc_123456",
|
||||
@@ -67,11 +63,10 @@ async def test_tool_hint_sends_interactive_card(mock_feishu_channel):
|
||||
|
||||
@mark.asyncio
|
||||
async def test_tool_hint_empty_content_does_not_send(mock_feishu_channel):
|
||||
"""Empty tool hint messages should not be sent."""
|
||||
msg = OutboundMessage(
|
||||
channel="feishu",
|
||||
chat_id="oc_123456",
|
||||
content=" ", # whitespace only
|
||||
content=" ",
|
||||
event=ProgressEvent(tool_hint=True),
|
||||
)
|
||||
|
||||
@@ -82,7 +77,6 @@ async def test_tool_hint_empty_content_does_not_send(mock_feishu_channel):
|
||||
|
||||
@mark.asyncio
|
||||
async def test_tool_hint_without_metadata_sends_as_normal(mock_feishu_channel):
|
||||
"""Regular messages without _tool_hint should use normal formatting."""
|
||||
msg = OutboundMessage(
|
||||
channel="feishu",
|
||||
chat_id="oc_123456",
|
||||
@@ -102,7 +96,6 @@ async def test_tool_hint_without_metadata_sends_as_normal(mock_feishu_channel):
|
||||
|
||||
@mark.asyncio
|
||||
async def test_tool_hint_multiple_tools_in_one_message(mock_feishu_channel):
|
||||
"""Multiple tool calls should each get the 🔧 prefix."""
|
||||
msg = OutboundMessage(
|
||||
channel="feishu",
|
||||
chat_id="oc_123456",
|
||||
@@ -169,7 +162,6 @@ async def test_tool_hint_preserves_arguments(mock_feishu_channel, content, first
|
||||
|
||||
@mark.asyncio
|
||||
async def test_tool_hint_new_format_mcp(mock_feishu_channel):
|
||||
"""MCP tool format (server::tool) should parse correctly."""
|
||||
msg = OutboundMessage(
|
||||
channel="feishu",
|
||||
chat_id="oc_123456",
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Feishu/Lark setup validation owned by the channel package."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Native Linear Agent channel."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Installation-scoped member choices, with non-destructive legacy approval fallback."""
|
||||
|
||||
from nanobot.channels.linear.config import LinearConfig
|
||||
from nanobot.channels.linear.state import LinearStateStore
|
||||
from nanobot.pairing.store import is_approved
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Minimal async Linear OAuth and GraphQL client."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Configuration and URL validation for the native Linear channel."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""WebUI OAuth connection flow for Linear workspace installations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Dependency-free management contract for the native Linear Agent channel."""
|
||||
|
||||
from nanobot.channels._manifest import field, required_fields
|
||||
from nanobot.channels.contracts import ChannelManagementSpec, ChannelSetupSpec
|
||||
from nanobot.channels.linear.state import local_state_present
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""PKCE OAuth flow state for Linear app installations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Native Linear Agent channel runtime."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -612,7 +610,6 @@ def _prompt_text(
|
||||
|
||||
|
||||
def _issue_context(session: dict[str, Any]) -> str:
|
||||
"""Include issue identity even when pairing prevented the initial turn."""
|
||||
issue = _optional_object(session.get("issue"))
|
||||
fields: dict[str, str] = {}
|
||||
for key, limit in (("id", 200), ("identifier", 200), ("title", 500),
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Shared local HTTP listener for Linear webhooks and OAuth callbacks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Durable installation and webhook state owned by the Linear channel."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the native Linear channel."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Keep Linear installation and permission state out of the user's real profile."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Delayed network responses must not restore or overwrite workspace authorizations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -149,14 +147,13 @@ async def test_member_read_cannot_restore_or_overwrite_a_changed_installation(
|
||||
release.set()
|
||||
with pytest.raises(linear_connect.ChannelConnectError, match="authorization changed"):
|
||||
await pending
|
||||
assert "/graphql" not in requests # Never use a discarded refresh result.
|
||||
assert "/graphql" not in requests
|
||||
assert LinearStateStore(state.path).installation("org-1") == expected
|
||||
assert state.installation("org-2") is not None
|
||||
if expected is None:
|
||||
assert state.member_access("client-id", "org-1", "user-1") is None
|
||||
else:
|
||||
assert state.member_access(expected.oauth_client_id, "org-1", "user-1") is False
|
||||
# The genuine removal notice can arrive after the network response.
|
||||
channel, _ = _runtime(tmp_path / "runtime")
|
||||
channel._state = state # pyright: ignore[reportPrivateUsage]
|
||||
channel._process_lifecycle_event({ # pyright: ignore[reportPrivateUsage]
|
||||
@@ -206,7 +203,6 @@ async def test_late_refresh_cannot_overwrite_another_clients_rotation(tmp_path:
|
||||
assert error.value.retryable
|
||||
assert state.installation("org-1") == winner
|
||||
assert state.member_access("client-id", "org-1", "user-1") is False
|
||||
# Retrying reads the winner's credentials, without another rotation.
|
||||
await first.graphql("org-1", "query Test { viewer { id } }", {})
|
||||
assert count == 2
|
||||
assert tokens_used == ["Bearer access-2", "Bearer access-2"]
|
||||
@@ -241,7 +237,6 @@ async def test_normal_refresh_preserves_authorization_and_member_choices(
|
||||
assert rotated is not None and rotated.access_token == "rotated"
|
||||
assert rotated.authorized_at == 1000.0
|
||||
assert reopened.member_access("client-id", "org-1", "user-1") is False
|
||||
# Refresh is not a new grant: a real revocation from before the refresh still wins.
|
||||
assert reopened.delete_installation("org-1", revoked_at=1500.0)
|
||||
|
||||
|
||||
@@ -253,14 +248,13 @@ async def test_forced_refresh_does_not_use_a_different_apps_credentials(tmp_path
|
||||
def handler(_request: httpx.Request) -> httpx.Response:
|
||||
nonlocal requests
|
||||
requests += 1
|
||||
# The app changed while an earlier API request was in flight.
|
||||
state.save_installation(replace(_installation(), oauth_client_id="other-app"))
|
||||
return httpx.Response(401)
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
|
||||
with pytest.raises(LinearApiError, match="authorization changed"):
|
||||
await LinearClient(_config(), state, http).graphql("org-1", "query Test { viewer { id } }", {})
|
||||
assert requests == 1 # No refresh request with another app's token.
|
||||
assert requests == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("replacement", ["reauthorized", "same_tokens", "other_app"])
|
||||
|
||||
@@ -1394,8 +1394,6 @@ def test_delayed_revocation_does_not_remove_new_authorization(tmp_path: Path) ->
|
||||
})
|
||||
state.save_installation(replace(_installation(), access_token="new-access"))
|
||||
state.set_member_access("client-id", "org-1", "user-1", allowed=False)
|
||||
# The channel was stopped during removal, so the old notice is consumed
|
||||
# only after the user has authorized and enabled the channel again.
|
||||
event = state.claim_webhooks()[0]
|
||||
channel._process_lifecycle_event(event.payload) # pyright: ignore[reportPrivateUsage]
|
||||
current = state.installation("org-1")
|
||||
|
||||
@@ -27,7 +27,6 @@ from nanobot.pairing.store import approve_code, generate_code
|
||||
def test_upgrade_preserves_existing_installation_and_pairing(tmp_path: Path) -> None:
|
||||
path = tmp_path / "state.sqlite3"
|
||||
original = _installation()
|
||||
# Schema immediately before member access and authorization-generation tracking.
|
||||
with sqlite3.connect(path) as connection:
|
||||
connection.execute("""CREATE TABLE installations (
|
||||
organization_id TEXT PRIMARY KEY, oauth_client_id TEXT NOT NULL,
|
||||
@@ -55,7 +54,6 @@ def test_upgrade_preserves_existing_installation_and_pairing(tmp_path: Path) ->
|
||||
assert reopened.installation("org-1") == original
|
||||
assert not member_allowed(config, reopened, "org-1", "user-1")
|
||||
with sqlite3.connect(path) as connection:
|
||||
# Additive migration retains the old reader's columns and token values.
|
||||
row = connection.execute(
|
||||
"SELECT access_token, refresh_token, authorized_at FROM installations "
|
||||
"WHERE organization_id = ?", ("org-1",),
|
||||
@@ -73,7 +71,6 @@ def test_member_choice_overrides_legacy_and_survives_restart(tmp_path: Path, leg
|
||||
state.save_installation(_installation())
|
||||
assert member_allowed(config, state, "org-1", "user-1") is (legacy != "none")
|
||||
state.set_member_access(config.client_id, "org-1", "user-1", allowed=False)
|
||||
# A new legacy approval must not resurrect an explicit off switch.
|
||||
approve_code(generate_code("linear", "user-1"))
|
||||
reopened = LinearStateStore(state.path)
|
||||
assert not member_allowed(config, reopened, "org-1", "user-1")
|
||||
@@ -134,7 +131,6 @@ def test_reauthorize_keeps_choices_but_remove_and_reconnect_uses_legacy_fallback
|
||||
state.set_member_access(config.client_id, "org-1", "user-1", allowed=allowed)
|
||||
state.set_member_access(config.client_id, "org-2", "user-1", allowed=not allowed)
|
||||
|
||||
# Reauthorization updates tokens without duplicating the workspace or resetting choices.
|
||||
renewed = replace(first, access_token="renewed", refresh_token="renewed-refresh")
|
||||
state.save_installation(renewed)
|
||||
reopened = LinearStateStore(state.path)
|
||||
@@ -142,7 +138,6 @@ def test_reauthorize_keeps_choices_but_remove_and_reconnect_uses_legacy_fallback
|
||||
assert member_allowed(config, reopened, "org-1", "user-1") is allowed
|
||||
assert member_allowed(config, reopened, "org-2", "user-1") is not allowed
|
||||
|
||||
# Deliberately removing a workspace clears only its explicit choices, not pairing.
|
||||
reopened.delete_installation("org-1")
|
||||
assert not member_allowed(config, reopened, "org-1", "user-1")
|
||||
reopened.save_installation(renewed)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Store operations release SQLite resources without waiting for cyclic GC."""
|
||||
|
||||
import sqlite3
|
||||
from dataclasses import replace
|
||||
|
||||
@@ -61,7 +59,6 @@ def test_store_closes_connections_and_commits_public_operations(tmp_path, connec
|
||||
def test_store_rolls_back_and_closes_after_partial_write(tmp_path, connections):
|
||||
store = LinearStateStore(tmp_path / "state.sqlite3")
|
||||
assert store.enqueue_webhook("delivery", {"type": "original"})
|
||||
# Force the second enqueue statement to fail, after it writes a receipt.
|
||||
with store._connect() as connection:
|
||||
connection.execute("DELETE FROM webhook_receipts WHERE delivery_id = 'delivery'")
|
||||
|
||||
@@ -70,7 +67,6 @@ def test_store_rolls_back_and_closes_after_partial_write(tmp_path, connections):
|
||||
_assert_closed(connections)
|
||||
|
||||
store.complete_webhook("delivery")
|
||||
# The failed enqueue's receipt must have rolled back, not blocked a retry.
|
||||
assert store.enqueue_webhook("delivery", {"type": "retry"})
|
||||
assert store.claim_webhooks()[0].payload == {"type": "retry"}
|
||||
_assert_closed(connections)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Setup validation for Linear's public callback requirements."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Channel manager for coordinating chat channels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -54,7 +52,6 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
def _default_webui_dist() -> Path | None:
|
||||
"""Return the absolute path to the bundled webui dist directory if it exists."""
|
||||
try:
|
||||
import nanobot.web as web_pkg # type: ignore[import-not-found]
|
||||
except ImportError:
|
||||
@@ -63,7 +60,6 @@ def _default_webui_dist() -> Path | None:
|
||||
return candidate if candidate.is_dir() else None
|
||||
|
||||
|
||||
# Upper bounds for local equal-jitter send backoff (1s, 2s, then 4s).
|
||||
_SEND_RETRY_DELAYS = (1, 2, 4)
|
||||
_OUTBOUND_CONCURRENCY = 32
|
||||
_OUTBOUND_PENDING_LIMIT = 256
|
||||
@@ -268,7 +264,6 @@ class ChannelManager:
|
||||
return channel
|
||||
|
||||
def _init_channels(self) -> None:
|
||||
"""Initialize enabled runtimes from dependency-free channel descriptors."""
|
||||
from nanobot.channels.registry import discover_plugins
|
||||
from nanobot.optional_features import ensure_enabled_channel_dependencies
|
||||
|
||||
@@ -380,7 +375,6 @@ class ChannelManager:
|
||||
)
|
||||
|
||||
def _should_send_progress(self, channel_name: str, *, tool_hint: bool = False) -> bool:
|
||||
"""Return whether progress (or tool-hints) may be sent to *channel_name*."""
|
||||
ch = self.channels.get(channel_name)
|
||||
if ch is None:
|
||||
logger.debug("Progress check for unknown channel: {}", channel_name)
|
||||
@@ -388,12 +382,6 @@ class ChannelManager:
|
||||
return ch.send_tool_hints if tool_hint else ch.send_progress
|
||||
|
||||
def _resolve_bool_override(self, section: Any, key: str, default: bool) -> bool:
|
||||
"""Return *key* from *section* if it is a bool, otherwise *default*.
|
||||
|
||||
For dict configs also checks the camelCase alias (e.g. ``sendProgress``
|
||||
for ``send_progress``) so raw JSON/TOML configs work alongside
|
||||
Pydantic models.
|
||||
"""
|
||||
if isinstance(section, dict):
|
||||
section_data = cast(dict[str, Any], section)
|
||||
value = section_data.get(key)
|
||||
@@ -406,7 +394,6 @@ class ChannelManager:
|
||||
return value if isinstance(value, bool) else default
|
||||
|
||||
async def _start_channel(self, name: str, channel: BaseChannel) -> None:
|
||||
"""Start a channel and log any exceptions."""
|
||||
errors = getattr(self, "_channel_errors", None)
|
||||
if errors is None:
|
||||
errors = self._channel_errors = {}
|
||||
@@ -642,21 +629,17 @@ class ChannelManager:
|
||||
return
|
||||
|
||||
self._started = True
|
||||
# Start outbound dispatcher
|
||||
self._dispatch_task = asyncio.create_task(self._dispatch_outbound())
|
||||
|
||||
# Start channels
|
||||
tasks: list[asyncio.Task[None]] = []
|
||||
for name, channel in self.channels.items():
|
||||
tasks.append(self._start_channel_task(name, channel))
|
||||
|
||||
self._notify_restart_done_if_needed()
|
||||
|
||||
# Wait for all to complete (they should run forever)
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
def _notify_restart_done_if_needed(self) -> asyncio.Task[None] | None:
|
||||
"""Schedule restart completion after the target channel starts."""
|
||||
notice = consume_restart_notice_from_env()
|
||||
if not notice:
|
||||
return None
|
||||
@@ -670,7 +653,6 @@ class ChannelManager:
|
||||
timeout_s: float = _RESTART_NOTICE_START_TIMEOUT_S,
|
||||
poll_s: float = _RESTART_NOTICE_START_POLL_S,
|
||||
) -> None:
|
||||
"""Deliver a restart notice after the target channel starts."""
|
||||
await self.bus.admission.wait_until_open()
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + timeout_s
|
||||
@@ -712,7 +694,6 @@ class ChannelManager:
|
||||
logger.info("Stopping all channels...")
|
||||
self._started = False
|
||||
|
||||
# Stop dispatcher
|
||||
if self._dispatch_task:
|
||||
self._dispatch_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
@@ -724,7 +705,6 @@ class ChannelManager:
|
||||
await self._restart_notice_task
|
||||
self._restart_notice_task = None
|
||||
|
||||
# Stop all channels
|
||||
for name in list(self.channels):
|
||||
await self._stop_channel(name)
|
||||
if self._remove_delivery_check is not None:
|
||||
@@ -901,7 +881,6 @@ class ChannelManager:
|
||||
await self._cancel_outbound()
|
||||
|
||||
async def _dispatch_outbound_loop(self) -> None:
|
||||
"""Dispatch outbound messages to the appropriate channel."""
|
||||
logger.info("Outbound dispatcher started")
|
||||
|
||||
# Buffer for messages that couldn't be processed during delta coalescing
|
||||
@@ -918,7 +897,6 @@ class ChannelManager:
|
||||
await self._recover_scheduled()
|
||||
except Exception:
|
||||
logger.exception("Scheduled delivery recovery failed; check the instance delivery store")
|
||||
# First check pending buffer before waiting on queue
|
||||
if pending:
|
||||
msg = pending.pop(0)
|
||||
else:
|
||||
@@ -969,8 +947,6 @@ class ChannelManager:
|
||||
):
|
||||
continue
|
||||
|
||||
# Coalesce consecutive stream delta messages for the same (channel, chat_id)
|
||||
# to reduce API calls and improve streaming latency
|
||||
if isinstance(event, StreamDeltaEvent):
|
||||
msg, extra_pending = self._coalesce_stream_deltas(msg)
|
||||
pending.extend(extra_pending)
|
||||
@@ -1086,14 +1062,6 @@ class ChannelManager:
|
||||
def _coalesce_stream_deltas(
|
||||
self, first_msg: OutboundMessage
|
||||
) -> tuple[OutboundMessage, list[OutboundMessage]]:
|
||||
"""Merge consecutive stream deltas for the same (channel, chat_id, stream_id).
|
||||
|
||||
This reduces the number of API calls when the queue has accumulated multiple
|
||||
deltas, which happens when LLM generates faster than the channel can process.
|
||||
|
||||
Returns:
|
||||
tuple of (merged_message, list_of_non_matching_messages)
|
||||
"""
|
||||
first_event = first_msg.event
|
||||
first_stream_id = first_event.stream_id if isinstance(first_event, StreamDeltaEvent) else None
|
||||
target_key = (first_msg.channel, first_msg.chat_id, first_stream_id)
|
||||
@@ -1113,7 +1081,6 @@ class ChannelManager:
|
||||
except asyncio.QueueEmpty:
|
||||
break
|
||||
|
||||
# Check if this message belongs to the same stream
|
||||
next_event = next_msg.event
|
||||
next_stream_id = (
|
||||
next_event.stream_id
|
||||
@@ -1133,19 +1100,15 @@ class ChannelManager:
|
||||
== first_msg.metadata.get("response_sources")
|
||||
)
|
||||
if same_target and same_response_sources and (is_delta or (is_end and next_msg.content)):
|
||||
# Accumulate content
|
||||
combined_content += next_msg.content
|
||||
# If we see stream_end, remember it and stop coalescing this stream
|
||||
if isinstance(next_event, StreamEndEvent):
|
||||
final_event = StreamEndEvent(
|
||||
stream_id=next_stream_id,
|
||||
resuming=next_event.resuming,
|
||||
merge_next=next_event.merge_next,
|
||||
)
|
||||
# Stream ended - stop coalescing this stream
|
||||
break
|
||||
else:
|
||||
# First non-matching message defines the coalescing boundary.
|
||||
non_matching.append(next_msg)
|
||||
break
|
||||
|
||||
@@ -1159,13 +1122,6 @@ class ChannelManager:
|
||||
*,
|
||||
deadline: float | None = None,
|
||||
) -> None:
|
||||
"""Send a message with retry on failure using exponential backoff.
|
||||
|
||||
When deadline is provided, retry until that monotonic time instead of
|
||||
stopping at the configured attempt limit.
|
||||
|
||||
Note: CancelledError is re-raised to allow graceful shutdown.
|
||||
"""
|
||||
max_attempts = max(self.config.channels.send_max_retries, 1)
|
||||
attempt = 0
|
||||
|
||||
@@ -1186,7 +1142,7 @@ class ChannelManager:
|
||||
await self._send_once(channel, msg)
|
||||
finally:
|
||||
self._outbound_sends.release()
|
||||
return # Send succeeded
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
raise # Propagate cancellation for graceful shutdown
|
||||
except Exception as e:
|
||||
@@ -1224,7 +1180,7 @@ class ChannelManager:
|
||||
try:
|
||||
await asyncio.sleep(delay)
|
||||
except asyncio.CancelledError:
|
||||
raise # Propagate cancellation during sleep
|
||||
raise
|
||||
|
||||
def get_channel(self, name: str) -> BaseChannel | None:
|
||||
"""Get a channel by name."""
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Matrix channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Matrix management contract."""
|
||||
|
||||
from nanobot.channels._manifest import GROUP_POLICIES, field, one_of, required_fields
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.matrix.validation import validate
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Matrix (Element) channel — inbound sync + outbound message/media delivery."""
|
||||
|
||||
# pyright: reportMissingTypeStubs=false
|
||||
|
||||
import asyncio
|
||||
@@ -140,7 +138,6 @@ _MXC_PLACEHOLDER_SRC_RE = re.compile(
|
||||
|
||||
|
||||
def _filter_matrix_html_attribute(tag: str, attr: str, value: str) -> str | None:
|
||||
"""Filter attribute values to a safe Matrix-compatible subset."""
|
||||
if tag == "a" and attr == "href":
|
||||
return value if value.lower().startswith(("https://", "http://", "matrix:", "mailto:")) else None
|
||||
if tag == "img" and attr == "src":
|
||||
@@ -231,7 +228,6 @@ _LISTEN_LINE_MAX_CHARS = 500
|
||||
|
||||
|
||||
def _render_markdown_html(text: str) -> str | None:
|
||||
"""Render markdown to sanitized HTML; returns None for plain text."""
|
||||
try:
|
||||
masked_text = _mask_mxc_markdown_image_sources(text)
|
||||
rendered = _mask_mxc_image_sources(cast(str, MATRIX_MARKDOWN(masked_text)))
|
||||
@@ -240,7 +236,6 @@ def _render_markdown_html(text: str) -> str | None:
|
||||
return None
|
||||
if not formatted:
|
||||
return None
|
||||
# Skip formatted_body for plain <p>text</p> to keep payload minimal.
|
||||
if formatted.startswith("<p>") and formatted.endswith("</p>"):
|
||||
inner = formatted[3:-4]
|
||||
if "<" not in inner and ">" not in inner:
|
||||
@@ -332,7 +327,7 @@ class MatrixChannel(BaseChannel):
|
||||
name = "matrix"
|
||||
display_name = "Matrix"
|
||||
uses_shared_proxy = True
|
||||
_STREAM_EDIT_INTERVAL = 2 # min seconds between edit_message_text calls
|
||||
_STREAM_EDIT_INTERVAL = 2
|
||||
monotonic_time: Callable[[], float] = staticmethod(time.monotonic)
|
||||
|
||||
@classmethod
|
||||
@@ -479,7 +474,6 @@ class MatrixChannel(BaseChannel):
|
||||
await self.client.close()
|
||||
|
||||
def _write_session_to_disk(self, resp: LoginResponse) -> None:
|
||||
"""Save login session to disk for persistence across restarts."""
|
||||
session = {
|
||||
"access_token": resp.access_token,
|
||||
"device_id": resp.device_id,
|
||||
@@ -492,13 +486,11 @@ class MatrixChannel(BaseChannel):
|
||||
self.logger.warning("Failed to save session: {}", e)
|
||||
|
||||
def _is_workspace_path_allowed(self, path: Path) -> bool:
|
||||
"""Check path is inside workspace (when restriction enabled)."""
|
||||
if not self._restrict_to_workspace or not self._workspace:
|
||||
return True
|
||||
return is_path_within(path, self._workspace)
|
||||
|
||||
def _collect_outbound_media_candidates(self, media: list[str]) -> list[Path]:
|
||||
"""Deduplicate and resolve outbound attachment paths."""
|
||||
seen: set[str] = set()
|
||||
candidates: list[Path] = []
|
||||
for raw in media:
|
||||
@@ -541,7 +533,6 @@ class MatrixChannel(BaseChannel):
|
||||
|
||||
async def _send_room_content(self, room_id: str,
|
||||
content: dict[str, Any]) -> None | RoomSendResponse | RoomSendError:
|
||||
"""Send m.room.message with E2EE options."""
|
||||
if not self.client:
|
||||
return None
|
||||
kwargs: dict[str, Any] = {"room_id": room_id, "message_type": "m.room.message", "content": content}
|
||||
@@ -552,7 +543,6 @@ class MatrixChannel(BaseChannel):
|
||||
return response
|
||||
|
||||
async def _resolve_server_upload_limit_bytes(self) -> int | None:
|
||||
"""Query homeserver upload limit once per channel lifecycle."""
|
||||
if self._server_upload_limit_checked:
|
||||
return self._server_upload_limit_bytes
|
||||
self._server_upload_limit_checked = True
|
||||
@@ -570,7 +560,6 @@ class MatrixChannel(BaseChannel):
|
||||
return None
|
||||
|
||||
async def _effective_media_limit_bytes(self) -> int:
|
||||
"""min(local config, server advertised) — 0 blocks all uploads."""
|
||||
local_limit = max(int(self.config.max_media_bytes), 0)
|
||||
server_limit = await self._resolve_server_upload_limit_bytes()
|
||||
if server_limit is None:
|
||||
@@ -581,7 +570,6 @@ class MatrixChannel(BaseChannel):
|
||||
self, room_id: str, path: Path, limit_bytes: int,
|
||||
relates_to: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""Upload one local file to Matrix and send it as a media message. Returns failure marker or None."""
|
||||
if not self.client:
|
||||
return _ATTACH_UPLOAD_FAILED.format(path.name or _DEFAULT_ATTACH_NAME)
|
||||
|
||||
@@ -737,7 +725,6 @@ class MatrixChannel(BaseChannel):
|
||||
raise RuntimeError(f"Matrix stream was not delivered: {response}")
|
||||
buf.last_edit = now
|
||||
if not buf.event_id:
|
||||
# we are editing the same message all the time, so only the first time the event id needs to be set
|
||||
buf.event_id = cast(RoomSendResponse, response).event_id
|
||||
except Exception:
|
||||
buf.text = previous_text
|
||||
@@ -1012,7 +999,6 @@ class MatrixChannel(BaseChannel):
|
||||
return is_auth or bool(getattr(response, "soft_logout", False))
|
||||
|
||||
def _log_response_error(self, label: str, response: Any) -> None:
|
||||
"""Log Matrix response errors — auth errors at ERROR level, rest at WARNING."""
|
||||
is_fatal = self._is_fatal_auth_response(response)
|
||||
(self.logger.error if is_fatal else self.logger.warning)("{} failed: {}", label, response)
|
||||
|
||||
@@ -1079,7 +1065,6 @@ class MatrixChannel(BaseChannel):
|
||||
self._log_response_error("send", response)
|
||||
|
||||
async def _set_typing(self, room_id: str, typing: bool) -> None:
|
||||
"""Best-effort typing indicator update."""
|
||||
if not self.client:
|
||||
return
|
||||
with suppress(Exception):
|
||||
@@ -1135,7 +1120,6 @@ class MatrixChannel(BaseChannel):
|
||||
return isinstance(count, int) and count <= 2
|
||||
|
||||
def _is_bot_mentioned(self, event: RoomMessage) -> bool:
|
||||
"""Check m.mentions payload for bot mention."""
|
||||
source = getattr(event, "source", None)
|
||||
if not isinstance(source, dict):
|
||||
return False
|
||||
@@ -1164,7 +1148,6 @@ class MatrixChannel(BaseChannel):
|
||||
return isinstance(ts, int) and ts < self._started_at_ms
|
||||
|
||||
def _buffer_listen_message(self, room_id: str, sender: str, content: str) -> None:
|
||||
"""Record an unanswered room message for listen-mode context."""
|
||||
text = " ".join(str(content).split())[:_LISTEN_LINE_MAX_CHARS]
|
||||
line = f"{sender}: {text}" if text else f"{sender}: [attachment]"
|
||||
buffer = self._listen_buffers.setdefault(room_id, deque())
|
||||
@@ -1181,7 +1164,6 @@ class MatrixChannel(BaseChannel):
|
||||
self._listen_dropped[room_id] = dropped
|
||||
|
||||
def _listen_context(self, room_id: str, content: str) -> list[RuntimeContextBlock] | None:
|
||||
"""Read pending discussion for agent input, leaving control commands untouched."""
|
||||
buffer = self._listen_buffers.get(room_id)
|
||||
if not buffer:
|
||||
return None
|
||||
@@ -1215,17 +1197,14 @@ class MatrixChannel(BaseChannel):
|
||||
def _consume_listen_context(
|
||||
self, room_id: str, content: str, context: list[RuntimeContextBlock] | None,
|
||||
) -> None:
|
||||
"""Clear handed-off discussion or an explicit room-session reset."""
|
||||
if context or normalize_command_text(content).lower() == "/new":
|
||||
self._listen_buffers.pop(room_id, None)
|
||||
self._listen_dropped.pop(room_id, None)
|
||||
|
||||
def _effective_group_policy(self, room_id: str) -> MatrixGroupPolicy:
|
||||
"""Per-room override when present, else the channel-level group policy."""
|
||||
return self.config.group_policy_overrides.get(room_id, self.config.group_policy)
|
||||
|
||||
def _should_process_message(self, room: MatrixRoom, event: RoomMessage) -> bool:
|
||||
"""Apply sender and room policy checks."""
|
||||
if not self.is_allowed(event.sender):
|
||||
return False
|
||||
if self._is_direct_room(room):
|
||||
@@ -1293,7 +1272,6 @@ class MatrixChannel(BaseChannel):
|
||||
def _build_outbound_relates_to(
|
||||
self, metadata: dict[str, Any] | None
|
||||
) -> dict[str, Any] | None:
|
||||
"""Keep thread relations; optionally link room-level replies to the user event."""
|
||||
if thread := self._build_thread_relates_to(metadata):
|
||||
return thread
|
||||
if not self.config.reply_to_message or not metadata:
|
||||
@@ -1426,7 +1404,6 @@ class MatrixChannel(BaseChannel):
|
||||
async def _fetch_media_attachment(
|
||||
self, event: MatrixMediaEvent,
|
||||
) -> tuple[dict[str, Any] | None, str]:
|
||||
"""Download, decrypt if needed, and persist a Matrix attachment."""
|
||||
atype = self._event_attachment_type(event)
|
||||
mime = self._event_mime(event)
|
||||
filename = self._event_filename(event, atype)
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the Matrix channel package."""
|
||||
@@ -878,7 +878,6 @@ async def test_room_invite_respects_allow_list_when_configured() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_sync_invite_fallback_joins_pending_invites() -> None:
|
||||
"""_on_sync_invite_fallback joins rooms from sync invite_state for allowed senders."""
|
||||
channel = MatrixChannel(
|
||||
_make_config(allow_from=["@alice:matrix.org"]), MessageBus()
|
||||
)
|
||||
@@ -897,7 +896,6 @@ async def test_on_sync_invite_fallback_joins_pending_invites() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_sync_invite_fallback_skips_when_no_invites() -> None:
|
||||
"""_on_sync_invite_fallback is a no-op when sync has no invites."""
|
||||
channel = MatrixChannel(
|
||||
_make_config(allow_from=["@alice:matrix.org"]), MessageBus()
|
||||
)
|
||||
@@ -914,7 +912,6 @@ async def test_on_sync_invite_fallback_skips_when_no_invites() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_sync_invite_fallback_skips_denied_sender() -> None:
|
||||
"""_on_sync_invite_fallback respects the allow list."""
|
||||
channel = MatrixChannel(
|
||||
_make_config(allow_from=["@bob:matrix.org"]), MessageBus()
|
||||
)
|
||||
@@ -2146,7 +2143,6 @@ async def test_send_progress_keeps_typing_keepalive_running() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_empty_content_does_not_call_room_send() -> None:
|
||||
"""Progress messages with empty content must not produce an empty body: '' event."""
|
||||
channel = MatrixChannel(_make_config(), MessageBus())
|
||||
client = _FakeAsyncClient("", "", "", None)
|
||||
channel.client = client
|
||||
@@ -2165,7 +2161,6 @@ async def test_send_empty_content_does_not_call_room_send() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_whitespace_only_content_does_not_call_room_send() -> None:
|
||||
"""Progress messages with whitespace-only content must not produce an empty message."""
|
||||
channel = MatrixChannel(_make_config(), MessageBus())
|
||||
client = _FakeAsyncClient("", "", "", None)
|
||||
channel.client = client
|
||||
@@ -2321,7 +2316,6 @@ async def test_send_keeps_plaintext_only_for_plain_text() -> None:
|
||||
|
||||
|
||||
def test_build_matrix_text_content_basic_text() -> None:
|
||||
"""Test basic text content without HTML formatting."""
|
||||
result = _build_matrix_text_content("Hello, World!")
|
||||
expected = {
|
||||
"msgtype": "m.text",
|
||||
@@ -2332,7 +2326,6 @@ def test_build_matrix_text_content_basic_text() -> None:
|
||||
|
||||
|
||||
def test_build_matrix_text_content_with_markdown() -> None:
|
||||
"""Test text content with markdown that renders to HTML."""
|
||||
text = "*Hello* **World**"
|
||||
result = _build_matrix_text_content(text)
|
||||
assert "msgtype" in result
|
||||
@@ -2346,7 +2339,6 @@ def test_build_matrix_text_content_with_markdown() -> None:
|
||||
|
||||
|
||||
def test_build_matrix_text_content_with_event_id() -> None:
|
||||
"""Test text content with event_id for message replacement."""
|
||||
event_id = "$8E2XVyINbEhcuAxvxd1d9JhQosNPzkVoU8TrbCAvyHo"
|
||||
result = _build_matrix_text_content("Updated message", event_id)
|
||||
assert "msgtype" in result
|
||||
@@ -2358,7 +2350,6 @@ def test_build_matrix_text_content_with_event_id() -> None:
|
||||
|
||||
|
||||
def test_build_matrix_text_content_with_event_id_preserves_thread_relation() -> None:
|
||||
"""Thread relations for edits should stay inside m.new_content."""
|
||||
relates_to = {
|
||||
"rel_type": "m.thread",
|
||||
"event_id": "$root1",
|
||||
@@ -2376,7 +2367,6 @@ def test_build_matrix_text_content_with_event_id_preserves_thread_relation() ->
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_room_content_returns_room_send_response():
|
||||
"""Test that _send_room_content returns the response from client.room_send."""
|
||||
client = _FakeAsyncClient("", "", "", None)
|
||||
channel = MatrixChannel(_make_config(), MessageBus())
|
||||
channel.client = client
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Matrix setup validation owned by the channel package."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Mattermost channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Mattermost management contract."""
|
||||
|
||||
from nanobot.channels._manifest import GROUP_POLICIES, field, required_fields
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Mattermost channel implementation using WebSocket + REST API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -119,7 +117,6 @@ class MattermostChannel(BaseChannel):
|
||||
self._stream_root_ids: dict[str, str] = {}
|
||||
self._thread_context_attempted: set[str] = set()
|
||||
|
||||
# Lifecycle ----------------------------------------------------------------
|
||||
|
||||
async def start(self) -> None:
|
||||
if not self.config.server_url or not self.config.token:
|
||||
@@ -169,7 +166,6 @@ class MattermostChannel(BaseChannel):
|
||||
await self._http_client.aclose()
|
||||
self._http_client = None
|
||||
|
||||
# WebSocket ----------------------------------------------------------------
|
||||
|
||||
async def _ws_listen_loop(self) -> None:
|
||||
import websockets
|
||||
@@ -205,7 +201,6 @@ class MattermostChannel(BaseChannel):
|
||||
elif event == "post_deleted":
|
||||
await self._handle_post_deleted_event(msg)
|
||||
|
||||
# Event: posted ------------------------------------------------------------
|
||||
|
||||
async def _handle_posted_event(self, msg: dict[str, Any]) -> None:
|
||||
data = cast(dict[str, Any], msg.get("data", {}))
|
||||
@@ -315,7 +310,6 @@ class MattermostChannel(BaseChannel):
|
||||
is_dm=is_dm,
|
||||
)
|
||||
|
||||
# Event: action ------------------------------------------------------------
|
||||
|
||||
async def _handle_action_event(self, msg: dict[str, Any]) -> None:
|
||||
data = cast(dict[str, Any], msg.get("data", {}))
|
||||
@@ -342,7 +336,6 @@ class MattermostChannel(BaseChannel):
|
||||
metadata={"mattermost": {"channel_type": channel_type, "is_action": True}},
|
||||
)
|
||||
|
||||
# Event: post_deleted ------------------------------------------------------
|
||||
|
||||
async def _handle_post_deleted_event(self, msg: dict[str, Any]) -> None:
|
||||
data = cast(dict[str, Any], msg.get("data", {}))
|
||||
@@ -364,7 +357,6 @@ class MattermostChannel(BaseChannel):
|
||||
self._stream_last_content.pop(sid, None)
|
||||
self._stream_committed.pop(sid, None)
|
||||
|
||||
# Permission / policy ------------------------------------------------------
|
||||
|
||||
def is_allowed(self, sender_id: str) -> bool:
|
||||
return True
|
||||
@@ -451,7 +443,6 @@ class MattermostChannel(BaseChannel):
|
||||
self.logger.warning("failed to resolve email for {}: {}", user_id, e)
|
||||
return None
|
||||
|
||||
# Thread context -----------------------------------------------------------
|
||||
|
||||
async def _with_thread_context(self, text: str, *, channel_id: str, root_id: str) -> str:
|
||||
key = f"{channel_id}:{root_id}"
|
||||
@@ -492,7 +483,6 @@ class MattermostChannel(BaseChannel):
|
||||
return text
|
||||
return "Mattermost thread context before this mention:\n" + "\n".join(lines) + f"\n\nCurrent message:\n{text}"
|
||||
|
||||
# Send ---------------------------------------------------------------------
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
if isinstance(msg.event, ContextCompactionEvent) and not (
|
||||
@@ -545,7 +535,6 @@ class MattermostChannel(BaseChannel):
|
||||
self.logger.exception("Error sending message")
|
||||
raise
|
||||
|
||||
# Streaming -----------------------------------------------------------------
|
||||
|
||||
async def send_delta(
|
||||
self,
|
||||
@@ -646,7 +635,6 @@ class MattermostChannel(BaseChannel):
|
||||
self._stream_last_content.pop(stream_id, None)
|
||||
self._stream_committed.pop(stream_id, None)
|
||||
|
||||
# API helpers ---------------------------------------------------------------
|
||||
|
||||
def _require_http_client(self) -> httpx.AsyncClient:
|
||||
if self._http_client is None:
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the Mattermost channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for the Mattermost channel implementation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -99,11 +97,6 @@ def _make_channel(
|
||||
return channel, fake
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_config_defaults():
|
||||
config = MattermostConfig()
|
||||
assert config.enabled is False
|
||||
@@ -159,11 +152,6 @@ def test_config_default_config_classmethod():
|
||||
assert d["token"] == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Self-identification on start
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_identifies_bot():
|
||||
channel, fake = _make_channel({"serverUrl": "https://chat.example.com", "token": "tok"})
|
||||
@@ -199,11 +187,6 @@ async def test_start_missing_config():
|
||||
assert channel._self_id is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Server URL normalization
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_server_url_normalization():
|
||||
config = MattermostConfig.model_validate({
|
||||
"serverUrl": "https://chat.example.com/",
|
||||
@@ -224,11 +207,6 @@ def test_server_url_no_trailing_slash():
|
||||
assert channel._server_url == "https://chat.example.com"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Inbound routing: posted event
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_posted_event_routes_to_handle_message():
|
||||
channel, fake = _make_channel()
|
||||
@@ -303,11 +281,6 @@ async def test_posted_event_channel_type_detection():
|
||||
assert mock_handle.call_args[1]["is_dm"] == expected_dm
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bot @mention stripping
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_strip_bot_mention_from_incoming():
|
||||
channel, fake = _make_channel()
|
||||
@@ -331,11 +304,6 @@ async def test_strip_bot_mention_from_incoming():
|
||||
assert mock_handle.call_args[1]["content"] == "hello there"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DM policy: open / allowlist
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dm_policy_open():
|
||||
channel, fake = _make_channel({"dm": {"policy": "open"}})
|
||||
@@ -356,11 +324,6 @@ async def test_dm_disabled():
|
||||
assert await channel._is_allowed("u1", "dm_chan", "dm") is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Group policy: mention / open / allowlist
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_policy_mention():
|
||||
channel, fake = _make_channel({"groupPolicy": "mention"})
|
||||
@@ -384,33 +347,27 @@ async def test_group_policy_allowlist():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_policy_in_thread_defaults_to_group_policy():
|
||||
"""Existing configs keep their main-channel behavior in threads."""
|
||||
channel, fake = _make_channel({"groupPolicy": "mention"})
|
||||
channel._self_username = "nanobot"
|
||||
# In a main channel (not thread), mention is required
|
||||
assert channel._should_respond_in_channel("hello", "c1", in_thread=False) is False
|
||||
assert channel._should_respond_in_channel("@nanobot hello", "c1", in_thread=False) is True
|
||||
# In a thread, the omitted override inherits mention policy.
|
||||
assert channel._should_respond_in_channel("hello", "c1", in_thread=True) is False
|
||||
assert channel._should_respond_in_channel("@nanobot hello", "c1", in_thread=True) is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_policy_in_thread_mention():
|
||||
"""Thread can also use mention policy when configured."""
|
||||
channel, fake = _make_channel({
|
||||
"groupPolicy": "mention",
|
||||
"groupPolicyInThread": "mention",
|
||||
})
|
||||
channel._self_username = "nanobot"
|
||||
# In a thread with mention policy, mention is required
|
||||
assert channel._should_respond_in_channel("hello", "c1", in_thread=True) is False
|
||||
assert channel._should_respond_in_channel("@nanobot hello", "c1", in_thread=True) is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_policy_in_thread_open():
|
||||
"""Thread uses open policy when explicitly configured."""
|
||||
channel, fake = _make_channel({
|
||||
"groupPolicy": "mention",
|
||||
"groupPolicyInThread": "open",
|
||||
@@ -420,7 +377,6 @@ async def test_group_policy_in_thread_open():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_posted_thread_event_uses_thread_policy():
|
||||
"""A real posted event derives thread policy from its root_id."""
|
||||
channel, fake = _make_channel({
|
||||
"groupPolicy": "mention",
|
||||
"groupPolicyInThread": "open",
|
||||
@@ -478,7 +434,6 @@ async def test_posted_event_ignores_system_posts(post_type: str):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_policy_in_thread_allowlist():
|
||||
"""Thread uses allowlist policy when configured."""
|
||||
channel, fake = _make_channel({
|
||||
"groupPolicy": "mention",
|
||||
"groupPolicyInThread": "allowlist",
|
||||
@@ -488,11 +443,6 @@ async def test_group_policy_in_thread_allowlist():
|
||||
assert channel._should_respond_in_channel("msg", "c2", in_thread=True) is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Match mode: id / username / email
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_mode_id():
|
||||
channel, fake = _make_channel({"allowFromMatchMode": "id", "allowFrom": ["u1", "u2"]})
|
||||
@@ -516,11 +466,6 @@ async def test_match_mode_email():
|
||||
assert await channel._match_sender("u2", ["alice@x.com"]) is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Identity cache
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_identity_cache_username():
|
||||
channel, fake = _make_channel({"allowFromMatchMode": "username", "allowFrom": ["alice"]})
|
||||
@@ -534,11 +479,6 @@ async def test_identity_cache_username():
|
||||
assert len(fake.get_calls) == calls_before + 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Send
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_creates_post():
|
||||
channel, fake = _make_channel()
|
||||
@@ -629,11 +569,6 @@ async def test_send_reactions_complete_after_final_reply():
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Streaming
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_first_delta_buffers_content():
|
||||
channel, fake = _make_channel()
|
||||
@@ -775,11 +710,6 @@ async def test_coalesced_stream_end_posts_inline_content():
|
||||
assert posts[0]["json"]["root_id"] == "root_1"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reactions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reaction_add_on_receipt():
|
||||
channel, fake = _make_channel()
|
||||
@@ -800,11 +730,6 @@ async def test_reaction_remove():
|
||||
assert "eyes" in fake.delete_calls[-1]["path"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Team filtering
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_team_filtering_rejects_wrong_team():
|
||||
channel, fake = _make_channel({"teamId": "team_a"})
|
||||
@@ -892,11 +817,6 @@ async def test_team_filtering_resolves_missing_broadcast_team_and_rejects_wrong_
|
||||
mock_handle.assert_not_awaited()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Thread session key
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_thread_session_key():
|
||||
channel, fake = _make_channel()
|
||||
@@ -946,11 +866,6 @@ async def test_top_level_mention_uses_thread_session_key():
|
||||
assert kwargs["metadata"]["mattermost"]["thread_ts"] == "post_1"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action event (interactive buttons)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_action_event():
|
||||
channel, fake = _make_channel()
|
||||
@@ -1017,11 +932,6 @@ async def test_action_event_rejects_wrong_team():
|
||||
mock_handle.assert_not_awaited()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Post deleted event
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_post_deleted_cleans_stream_state():
|
||||
channel, fake = _make_channel()
|
||||
@@ -1041,11 +951,6 @@ async def test_post_deleted_cleans_stream_state():
|
||||
assert channel._stream_posts["s2"] == "keep_post_2"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Auth failure
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auth_failure_prevents_start():
|
||||
channel, fake = _make_channel()
|
||||
@@ -1055,11 +960,6 @@ async def test_auth_failure_prevents_start():
|
||||
assert channel._self_id is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DM allowlist with match mode
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dm_allowlist_with_username_match():
|
||||
channel, fake = _make_channel({
|
||||
@@ -1078,11 +978,6 @@ async def test_dm_allowlist_accepts_pairing_approval():
|
||||
assert await channel._is_allowed("u_paired", "dm_chan", "dm") is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Denied DM sends pairing code (not empty message)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_denied_dm_sends_pairing_not_empty_inbound():
|
||||
channel, fake = _make_channel({"dm": {"policy": "allowlist", "allowFrom": ["u_allowed"]}})
|
||||
@@ -1116,11 +1011,6 @@ async def test_denied_dm_sends_pairing_not_empty_inbound():
|
||||
assert len(inbound_events) == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bot mention boundary
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_is_mentioned_exact():
|
||||
channel, fake = _make_channel({"groupPolicy": "mention"})
|
||||
channel._self_username = "nanobot"
|
||||
@@ -1136,11 +1026,6 @@ def test_is_mentioned_no_username():
|
||||
assert channel._is_mentioned("hello @nanobot") is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# split_message helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_message_splitting():
|
||||
from nanobot.utils.helpers import split_message
|
||||
short = "short message"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""MoChat channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""MoChat management contract."""
|
||||
|
||||
from nanobot.channels._manifest import field, required
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
# pyright: reportConstantRedefinition=false, reportMissingTypeStubs=false
|
||||
"""Mochat channel implementation using Socket.IO with HTTP polling fallback."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -40,10 +39,6 @@ MAX_SEEN_MESSAGE_IDS = 2000
|
||||
CURSOR_SAVE_DEBOUNCE_S = 0.5
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data classes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class MochatBufferedEntry:
|
||||
"""Buffered inbound entry for delayed dispatch."""
|
||||
@@ -71,17 +66,11 @@ class MochatTarget:
|
||||
is_panel: bool
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pure helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _safe_dict(value: Any) -> dict[str, Any]:
|
||||
"""Return *value* if it's a dict, else empty dict."""
|
||||
return cast(dict[str, Any], value) if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _str_field(src: dict[str, Any], *keys: str) -> str:
|
||||
"""Return the first non-empty str value found for *keys*, stripped."""
|
||||
for k in keys:
|
||||
v = src.get(k)
|
||||
if isinstance(v, str) and v.strip():
|
||||
@@ -94,7 +83,6 @@ def _make_synthetic_event(
|
||||
meta: Any, group_id: str, converse_id: str,
|
||||
timestamp: Any = None, *, author_info: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build a synthetic ``message.add`` event dict."""
|
||||
payload: dict[str, Any] = {
|
||||
"messageId": message_id, "author": author,
|
||||
"content": content, "meta": _safe_dict(meta),
|
||||
@@ -215,10 +203,6 @@ def parse_timestamp(value: Any) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config classes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class MochatMentionConfig(Base):
|
||||
"""Mochat mention behavior configuration."""
|
||||
|
||||
@@ -258,10 +242,6 @@ class MochatConfig(Base):
|
||||
reply_delay_ms: int = 120000
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Channel
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class MochatChannel(BaseChannel):
|
||||
"""Mochat channel using socket.io with fallback polling workers."""
|
||||
|
||||
@@ -303,7 +283,6 @@ class MochatChannel(BaseChannel):
|
||||
self._refresh_task: asyncio.Task[None] | None = None
|
||||
self._target_locks: dict[str, asyncio.Lock] = {}
|
||||
|
||||
# ---- lifecycle ---------------------------------------------------------
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start Mochat channel workers and websocket connection."""
|
||||
@@ -386,7 +365,6 @@ class MochatChannel(BaseChannel):
|
||||
self.logger.exception("Failed to send message")
|
||||
raise
|
||||
|
||||
# ---- config / init helpers ---------------------------------------------
|
||||
|
||||
def _seed_targets_from_config(self) -> None:
|
||||
sessions, self._auto_discover_sessions = self._normalize_id_list(self.config.sessions)
|
||||
@@ -402,7 +380,6 @@ class MochatChannel(BaseChannel):
|
||||
cleaned = [str(v).strip() for v in values if str(v).strip()]
|
||||
return sorted({v for v in cleaned if v != "*"}), "*" in cleaned
|
||||
|
||||
# ---- websocket ---------------------------------------------------------
|
||||
|
||||
async def _start_socket_client(self) -> bool:
|
||||
if not SOCKETIO_AVAILABLE:
|
||||
@@ -488,7 +465,6 @@ class MochatChannel(BaseChannel):
|
||||
await self._handle_notify_chat_message(payload)
|
||||
return handler
|
||||
|
||||
# ---- subscribe ---------------------------------------------------------
|
||||
|
||||
async def _subscribe_all(self) -> bool:
|
||||
ok = await self._subscribe_sessions(sorted(self._session_set))
|
||||
@@ -557,7 +533,6 @@ class MochatChannel(BaseChannel):
|
||||
else {"result": True, "data": raw}
|
||||
)
|
||||
|
||||
# ---- refresh / discovery -----------------------------------------------
|
||||
|
||||
async def _refresh_loop(self) -> None:
|
||||
interval_s = max(1.0, self.config.refresh_interval_ms / 1000.0)
|
||||
@@ -642,7 +617,6 @@ class MochatChannel(BaseChannel):
|
||||
if self._fallback_mode:
|
||||
await self._ensure_fallback_workers()
|
||||
|
||||
# ---- fallback workers --------------------------------------------------
|
||||
|
||||
async def _ensure_fallback_workers(self) -> None:
|
||||
if not self._running:
|
||||
@@ -711,7 +685,6 @@ class MochatChannel(BaseChannel):
|
||||
self.logger.warning("panel polling error ({}): {}", panel_id, e)
|
||||
await asyncio.sleep(sleep_s)
|
||||
|
||||
# ---- inbound event processing ------------------------------------------
|
||||
|
||||
async def _handle_watch_payload(self, payload: dict[str, Any], target_kind: str) -> None:
|
||||
if not isinstance(cast(object, payload), dict):
|
||||
@@ -791,7 +764,6 @@ class MochatChannel(BaseChannel):
|
||||
|
||||
await self._dispatch_entries(target_id, target_kind, [entry], was_mentioned)
|
||||
|
||||
# ---- dedup / buffering -------------------------------------------------
|
||||
|
||||
def _remember_message_id(self, key: str, message_id: str) -> bool:
|
||||
seen_set = self._seen_set.setdefault(key, set())
|
||||
@@ -853,7 +825,6 @@ class MochatChannel(BaseChannel):
|
||||
state.timer.cancel()
|
||||
self._delay_states.clear()
|
||||
|
||||
# ---- notify handlers ---------------------------------------------------
|
||||
|
||||
async def _handle_notify_chat_message(self, payload: Any) -> None:
|
||||
if not isinstance(payload, dict):
|
||||
@@ -907,7 +878,6 @@ class MochatChannel(BaseChannel):
|
||||
)
|
||||
await self._process_inbound_event(session_id, evt, "session")
|
||||
|
||||
# ---- cursor persistence ------------------------------------------------
|
||||
|
||||
def _mark_session_cursor(self, session_id: str, cursor: int) -> None:
|
||||
if cursor < 0 or cursor < self._session_cursor.get(session_id, 0):
|
||||
@@ -950,7 +920,6 @@ class MochatChannel(BaseChannel):
|
||||
except Exception as e:
|
||||
self.logger.warning("Failed to save cursor file: {}", e)
|
||||
|
||||
# ---- HTTP helpers ------------------------------------------------------
|
||||
|
||||
async def _post_json(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not self._http:
|
||||
@@ -984,7 +953,6 @@ class MochatChannel(BaseChannel):
|
||||
|
||||
async def _api_send(self, path: str, id_key: str, id_val: str,
|
||||
content: str, reply_to: str | None, group_id: str | None = None) -> dict[str, Any]:
|
||||
"""Unified send helper for session and panel messages."""
|
||||
body: dict[str, Any] = {id_key: id_val, "content": content}
|
||||
if reply_to:
|
||||
body["replyTo"] = reply_to
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Microsoft Teams channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Microsoft Teams management contract."""
|
||||
|
||||
from nanobot.channels._manifest import field, required_fields
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
|
||||
@@ -292,7 +292,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
raise
|
||||
|
||||
async def _handle_activity(self, activity: dict[str, Any]) -> None:
|
||||
"""Handle inbound Teams/Bot Framework activity."""
|
||||
if activity.get("type") != "message":
|
||||
return
|
||||
|
||||
@@ -320,7 +319,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
if recipient.get("id") and from_user.get("id") == recipient.get("id"):
|
||||
return
|
||||
|
||||
# DM-only MVP: ignore group/channel traffic for now
|
||||
if conversation_type and conversation_type not in ("personal", ""):
|
||||
self.logger.debug("Ignoring non-DM conversation {}", conversation_type)
|
||||
return
|
||||
@@ -376,7 +374,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
)
|
||||
|
||||
def _sanitize_inbound_text(self, activity: dict[str, Any]) -> str:
|
||||
"""Extract the user-authored text from a Teams activity."""
|
||||
text = str(activity.get("text") or "")
|
||||
text = self._strip_possible_bot_mention(text)
|
||||
text = self._normalize_html_whitespace(text)
|
||||
@@ -398,20 +395,17 @@ class MSTeamsChannel(BaseChannel):
|
||||
return text.strip()
|
||||
|
||||
def _strip_possible_bot_mention(self, text: str) -> str:
|
||||
"""Remove simple Teams mention markup from message text."""
|
||||
cleaned = re.sub(r"<at\b[^>]*>.*?</at>", " ", text, flags=re.IGNORECASE | re.DOTALL)
|
||||
cleaned = re.sub(r"[^\S\r\n]+", " ", cleaned)
|
||||
cleaned = re.sub(r"(?:\r?\n){3,}", "\n\n", cleaned)
|
||||
return cleaned.strip()
|
||||
|
||||
def _normalize_html_whitespace(self, text: str) -> str:
|
||||
"""Normalize common HTML whitespace/entities from Teams into plain text spacing."""
|
||||
normalized = html.unescape(text).replace("&rsquo", "’")
|
||||
normalized = normalized.replace("\xa0", " ")
|
||||
return normalized
|
||||
|
||||
def _normalize_teams_reply_quote(self, text: str) -> str:
|
||||
"""Normalize Teams quoted replies into a compact structured form."""
|
||||
cleaned = self._normalize_html_whitespace(text).strip()
|
||||
if not cleaned:
|
||||
return ""
|
||||
@@ -466,7 +460,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
return cleaned
|
||||
|
||||
def _format_reply_with_quote(self, quoted: str, reply: str) -> str:
|
||||
"""Format a reply-with-context message for the model without Teams wrapper noise."""
|
||||
quoted = quoted.strip()
|
||||
reply = reply.strip()
|
||||
if quoted and reply:
|
||||
@@ -476,7 +469,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
return quoted
|
||||
|
||||
async def _validate_inbound_auth(self, auth_header: str, activity: dict[str, Any]) -> None:
|
||||
"""Validate inbound Bot Framework bearer token."""
|
||||
if not MSTEAMS_AVAILABLE:
|
||||
raise RuntimeError("PyJWT not installed. Run: nanobot plugins enable msteams")
|
||||
|
||||
@@ -518,7 +510,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
raise ValueError("serviceUrl claim mismatch")
|
||||
|
||||
async def _get_botframework_openid_config(self) -> dict[str, Any]:
|
||||
"""Fetch and cache Bot Framework OpenID configuration."""
|
||||
|
||||
now = time.time()
|
||||
if self._botframework_openid_config and now < self._botframework_openid_config_expires_at:
|
||||
@@ -535,7 +526,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
return openid_config
|
||||
|
||||
async def _get_botframework_jwks(self) -> dict[str, Any]:
|
||||
"""Fetch and cache Bot Framework JWKS."""
|
||||
|
||||
now = time.time()
|
||||
if self._botframework_jwks and now < self._botframework_jwks_expires_at:
|
||||
@@ -567,7 +557,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
return None
|
||||
|
||||
def _normalize_ref_record(self, value: object) -> ConversationRef | None:
|
||||
"""Normalize a stored ref record from legacy/current schema."""
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
record = cast(dict[str, Any], value)
|
||||
@@ -586,7 +575,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
)
|
||||
|
||||
def _load_refs_raw(self) -> tuple[dict[str, Any], dict[str, Any], bool]:
|
||||
"""Load raw refs/main+meta JSON payloads."""
|
||||
main_data: dict[str, Any] = {}
|
||||
meta_data: dict[str, Any] = {}
|
||||
meta_exists = self._refs_meta_path.exists()
|
||||
@@ -612,7 +600,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
return main_data, meta_data, meta_exists
|
||||
|
||||
def _load_refs_from_disk(self) -> dict[str, ConversationRef]:
|
||||
"""Load refs from disk with compatibility fallback for legacy layouts."""
|
||||
main_data, meta_data, meta_exists = self._load_refs_raw()
|
||||
if not main_data:
|
||||
return {}
|
||||
@@ -645,7 +632,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
return out
|
||||
|
||||
def _load_refs(self) -> dict[str, ConversationRef]:
|
||||
"""Load stored conversation references."""
|
||||
return self._load_refs_from_disk()
|
||||
|
||||
@contextmanager
|
||||
@@ -665,7 +651,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
lock_fp.close()
|
||||
|
||||
def _is_webchat_service_url(self, service_url: str) -> bool:
|
||||
"""Return True when service URL points to unsupported Bot Framework Web Chat."""
|
||||
normalized = service_url.strip()
|
||||
if not normalized:
|
||||
return False
|
||||
@@ -675,7 +660,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
return MSTEAMS_WEBCHAT_HOST in normalized.lower()
|
||||
|
||||
def _is_trusted_service_url(self, service_url: str) -> bool:
|
||||
"""Return True for HTTPS Bot Framework service URLs trusted for bearer replies."""
|
||||
parsed = urlparse(service_url.strip())
|
||||
if parsed.scheme.lower() != "https":
|
||||
return False
|
||||
@@ -698,7 +682,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
return False
|
||||
|
||||
def _prune_conversation_refs(self, *, now: float | None = None) -> bool:
|
||||
"""Remove stale and unsupported conversation refs from memory."""
|
||||
if not self._conversation_refs:
|
||||
return False
|
||||
|
||||
@@ -754,7 +737,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
self._conversation_refs[key] = disk_ref
|
||||
|
||||
def _touch_conversation_ref(self, chat_id: str, *, persist: bool = False) -> None:
|
||||
"""Refresh updated_at for an active ref to keep it from expiring while used."""
|
||||
with self._refs_guard:
|
||||
ref = self._conversation_refs.get(str(chat_id))
|
||||
if not ref:
|
||||
@@ -769,7 +751,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
self._save_refs_locked()
|
||||
|
||||
def _write_json_atomically(self, path: Path, data: dict[str, Any]) -> None:
|
||||
"""Write refs JSON atomically to reduce corruption risk during crashes."""
|
||||
payload = json.dumps(data, indent=2)
|
||||
tmp_path: str | None = None
|
||||
try:
|
||||
@@ -818,7 +799,6 @@ class MSTeamsChannel(BaseChannel):
|
||||
self.logger.warning("Failed to save conversation refs: {}", e)
|
||||
|
||||
async def _get_access_token(self) -> str:
|
||||
"""Fetch an access token for Bot Framework / Azure Bot auth."""
|
||||
|
||||
now = time.time()
|
||||
if self._token and now < self._token_expires_at - 60:
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the Microsoft Teams channel package."""
|
||||
@@ -3,7 +3,6 @@ import time
|
||||
|
||||
import pytest
|
||||
|
||||
# Check optional msteams dependencies before running tests
|
||||
try:
|
||||
import nanobot.channels.msteams.runtime as msteams_module
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""NapCat channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""NapCat management contract."""
|
||||
|
||||
from nanobot.channels._manifest import DIRECT_GROUP_POLICIES, field, required
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Napcat (OneBot v11) channel for QQ, over WebSocket."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -51,7 +49,6 @@ class NapcatConfig(Base):
|
||||
# Falls back to `group_policy` when a group_id isn't listed.
|
||||
group_policy_overrides: dict[str, GroupPolicy] = Field(default_factory=dict)
|
||||
welcome_new_members: bool = True
|
||||
# Hard cap for inbound image downloads. Bigger images are dropped.
|
||||
max_image_bytes: int = Field(default=20 * 1024 * 1024, ge=1)
|
||||
|
||||
|
||||
@@ -80,9 +77,6 @@ class NapcatChannel(BaseChannel):
|
||||
self._bot_outbound_ids: deque[int] = deque(maxlen=2000)
|
||||
self._background_tasks: set[asyncio.Task[None]] = set()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def start(self) -> None:
|
||||
if not self.config.ws_url:
|
||||
@@ -92,11 +86,11 @@ class NapcatChannel(BaseChannel):
|
||||
self._running = True
|
||||
self._http = aiohttp.ClientSession(timeout=_DOWNLOAD_TIMEOUT)
|
||||
|
||||
backoff = iter((5, 10)) # then 30s forever
|
||||
backoff = iter((5, 10))
|
||||
while self._running:
|
||||
try:
|
||||
await self._run_once()
|
||||
backoff = iter((5, 10)) # reset after a clean session
|
||||
backoff = iter((5, 10))
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
@@ -183,12 +177,8 @@ class NapcatChannel(BaseChannel):
|
||||
fut.set_exception(err)
|
||||
self._pending.clear()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Frame dispatch
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _dispatch_frame(self, raw: str | bytes) -> None:
|
||||
# logger.debug("dispatch frame {}", raw)
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
@@ -198,7 +188,6 @@ class NapcatChannel(BaseChannel):
|
||||
return
|
||||
frame = cast(dict[str, Any], payload)
|
||||
|
||||
# Action response: identified by `echo` and absence of post_type.
|
||||
if "echo" in frame and frame.get("post_type") is None:
|
||||
echo = frame.get("echo")
|
||||
fut = self._pending.pop(echo, None) if isinstance(echo, str) else None
|
||||
@@ -233,9 +222,6 @@ class NapcatChannel(BaseChannel):
|
||||
|
||||
task.add_done_callback(_done)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Inbound: messages
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _on_message(self, ev: dict[str, Any]) -> None:
|
||||
msg_id = ev.get("message_id")
|
||||
@@ -372,7 +358,6 @@ class NapcatChannel(BaseChannel):
|
||||
return True
|
||||
if policy == "mention":
|
||||
return False
|
||||
# Probability case: float in [0.0, 1.0].
|
||||
return random.random() < float(policy)
|
||||
|
||||
@staticmethod
|
||||
@@ -385,9 +370,6 @@ class NapcatChannel(BaseChannel):
|
||||
label = nickname or str(user_id)
|
||||
return f"{label}: {text}"
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Inbound: notices (member joined etc.)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _on_notice(self, ev: dict[str, Any]) -> None:
|
||||
if ev.get("notice_type") != "group_increase" or not self.config.welcome_new_members:
|
||||
@@ -421,22 +403,17 @@ class NapcatChannel(BaseChannel):
|
||||
)
|
||||
|
||||
async def _lookup_member_name(self, group_id: int, user_id: int) -> str:
|
||||
"""Lookup group member nickname. Fallback to user id."""
|
||||
try:
|
||||
resp = await self._call_action(
|
||||
"get_group_member_info",
|
||||
{"group_id": group_id, "user_id": user_id, "no_cache": True},
|
||||
)
|
||||
data = resp.get("data", {})
|
||||
# logger.debug("get_group_member_info: {}", resp)
|
||||
return data.get("card") or data.get("nickname") or str(user_id)
|
||||
except Exception as e:
|
||||
logger.warning("napcat: get_group_member_info failed: {}", e)
|
||||
return str(user_id)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Outbound
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
if isinstance(msg.event, ContextCompactionEvent) and not (
|
||||
@@ -519,15 +496,11 @@ class NapcatChannel(BaseChannel):
|
||||
finally:
|
||||
self._pending.pop(echo, None)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Image download
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _download_image(self, info: dict[str, Any]) -> str | None:
|
||||
url = info.get("url")
|
||||
if not isinstance(url, str):
|
||||
return None
|
||||
# logger.debug("napcat: downloading image from {}", url)
|
||||
if self._http is None:
|
||||
return None
|
||||
ok, err = validate_url_target(url)
|
||||
@@ -536,7 +509,6 @@ class NapcatChannel(BaseChannel):
|
||||
return None
|
||||
max_bytes = self.config.max_image_bytes
|
||||
|
||||
# Reject upfront when napcat tells us the size and it's too big.
|
||||
try:
|
||||
declared_size = int(info["file_size"])
|
||||
if declared_size > max_bytes:
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the NapCat channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Channel-owned address metadata retained for later session notifications."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from copy import deepcopy
|
||||
from typing import Any, cast
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Bounded storage for scheduled results; never reruns an agent turn."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Typed metadata for self-contained channel packages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""QQ channel package."""
|
||||
@@ -41,7 +41,6 @@ class QQConnectSession:
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""QQ management contract."""
|
||||
|
||||
from nanobot.channels._manifest import field, required_fields
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
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"),
|
||||
|
||||
@@ -81,12 +81,10 @@ _IMAGE_EXTS = {
|
||||
".svg",
|
||||
}
|
||||
|
||||
# Replace unsafe characters with "_", keep Chinese and common safe punctuation.
|
||||
_SAFE_NAME_RE = re.compile(r"[^\w.\-()\[\]()【】\u4e00-\u9fff]+", re.UNICODE)
|
||||
|
||||
|
||||
def _sanitize_filename(name: str) -> str:
|
||||
"""Sanitize filename to avoid traversal and problematic chars."""
|
||||
name = (name or "").strip()
|
||||
name = Path(name).name
|
||||
name = _SAFE_NAME_RE.sub("_", name).strip("._ ")
|
||||
@@ -98,7 +96,6 @@ def _is_image_name(name: str) -> bool:
|
||||
|
||||
|
||||
def _guess_send_file_type(filename: str) -> int:
|
||||
"""Conservative send type: images -> 1, else -> 4."""
|
||||
ext = Path(filename).suffix.lower()
|
||||
mime, _ = mimetypes.guess_type(filename)
|
||||
if ext in _IMAGE_EXTS or (mime and mime.startswith("image/")):
|
||||
@@ -111,7 +108,6 @@ _RECONNECT_BACKOFF_MAX = 300
|
||||
|
||||
|
||||
def _is_network_error(exc: BaseException) -> bool:
|
||||
"""Check whether an exception is a transient network/DNS error."""
|
||||
return isinstance(
|
||||
exc,
|
||||
(aiohttp.ClientConnectorError, OSError),
|
||||
@@ -119,7 +115,6 @@ def _is_network_error(exc: BaseException) -> bool:
|
||||
|
||||
|
||||
def _make_bot_class(channel: QQChannel) -> type[Any]:
|
||||
"""Create a botpy client with per-session reconnect backoff."""
|
||||
botpy_sdk = cast(Any, botpy)
|
||||
intents = botpy_sdk.Intents(public_messages=True, direct_message=True)
|
||||
|
||||
@@ -146,7 +141,6 @@ def _make_bot_class(channel: QQChannel) -> type[Any]:
|
||||
await channel._on_message(message, is_group=False)
|
||||
|
||||
async def bot_connect(self, session: object) -> None:
|
||||
"""Connect a botpy session with exponential retry backoff."""
|
||||
session_id = id(session)
|
||||
retry_at = self._ws_retry_at.pop(session_id, None)
|
||||
if retry_at is not None:
|
||||
@@ -178,9 +172,6 @@ def _make_bot_class(channel: QQChannel) -> type[Any]:
|
||||
return _Bot
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Quoted messages
|
||||
#
|
||||
# QQ's C2C/group events do not carry ``message_reference``; botpy models that
|
||||
# field because the object is shared with guild messages, but QQ never sends it
|
||||
# here. The quoted original arrives in ``msg_elements``, linked from
|
||||
@@ -190,7 +181,6 @@ def _make_bot_class(channel: QQChannel) -> type[Any]:
|
||||
# it is discarded. If a future botpy exposes those fields on the message
|
||||
# object, ``_quoted_content_for`` prefers that copy and the hook becomes dead
|
||||
# weight rather than a correctness dependency.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
QQ_QUOTED_CONTEXT_MAX_CHARS = 4_000
|
||||
QQ_RAW_PAYLOAD_CACHE = 200
|
||||
@@ -199,7 +189,6 @@ _qq_raw_payloads: dict[str, dict[str, Any]] = {}
|
||||
|
||||
|
||||
def _flatten_scene_ext(scene: Any) -> dict[str, str]:
|
||||
"""Turn QQ's ``message_scene.ext`` (``["key=value", ...]``) into a mapping."""
|
||||
if not isinstance(scene, Mapping):
|
||||
return {}
|
||||
ext = cast("Mapping[str, Any]", scene).get("ext")
|
||||
@@ -283,7 +272,6 @@ def _install_qq_payload_capture() -> None:
|
||||
|
||||
|
||||
def _quoted_content_for(message: Any) -> str | None:
|
||||
"""Resolve the quoted text for one inbound QQ message."""
|
||||
scene = getattr(message, "message_scene", None)
|
||||
elements = getattr(message, "msg_elements", None)
|
||||
if scene is not None or elements is not None:
|
||||
@@ -304,9 +292,8 @@ class QQConfig(Base):
|
||||
# Optional: directory to save inbound attachments. If empty, use nanobot get_media_dir("qq").
|
||||
media_dir: str = ""
|
||||
|
||||
# Download tuning
|
||||
download_chunk_size: int = 1024 * 256 # 256KB
|
||||
download_max_bytes: int = 1024 * 1024 * 200 # 200MB safety limit
|
||||
download_chunk_size: int = 1024 * 256
|
||||
download_max_bytes: int = 1024 * 1024 * 200
|
||||
|
||||
# QQ's C2C/group message API has no edit or recall endpoint, so automatic
|
||||
# notices would land as separate permanent messages (#5784). Unset inherits
|
||||
@@ -340,17 +327,12 @@ class QQChannel(BaseChannel):
|
||||
self._msg_seq: int = 1 # used to avoid QQ API dedup
|
||||
self._chat_type_cache: dict[str, str] = {}
|
||||
|
||||
# QQ delivers the quoted original in a payload field botpy discards.
|
||||
_install_qq_payload_capture()
|
||||
|
||||
self._media_root: Path = self._init_media_root()
|
||||
|
||||
# ---------------------------
|
||||
# Lifecycle
|
||||
# ---------------------------
|
||||
|
||||
def _init_media_root(self) -> Path:
|
||||
"""Choose a directory for saving inbound attachments."""
|
||||
if self.config.media_dir:
|
||||
root = Path(self.config.media_dir).expanduser()
|
||||
elif get_media_dir:
|
||||
@@ -396,7 +378,6 @@ class QQChannel(BaseChannel):
|
||||
await self._run_bot()
|
||||
|
||||
async def _run_bot(self) -> None:
|
||||
"""Run botpy with fallback backoff for errors escaping start()."""
|
||||
backoff = 5
|
||||
max_backoff = 300
|
||||
while self._running:
|
||||
@@ -431,17 +412,9 @@ class QQChannel(BaseChannel):
|
||||
|
||||
self.logger.info("bot stopped")
|
||||
|
||||
# ---------------------------
|
||||
# Outbound (send)
|
||||
# ---------------------------
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
"""Send attachments first, then text."""
|
||||
# Compaction notices assume the channel can update one message in place
|
||||
# (Telegram/Discord edit their notice; WebSocket projects it as status).
|
||||
# QQ's C2C/group API has no edit or recall endpoint, so by default the
|
||||
# automatic lifecycle is quiet by default (#5784). Explicit opt-in
|
||||
# restores it; manual /compact always retains its requested feedback.
|
||||
if (
|
||||
isinstance(msg.event, ContextCompactionEvent)
|
||||
and not (msg.event.notify or self.show_compaction_notices)
|
||||
@@ -456,7 +429,6 @@ class QQChannel(BaseChannel):
|
||||
chat_type = self._chat_type_cache.get(msg.chat_id, "c2c")
|
||||
is_group = chat_type == "group"
|
||||
|
||||
# 1) Send media
|
||||
for media_ref in msg.media or []:
|
||||
ok = await self._send_media(
|
||||
chat_id=msg.chat_id,
|
||||
@@ -477,7 +449,6 @@ class QQChannel(BaseChannel):
|
||||
content=f"[Attachment send failed: {filename}]",
|
||||
)
|
||||
|
||||
# 2) Send text
|
||||
if msg.content and msg.content.strip():
|
||||
await self._send_text_only(
|
||||
chat_id=msg.chat_id,
|
||||
@@ -499,7 +470,6 @@ class QQChannel(BaseChannel):
|
||||
msg_id: str | None,
|
||||
content: str,
|
||||
) -> None:
|
||||
"""Send a plain/markdown text message."""
|
||||
if not self._client:
|
||||
return
|
||||
|
||||
@@ -527,7 +497,6 @@ class QQChannel(BaseChannel):
|
||||
msg_id: str | None,
|
||||
is_group: bool,
|
||||
) -> bool:
|
||||
"""Read bytes -> base64 upload -> msg_type=7 send."""
|
||||
if not self._client:
|
||||
return False
|
||||
|
||||
@@ -581,12 +550,10 @@ class QQChannel(BaseChannel):
|
||||
return False
|
||||
|
||||
async def _read_media_bytes(self, media_ref: str) -> tuple[bytes | None, str | None]:
|
||||
"""Read bytes from http(s) or local file path; return (data, filename)."""
|
||||
media_ref = (media_ref or "").strip()
|
||||
if not media_ref:
|
||||
return None, None
|
||||
|
||||
# Local file: plain path or file:// URI
|
||||
if not media_ref.startswith("http://") and not media_ref.startswith("https://"):
|
||||
try:
|
||||
if media_ref.startswith("file://"):
|
||||
@@ -607,7 +574,6 @@ class QQChannel(BaseChannel):
|
||||
self.logger.warning("outbound media read error ref={} err={}", media_ref, e)
|
||||
return None, None
|
||||
|
||||
# Remote URL
|
||||
ok, err = validate_url_target(media_ref)
|
||||
if not ok:
|
||||
self.logger.warning("outbound media URL validation failed url={} err={}", media_ref, err)
|
||||
@@ -644,7 +610,6 @@ class QQChannel(BaseChannel):
|
||||
file_name: str | None = None,
|
||||
srv_send_msg: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Upload base64-encoded file and return Media object."""
|
||||
if not self._client:
|
||||
raise RuntimeError("QQ client not initialized")
|
||||
|
||||
@@ -679,12 +644,8 @@ class QQChannel(BaseChannel):
|
||||
return {"file_info": result_data["file_info"]}
|
||||
return cast(dict[str, Any], result)
|
||||
|
||||
# ---------------------------
|
||||
# Inbound (receive)
|
||||
# ---------------------------
|
||||
|
||||
async def _on_message(self, data: object, is_group: bool = False) -> None:
|
||||
"""Parse inbound message, download attachments, and publish to the bus."""
|
||||
try:
|
||||
message = cast(Any, data)
|
||||
if is_group:
|
||||
@@ -727,15 +688,12 @@ class QQChannel(BaseChannel):
|
||||
quote_tag = f"[Reply to: {quoted}]"
|
||||
content = f"{quote_tag}\n{content}" if content else quote_tag
|
||||
|
||||
# the data used by tests don't contain attachments property
|
||||
# so we use getattr with a default of [] to avoid AttributeError in tests
|
||||
attachments = cast(
|
||||
list[object],
|
||||
getattr(message, "attachments", None) or [],
|
||||
)
|
||||
media_paths, recv_lines, att_meta = await self._handle_attachments(attachments)
|
||||
|
||||
# Compose content that always contains actionable saved paths
|
||||
if recv_lines:
|
||||
tag = (
|
||||
"[Image]"
|
||||
@@ -782,7 +740,6 @@ class QQChannel(BaseChannel):
|
||||
self,
|
||||
attachments: list[object],
|
||||
) -> tuple[list[str], list[str], list[dict[str, Any]]]:
|
||||
"""Extract, download (chunked), and format attachments for agent consumption."""
|
||||
media_paths: list[str] = []
|
||||
recv_lines: list[str] = []
|
||||
att_meta: list[dict[str, Any]] = []
|
||||
@@ -822,13 +779,6 @@ class QQChannel(BaseChannel):
|
||||
url: str,
|
||||
filename_hint: str = "",
|
||||
) -> str | None:
|
||||
"""Download an inbound attachment using streaming chunk write.
|
||||
|
||||
Uses chunked streaming to avoid loading large files into memory.
|
||||
Enforces a max download size and writes to a .part temp file
|
||||
that is atomically renamed on success.
|
||||
"""
|
||||
# Handle protocol-relative URLs (e.g. "//multimedia.nt.qq.com/...")
|
||||
if url.startswith("//"):
|
||||
url = f"https:{url}"
|
||||
|
||||
@@ -860,7 +810,6 @@ class QQChannel(BaseChannel):
|
||||
|
||||
ctype = (resp.headers.get("Content-Type") or "").lower()
|
||||
|
||||
# Infer extension: url -> filename_hint -> content-type -> fallback
|
||||
ext = Path(urlparse(url).path).suffix
|
||||
if not ext:
|
||||
ext = Path(filename_hint).suffix
|
||||
@@ -891,7 +840,6 @@ class QQChannel(BaseChannel):
|
||||
|
||||
tmp_path = target.with_suffix(target.suffix + ".part")
|
||||
|
||||
# Stream write
|
||||
downloaded = 0
|
||||
chunk_size = max(1024, int(self.config.download_chunk_size or 262144))
|
||||
max_bytes = max(
|
||||
@@ -902,7 +850,7 @@ class QQChannel(BaseChannel):
|
||||
|
||||
def _open_tmp() -> BinaryIO:
|
||||
active_tmp_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
return active_tmp_path.open("wb") # noqa: SIM115
|
||||
return active_tmp_path.open("wb")
|
||||
|
||||
f = await asyncio.to_thread(_open_tmp)
|
||||
try:
|
||||
@@ -921,9 +869,8 @@ class QQChannel(BaseChannel):
|
||||
finally:
|
||||
await asyncio.to_thread(f.close)
|
||||
|
||||
# Atomic rename
|
||||
await asyncio.to_thread(os.replace, active_tmp_path, target)
|
||||
tmp_path = None # mark as moved
|
||||
tmp_path = None
|
||||
self.logger.info("file saved: {}", str(target))
|
||||
return str(target)
|
||||
|
||||
@@ -931,7 +878,6 @@ class QQChannel(BaseChannel):
|
||||
self.logger.exception("download error")
|
||||
return None
|
||||
finally:
|
||||
# Cleanup partial file
|
||||
if tmp_path is not None:
|
||||
with suppress(Exception):
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the QQ channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Keep QQ channel tests out of the user's configured media directory."""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
|
||||
@@ -275,14 +275,12 @@ def test_qq_credentials_serialize_with_settings_mutations(monkeypatch: pytest.Mo
|
||||
|
||||
def qq_load(path: Path | None = None) -> Config:
|
||||
config = original_load(path)
|
||||
# An unlocked QQ read must finish after Settings, exposing a stale write.
|
||||
qq_started.set()
|
||||
if not settings_saved.wait(timeout=5):
|
||||
raise TimeoutError("settings mutation did not finish")
|
||||
return config
|
||||
|
||||
def acquire(lock, *args, **kwargs):
|
||||
# Observe contention without replacing the real cross-process file lock.
|
||||
if threading.current_thread().name == "qq-credentials":
|
||||
qq_started.set()
|
||||
return original_acquire(lock, *args, **kwargs)
|
||||
|
||||
@@ -1,13 +1,3 @@
|
||||
"""Tests for QQ channel ack_message feature.
|
||||
|
||||
Covers the four verification points from the PR:
|
||||
1. C2C message: ack appears instantly
|
||||
2. Group message: ack appears instantly
|
||||
3. ack_message set to "": no ack sent
|
||||
4. Custom ack_message text: correct text delivered
|
||||
Each test also verifies that normal message processing is not blocked.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -45,7 +35,6 @@ class _FakeClient:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ack_sent_on_c2c_message() -> None:
|
||||
"""Ack is sent immediately for C2C messages, then normal processing continues."""
|
||||
channel = QQChannel(
|
||||
QQConfig(
|
||||
app_id="app",
|
||||
@@ -79,7 +68,6 @@ async def test_ack_sent_on_c2c_message() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ack_sent_on_group_message() -> None:
|
||||
"""Ack is sent immediately for group messages, then normal processing continues."""
|
||||
channel = QQChannel(
|
||||
QQConfig(
|
||||
app_id="app",
|
||||
@@ -114,7 +102,6 @@ async def test_ack_sent_on_group_message() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_ack_when_ack_message_empty() -> None:
|
||||
"""Setting ack_message to empty string disables the ack entirely."""
|
||||
channel = QQChannel(
|
||||
QQConfig(
|
||||
app_id="app",
|
||||
@@ -143,7 +130,6 @@ async def test_no_ack_when_ack_message_empty() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_ack_message_text() -> None:
|
||||
"""Custom Chinese ack_message text is delivered correctly."""
|
||||
custom = "正在处理中,请稍候..."
|
||||
channel = QQChannel(
|
||||
QQConfig(
|
||||
|
||||
@@ -5,7 +5,6 @@ from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
# Check optional QQ dependencies before running tests
|
||||
try:
|
||||
from nanobot.channels.qq import runtime as qq
|
||||
QQ_AVAILABLE = getattr(qq, "QQ_AVAILABLE", False)
|
||||
@@ -220,10 +219,6 @@ async def test_read_media_bytes_missing_file() -> None:
|
||||
assert filename is None
|
||||
|
||||
|
||||
# -------------------------------------------------------
|
||||
# Tests for _send_media exception handling
|
||||
# -------------------------------------------------------
|
||||
|
||||
def _make_channel_with_local_file(suffix: str = ".png", content: bytes = b"\x89PNG\r\n"):
|
||||
"""Create a QQChannel with a fake client and a temp file for media."""
|
||||
channel = QQChannel(
|
||||
@@ -241,10 +236,8 @@ def _make_channel_with_local_file(suffix: str = ".png", content: bytes = b"\x89P
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_network_error_propagates() -> None:
|
||||
"""aiohttp.ClientError (network/transport) should re-raise, not return False."""
|
||||
channel, tmp_path = _make_channel_with_local_file()
|
||||
|
||||
# Make the base64 upload raise a network error
|
||||
channel._client.api._http = SimpleNamespace()
|
||||
channel._client.api._http.request = AsyncMock(
|
||||
side_effect=aiohttp.ServerDisconnectedError("connection lost"),
|
||||
@@ -261,7 +254,6 @@ async def test_send_media_network_error_propagates() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_client_connector_error_propagates() -> None:
|
||||
"""aiohttp.ClientConnectorError (DNS/connection refused) should re-raise."""
|
||||
channel, tmp_path = _make_channel_with_local_file()
|
||||
|
||||
from aiohttp.client_reqrep import ConnectionKey
|
||||
@@ -287,7 +279,6 @@ async def test_send_media_client_connector_error_propagates() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_oserror_propagates() -> None:
|
||||
"""OSError (low-level I/O) should re-raise for retry."""
|
||||
channel, tmp_path = _make_channel_with_local_file()
|
||||
|
||||
channel._client.api._http = SimpleNamespace()
|
||||
@@ -306,10 +297,8 @@ async def test_send_media_oserror_propagates() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_api_error_returns_false() -> None:
|
||||
"""API-level errors (botpy RuntimeError subclasses) should return False, not raise."""
|
||||
channel, tmp_path = _make_channel_with_local_file()
|
||||
|
||||
# Simulate a botpy API error (e.g. ServerError is a RuntimeError subclass)
|
||||
from botpy.errors import ServerError
|
||||
|
||||
channel._client.api._http = SimpleNamespace()
|
||||
@@ -328,7 +317,6 @@ async def test_send_media_api_error_returns_false() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_generic_runtime_error_returns_false() -> None:
|
||||
"""Generic RuntimeError (not network) should return False."""
|
||||
channel, tmp_path = _make_channel_with_local_file()
|
||||
|
||||
channel._client.api._http = SimpleNamespace()
|
||||
@@ -347,7 +335,6 @@ async def test_send_media_generic_runtime_error_returns_false() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_value_error_returns_false() -> None:
|
||||
"""ValueError (bad API response data) should return False."""
|
||||
channel, tmp_path = _make_channel_with_local_file()
|
||||
|
||||
channel._client.api._http = SimpleNamespace()
|
||||
@@ -387,7 +374,6 @@ async def test_send_media_timeout_error_propagates() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_fallback_text_on_api_error() -> None:
|
||||
"""When _send_media returns False (API error), send() should emit fallback text."""
|
||||
channel, tmp_path = _make_channel_with_local_file()
|
||||
|
||||
from botpy.errors import ServerError
|
||||
@@ -407,7 +393,6 @@ async def test_send_fallback_text_on_api_error() -> None:
|
||||
)
|
||||
)
|
||||
|
||||
# Should have sent a fallback text message
|
||||
assert len(channel._client.api.c2c_calls) == 1
|
||||
fallback_content = channel._client.api.c2c_calls[0]["content"]
|
||||
assert "Attachment send failed" in fallback_content
|
||||
@@ -415,7 +400,6 @@ async def test_send_fallback_text_on_api_error() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_propagates_network_error_no_fallback() -> None:
|
||||
"""When _send_media raises a network error, send() should NOT silently fallback."""
|
||||
channel, tmp_path = _make_channel_with_local_file()
|
||||
|
||||
channel._client.api._http = SimpleNamespace()
|
||||
@@ -434,5 +418,4 @@ async def test_send_propagates_network_error_no_fallback() -> None:
|
||||
)
|
||||
)
|
||||
|
||||
# No fallback text should have been sent
|
||||
assert len(channel._client.api.c2c_calls) == 0
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for QQ channel media support: helpers, send, inbound, and upload."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
@@ -58,9 +56,6 @@ class _FakeClient:
|
||||
self.api._http = _FakeHttp(http_return)
|
||||
|
||||
|
||||
# ── Helper function tests (pure, no async) ──────────────────────────
|
||||
|
||||
|
||||
def test_sanitize_filename_strips_path_traversal() -> None:
|
||||
assert _sanitize_filename("../../etc/passwd") == "passwd"
|
||||
|
||||
@@ -71,7 +66,6 @@ def test_sanitize_filename_keeps_chinese_chars() -> None:
|
||||
|
||||
def test_sanitize_filename_strips_unsafe_chars() -> None:
|
||||
result = _sanitize_filename('file<>:"|?*.txt')
|
||||
# All unsafe chars replaced with "_", but * is replaced too
|
||||
assert result.startswith("file")
|
||||
assert result.endswith(".txt")
|
||||
assert "<" not in result
|
||||
@@ -112,12 +106,8 @@ def test_guess_send_file_type_by_mime() -> None:
|
||||
guess_type.assert_called_once_with(filename)
|
||||
|
||||
|
||||
# ── send() exception handling ───────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_exception_propagates_for_manager_retry() -> None:
|
||||
"""Delivery failures must propagate to the channel manager."""
|
||||
channel = QQChannel(QQConfig(app_id="app", secret="secret", allow_from=["*"]), MessageBus())
|
||||
channel._client = _FakeClient()
|
||||
|
||||
@@ -133,7 +123,6 @@ async def test_send_exception_propagates_for_manager_retry() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_then_text() -> None:
|
||||
"""Media is sent before text when both are present."""
|
||||
import tempfile
|
||||
|
||||
channel = QQChannel(QQConfig(app_id="app", secret="secret", allow_from=["*"]), MessageBus())
|
||||
@@ -156,7 +145,6 @@ async def test_send_media_then_text() -> None:
|
||||
)
|
||||
assert mock_upload.called
|
||||
|
||||
# Text should have been sent via c2c (default chat type)
|
||||
text_calls = [c for c in channel._client.api.c2c_calls if c.get("msg_type") == 0]
|
||||
assert len(text_calls) >= 1
|
||||
assert text_calls[-1]["content"] == "text after image"
|
||||
@@ -167,7 +155,6 @@ async def test_send_media_then_text() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_failure_falls_back_to_text() -> None:
|
||||
"""When _send_media returns False, a failure notice is appended."""
|
||||
channel = QQChannel(QQConfig(app_id="app", secret="secret", allow_from=["*"]), MessageBus())
|
||||
channel._client = _FakeClient()
|
||||
|
||||
@@ -182,7 +169,6 @@ async def test_send_media_failure_falls_back_to_text() -> None:
|
||||
)
|
||||
)
|
||||
|
||||
# Should have the failure text among the c2c calls
|
||||
failure_calls = [c for c in channel._client.api.c2c_calls if "Attachment send failed" in c.get("content", "")]
|
||||
assert len(failure_calls) == 1
|
||||
assert "bad.png" in failure_calls[0]["content"]
|
||||
@@ -253,18 +239,12 @@ async def test_on_message_ignores_unauthorized_group_before_attachments_and_ack(
|
||||
assert channel._client.api.group_calls == []
|
||||
|
||||
|
||||
# ── _on_message() exception handling ────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_exception_caught_not_raised() -> None:
|
||||
"""Missing required attributes should not crash _on_message."""
|
||||
channel = QQChannel(QQConfig(app_id="app", secret="secret", allow_from=["*"]), MessageBus())
|
||||
channel._client = _FakeClient()
|
||||
|
||||
# Construct a message-like object that lacks 'author' — triggers AttributeError
|
||||
bad_data = SimpleNamespace(id="x1", content="hi")
|
||||
# Should not raise
|
||||
await channel._on_message(bad_data, is_group=False)
|
||||
assert channel._client.api.c2c_calls == []
|
||||
assert channel._client.api.group_calls == []
|
||||
@@ -272,7 +252,6 @@ async def test_on_message_exception_caught_not_raised() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_message_with_attachments() -> None:
|
||||
"""Messages with attachments produce media_paths and formatted content."""
|
||||
import tempfile
|
||||
|
||||
channel = QQChannel(QQConfig(app_id="app", secret="secret", allow_from=["*"]), MessageBus())
|
||||
@@ -284,7 +263,6 @@ async def test_on_message_with_attachments() -> None:
|
||||
|
||||
att = SimpleNamespace(url="", filename="screenshot.png", content_type="image/png")
|
||||
|
||||
# Patch _download_to_media_dir_chunked to return the temp file path
|
||||
async def fake_download(url, filename_hint=""):
|
||||
return saved_path
|
||||
|
||||
@@ -309,9 +287,6 @@ async def test_on_message_with_attachments() -> None:
|
||||
os.unlink(saved_path)
|
||||
|
||||
|
||||
# ── _post_base64file() ─────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_post_base64file_omits_file_name_for_images() -> None:
|
||||
"""file_type=1 (image) → payload must not contain file_name."""
|
||||
@@ -335,7 +310,6 @@ async def test_post_base64file_omits_file_name_for_images() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_post_base64file_includes_file_name_for_files() -> None:
|
||||
"""file_type=4 (file) → payload must contain file_name."""
|
||||
channel = QQChannel(QQConfig(app_id="app", secret="secret"), MessageBus())
|
||||
channel._client = _FakeClient(http_return={"file_info": "file_abc"})
|
||||
|
||||
@@ -356,7 +330,6 @@ async def test_post_base64file_includes_file_name_for_files() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_post_base64file_filters_response_to_file_info() -> None:
|
||||
"""Response with file_info + extra fields must be filtered to only file_info."""
|
||||
channel = QQChannel(QQConfig(app_id="app", secret="secret"), MessageBus())
|
||||
channel._client = _FakeClient(http_return={
|
||||
"file_info": "fi_123",
|
||||
|
||||
@@ -16,8 +16,6 @@ from nanobot.channels.qq.runtime import (
|
||||
extract_quoted_content,
|
||||
)
|
||||
|
||||
# --- Real payload shapes ----------------------------------------------------
|
||||
|
||||
# C2C message quoting the bot. A plain message has no `ref_msg_idx` and no
|
||||
# `msg_elements`; both appear only when the user quotes something.
|
||||
C2C_QUOTING_BOT = {
|
||||
@@ -60,7 +58,6 @@ GROUP_QUOTING_USER = {
|
||||
],
|
||||
}
|
||||
|
||||
# Control group: a plain message. Same key set, but no quote links.
|
||||
PLAIN_MESSAGE = {
|
||||
"id": "ROBOT1.0_DBiKWe9lNhRwiQwghzMwQssT-SFcYlBDrD9xdX4A1hFupGIiqoLgkdtaAy.MKGwqGdR9Jb8mCS5DnjCudEwIjP9OC35zpbTlRPq8A8ILhi0!",
|
||||
"content": "接下来我要发几条测试消息,你忽略就行",
|
||||
@@ -74,9 +71,6 @@ PLAIN_MESSAGE = {
|
||||
}
|
||||
|
||||
|
||||
# --- extract_quoted_content -------------------------------------------------
|
||||
|
||||
|
||||
def test_extracts_c2c_quoted_message():
|
||||
assert extract_quoted_content(C2C_QUOTING_BOT) == "查完了,两处都没有叫 reference 的东西。"
|
||||
|
||||
@@ -86,12 +80,10 @@ def test_extracts_group_quoted_message():
|
||||
|
||||
|
||||
def test_plain_message_has_no_quoted_content():
|
||||
"""The control group: no ref_msg_idx, so nothing to surface."""
|
||||
assert extract_quoted_content(PLAIN_MESSAGE) is None
|
||||
|
||||
|
||||
def test_picks_element_matching_ref_idx_not_the_first():
|
||||
"""Elements are matched by index, so extra elements cannot shadow the quote."""
|
||||
payload = {
|
||||
"message_scene": {"ext": ["ref_msg_idx=wanted"]},
|
||||
"msg_elements": [
|
||||
@@ -103,7 +95,6 @@ def test_picks_element_matching_ref_idx_not_the_first():
|
||||
|
||||
|
||||
def test_ref_idx_without_matching_element_returns_none():
|
||||
"""Degradation: the quote is announced but the original is not attached."""
|
||||
payload = {
|
||||
"message_scene": {"ext": ["ref_msg_idx=missing"]},
|
||||
"msg_elements": [{"content": "something", "msg_idx": "other"}],
|
||||
@@ -148,15 +139,10 @@ def test_quoted_content_is_truncated():
|
||||
],
|
||||
)
|
||||
def test_malformed_payloads_return_none(payload):
|
||||
"""Unexpected shapes must degrade, never raise."""
|
||||
assert extract_quoted_content(payload) is None
|
||||
|
||||
|
||||
# --- _flatten_scene_ext -----------------------------------------------------
|
||||
|
||||
|
||||
def test_flatten_scene_ext_splits_on_first_equals_only():
|
||||
"""Values (e.g. base64 indexes) may themselves contain '='."""
|
||||
assert _flatten_scene_ext({"ext": ["a=b=c", "plain", "k=v"]}) == {"a": "b=c", "k": "v"}
|
||||
|
||||
|
||||
@@ -164,9 +150,6 @@ def test_flatten_scene_ext_ignores_non_string_entries():
|
||||
assert _flatten_scene_ext({"ext": [123, None, "k=v"]}) == {"k": "v"}
|
||||
|
||||
|
||||
# --- _quoted_content_for ----------------------------------------------------
|
||||
|
||||
|
||||
class _FakeMessage:
|
||||
"""Duck-typed stand-in for a botpy message object."""
|
||||
|
||||
@@ -177,7 +160,6 @@ class _FakeMessage:
|
||||
|
||||
|
||||
def test_quoted_content_prefers_fields_on_the_message_object(monkeypatch):
|
||||
"""A botpy that parses these fields makes the payload hook redundant."""
|
||||
message = _FakeMessage(
|
||||
"whatever",
|
||||
message_scene=C2C_QUOTING_BOT["message_scene"],
|
||||
@@ -207,7 +189,6 @@ def test_quoted_content_is_none_for_unknown_message():
|
||||
|
||||
|
||||
# --- End-to-end: capture -> lookup -> content ------------------------------
|
||||
#
|
||||
# These exercise the real botpy message classes, so they are skipped wherever
|
||||
# the optional QQ dependency is absent (same gate as the other QQ test modules).
|
||||
|
||||
@@ -253,7 +234,6 @@ def captured():
|
||||
|
||||
@requires_botpy
|
||||
def test_capture_hook_keeps_payload_from_real_botpy_class(captured):
|
||||
"""botpy drops these fields, so the constructor hook is the only way in."""
|
||||
from botpy import message as botpy_message
|
||||
|
||||
qq_runtime._install_qq_payload_capture()
|
||||
@@ -335,7 +315,6 @@ async def test_group_quote_is_prefixed_onto_content(captured):
|
||||
@pytest.mark.asyncio
|
||||
@requires_botpy
|
||||
async def test_plain_message_content_is_unchanged(captured):
|
||||
"""Control group: no quote link, so the message must reach the agent as-is."""
|
||||
channel = QQChannel(
|
||||
QQConfig(app_id="app", secret="secret", allow_from=["user1"]), MessageBus()
|
||||
)
|
||||
@@ -350,7 +329,6 @@ async def test_plain_message_content_is_unchanged(captured):
|
||||
@pytest.mark.asyncio
|
||||
@requires_botpy
|
||||
async def test_quote_without_text_is_not_dropped(captured):
|
||||
"""A quote-only message carries meaning, so it must survive the empty-content gate."""
|
||||
channel = QQChannel(
|
||||
QQConfig(app_id="app", secret="secret", allow_from=["user1"]), MessageBus()
|
||||
)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Discover channel descriptors and load their runtimes lazily."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pkgutil
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Signal channel package."""
|
||||
Loaded 100 of 922 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user