The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(wecom): split long messages instead of silently truncating them
teknium1a959a6ede13d
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.pyindex f2bcd992287..7d45e6500d1 100644--- a/plugins/platforms/wecom/adapter.py+++ b/plugins/platforms/wecom/adapter.py@@ -107,6 +107,7 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAccSUPPORTS_MESSAGE_EDITING = FalseSUPPORTS_NATIVE_STREAMING = True # msgtype "stream" via aibot_respond_msg, not edit-basedMAX_STREAM_CONTENT_LENGTH = MAX_STREAM_CONTENT_LENGTH+ splits_long_messages = True # send() chunks via truncate_message(MAX_MESSAGE_LENGTH)_SPLIT_THRESHOLD = 3900 # chunks near the 4000-char client split are almost certainly continueddef __init__(self, config: PlatformConfig):@@ -598,7 +599,13 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAccis_control = metadata.pop("is_approval_prompt", False)# Approval *confirmations* must not consume the req_id the stream consumer still needs.force_proactive = bool(metadata.pop("force_proactive_send", False))- return await self._enqueue_chat_send(chat_id, lambda: self._send_inner(chat_id, content, reply_to, force_proactive=force_proactive), is_control=is_control)+ # One queued send per chunk so each one draws a token from the 30 msgs/min bucket.+ result = SendResult(success=False, error="nothing to send")+ for chunk in self.truncate_message(content, self.MAX_MESSAGE_LENGTH):+ result = await self._enqueue_chat_send(chat_id, lambda c=chunk: self._send_inner(chat_id, c, reply_to, force_proactive=force_proactive), is_control=is_control)+ if not result.success:+ break+ return resultasync def _send_inner(self, chat_id: str, content: str, reply_to: Optional[str] = None, *, force_proactive: bool = False) -> SendResult:"""Send under the per-chat queue; force_proactive skips passive reply except in groups."""diff --git a/plugins/platforms/wecom/callback_adapter.py b/plugins/platforms/wecom/callback_adapter.pyindex 1a6004b43bd..7dafb76baeb 100644--- a/plugins/platforms/wecom/callback_adapter.py+++ b/plugins/platforms/wecom/callback_adapter.py@@ -49,6 +49,10 @@ _SEND_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"+def _utf8_len(text: str) -> int:+ return len(text.encode("utf-8"))++def check_wecom_callback_requirements() -> bool:"""PASSIVE probe (registry ``check_fn``) — must never install anything."""return AIOHTTP_AVAILABLE and HTTPX_AVAILABLE and DEFUSEDXML_AVAILABLE@@ -86,6 +90,9 @@ def _ack():class WecomCallbackAdapter(BasePlatformAdapter):# Answers /p/<profile>/... on the default listener for a served secondary (shared_ingress).serves_profile_prefix: bool = True+ # message/send keeps only the first 2048 BYTES of text.content and drops the rest silently.+ MAX_MESSAGE_LENGTH = 2048+ splits_long_messages = True # send() chunks via truncate_message(MAX_MESSAGE_LENGTH, _utf8_len)def __init__(self, config: PlatformConfig):super().__init__(config, Platform.WECOM_CALLBACK)extra = config.extra or {}@@ -181,9 +188,18 @@ class WecomCallbackAdapter(BasePlatformAdapter):self._http_client = Noneasync def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:+ """One text message per MAX_MESSAGE_LENGTH-byte chunk; stops at the first failure."""app = self._resolve_app_for_chat(chat_id)+ result = SendResult(success=False, error="nothing to send")+ for chunk in self.truncate_message(content, self.MAX_MESSAGE_LENGTH, len_fn=_utf8_len):+ result = await self._send_text(app, chat_id, chunk)+ if not result.success:+ break+ return result++ async def _send_text(self, app: Dict[str, Any], chat_id: str, content: str) -> SendResult:try:- payload = {"touser": chat_id.split(":", 1)[-1], "msgtype": "text", "agentid": int(str(app.get("agent_id") or 0)), "text": {"content": content[:2048]}, "safe": 0}+ payload = {"touser": chat_id.split(":", 1)[-1], "msgtype": "text", "agentid": int(str(app.get("agent_id") or 0)), "text": {"content": content}, "safe": 0}for _attempt in range(2):token = await self._get_access_token(app)resp = await self._http_client.post(f"{_SEND_URL}{token}", json=payload)diff --git a/tests/gateway/test_wecom.py b/tests/gateway/test_wecom.pyindex 16d7ee4e903..f8e23f20d72 100644--- a/tests/gateway/test_wecom.py+++ b/tests/gateway/test_wecom.py@@ -1285,3 +1285,37 @@ class TestFinalFrameAckTimeoutSemantics:{"msgtype": "stream", "stream": {"id": "stream_x", "content": "x", "finish": True}},is_final=True,)++++async def test_oversized_cron_output_is_sent_as_successive_markdown_replies():+ """The router hands the full cron payload over and every chunk goes out on the cached reply+ req_id (groups cannot send proactively), each through the rate-limited per-chat queue,+ instead of the tail being sliced off at 4000 chars."""+ from gateway.config import GatewayConfig+ from gateway.delivery import DeliveryRouter+ from plugins.platforms.wecom.adapter import MAX_MESSAGE_LENGTH, WeComAdapter++ adapter = WeComAdapter(PlatformConfig(enabled=True))+ adapter._last_chat_req_ids["group-1"] = "req-1"+ adapter._group_chat_ids.add("group-1")+ sent = []++ async def _reply(req_id, body, **_):+ sent.append((req_id, body["markdown"]["content"]))+ return {"headers": {"req_id": req_id}, "errcode": 0}++ adapter._send_reply_request = _reply+ adapter._send_request = AsyncMock()+ content = "\n\n".join(f"line {i} " + "x" * 200 for i in range(60))+ payload = DeliveryRouter(GatewayConfig())._cap_oversized_output(adapter, content, "job")+ result = await adapter.send("group-1", payload)++ assert result.success+ assert len(sent) > 1 and {req for req, _ in sent} == {"req-1"}+ assert max(len(text) for _, text in sent) <= MAX_MESSAGE_LENGTH+ assert "line 59 " in sent[-1][1]+ adapter._send_request.assert_not_awaited()+ # Each chunk is its own queued send, so each draws a token from the 30 msgs/min bucket.+ assert adapter._get_token_usage("group-1")["normal"] == len(sent)diff --git a/tests/gateway/test_wecom_callback.py b/tests/gateway/test_wecom_callback.pyindex 78343dfd383..ef7d6c5dc20 100644--- a/tests/gateway/test_wecom_callback.py+++ b/tests/gateway/test_wecom_callback.py@@ -211,4 +211,28 @@ class TestWecomCallbackBodySizeLimit:response = await adapter._handle_callback(self._request(oversized))assert response.status == 413-+async def test_oversized_cron_output_is_split_under_the_2048_byte_text_limit():+ """message/send keeps only the first 2048 BYTES of text.content; CJK output used to lose+ everything past ~680 characters. The router now hands over the full payload and send()+ splits it by UTF-8 bytes."""+ from gateway.config import GatewayConfig+ from gateway.delivery import DeliveryRouter++ adapter = WecomCallbackAdapter(_config())+ adapter._access_tokens["test-app"] = {"token": "tok", "expires_at": 9999999999}+ sent = []++ class _Client:+ async def post(self, url, json):+ sent.append(json["text"]["content"])+ return type("R", (), {"json": lambda self: {"errcode": 0, "msgid": "m"}})()++ adapter._http_client = _Client()+ content = "\n\n".join(f"第{i}段 " + "数据" * 100 for i in range(40))+ payload = DeliveryRouter(GatewayConfig())._cap_oversized_output(adapter, content, "job")+ result = await adapter.send("test-app:user1", payload)++ assert result.success+ assert len(sent) > 1 and max(len(s.encode()) for s in sent) <= 2048+ assert "第39段" in sent[-1]diff --git a/website/docs/user-guide/messaging/wecom-callback.md b/website/docs/user-guide/messaging/wecom-callback.mdindex f6cf5ed4a47..f33f26eef1d 100644--- a/website/docs/user-guide/messaging/wecom-callback.md+++ b/website/docs/user-guide/messaging/wecom-callback.md@@ -151,6 +151,7 @@ The crypto implementation is compatible with Tencent's official WXBizMsgCrypt SD- **No typing indicators** — the callback model doesn't support typing status- **Text only** — currently supports text messages for input; image/file/voice input not yet implemented. The agent is aware of outbound media capabilities via the WeCom platform hint (images, documents, video, voice).- **Response latency** — agent sessions take 3–30 minutes; users see the reply when processing completes+- **2048-byte text messages** — WeCom keeps only the first 2048 bytes of a text message, so longer replies (and cron output) are split across several messages; CJK text fits roughly 680 characters per message## Troubleshootingdiff --git a/website/docs/user-guide/messaging/wecom.md b/website/docs/user-guide/messaging/wecom.mdindex 8874a8fbc0c..83feb750980 100644--- a/website/docs/user-guide/messaging/wecom.md+++ b/website/docs/user-guide/messaging/wecom.md@@ -227,7 +227,7 @@ No configuration is needed — decryption happens transparently when encrypted m| Method | What it sends | Size limit ||--------|--------------|------------|-| `send` | Markdown text messages | 4000 chars |+| `send` | Markdown text messages | 4000 chars per message; longer text is split across messages || `send_image` / `send_image_file` | Native image messages | 10 MB || `send_document` | File attachments | 20 MB || `send_voice` | Voice messages (AMR format only for native voice) | 2 MB |diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/wecom-callback.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/wecom-callback.mdindex 811c566b5c3..c3696fd6bf5 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/wecom-callback.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/wecom-callback.md@@ -146,4 +146,5 @@ WECOM_CALLBACK_ALLOW_ALL_USERS=true- **不支持流式输出** — 回复在 agent 完成处理后以完整消息形式送达- **不支持正在输入提示** — 回调模式不支持输入状态- **仅支持文本** — 目前仅支持文本消息输入;图片/文件/语音输入尚未实现。Agent 可通过企业微信平台提示感知出站媒体能力(图片、文档、视频、语音)。-- **响应延迟** — Agent 会话需要 3–30 分钟;用户在处理完成后收到回复\ No newline at end of file+- **响应延迟** — Agent 会话需要 3–30 分钟;用户在处理完成后收到回复+- **文本消息上限 2048 字节** — 企业微信只保留文本消息的前 2048 字节,因此更长的回复(包括定时任务输出)会拆分为多条消息;中文每条约 680 字\ No newline at end of filediff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/wecom.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/wecom.mdindex fc1b04aeb63..c363b916803 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/wecom.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/wecom.md@@ -210,7 +210,7 @@ WeCom 对部分入站媒体附件使用 AES-256-CBC 加密。适配器会自动| 方法 | 发送内容 | 大小限制 ||--------|--------------|------------|-| `send` | Markdown 文本消息 | 4000 字符 |+| `send` | Markdown 文本消息 | 每条 4000 字符;更长的文本会拆分为多条消息 || `send_image` / `send_image_file` | 原生图片消息 | 10 MB || `send_document` | 文件附件 | 20 MB || `send_voice` | 语音消息(原生语音仅支持 AMR 格式) | 2 MB |