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(discord): split oversized result replies

cyh935befc7e3f2
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index cd16ef9e1..abb65e8fa 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -124,6 +124,11 @@ class ConsolidatedMessageDispatcher:
return 1900
return 30000
+ 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"
+
def _supports_quick_replies(self, context: MessageContext) -> bool:
return (
context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
@@ -142,6 +147,34 @@ class ConsolidatedMessageDispatcher:
keep = max(0, max_chars - len(prefix) - len(suffix))
return f"{prefix}{text[:keep]}{suffix}"
+ @staticmethod
+ def _find_result_split_index(text: str, max_chars: int) -> int:
+ minimum_boundary = max_chars // 2
+ for separator in ("\n\n", "\n", " "):
+ index = text.rfind(separator, 0, max_chars + 1)
+ if index >= minimum_boundary:
+ return index + len(separator)
+ return max_chars
+
+ def _split_result_text(self, text: str, max_chars: int) -> list[str]:
+ if len(text) <= max_chars:
+ return [text]
+
+ chunks: list[str] = []
+ remaining = text
+
+ while len(remaining) > max_chars:
+ split_at = self._find_result_split_index(remaining, max_chars)
+ if split_at <= 0:
+ split_at = max_chars
+ chunks.append(remaining[:split_at])
+ remaining = remaining[split_at:]
+
+ if remaining:
+ chunks.append(remaining)
+
+ return chunks
+
def _truncate_consolidated(self, text: str, max_bytes: int) -> str:
if self._get_text_byte_length(text) <= max_bytes:
return text
@@ -219,6 +252,17 @@ class ConsolidatedMessageDispatcher:
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):
+ try:
+ primary_message_id = await self._send_split_result_messages(
+ im_client,
+ target_context,
+ display_text,
+ enhanced.buttons if enhanced else [],
+ parse_mode,
+ )
+ except Exception as err:
+ logger.error("Failed to send split result messages: %s", err)
else:
summary = self._build_result_summary(display_text, self._get_result_max_chars(context))
try:
@@ -413,6 +457,41 @@ class ConsolidatedMessageDispatcher:
parse_mode=parse_mode,
)
+ async def _send_split_result_messages(
+ self,
+ im_client,
+ context: MessageContext,
+ text: str,
+ buttons,
+ parse_mode,
+ ) -> Optional[str]:
+ chunks = self._split_result_text(text, self._get_result_max_chars(context))
+ first_message_id: Optional[str] = None
+
+ for index, chunk in enumerate(chunks):
+ is_last_chunk = index == len(chunks) - 1
+ message_id: Optional[str] = None
+
+ if is_last_chunk and buttons and self._supports_quick_replies(context):
+ try:
+ message_id = await self._send_with_quick_replies(
+ im_client,
+ context,
+ chunk,
+ buttons,
+ parse_mode,
+ )
+ except Exception as err:
+ logger.warning("Failed to send split result chunk with quick replies, falling back: %s", err)
+
+ if message_id is None:
+ message_id = await im_client.send_message(context, chunk, parse_mode=parse_mode)
+
+ if first_message_id is None:
+ first_message_id = message_id
+
+ return first_message_id
+
async def _upload_file_links(
self,
im_client,
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index c66de626e..a9e3f3580 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -13,16 +13,21 @@ from modules.im import MessageContext
class _StubIMClient:
def __init__(self):
self.sent = []
+ self._next_id = 1
def should_use_thread_for_reply(self):
return False
async def send_message(self, context, text, parse_mode=None, reply_to=None):
self.sent.append((context.channel_id, context.thread_id, text))
- return "bot-msg-1"
+ message_id = f"bot-msg-{self._next_id}"
+ self._next_id += 1
+ return message_id
async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):
- return "bot-msg-1"
+ message_id = f"bot-msg-{self._next_id}"
+ self._next_id += 1
+ return message_id
class _StubSettingsManager:
@@ -112,3 +117,25 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(message_id, "bot-msg-1")
self.assertEqual(controller.im_client.sent, [("C123", None, "hello")])
self.assertEqual(controller.session_handler.calls, [("C123", "171717.123", "bot-msg-1")])
+
+ async def test_discord_long_result_uses_first_chunk_as_scheduled_anchor(self):
+ controller = _StubController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="discord",
+ platform_specific={
+ "turn_source": "scheduled",
+ "turn_base_session_id": "discord_scheduled-1",
+ "scheduled_anchor_required": True,
+ },
+ )
+ long_text = "x" * 4200
+
+ message_id = await dispatcher.emit_agent_message(context, "result", long_text)
+
+ self.assertEqual(message_id, "bot-msg-1")
+ self.assertEqual(len(controller.im_client.sent), 3)
+ self.assertEqual("".join(text for _, _, text in controller.im_client.sent), long_text)
+ self.assertEqual(controller.session_handler.calls, [("C123", None, "bot-msg-1")])
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index c8a401f61..313bc7a11 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -25,6 +25,8 @@ class _StubIMClient:
def __init__(self):
self.sent_messages = []
self.sent_button_messages = []
+ self.uploaded_markdowns = []
+ self._next_id = 1
@staticmethod
def should_use_thread_for_reply() -> bool:
@@ -32,11 +34,19 @@ class _StubIMClient:
async def send_message(self, context, text, parse_mode=None, reply_to=None):
self.sent_messages.append((context.channel_id, text, parse_mode))
- return "msg-1"
+ message_id = f"msg-{self._next_id}"
+ self._next_id += 1
+ return message_id
async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):
self.sent_button_messages.append((context.channel_id, text, parse_mode, keyboard))
- return "btn-1"
+ message_id = f"btn-{self._next_id}"
+ self._next_id += 1
+ return message_id
+
+ async def upload_markdown(self, context, title, content, filetype="markdown"):
+ self.uploaded_markdowns.append((context.channel_id, title, content, filetype))
+ return "file-1"
class _StubController:
@@ -186,6 +196,22 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
keyboard = controller.im_client.sent_button_messages[0][3]
self.assertEqual([[button.text for button in row] for row in keyboard.buttons], [["继续"], ["提交PR"]])
+ async def test_discord_long_result_splits_into_multiple_messages_without_markdown_attachment(self):
+ controller = _StubController("discord")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C1", platform="discord")
+ long_text = " ".join(["Alpha"] * 320) + "\n\n" + " ".join(["Beta"] * 120)
+
+ message_id = await dispatcher.emit_agent_message(context, "result", long_text)
+
+ self.assertEqual(message_id, "msg-1")
+ self.assertGreater(len(controller.im_client.sent_messages), 1)
+ self.assertEqual(
+ "".join(text for _, text, _ in controller.im_client.sent_messages),
+ long_text,
+ )
+ self.assertEqual(controller.im_client.uploaded_markdowns, [])
+
if __name__ == "__main__":
unittest.main()