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(slack): split long quick-reply messages

cyh83c97e906eea
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 1b393b3db..65b851773 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -40,6 +40,7 @@ from modules.agents.native_sessions.types import NativeResumeSession
logger = logging.getLogger(__name__)
_UNSET = object()
+_SLACK_SECTION_TEXT_LIMIT = 3000
class SlackBot(BaseIMClient):
@@ -284,6 +285,105 @@ class SlackBot(BaseIMClient):
context.thread_id = None
return await self.web_client.chat_postMessage(**kwargs)
+ @staticmethod
+ def _find_text_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:
+ candidate = index + len(separator)
+ return candidate if candidate <= max_chars else index
+ return max_chars
+
+ @classmethod
+ def _split_text(cls, 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 = cls._find_text_split_index(remaining, max_chars)
+ chunks.append(remaining[:split_at])
+ remaining = remaining[split_at:]
+ if remaining:
+ chunks.append(remaining)
+ return chunks
+
+ @classmethod
+ def _get_visible_text(cls, text: str, max_chars: int = _SLACK_SECTION_TEXT_LIMIT) -> str:
+ return cls._split_text(text, max_chars)[-1]
+
+ @staticmethod
+ def _build_section_block(text: str, parse_mode: Optional[str] = None) -> Dict[str, Any]:
+ return {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn" if parse_mode == "markdown" else "plain_text",
+ "text": text,
+ },
+ }
+
+ def _build_button_blocks(
+ self,
+ text: Optional[str],
+ keyboard: InlineKeyboard,
+ parse_mode: Optional[str] = None,
+ ) -> List[Dict[str, Any]]:
+ blocks: List[Dict[str, Any]] = []
+ if text:
+ blocks.append(self._build_section_block(text, parse_mode=parse_mode))
+
+ for row_idx, row in enumerate(keyboard.buttons):
+ elements = []
+ for button in row:
+ elements.append(
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": button.text},
+ "action_id": button.callback_data,
+ "value": button.callback_data,
+ }
+ )
+
+ blocks.append(
+ {
+ "type": "actions",
+ "block_id": f"actions_{row_idx}",
+ "elements": elements,
+ }
+ )
+
+ return blocks
+
+ async def _send_prepared_text_message(
+ self,
+ context: MessageContext,
+ text: str,
+ parse_mode: Optional[str] = None,
+ reply_to: Optional[str] = None,
+ ):
+ kwargs = {"channel": context.channel_id, "text": text}
+
+ if context.thread_id:
+ kwargs["thread_ts"] = context.thread_id
+ if context.platform_specific and context.platform_specific.get("reply_broadcast"):
+ kwargs["reply_broadcast"] = True
+ elif reply_to:
+ kwargs["thread_ts"] = reply_to
+
+ if parse_mode == "markdown":
+ kwargs["mrkdwn"] = True
+
+ if "\n" in text and len(text) <= _SLACK_SECTION_TEXT_LIMIT:
+ kwargs["blocks"] = [self._build_section_block(text, parse_mode=parse_mode)]
+
+ return await self._post_message_with_dm_recovery(
+ context,
+ kwargs,
+ log_label="message send",
+ )
+
async def send_dm(self, user_id: str, text: str, **kwargs) -> Optional[str]:
"""Send a direct message to a Slack user by opening a DM channel first."""
self._ensure_clients()
@@ -315,41 +415,11 @@ class SlackBot(BaseIMClient):
if parse_mode == "markdown":
text = self._convert_markdown_to_slack_mrkdwn(text)
- # Prepare message kwargs
- kwargs = {"channel": context.channel_id, "text": text}
-
- # Handle thread replies
- if context.thread_id:
- kwargs["thread_ts"] = context.thread_id
- # Optionally broadcast to channel
- if context.platform_specific and context.platform_specific.get("reply_broadcast"):
- kwargs["reply_broadcast"] = True
- elif reply_to:
- # If reply_to is specified, use it as thread timestamp
- kwargs["thread_ts"] = reply_to
-
- # Handle formatting
- if parse_mode == "markdown":
- kwargs["mrkdwn"] = True
-
- # Workaround: ensure multi-line content is preserved. Slack sometimes collapses
- # rich_text rendering for bot messages; sending with blocks+mrkdwn forces line breaks.
- if "\n" in text and "blocks" not in kwargs and len(text) <= 3000:
- kwargs["blocks"] = [
- {
- "type": "section",
- "text": {
- "type": "mrkdwn" if parse_mode == "markdown" else "plain_text",
- "text": text,
- },
- }
- ]
-
- # Send message
- response = await self._post_message_with_dm_recovery(
+ response = await self._send_prepared_text_message(
context,
- kwargs,
- log_label="message send",
+ text,
+ parse_mode=parse_mode,
+ reply_to=reply_to,
)
# Mark thread as active if we sent a message to a thread
@@ -935,38 +1005,14 @@ class SlackBot(BaseIMClient):
if parse_mode == "markdown":
text = self._convert_markdown_to_slack_mrkdwn(text)
- # Convert our generic keyboard to Slack blocks
- blocks = [
- {
- "type": "section",
- "text": {
- "type": "mrkdwn" if parse_mode == "markdown" else "plain_text",
- "text": text,
- "verbatim": True,
- },
- }
- ]
-
- # Add action blocks for buttons
- for row_idx, row in enumerate(keyboard.buttons):
- elements = []
- for button in row:
- elements.append(
- {
- "type": "button",
- "text": {"type": "plain_text", "text": button.text},
- "action_id": button.callback_data,
- "value": button.callback_data,
- }
- )
+ chunks = self._split_text(text, _SLACK_SECTION_TEXT_LIMIT)
+ for chunk in chunks[:-1]:
+ await self._send_prepared_text_message(context, chunk, parse_mode=parse_mode)
+ text = chunks[-1]
- blocks.append(
- {
- "type": "actions",
- "block_id": f"actions_{row_idx}",
- "elements": elements,
- }
- )
+ blocks = self._build_button_blocks(text, keyboard, parse_mode=parse_mode)
+ if blocks and blocks[0].get("type") == "section":
+ blocks[0]["text"]["verbatim"] = True
# Prepare message kwargs
kwargs = {
@@ -1014,43 +1060,11 @@ class SlackBot(BaseIMClient):
kwargs = {"channel": context.channel_id, "ts": message_id}
if text is not None:
- kwargs["text"] = text
+ kwargs["text"] = self._get_visible_text(text) if keyboard else text
if keyboard:
- # Convert keyboard to blocks (similar to send_message_with_buttons)
- blocks = []
- if text:
- blocks.append(
- {
- "type": "section",
- "text": {
- "type": "mrkdwn" if parse_mode == "markdown" else "plain_text",
- "text": text,
- },
- }
- )
-
- for row_idx, row in enumerate(keyboard.buttons):
- elements = []
- for button in row:
- elements.append(
- {
- "type": "button",
- "text": {"type": "plain_text", "text": button.text},
- "action_id": button.callback_data,
- "value": button.callback_data,
- }
- )
-
- blocks.append(
- {
- "type": "actions",
- "block_id": f"actions_{row_idx}",
- "elements": elements,
- }
- )
-
- kwargs["blocks"] = blocks
+ visible_text = kwargs.get("text") if isinstance(kwargs.get("text"), str) else None
+ kwargs["blocks"] = self._build_button_blocks(visible_text, keyboard, parse_mode=parse_mode)
await self.web_client.chat_update(**kwargs)
return True
@@ -1086,22 +1100,16 @@ class SlackBot(BaseIMClient):
fallback_text = text
if fallback_text is not None and parse_mode == "markdown":
fallback_text = self._convert_markdown_to_slack_mrkdwn(fallback_text)
+ if fallback_text:
+ fallback_text = self._get_visible_text(fallback_text)
if fallback_text is None and isinstance(payload_message, dict):
payload_text = payload_message.get("text")
if isinstance(payload_text, str):
- fallback_text = payload_text
+ fallback_text = self._get_visible_text(payload_text)
if not blocks and fallback_text:
- blocks = [
- {
- "type": "section",
- "text": {
- "type": "mrkdwn" if parse_mode == "markdown" else "plain_text",
- "text": fallback_text,
- },
- }
- ]
+ blocks = [self._build_section_block(fallback_text, parse_mode=parse_mode)]
kwargs = {"channel": context.channel_id, "ts": message_id, "blocks": blocks}
if fallback_text is not None:
@@ -1253,9 +1261,13 @@ class SlackBot(BaseIMClient):
thread_ts = event.get("thread_ts")
# If we have settings_manager, check if thread is active
if self.settings_manager:
- thread_active = self.sessions.is_thread_active(user_id, channel_id, thread_ts) if self.sessions else False
+ thread_active = (
+ self.sessions.is_thread_active(user_id, channel_id, thread_ts) if self.sessions else False
+ )
scheduled_thread_active = (
- self.sessions.is_thread_active("scheduled", channel_id, thread_ts) if self.sessions else False
+ self.sessions.is_thread_active("scheduled", channel_id, thread_ts)
+ if self.sessions
+ else False
)
if not thread_active and not scheduled_thread_active:
logger.debug(f"Ignoring message in inactive thread {thread_ts}: '{text}'")
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index 6ee89a4a5..0f886ba00 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -185,13 +185,7 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
thread_id="1710000000.000100",
platform_specific={"is_dm": True},
)
- keyboard = InlineKeyboard(
- buttons=[
- [
- InlineButton(text="One", callback_data="choose:1")
- ]
- ]
- )
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="One", callback_data="choose:1")]])
message_ts = await slack.send_message_with_buttons(context, "hello", keyboard, parse_mode="markdown")
@@ -201,6 +195,57 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(context.channel_id, "D999")
self.assertIsNone(context.thread_id)
+ async def test_send_message_with_buttons_splits_long_text_before_button_block(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ sent_payloads = []
+
+ class _WebClient:
+ async def chat_postMessage(self, **kwargs):
+ sent_payloads.append(kwargs)
+ return {"ts": f"1710000000.00000{len(sent_payloads)}"}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="One", callback_data="choose:1")]])
+ text = "\n\n".join([f"Paragraph {index} {'x' * 120}" for index in range(30)])
+
+ message_ts = await slack.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+
+ self.assertEqual(message_ts, "1710000000.000002")
+ self.assertEqual(len(sent_payloads), 2)
+ self.assertEqual(sent_payloads[0]["text"] + sent_payloads[1]["text"], text)
+ self.assertTrue(all(len(payload["text"]) <= 3000 for payload in sent_payloads))
+ self.assertFalse(any(block["type"] == "actions" for block in sent_payloads[0].get("blocks", [])))
+ self.assertEqual(sent_payloads[1]["blocks"][0]["type"], "section")
+ self.assertEqual(sent_payloads[1]["blocks"][1]["type"], "actions")
+
+ async def test_remove_inline_keyboard_uses_visible_chunk_for_long_text(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ updates = []
+
+ class _WebClient:
+ async def chat_update(self, **kwargs):
+ updates.append(kwargs)
+ return {"ok": True}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+ text = "\n\n".join([f"Paragraph {index} {'x' * 120}" for index in range(30)])
+
+ ok = await slack.remove_inline_keyboard(context, "1710000000.000002", text=text, parse_mode="markdown")
+
+ self.assertTrue(ok)
+ self.assertEqual(len(updates), 1)
+ self.assertLessEqual(len(updates[0]["text"]), 3000)
+ self.assertEqual(updates[0]["text"], slack._get_visible_text(text))
+ self.assertEqual(updates[0]["blocks"][0]["type"], "section")
+
+ def test_split_text_keeps_boundary_chunk_within_limit(self):
+ chunks = SlackBot._split_text("a" * 3000 + " " + "b", 3000)
+
+ self.assertEqual(chunks, ["a" * 3000, " b"])
+ self.assertTrue(all(len(chunk) <= 3000 for chunk in chunks))
+
async def test_get_user_info_prefers_normalized_profile_names(self):
slack = SlackBot(SlackConfig(bot_token="xoxb-test"))