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(im): one literal-text operation every transport resolves (#2827)

Call White1e816a9af9a4
diff --git a/core/hosted_activity.py b/core/hosted_activity.py
index 33ff84ccc..c02d2f5ae 100644
--- a/core/hosted_activity.py
+++ b/core/hosted_activity.py
@@ -425,8 +425,9 @@ def hosted_line(activity: HostedActivity, lang: str, *, escape: Callable[[str],
``🔎 Web search "query" · native (xAI) · 6 sources · $0.01``, or for an image
``🖼 Image generation "prompt" · gpt-image-2 · 1536×1024 · $0.02``. A call that did
not complete says why instead of how it ran or what it found, and keeps a
- known cost (``HostedActivity.completed``). ``escape`` makes the quoted
- subject safe for the destination's markup.
+ known cost (``HostedActivity.completed``). ``escape`` is the destination
+ formatter's literal-text operation (``escape_special_chars``), so a quoted
+ query such as ``*domain*`` reads as written rather than as markup.
"""
emoji = "🖼" if activity.tool == "image_generate" else "🔎"
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index 3bf464ce0..97fbc7a3d 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -20,7 +20,7 @@ from .base import (
InlineKeyboard,
MessageContext,
)
-from .formatters import FeishuFormatter
+from .formatters import FeishuFormatter, hold_markdown_escapes, restore_held
from .message_facts import (
feishu_message_kind,
is_original_human_feishu_attachment,
@@ -28,6 +28,8 @@ from .message_facts import (
)
from .download_target import open_download_target
from config.v2_config import LarkConfig
+from core.citations import spell_destination
+from core.reply_enhancer import inline_links
from vibe.i18n import get_supported_languages, t as i18n_t
from modules.agents.opencode.utils import (
build_claude_reasoning_options,
@@ -227,8 +229,37 @@ class FeishuBot(BaseIMClient):
return lark.FEISHU_DOMAIN
def format_markdown(self, text: str) -> str:
- # Feishu's interactive card markdown is close to standard markdown
- return text
+ """Feishu card Markdown from the Markdown every surface shares.
+
+ Close to standard Markdown, except where a backslash escape is written.
+ Read back from Feishu's parsed card, an escape in prose shows its
+ character, but one in a link label shows the backslash too, and one in
+ a link destination is kept in the address. A numeric entity is what
+ Feishu documents for showing a syntax character, and it holds in prose
+ and labels alike, so each escape comes back as one (``\\*`` as
+ ``*``). A destination with an escape in it is an address, not text:
+ it is written as the address a Markdown reader resolves, spelled as a
+ URI (``spell_destination``: an existing ``%HH`` kept, a stray ``%``
+ encoded), parentheses included, since a bare one can end the link.
+ Text without an escape is handed over as it is.
+ """
+ if not text:
+ return text
+ held, escaped = hold_markdown_escapes(text)
+ if not escaped:
+ return text
+ parts: List[str] = []
+ cursor = 0
+ for link in inline_links(held):
+ source = held[link.destination_start : link.destination_end]
+ if not any(token in source for token in escaped):
+ continue
+ address = spell_destination(restore_held(link.destination, escaped))
+ parts.append(held[cursor : link.destination_start])
+ parts.append(address.replace("(", "%28").replace(")", "%29"))
+ cursor = link.destination_end
+ parts.append(held[cursor:])
+ return restore_held("".join(parts), {token: f"&#{ord(character)};" for token, character in escaped.items()})
# ------------------------------------------------------------------
# SDK initialisation helpers
@@ -537,7 +568,7 @@ class FeishuBot(BaseIMClient):
# (text empty AND subtext set) drops the empty body so the note stands
# alone.
if text or subtext is None:
- elements.append({"tag": "markdown", "content": text})
+ elements.append({"tag": "markdown", "content": self.format_markdown(text)})
if buttons:
# Full-width ``fill`` only when the whole keyboard is a lone button.
# A single-button row that is merely the remainder of a chunked
@@ -605,7 +636,7 @@ class FeishuBot(BaseIMClient):
elements.append(
{
"tag": "markdown",
- "content": f"<font color='grey'>{subtext}</font>",
+ "content": f"<font color='grey'>{self.format_markdown(subtext)}</font>",
"text_size": "notation",
}
)
diff --git a/modules/im/formatters/avibe_formatter.py b/modules/im/formatters/avibe_formatter.py
index db97824fb..9a098304e 100644
--- a/modules/im/formatters/avibe_formatter.py
+++ b/modules/im/formatters/avibe_formatter.py
@@ -24,11 +24,6 @@ class AvibeFormatter(BaseMarkdownFormatter):
def format_link(self, text: str, url: str) -> str:
return f"[{text}]({url})"
- def escape_special_chars(self, text: str) -> str:
- for ch in ("\\", "*", "_", "~", "`", "|"):
- text = text.replace(ch, f"\\{ch}")
- return text
-
def format_code_block(self, code: str, language: str = "") -> str:
if language:
return f"```{language}\n{code}\n```"
diff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.py
index a0ec30222..aace70c07 100644
--- a/modules/im/formatters/base_formatter.py
+++ b/modules/im/formatters/base_formatter.py
@@ -24,17 +24,19 @@ def hold_markdown_escapes(
converts the text locally, turning
``[a\\*b\\*.example](https://a*b*.example/x)`` into
``a*b*.example (https://a*b*.example/x)``, so an escaped bracket or star is
- a syntax question for that conversion too. Discord and Feishu were measured
- here only as local pass-through - what their renderers show for a stray
- backslash has not been observed on those platforms. So the escape is
- resolved here, before a platform formatter runs, and the character it
- protected is held behind a placeholder until that formatter is done - which
- is the same reason it was escaped upstream, honoured in the dialect that is
- actually about to parse the text.
+ a syntax question for that conversion too. Feishu's card Markdown keeps the
+ backslash of an escape in a link label or address, and documents HTML
+ entities as its way to show a syntax character. Discord, Slack's ``markdown`` block and the Web read CommonMark escapes
+ themselves and are handed the text as it is. So the escape is resolved
+ here, before a platform formatter runs, and the character it protected is
+ held behind a placeholder until that formatter is done - which is the same
+ reason it was escaped upstream, honoured in the dialect that is actually
+ about to parse the text.
``render`` is how the platform wants the character to come back: Telegram
- needs it HTML-escaped, the others want it verbatim. Restore with
- ``restore_held`` once the platform pass is finished.
+ needs it HTML-escaped, Feishu as a numeric entity, Slack's mrkdwn with its
+ three delimiters encoded, WeChat verbatim. Restore with ``restore_held``
+ once the platform pass is finished.
"""
held: Dict[str, str] = {}
@@ -92,6 +94,15 @@ def hold_links(
return "".join(parts), held
+# The characters that are markup somewhere a message is delivered when they
+# stand inside a line: emphasis, strikethrough and code; link brackets; table
+# and Slack link bars; autolinks, HTML and Slack mentions; character references;
+# and the backslash itself. CommonMark lets any ASCII punctuation be escaped,
+# and every transport resolves exactly that grammar, so escaping a character
+# outside this set would only clutter the text.
+_LITERAL_MARKUP = frozenset("\\`*_~|[]<>&")
+
+
def _placeholder() -> str:
"""An inert stand-in no platform's formatter reads as markup of its own.
@@ -217,10 +228,18 @@ class BaseMarkdownFormatter(ABC):
"""Format hyperlink - platform specific"""
pass
- @abstractmethod
def escape_special_chars(self, text: str) -> str:
- """Escape platform-specific special characters"""
- pass
+ """Text that must reach the reader exactly as written: a query, a path, a tool name, an error.
+
+ The one literal-text operation. A message is Markdown until its transport
+ spells it in its own dialect, so the text is written once as CommonMark
+ backslash escapes, and each transport resolves them into its own literal:
+ Discord, Slack's ``markdown`` block and the Web read the escapes
+ natively, and Telegram, Feishu, WeChat and Slack's mrkdwn resolve them
+ through ``hold_markdown_escapes``. Not for code spans, whose content is
+ already literal and where a backslash is shown as written.
+ """
+ return "".join(f"\\{character}" if character in _LITERAL_MARKUP else character for character in text)
# High-level message composition methods
def format_message(self, *lines) -> str:
@@ -363,13 +382,11 @@ class BaseMarkdownFormatter(ABC):
# Convenience methods that combine formatting
def format_tool_name(self, tool_name: str, emoji: str = "🔧") -> str:
"""Format tool name with emoji and styling"""
- escaped_name = self.escape_special_chars(tool_name)
- return f"{emoji} {self.format_bold('Tool')}: {self.format_code_inline(escaped_name)}"
+ return f"{emoji} {self.format_bold('Tool')}: {self.format_code_inline(tool_name)}"
def format_file_path(self, path: str, emoji: str = "📁") -> str:
"""Format file path with emoji"""
- escaped_path = self.escape_special_chars(path)
- return f"{emoji} File: {self.format_code_inline(escaped_path)}"
+ return f"{emoji} File: {self.format_code_inline(path)}"
def format_command(self, command: str) -> str:
"""Format shell command"""
@@ -377,8 +394,7 @@ class BaseMarkdownFormatter(ABC):
if "\n" in command or len(command) > 80:
return f"💻 Command:\n{self.format_code_block(command, 'bash')}"
else:
- escaped_cmd = self.escape_special_chars(command)
- return f"💻 Command: {self.format_code_inline(escaped_cmd)}"
+ return f"💻 Command: {self.format_code_inline(command)}"
def format_error(self, error_text: str) -> str:
"""Format error message"""
@@ -696,7 +712,9 @@ class BaseMarkdownFormatter(ABC):
label = f"🔧 {tool_name}: {detail}"
else:
label = f"🔧 {tool_name}"
- return _truncate_status(label, max_len)
+ # Shortened first, so the cut can never split an escape; the label is the
+ # tool's own words, shown as written.
+ return self.escape_special_chars(_truncate_status(label, max_len))
@staticmethod
def _clean_label_value(value: str) -> str:
diff --git a/modules/im/formatters/discord_formatter.py b/modules/im/formatters/discord_formatter.py
index 8584dc052..9508b7ba6 100644
--- a/modules/im/formatters/discord_formatter.py
+++ b/modules/im/formatters/discord_formatter.py
@@ -20,12 +20,6 @@ class DiscordFormatter(BaseMarkdownFormatter):
def format_link(self, text: str, url: str) -> str:
return f"[{text}]({url})"
- def escape_special_chars(self, text: str) -> str:
- # Escape basic markdown characters to avoid unintended formatting.
- for ch in ("\\", "*", "_", "~", "`", "|"):
- text = text.replace(ch, f"\\{ch}")
- return text
-
def format_code_block(self, code: str, language: str = "") -> str:
if language:
return f"```{language}\n{code}\n```"
diff --git a/modules/im/formatters/feishu_formatter.py b/modules/im/formatters/feishu_formatter.py
index 593bfdd3d..37c8e6a1f 100644
--- a/modules/im/formatters/feishu_formatter.py
+++ b/modules/im/formatters/feishu_formatter.py
@@ -20,10 +20,6 @@ class FeishuFormatter(BaseMarkdownFormatter):
def format_link(self, text: str, url: str) -> str:
return f"[{text}]({url})"
- def escape_special_chars(self, text: str) -> str:
- # Feishu doesn't require special character escaping for most cases
- return text
-
def format_code_inline(self, text: str) -> str:
return f"`{text}`"
diff --git a/modules/im/formatters/slack_formatter.py b/modules/im/formatters/slack_formatter.py
index 4c770a485..fbe679a0e 100644
--- a/modules/im/formatters/slack_formatter.py
+++ b/modules/im/formatters/slack_formatter.py
@@ -20,9 +20,8 @@ def encode_slack_delimiters(text: str) -> str:
string for both, which is the caller's distinction to keep, not this
function's to guess from the finished text.
- Not the same job as ``escape_special_chars``, which encodes text that was
- never Markdown (a path, a tool name) - the same encoding, reached without
- any Markdown interpretation in between.
+ It is also how a character a backslash escape protected comes back into
+ mrkdwn, which has no escape of its own.
"""
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
@@ -84,16 +83,6 @@ class SlackFormatter(BaseMarkdownFormatter):
# Slack uses a different link format: <url|text>
return f"<{url}|{text}>"
- def escape_special_chars(self, text: str) -> str:
- """Escape Slack mrkdwn special characters
-
- Slack requires escaping these characters: &, <, >
- """
- text = text.replace("&", "&amp;")
- text = text.replace("<", "&lt;")
- text = text.replace(">", "&gt;")
- return text
-
def format_code_inline(self, text: str) -> str:
"""Format inline code - no escaping inside code blocks"""
# In Slack, content inside backticks should NOT be escaped
@@ -164,16 +153,6 @@ class SlackFormatter(BaseMarkdownFormatter):
# Use a series of dashes as a visual separator
return "─" * 40
- def format_tool_name(self, tool_name: str, emoji: str = "🔧") -> str:
- """Format tool name with emoji and styling"""
- # Don't escape tool name - it goes directly in code blocks
- return f"{emoji} {self.format_bold('Tool')}: {self.format_code_inline(tool_name)}"
-
- def format_file_path(self, path: str, emoji: str = "📁") -> str:
- """Format file path with emoji"""
- # Don't escape path - it goes directly in code blocks
- return f"{emoji} File: {self.format_code_inline(path)}"
-
def format_command(self, command: str) -> str:
"""Format shell command"""
# For multi-line or long commands, use code block
diff --git a/modules/im/formatters/telegram_formatter.py b/modules/im/formatters/telegram_formatter.py
index a5f965707..9e20cfc79 100644
--- a/modules/im/formatters/telegram_formatter.py
+++ b/modules/im/formatters/telegram_formatter.py
@@ -35,9 +35,6 @@ class TelegramFormatter(BaseMarkdownFormatter):
def format_link(self, text: str, url: str) -> str:
return f"[{text}]({url})"
- def escape_special_chars(self, text: str) -> str:
- return text
-
@staticmethod
def _find_link_url_end(text: str, start: int) -> int | None:
depth = 0
diff --git a/modules/im/formatters/wechat_formatter.py b/modules/im/formatters/wechat_formatter.py
index 06333fcf6..890c756d4 100644
--- a/modules/im/formatters/wechat_formatter.py
+++ b/modules/im/formatters/wechat_formatter.py
@@ -30,9 +30,6 @@ class WeChatFormatter(BaseMarkdownFormatter):
def format_link(self, text: str, url: str) -> str:
return f"{text} ({url})"
- def escape_special_chars(self, text: str) -> str:
- return text
-
def format_code_inline(self, text: str) -> str:
# No inline code styling in plain text; return as-is
return text
diff --git a/modules/im/slack.py b/modules/im/slack.py
index b172ea78c..4d4ebeaee 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -68,6 +68,28 @@ _SOFT_LINE_BREAK_RE = re.compile(r"[ \t]*(?:\r\n|\r|\n)[ \t]*")
_EVENT_TASK_SHUTDOWN_DRAIN_TIMEOUT_SECONDS = 70.0
+# Invisible, and enough to keep mrkdwn from reading the delimiter after it as
+# markup (U+034F COMBINING GRAPHEME JOINER).
+_MRKDWN_INERT = "\u034f"
+
+
+def _shown_in_mrkdwn(character: str) -> str:
+ """A character a backslash escape protected, spelled so mrkdwn shows it as written.
+
+ mrkdwn has no escape. ``&``, ``<`` and ``>`` have entities, and a bare one
+ is markup (``<!channel>`` is a mention). A paired ``*``, ``_``, ``~`` or
+ backtick has no spelling at all: measured by posting and reading the
+ message back as rich text, a zero-width space, word joiner or zero-width
+ (non-)joiner beside it still formats, and a combining grapheme joiner
+ written before it does not. Every other character is not markup in mrkdwn.
+ """
+ if character in "&<>":
+ return encode_slack_delimiters(character)
+ if character in "*_~`":
+ return _MRKDWN_INERT + character
+ return character
+
+
class SlackBot(BaseIMClient):
"""Slack implementation of the IM client"""
@@ -477,7 +499,12 @@ class SlackBot(BaseIMClient):
# them. A placeholder left inside a wrapper would come back as a
# raw character with nothing able to encode it any more.
converted_text = restore_held(converted_text, links)
- return restore_held(converted_text, escaped)
+ # Outside a link, an escaped character comes back the way mrkdwn
+ # shows it as written (``_shown_in_mrkdwn``).
+ return restore_held(
+ converted_text,
+ {token: _shown_in_mrkdwn(character) for token, character in escaped.items()},
+ )
except Exception as e:
logger.warning(f"Error converting markdown to mrkdwn: {e}, using original text")
# Fallback to original text if conversion fails
@@ -662,6 +689,15 @@ class SlackBot(BaseIMClient):
},
}
+ def _markdown_block_fallback(self, text: str) -> str:
+ """The top-level ``text`` beside a ``markdown`` block: what notifications and screen readers get.
+
+ Slack reads that field as mrkdwn, not Markdown, so it is the block's text
+ converted the way every mrkdwn message is (escapes resolved, links
+ re-spelled), never the Markdown as written.
+ """
+ return self._get_visible_text(self._convert_markdown_to_slack_mrkdwn(text))
+
@staticmethod
def _build_markdown_block(text: str) -> Dict[str, Any]:
return {
@@ -749,7 +785,7 @@ class SlackBot(BaseIMClient):
blocks.append(self._build_context_footer_block(subtext, parse_mode=parse_mode))
if keyboard:
blocks.extend(self._build_actions_blocks(keyboard))
- fallback_text = self._get_visible_text(body) if (body and body.strip()) else (subtext or "").strip()
+ fallback_text = self._markdown_block_fallback(body) if (body and body.strip()) else (subtext or "").strip()
return blocks, fallback_text
@staticmethod
@@ -1027,7 +1063,7 @@ class SlackBot(BaseIMClient):
kwargs = {
"channel": context.channel_id,
- "text": self._get_visible_text(text),
+ "text": self._markdown_block_fallback(text),
"blocks": blocks,
}
diff --git a/tests/test_citation_consumers.py b/tests/test_citation_consumers.py
index 9c199847b..4a239022f 100644
--- a/tests/test_citation_consumers.py
+++ b/tests/test_citation_consumers.py
@@ -502,20 +502,64 @@ class WeChatConsumerTests(PlatformConsumerTests):
class PassThroughConsumerTests(unittest.TestCase):
- """Discord and Feishu render Markdown themselves and are handed it as-is.
+ """Discord renders Markdown itself and is handed it as-is.
- That is all this measures: the adapter changes nothing. What those two
- platforms then draw is not observable from here, and no message is sent.
+ That is all this measures: the adapter changes nothing. What Discord then
+ draws is not observable from here, and no message is sent.
"""
def setUp(self):
self.discord = DiscordBot(DiscordConfig(bot_token="test-token"))
- self.feishu = FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret"))
def test_the_adapter_hands_the_body_over_unchanged(self):
for row in CASES:
with self.subTest(case=row["key"]):
self.assertEqual(self.discord.format_markdown(row["im_text"]), row["im_text"])
+
+
+class FeishuConsumerTests(unittest.TestCase):
+ """Feishu's card Markdown, as Feishu itself parses it.
+
+ Read back from Feishu's parsed card (``card_msg_content_type=raw_card_content``),
+ a backslash escape in a link label is shown with its backslash, and one in a
+ link destination stays in the address. So the adapter writes each escape as a
+ numeric entity and each address unescaped, its parentheses spelled. Every
+ expected body below was posted and read back: each label reads as the
+ characters, and each link opens its address.
+ """
+
+ def setUp(self):
+ self.feishu = FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret"))
+
+ def test_a_label_shows_its_characters_and_the_link_opens_its_address(self):
+ expected = {
+ "star_host": "Cited. [a&#42;b&#42;.example](https://a*b*.example/x)",
+ "entity_host": "Cited. [a&#38;copy;.example](https://a%26copy%3B.example/x)",
+ "ipv6_port": "Cited. [&#91;::1&#93;](https://[::1]:8443/x?q=1)",
+ "paren_path": (
+ "One [en.wikipedia.org](https://en.wikipedia.org/wiki/Foo_%28bar%29), "
+ "two [example.com](https://example.com/a_%28b?q=c%29d), "
+ "three [example.com](https://example.com/a%28b%29), "
+ "four [&#91;::1&#93;](https://[::1]:8443/x%28y)."
+ ),
+ "multi_source": "First [example.com](https://example.com/x), second [a&#42;b&#42;.example](https://a*b*.example/y).",
+ }
+ for key, body in expected.items():
+ with self.subTest(case=key):
+ self.assertEqual(self.feishu.format_markdown(case(key)["im_text"]), body)
+
+ def test_an_escaped_address_is_the_one_a_markdown_reader_resolves(self):
+ """``\\%`` resolves to ``%``, so ``a\\%20b`` names ``a%20b``: the escape it spells is kept, not encoded again."""
+ self.assertEqual(
+ self.feishu.format_markdown(r"[x](https://example.com/a\%20b) and [y](<https://example.com/a\_b c>)"),
+ "[x](https://example.com/a%20b) and [y](https://example.com/a_b%20c)",
+ )
+
+ def test_a_body_with_no_escape_is_handed_over_unchanged(self):
+ for row in CASES:
+ if "\\" in row["im_text"]:
+ continue
+ with self.subTest(case=row["key"]):
self.assertEqual(self.feishu.format_markdown(row["im_text"]), row["im_text"])
diff --git a/tests/test_markdown_escape_delivery.py b/tests/test_markdown_escape_delivery.py
index 05fb96eb8..f8b220129 100644
--- a/tests/test_markdown_escape_delivery.py
+++ b/tests/test_markdown_escape_delivery.py
@@ -29,6 +29,8 @@ from modules.im.slack import SlackBot, SlackMarkdownConverter
from modules.im.wechat import WeChatBot
LINK = "https://s.example/p"
+# U+034F COMBINING GRAPHEME JOINER, invisible: what keeps mrkdwn from reading the delimiter after it.
+CGJ = "\u034f"
def telegram(text: str) -> str:
@@ -59,18 +61,20 @@ class TestEscapedProse:
@DIALECTS
@pytest.mark.parametrize(
- "raw, shown",
+ "raw, shown, in_mrkdwn",
[
- (r"plain \*literal\* text", "plain *literal* text"),
- (r"a \_b\_ c", "a _b_ c"),
- (r"tick \` tick", "tick ` tick"),
- (r"a \~b\~ c", "a ~b~ c"),
- (r"a \\ b", "a \\ b"),
+ (r"plain \*literal\* text", "plain *literal* text", f"plain {CGJ}*literal{CGJ}* text"),
+ (r"a \_b\_ c", "a _b_ c", f"a {CGJ}_b{CGJ}_ c"),
+ (r"tick \` tick", "tick ` tick", f"tick {CGJ}` tick"),
+ (r"a \~b\~ c", "a ~b~ c", f"a {CGJ}~b{CGJ}~ c"),
+ (r"a \\ b", "a \\ b", "a \\ b"),
],
ids=["asterisk", "underscore", "backtick", "tilde", "backslash"],
)
- def test_the_reader_sees_the_character_and_no_backslash(self, render, raw, shown):
- assert render(raw) == shown
+ def test_the_reader_sees_the_character_and_no_backslash(self, render, raw, shown, in_mrkdwn):
+ """mrkdwn has no escape: a delimiter is shown as written only behind an invisible combining grapheme joiner
+ (measured on Slack by reading the message back as rich text)."""
+ assert render(raw) == (in_mrkdwn if render is slack else shown)
@DIALECTS
def test_an_escape_inside_a_code_span_is_still_code(self, render):
@@ -139,3 +143,81 @@ class TestEscapedLinkLabel:
assert "ex`ample.com" in rendered
assert LINK in rendered
assert "](" not in rendered
+
+
+class TestLiteralText:
+ """Text that must reach the reader exactly as written (#2820): a search query, a path, a command.
+
+ The formatter writes it once, as CommonMark escapes (``escape_special_chars``),
+ and each transport resolves those into its own literal. ``*domain*`` is the
+ reported case: a query that ran as ``*domain*`` must not be shown as an
+ emphasised ``domain``.
+ """
+
+ QUERY = "*domain* _x_ `c` [l](u) <b> a&lt;b |t| ~s~ \\"
+
+ def test_telegram_shows_every_character(self):
+ literal = TelegramFormatter().escape_special_chars(self.QUERY)
+
+ assert telegram(literal) == "*domain* _x_ `c` [l](u) &lt;b&gt; a&amp;lt;b |t| ~s~ \\"
+
+ def test_wechat_shows_every_character(self):
+ literal = WeChatFormatter().escape_special_chars(self.QUERY)
+
+ assert wechat(literal) == self.QUERY
+
+ def test_feishu_writes_each_character_as_the_entity_it_shows(self):
+ """Measured by posting the card and reading back Feishu's own parse of it: every character is plain text."""
+ import json
+
+ from config.v2_config import LarkConfig
+ from modules.im.feishu import FeishuBot
+ from modules.im.formatters.feishu_formatter import FeishuFormatter
+
+ bot = FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret"))
+ card = json.loads(bot._build_card_json(FeishuFormatter().escape_special_chars(self.QUERY)))
+
+ assert card["body"]["elements"][0]["content"] == (
+ "&#42;domain&#42; &#95;x&#95; &#96;c&#96; &#91;l&#93;(u) &#60;b&#62; a&#38;lt;b "
+ "&#124;t&#124; &#126;s&#126; &#92;"
+ )
+
+ def test_slack_markdown_blocks_and_discord_read_the_escapes_themselves(self):
+ """Slack's ``markdown`` block (a status bubble) and Discord render CommonMark escapes as the character,
+ measured on Slack by reading the posted block back as rich text. So the text they are handed is the escape."""
+ from modules.im.formatters.discord_formatter import DiscordFormatter
+ from modules.im.formatters.slack_formatter import SlackFormatter
+
+ expected = r"\*domain\* \_x\_ \`c\` \[l\](u) \<b\> a\&lt;b \|t\| \~s\~ \\"
+ assert DiscordFormatter().escape_special_chars(self.QUERY) == expected
+ bot = SlackBot.__new__(SlackBot)
+ bot.markdown_converter = SlackMarkdownConverter()
+ blocks, fallback = bot._build_status_blocks(SlackFormatter().escape_special_chars(self.QUERY), "working")
+ assert blocks[0] == {"type": "markdown", "text": expected}
+ # The notification text beside the block is read as mrkdwn, so it is spelled as mrkdwn shows it.
+ assert fallback == slack(expected)
+
+ def test_slack_mrkdwn_shows_every_character(self):
+ """mrkdwn has no escape. Measured by posting and reading the message back as rich text: ``&``, ``<`` and ``>``
+ show as entities, and a paired ``*``, ``_``, ``~`` or backtick shows as written only behind a combining
+ grapheme joiner (a zero-width space, word joiner or zero-width joiner beside it still formats)."""
+ from modules.im.formatters.slack_formatter import SlackFormatter
+
+ literal = SlackFormatter().escape_special_chars(self.QUERY)
+
+ assert slack(literal) == (
+ f"{CGJ}*domain{CGJ}* {CGJ}_x{CGJ}_ {CGJ}`c{CGJ}` [l](u) &lt;b&gt; a&amp;lt;b |t| {CGJ}~s{CGJ}~ \\"
+ )
+ assert slack(r"a \<!channel\>") == "a &lt;!channel&gt;"
+
+ def test_a_tool_label_and_a_code_span_show_what_the_tool_was_given(self):
+ from modules.im.formatters.discord_formatter import DiscordFormatter
+
+ formatter = DiscordFormatter()
+
+ assert formatter.format_toolcall_label("Bash", {"command": "rg *domain* src"}) == r"🔧 Bash: rg \*domain\* src"
+ # Shortened before it is escaped, so the cut never leaves half an escape behind.
+ long = formatter.format_toolcall_label("Bash", {"command": "a" * 60 + "*"}, max_len=20)
+ assert long.endswith("…") and "\\" not in long
+ # A code span is literal already; a backslash there would be shown.
+ assert formatter.format_file_path("core/message_dispatcher.py") == "📁 File: `core/message_dispatcher.py`"
diff --git a/tests/test_message_dispatcher_status_bubble.py b/tests/test_message_dispatcher_status_bubble.py
index 2855aeb0e..432925188 100644
--- a/tests/test_message_dispatcher_status_bubble.py
+++ b/tests/test_message_dispatcher_status_bubble.py
@@ -1029,7 +1029,8 @@ class FormatToolcallLabelTests(unittest.TestCase):
def test_bash_uses_command(self):
self.assertEqual(
self.fmt.format_toolcall_label("Bash", {"command": "pytest tests/test_x.py"}),
- "🔧 Bash: pytest tests/test_x.py",
+ # Written as Markdown that shows each character as typed (``escape_special_chars``).
+ "🔧 Bash: pytest tests/test\\_x.py",
)
def test_read_file_path_strips_workspace_prefix(self):
@@ -1038,7 +1039,7 @@ class FormatToolcallLabelTests(unittest.TestCase):
{"file_path": "/workspace/repo/core/message_dispatcher.py"},
get_relative_path=lambda p: p.replace("/workspace/repo/", ""),
)
- self.assertEqual(out, "🔧 Read: core/message_dispatcher.py")
+ self.assertEqual(out, "🔧 Read: core/message\\_dispatcher.py")
def test_grep_pattern_strips_surrounding_quotes(self):
self.assertEqual(
@@ -1077,7 +1078,7 @@ class FormatToolcallLabelTests(unittest.TestCase):
def test_preserves_underscores_in_file_name(self):
out = self.fmt.format_toolcall_label("Read", {"file_path": "message_dispatcher.py"})
- self.assertEqual(out, "🔧 Read: message_dispatcher.py")
+ self.assertEqual(out, "🔧 Read: message\\_dispatcher.py")
if __name__ == "__main__":
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index c17c2384a..99bb78b56 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -143,7 +143,8 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
message_ts = await slack.send_markdown_message(context, text, keyboard=keyboard)
self.assertEqual(message_ts, "1710000000.000020")
- self.assertEqual(sent_payloads[0]["text"], text)
+ # Notifications and screen readers get the top-level text, which Slack reads as mrkdwn.
+ self.assertEqual(sent_payloads[0]["text"], "*Col 1* | *Col 2*\nA | B")
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")
diff --git a/tests/test_vault_request_im_notifications.py b/tests/test_vault_request_im_notifications.py
index 9c2860ef9..73f9ec012 100644
--- a/tests/test_vault_request_im_notifications.py
+++ b/tests/test_vault_request_im_notifications.py
@@ -11,6 +11,16 @@ from storage.db import create_sqlite_engine
from storage.models import agent_sessions, metadata as db_metadata, scopes
+def _shown_on_slack(text: str) -> str:
+ """The text a Slack reader is shown: the Markdown, through the adapter's own mrkdwn conversion, less the
+ invisible joiner that keeps mrkdwn from reading a literal ``_`` as markup."""
+ from modules.im.slack import SlackBot, SlackMarkdownConverter
+
+ bot = SlackBot.__new__(SlackBot)
+ bot.markdown_converter = SlackMarkdownConverter()
+ return bot._convert_markdown_to_slack_mrkdwn(text).replace("\u034f", "")
+
+
class FakeController:
def __init__(self, *, public_url: str = "https://desk.avibe.bot/u/team") -> None:
self.config = SimpleNamespace(
@@ -130,7 +140,7 @@ def test_notifies_im_session_with_platform_link_format(tmp_path: Path) -> None:
assert context.channel_id == "C123"
assert context.thread_id == "1719990000.1"
assert context.platform_specific["agent_session_id"] == "ses_im"
- assert "API_KEY" in emitted["text"]
+ assert "API_KEY" in _shown_on_slack(emitted["text"])
assert "<https://desk.avibe.bot/u/team/vaults?request_id=vrq_123|Review on the web>" in emitted["text"]
@@ -209,7 +219,7 @@ def test_provision_request_can_notify_from_secure_input_card(tmp_path: Path) ->
assert result["sent"] is True
assert "A secret to fill in" in controller.emitted[0]["text"]
- assert "NEW_TOKEN" in controller.emitted[0]["text"]
+ assert "NEW_TOKEN" in _shown_on_slack(controller.emitted[0]["text"])
def test_workbench_session_is_not_notified(tmp_path: Path) -> None: