Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(wechat): split oversized outbound messages

cyh5b5dde600699
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index d8cd02951..1b3ddc456 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -16,6 +16,9 @@ from core.reply_enhancer import process_reply
logger = logging.getLogger(__name__)
+_WECHAT_TEXT_LIMIT = 1900
+_WECHAT_CONSOLIDATED_SPLIT_THRESHOLD = 1700
+
class ConsolidatedMessageDispatcher:
"""Dispatch agent messages while preserving existing product behavior."""
@@ -100,17 +103,23 @@ class ConsolidatedMessageDispatcher:
self._consolidated_message_buffers.pop(key, None)
def _get_consolidated_max_bytes(self, context: MessageContext) -> int:
- if (
+ platform = (
context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
- ) == "discord":
+ )
+ if platform == "discord":
return 2000
+ if platform == "wechat":
+ return _WECHAT_TEXT_LIMIT
return 4000
def _get_consolidated_split_threshold(self, context: MessageContext) -> int:
- if (
+ platform = (
context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
- ) == "discord":
+ )
+ if platform == "discord":
return 1800
+ if platform == "wechat":
+ return _WECHAT_CONSOLIDATED_SPLIT_THRESHOLD
return 3600
@staticmethod
@@ -118,16 +127,31 @@ class ConsolidatedMessageDispatcher:
return len(text.encode("utf-8"))
def _get_result_max_chars(self, context: MessageContext) -> int:
- if (
+ platform = (
context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
- ) == "discord":
+ )
+ if platform == "discord":
return 1900
return 30000
+ def _get_result_max_bytes(self, context: MessageContext) -> Optional[int]:
+ platform = (
+ context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
+ )
+ if platform == "wechat":
+ return _WECHAT_TEXT_LIMIT
+ return None
+
def _should_split_long_result(self, context: MessageContext) -> bool:
return (
context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
- ) == "discord"
+ ) in {"discord", "wechat"}
+
+ def _result_within_limit(self, context: MessageContext, text: str) -> bool:
+ max_bytes = self._get_result_max_bytes(context)
+ if max_bytes is not None:
+ return self._get_text_byte_length(text) <= max_bytes
+ return len(text) <= self._get_result_max_chars(context)
def _supports_quick_replies(self, context: MessageContext) -> bool:
return (
@@ -153,7 +177,8 @@ class ConsolidatedMessageDispatcher:
for separator in ("\n\n", "\n", " "):
index = text.rfind(separator, 0, max_chars + 1)
if index >= minimum_boundary:
- return index + len(separator)
+ candidate = index + len(separator)
+ return candidate if candidate <= max_chars else index
return max_chars
def _split_result_text(self, text: str, max_chars: int) -> list[str]:
@@ -175,6 +200,38 @@ class ConsolidatedMessageDispatcher:
return chunks
+ def _split_result_text_by_bytes(self, text: str, max_bytes: int) -> list[str]:
+ if self._get_text_byte_length(text) <= max_bytes:
+ return [text]
+
+ chunks: list[str] = []
+ remaining = text
+
+ while self._get_text_byte_length(remaining) > max_bytes:
+ prefix = remaining.encode("utf-8")[:max_bytes].decode("utf-8", errors="ignore")
+ minimum_boundary = max(1, len(prefix) // 2)
+ split_at = len(prefix)
+ for separator in ("\n\n", "\n", " "):
+ index = prefix.rfind(separator)
+ if index >= minimum_boundary:
+ candidate = index + len(separator)
+ if self._get_text_byte_length(remaining[:candidate]) <= max_bytes:
+ split_at = candidate
+ break
+ chunks.append(remaining[:split_at])
+ remaining = remaining[split_at:]
+
+ if remaining:
+ chunks.append(remaining)
+
+ return chunks
+
+ def _split_result_text_for_context(self, context: MessageContext, text: str) -> list[str]:
+ max_bytes = self._get_result_max_bytes(context)
+ if max_bytes is not None:
+ return self._split_result_text_by_bytes(text, max_bytes)
+ return self._split_result_text(text, self._get_result_max_chars(context))
+
def _truncate_consolidated(self, text: str, max_bytes: int) -> str:
if self._get_text_byte_length(text) <= max_bytes:
return text
@@ -229,7 +286,7 @@ class ConsolidatedMessageDispatcher:
enhanced = None
display_text = text
- if len(display_text) <= self._get_result_max_chars(context):
+ if self._result_within_limit(context, display_text):
if enhanced and enhanced.buttons and self._supports_quick_replies(context):
try:
primary_message_id = await self._send_with_quick_replies(
@@ -249,7 +306,9 @@ class ConsolidatedMessageDispatcher:
logger.error("Failed to send fallback result message: %s", fallback_err)
else:
try:
- primary_message_id = await im_client.send_message(target_context, display_text, parse_mode=parse_mode)
+ primary_message_id = await im_client.send_message(
+ target_context, display_text, parse_mode=parse_mode
+ )
except Exception as err:
logger.error("Failed to send result message: %s", err)
elif self._should_split_long_result(context):
@@ -447,7 +506,9 @@ class ConsolidatedMessageDispatcher:
callback = f"quick_reply:{btn.text}"
row.append(InlineButton(text=btn.text, callback_data=callback))
- platform = context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
+ platform = (
+ context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
+ )
rows = [[button] for button in row] if platform in {"lark", "telegram"} else [row]
keyboard = InlineKeyboard(buttons=rows)
return await im_client.send_message_with_buttons(
@@ -465,7 +526,7 @@ class ConsolidatedMessageDispatcher:
buttons,
parse_mode,
) -> Optional[str]:
- chunks = self._split_result_text(text, self._get_result_max_chars(context))
+ chunks = self._split_result_text_for_context(context, text)
first_message_id: Optional[str] = None
for index, chunk in enumerate(chunks):
diff --git a/tests/test_message_dispatcher_platform_limits.py b/tests/test_message_dispatcher_platform_limits.py
new file mode 100644
index 000000000..a366da23f
--- /dev/null
+++ b/tests/test_message_dispatcher_platform_limits.py
@@ -0,0 +1,105 @@
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.message_dispatcher import ConsolidatedMessageDispatcher
+from modules.im import MessageContext
+
+
+class _StubIMClient:
+ def __init__(self, max_bytes: int | None = None):
+ self.sent = []
+ self._next_id = 1
+ self._max_bytes = max_bytes
+
+ def should_use_thread_for_reply(self):
+ return False
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ if self._max_bytes is not None and len(text.encode("utf-8")) > self._max_bytes:
+ raise RuntimeError("message too large")
+ self.sent.append((context.channel_id, context.thread_id, text, parse_mode))
+ message_id = f"bot-msg-{self._next_id}"
+ self._next_id += 1
+ return message_id
+
+ async def edit_message(self, context, message_id, text=None, keyboard=None, parse_mode=None):
+ return False
+
+
+class _StubSettingsManager:
+ def _canonicalize_message_type(self, message_type):
+ return message_type
+
+ def is_message_type_hidden(self, settings_key, canonical_type):
+ return False
+
+
+class _StubSessionHandler:
+ def __init__(self):
+ self.calls = []
+
+ def finalize_scheduled_delivery(self, context, sent_message_id):
+ self.calls.append((context.channel_id, context.thread_id, sent_message_id))
+
+
+class _StubController:
+ def __init__(self, platform: str, *, max_bytes: int | None = None):
+ self.config = type("Config", (), {"platform": platform, "reply_enhancements": False})()
+ self.session_handler = _StubSessionHandler()
+ self.im_client = _StubIMClient(max_bytes=max_bytes)
+
+ def _get_settings_key(self, context):
+ return context.channel_id
+
+ def _get_session_key(self, context):
+ return f"{context.platform}::{context.channel_id}"
+
+ def get_settings_manager_for_context(self, context):
+ return _StubSettingsManager()
+
+ def get_im_client_for_context(self, context):
+ return self.im_client
+
+
+class MessageDispatcherPlatformLimitTests(unittest.IsolatedAsyncioTestCase):
+ async def test_wechat_long_result_splits_across_messages(self):
+ controller = _StubController("wechat", max_bytes=1900)
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="wechat-user", channel_id="wechat-user", platform="wechat")
+ long_text = "你" * 1900
+
+ message_id = await dispatcher.emit_agent_message(context, "result", long_text)
+
+ self.assertEqual(message_id, "bot-msg-1")
+ self.assertGreater(len(controller.im_client.sent), 1)
+ self.assertEqual("".join(text for _, _, text, _ in controller.im_client.sent), long_text)
+ self.assertTrue(all(len(text.encode("utf-8")) <= 1900 for _, _, text, _ in controller.im_client.sent))
+
+ async def test_wechat_long_log_message_splits_before_send_failure(self):
+ controller = _StubController("wechat")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="wechat-user", channel_id="wechat-user", platform="wechat")
+ long_text = "x" * 5000
+
+ message_id = await dispatcher.emit_agent_message(context, "assistant", long_text)
+
+ self.assertIsNotNone(message_id)
+ self.assertGreater(len(controller.im_client.sent), 1)
+ self.assertTrue(all(len(text.encode("utf-8")) <= 1900 for _, _, text, _ in controller.im_client.sent))
+
+ def test_result_split_boundary_never_exceeds_platform_limit(self):
+ dispatcher = ConsolidatedMessageDispatcher(_StubController("wechat"))
+
+ chunks = dispatcher._split_result_text_by_bytes("你" * 633 + "你", 1900)
+
+ self.assertEqual(chunks, ["你" * 633, "你"])
+ self.assertTrue(all(len(chunk.encode("utf-8")) <= 1900 for chunk in chunks))
+
+
+if __name__ == "__main__":
+ unittest.main()