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.

feat(slack): render results with markdown block

cyh3cb1f6e2a719
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index dcd72efc4..98e903d53 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -347,17 +347,17 @@ class ConsolidatedMessageDispatcher:
display_text = text
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(
- im_client,
- target_context,
- display_text,
- enhanced.buttons,
- parse_mode,
- )
- scheduled_anchor_message_id = primary_message_id
- except Exception as err:
+ try:
+ primary_message_id = await self._send_result_inline(
+ im_client,
+ target_context,
+ display_text,
+ enhanced.buttons if enhanced else [],
+ parse_mode,
+ )
+ scheduled_anchor_message_id = primary_message_id
+ except Exception as err:
+ if enhanced and enhanced.buttons and self._supports_quick_replies(context):
logger.warning("Failed to send result with quick replies, falling back: %s", err)
try:
primary_message_id = await im_client.send_message(
@@ -366,13 +366,7 @@ class ConsolidatedMessageDispatcher:
scheduled_anchor_message_id = primary_message_id
except Exception as fallback_err:
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
- )
- scheduled_anchor_message_id = primary_message_id
- except Exception as err:
+ else:
logger.error("Failed to send result message: %s", err)
elif self._should_split_long_result(context):
try:
@@ -626,6 +620,15 @@ class ConsolidatedMessageDispatcher:
parse_mode,
) -> str:
"""Send a message with quick-reply buttons appended."""
+ keyboard = self._build_quick_reply_keyboard(context, buttons)
+ return await im_client.send_message_with_buttons(
+ context,
+ text,
+ keyboard,
+ parse_mode=parse_mode,
+ )
+
+ def _build_quick_reply_keyboard(self, context: MessageContext, buttons):
from modules.im.base import InlineButton, InlineKeyboard
row = []
@@ -634,13 +637,33 @@ class ConsolidatedMessageDispatcher:
row.append(InlineButton(text=btn.text, callback_data=callback))
rows = [[button] for button in row] if self._capabilities(context).quick_reply_single_column else [row]
- keyboard = InlineKeyboard(buttons=rows)
- return await im_client.send_message_with_buttons(
- context,
- text,
- keyboard,
- parse_mode=parse_mode,
- )
+ return InlineKeyboard(buttons=rows)
+
+ async def _send_result_inline(
+ self,
+ im_client,
+ context: MessageContext,
+ text: str,
+ buttons,
+ parse_mode,
+ ) -> str:
+ keyboard = None
+ if buttons and self._supports_quick_replies(context):
+ keyboard = self._build_quick_reply_keyboard(context, buttons)
+
+ native_markdown_sender = getattr(im_client, "send_markdown_message", None)
+ if parse_mode == "markdown" and callable(native_markdown_sender):
+ return await native_markdown_sender(context, text, keyboard=keyboard)
+
+ if keyboard is not None:
+ return await im_client.send_message_with_buttons(
+ context,
+ text,
+ keyboard,
+ parse_mode=parse_mode,
+ )
+
+ return await im_client.send_message(context, text, parse_mode=parse_mode)
async def _send_split_result_messages(
self,
@@ -659,7 +682,7 @@ class ConsolidatedMessageDispatcher:
if is_last_chunk and buttons and self._supports_quick_replies(context):
try:
- message_id = await self._send_with_quick_replies(
+ message_id = await self._send_result_inline(
im_client,
context,
chunk,
@@ -670,7 +693,7 @@ class ConsolidatedMessageDispatcher:
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)
+ message_id = await self._send_result_inline(im_client, context, chunk, [], parse_mode)
if first_message_id is None:
first_message_id = message_id
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 78b2ea987..d1c2cab55 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -42,6 +42,7 @@ logger = logging.getLogger(__name__)
_UNSET = object()
_SLACK_SECTION_TEXT_LIMIT = 3000
+_SLACK_MARKDOWN_TEXT_LIMIT = 12000
_BARE_HTTP_URL_RE = re.compile(r"https?://[^\s<>\|]+")
_TRAILING_URL_PUNCTUATION = ".,!?;:"
@@ -509,16 +510,16 @@ class SlackBot(BaseIMClient):
},
}
- 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))
+ @staticmethod
+ def _build_markdown_block(text: str) -> Dict[str, Any]:
+ return {
+ "type": "markdown",
+ "text": text,
+ }
+ @staticmethod
+ def _build_actions_blocks(keyboard: InlineKeyboard) -> List[Dict[str, Any]]:
+ blocks: List[Dict[str, Any]] = []
for row_idx, row in enumerate(keyboard.buttons):
elements = []
for button in row:
@@ -541,6 +542,29 @@ class SlackBot(BaseIMClient):
return blocks
+ 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))
+
+ blocks.extend(self._build_actions_blocks(keyboard))
+ return blocks
+
+ @staticmethod
+ def _is_markdown_block_rejection(error: SlackApiError) -> bool:
+ response = getattr(error, "response", None)
+ error_code = response.get("error") if hasattr(response, "get") else None
+ return error_code in {
+ "invalid_blocks",
+ "unsupported_block_type",
+ "invalid_arguments",
+ }
+
@staticmethod
def _linkify_bare_urls_for_verbatim_mrkdwn(text: str) -> str:
"""Convert bare URLs to explicit Slack links when automatic parsing is off."""
@@ -697,6 +721,68 @@ class SlackBot(BaseIMClient):
logger.error(f"Error sending Slack message: {e}")
raise
+ async def send_markdown_message(
+ self,
+ context: MessageContext,
+ text: str,
+ keyboard: Optional[InlineKeyboard] = None,
+ reply_to: Optional[str] = None,
+ ) -> str:
+ """Send standard Markdown using Slack's native markdown block.
+
+ This is intended for LLM-authored final results. Control messages and
+ editable status updates still use the legacy section/mrkdwn path.
+ """
+ self._ensure_clients()
+
+ if not text:
+ raise ValueError("Slack send_markdown_message requires non-empty text")
+
+ if len(text) > _SLACK_MARKDOWN_TEXT_LIMIT:
+ if keyboard:
+ return await self.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+ return await self.send_message(context, text, parse_mode="markdown", reply_to=reply_to)
+
+ blocks = [self._build_markdown_block(text)]
+ if keyboard:
+ blocks.extend(self._build_actions_blocks(keyboard))
+
+ kwargs = {
+ "channel": context.channel_id,
+ "text": self._get_visible_text(text),
+ "blocks": blocks,
+ }
+
+ 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
+
+ try:
+ response = await self._post_message_with_dm_recovery(
+ context,
+ kwargs,
+ log_label="native-markdown message send",
+ )
+ except SlackApiError as e:
+ if not self._is_markdown_block_rejection(e):
+ logger.error(f"Error sending Slack native markdown message: {e}")
+ raise
+ logger.warning("Slack rejected native markdown block; falling back to legacy mrkdwn rendering")
+ if keyboard:
+ return await self.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+ return await self.send_message(context, text, parse_mode="markdown", reply_to=reply_to)
+
+ if self.settings_manager and (context.thread_id or reply_to):
+ thread_ts = context.thread_id or reply_to
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
+ logger.debug(f"Marked thread {thread_ts} as active after bot native markdown message")
+
+ return response["ts"]
+
async def upload_markdown(
self,
context: MessageContext,
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index da206d592..4733f4255 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -52,6 +52,18 @@ class _StubIMClient:
return self._upload_id
+class _NativeMarkdownIMClient(_StubIMClient):
+ def __init__(self):
+ super().__init__()
+ self.native_markdown_messages = []
+
+ async def send_markdown_message(self, context, text, keyboard=None, reply_to=None):
+ self.native_markdown_messages.append((context.channel_id, text, keyboard, reply_to))
+ message_id = f"native-{self._next_id}"
+ self._next_id += 1
+ return message_id
+
+
class _StubController:
def __init__(
self,
@@ -60,14 +72,16 @@ class _StubController:
language: str = "en",
fail_first_send: bool = False,
upload_id: str = "file-1",
+ im_client=None,
+ reply_enhancements: bool = False,
):
self.config = type(
"Config",
(),
- {"platform": platform, "language": language, "reply_enhancements": False},
+ {"platform": platform, "language": language, "reply_enhancements": reply_enhancements},
)()
self.session_handler = _StubSessionHandler()
- self.im_client = _StubIMClient(fail_first_send=fail_first_send, upload_id=upload_id)
+ self.im_client = im_client or _StubIMClient(fail_first_send=fail_first_send, upload_id=upload_id)
def _get_settings_key(self, context):
return context.channel_id
@@ -83,6 +97,39 @@ class _StubController:
class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
+ async def test_slack_result_uses_native_markdown_sender_when_available(self):
+ im_client = _NativeMarkdownIMClient()
+ controller = _StubController(platform="slack", im_client=im_client)
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")
+ text = "| A | B |\n| - | - |\n| 1 | 2 |"
+
+ message_id = await dispatcher.emit_agent_message(context, "result", text)
+
+ self.assertEqual(message_id, "native-1")
+ self.assertEqual(im_client.sent_messages, [])
+ self.assertEqual(im_client.native_markdown_messages, [("C1", text, None, None)])
+
+ async def test_slack_result_passes_quick_replies_to_native_markdown_sender(self):
+ im_client = _NativeMarkdownIMClient()
+ controller = _StubController(platform="slack", im_client=im_client, reply_enhancements=True)
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")
+
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "Body\n\n---\n[Continue] | [Stop]",
+ )
+
+ self.assertEqual(message_id, "native-1")
+ self.assertEqual(im_client.sent_messages, [])
+ channel_id, text, keyboard, reply_to = im_client.native_markdown_messages[0]
+ self.assertEqual(channel_id, "C1")
+ self.assertEqual(text, "Body")
+ self.assertIsNone(reply_to)
+ self.assertEqual([button.text for button in keyboard.buttons[0]], ["Continue", "Stop"])
+
async def test_summary_upload_becomes_primary_anchor_without_duplicate_upload(self):
controller = _StubController(platform="lark", language="en", fail_first_send=True)
dispatcher = ConsolidatedMessageDispatcher(controller)
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index d2c25de08..3154549d1 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -113,7 +113,7 @@ def _install_slack_stubs() -> None:
_install_slack_stubs()
-from modules.im.slack import SlackBot
+from modules.im.slack import SlackApiError, SlackBot
class _ResponseLike:
@@ -159,6 +159,50 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("unfurl_links", sent_payloads[0])
self.assertNotIn("unfurl_media", sent_payloads[0])
+ async def test_send_markdown_message_uses_native_markdown_block_with_buttons(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ sent_payloads = []
+
+ class _WebClient:
+ async def chat_postMessage(self, **kwargs):
+ sent_payloads.append(kwargs)
+ return {"ts": "1710000000.000020"}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="Continue", callback_data="quick_reply:Continue")]])
+ text = "| Col 1 | Col 2 |\n| ----- | ----- |\n| A | B |"
+
+ message_ts = await slack.send_markdown_message(context, text, keyboard=keyboard)
+
+ self.assertEqual(message_ts, "1710000000.000020")
+ self.assertEqual(sent_payloads[0]["text"], text)
+ self.assertEqual(sent_payloads[0]["blocks"][0], {"type": "markdown", "text": text})
+ self.assertEqual(sent_payloads[0]["blocks"][1]["type"], "actions")
+ self.assertEqual(sent_payloads[0]["blocks"][1]["elements"][0]["value"], "quick_reply:Continue")
+
+ async def test_send_markdown_message_falls_back_when_native_block_is_rejected(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ sent_payloads = []
+
+ class _WebClient:
+ async def chat_postMessage(self, **kwargs):
+ sent_payloads.append(kwargs)
+ if len(sent_payloads) == 1:
+ raise SlackApiError("invalid blocks", response=_ResponseLike({"error": "invalid_blocks"}))
+ return {"ts": "1710000000.000021"}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+ text = "| Col 1 | Col 2 |\n| ----- | ----- |\n| A | B |"
+
+ message_ts = await slack.send_markdown_message(context, text)
+
+ self.assertEqual(message_ts, "1710000000.000021")
+ self.assertEqual(sent_payloads[0]["blocks"][0], {"type": "markdown", "text": text})
+ self.assertEqual(sent_payloads[1]["blocks"][0]["type"], "section")
+ self.assertEqual(sent_payloads[1]["blocks"][0]["text"]["type"], "mrkdwn")
+
async def test_send_message_disables_link_unfurl_when_configured(self):
slack = SlackBot(SlackConfig(bot_token="xoxb-test", disable_link_unfurl=True))
sent_payloads = []