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): keep links clickable without previews

cyh131b2d3c6a3d
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 7f142998f..1de70b0ba 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -42,6 +42,8 @@ logger = logging.getLogger(__name__)
_UNSET = object()
_SLACK_SECTION_TEXT_LIMIT = 3000
+_BARE_HTTP_URL_RE = re.compile(r"https?://[^\s<>\|]+")
+_TRAILING_URL_PUNCTUATION = ".,!?;:"
class SlackBot(BaseIMClient):
@@ -539,6 +541,78 @@ class SlackBot(BaseIMClient):
return blocks
+ @staticmethod
+ def _linkify_bare_urls_for_verbatim_mrkdwn(text: str) -> str:
+ """Convert bare URLs to explicit Slack links when automatic parsing is off."""
+ if not text or "http" not in text:
+ return text
+
+ def _linkify_segment(segment: str) -> str:
+ def _replace(match: re.Match) -> str:
+ url = match.group(0)
+ start = match.start()
+ end = match.end()
+ last_lt = segment.rfind("<", 0, start)
+ last_gt = segment.rfind(">", 0, start)
+ if last_lt > last_gt:
+ return url
+
+ trailing = ""
+ while url and url[-1] in _TRAILING_URL_PUNCTUATION:
+ trailing = url[-1] + trailing
+ url = url[:-1]
+
+ while url.endswith(")") and url.count("(") < url.count(")"):
+ trailing = ")" + trailing
+ url = url[:-1]
+
+ if end < len(segment) and segment[end : end + 1] == ">":
+ return url + trailing
+ if not url:
+ return match.group(0)
+ return f"<{url}|{url}>{trailing}"
+
+ return _BARE_HTTP_URL_RE.sub(_replace, segment)
+
+ result: List[str] = []
+ in_fenced_code = False
+ for line in text.splitlines(keepends=True):
+ cursor = 0
+ processed_parts: List[str] = []
+ for part in re.split(r"(```|`)", line):
+ if part == "```":
+ in_fenced_code = not in_fenced_code
+ processed_parts.append(part)
+ elif part == "`":
+ if in_fenced_code:
+ processed_parts.append(part)
+ else:
+ cursor ^= 1
+ processed_parts.append(part)
+ elif in_fenced_code or cursor:
+ processed_parts.append(part)
+ else:
+ processed_parts.append(_linkify_segment(part))
+ result.append("".join(processed_parts))
+ return "".join(result)
+
+ @classmethod
+ def _split_text_for_verbatim_mrkdwn(cls, text: str, max_chars: int) -> List[str]:
+ if len(cls._linkify_bare_urls_for_verbatim_mrkdwn(text)) <= max_chars:
+ return [text]
+
+ chunks: List[str] = []
+ remaining = text
+ while remaining and len(cls._linkify_bare_urls_for_verbatim_mrkdwn(remaining)) > max_chars:
+ split_at = cls._find_text_split_index(remaining, min(len(remaining) - 1, max_chars // 2))
+ if split_at <= 0:
+ split_at = max(1, min(len(remaining) - 1, max_chars // 2))
+ chunks.append(remaining[:split_at])
+ remaining = remaining[split_at:]
+ if remaining:
+ chunks.append(remaining)
+ return chunks
+
async def _send_prepared_text_message(
self,
context: MessageContext,
@@ -1222,12 +1296,18 @@ class SlackBot(BaseIMClient):
if parse_mode == "markdown":
text = self._convert_markdown_to_slack_mrkdwn(text)
- chunks = self._split_text(text, _SLACK_SECTION_TEXT_LIMIT)
+ linkify_verbatim_urls = parse_mode == "markdown" and getattr(self.config, "disable_link_unfurl", False)
+ chunks = (
+ self._split_text_for_verbatim_mrkdwn(text, _SLACK_SECTION_TEXT_LIMIT)
+ if linkify_verbatim_urls
+ else 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]
+ visible_text = self._linkify_bare_urls_for_verbatim_mrkdwn(text) if linkify_verbatim_urls else text
- blocks = self._build_button_blocks(text, keyboard, parse_mode=parse_mode)
+ blocks = self._build_button_blocks(visible_text, keyboard, parse_mode=parse_mode)
if blocks and blocks[0].get("type") == "section":
blocks[0]["text"]["verbatim"] = True
@@ -1235,7 +1315,7 @@ class SlackBot(BaseIMClient):
kwargs = {
"channel": context.channel_id,
"blocks": blocks,
- "text": text, # Fallback text
+ "text": visible_text, # Fallback text
}
# Handle thread replies
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index 923091aaa..763048a28 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -221,6 +221,86 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(message_ts, "1710000000.000013")
self.assertIs(sent_payloads[0]["unfurl_links"], False)
self.assertIs(sent_payloads[0]["unfurl_media"], False)
+ self.assertEqual(
+ sent_payloads[0]["blocks"][0]["text"]["text"],
+ "<https://example.com|https://example.com>",
+ )
+ self.assertIs(sent_payloads[0]["blocks"][0]["text"]["verbatim"], True)
+
+ async def test_send_message_with_buttons_linkifies_only_bare_urls_for_verbatim_blocks(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test", disable_link_unfurl=True))
+ sent_payloads = []
+
+ class _WebClient:
+ async def chat_postMessage(self, **kwargs):
+ sent_payloads.append(kwargs)
+ return {"ts": "1710000000.000014"}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="Open", callback_data="open")]])
+ text = (
+ "Open https://example.com/path?a=1&b=2.\n"
+ "Existing <https://example.org|Example>.\n"
+ "Date <!date^1392734382^{date_short}^https://date.example/|Feb 18>.\n"
+ "Inline `https://code.example`.\n"
+ "```\nhttps://block.example\n```"
+ )
+
+ await slack.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+
+ block_text = sent_payloads[0]["blocks"][0]["text"]["text"]
+ self.assertIn("<https://example.com/path?a=1&b=2|https://example.com/path?a=1&b=2>.", block_text)
+ self.assertIn("<https://example.org|Example>", block_text)
+ self.assertIn("<!date^1392734382^{date_short}^https://date.example/|Feb 18>", block_text)
+ self.assertIn("`https://code.example`", block_text)
+ self.assertIn("```\nhttps://block.example\n```", block_text)
+ self.assertNotIn("<<https://example.org", block_text)
+
+ async def test_send_message_with_buttons_keeps_default_preview_behavior(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.000015"}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="Open", callback_data="open")]])
+
+ await slack.send_message_with_buttons(
+ context,
+ "https://example.com",
+ keyboard,
+ parse_mode="markdown",
+ )
+
+ self.assertEqual(sent_payloads[0]["blocks"][0]["text"]["text"], "https://example.com")
+ self.assertNotIn("unfurl_links", sent_payloads[0])
+ self.assertNotIn("unfurl_media", sent_payloads[0])
+
+ async def test_send_message_with_buttons_splits_when_linkified_text_exceeds_section_limit(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test", disable_link_unfurl=True))
+ sent_payloads = []
+
+ class _WebClient:
+ async def chat_postMessage(self, **kwargs):
+ sent_payloads.append(kwargs)
+ return {"ts": f"1710000000.00001{len(sent_payloads)}"}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="Open", callback_data="open")]])
+ text = " ".join(["https://example.com/" + ("x" * 60) for _ in range(30)])
+
+ await slack.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+
+ self.assertGreater(len(sent_payloads), 1)
+ final_payload = sent_payloads[-1]
+ self.assertLessEqual(len(final_payload["blocks"][0]["text"]["text"]), 3000)
+ self.assertEqual(final_payload["blocks"][1]["type"], "actions")
async def test_send_message_recovers_dm_channel_after_channel_not_found(self):
slack = SlackBot(SlackConfig(bot_token="xoxb-test"))