Skip to content

The agent that grows with you

fix(imessage): strip markdown on every Photon plain send and keep link URLs on BlueBubbles

teknium173ba6390925b
diff --git a/gateway/platforms/bluebubbles.py b/gateway/platforms/bluebubbles.py
index 05b9ceeceef..5b937c4b45e 100644
--- a/gateway/platforms/bluebubbles.py
+++ b/gateway/platforms/bluebubbles.py
@@ -467,7 +467,7 @@ class BlueBubblesAdapter(BasePlatformAdapter):
return info
def format_message(self, content: str) -> str:
- return strip_markdown(content)
+ return strip_markdown(content, keep_link_targets=True) # iMessage auto-links bare URLs only
# --- Inbound attachment downloading ---
diff --git a/gateway/platforms/helpers.py b/gateway/platforms/helpers.py
index 0dec58d6c51..ee5699a5ee7 100644
--- a/gateway/platforms/helpers.py
+++ b/gateway/platforms/helpers.py
@@ -105,10 +105,6 @@ _HTTP_TARGET_RE = re.compile(r"https?://", re.IGNORECASE)
_NEWLINE_SQUEEZE_RE = re.compile(r"\n{3,}")
-def _drop_link_target(match: "re.Match[str]") -> str:
- return match.group(1)
-
-
def _keep_link_target(match: "re.Match[str]") -> str:
r"""``[label](https://url)`` -> ``label\nurl``.
@@ -131,7 +127,7 @@ def strip_markdown(text: str, *, keep_link_targets: bool = False) -> str:
"""
for pattern, repl in _STRIP_RULES:
text = pattern.sub(repl, text)
- text = _MD_LINK_RE.sub(_keep_link_target if keep_link_targets else _drop_link_target, text)
+ text = _MD_LINK_RE.sub(_keep_link_target if keep_link_targets else r"\1", text)
return _NEWLINE_SQUEEZE_RE.sub("\n\n", text).strip()
diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.py
index 39a41e6c2ef..2ee5d6756b8 100644
--- a/plugins/platforms/photon/adapter.py
+++ b/plugins/platforms/photon/adapter.py
@@ -303,26 +303,19 @@ def _markdown_enabled() -> bool:
_SIDECAR_URL_RE = re.compile(r"https?://[^\s)'\"<>]+", re.IGNORECASE)
-def _strip_for_imessage(text: str) -> str:
- """Strip markdown, but keep ``[label](url)`` targets as a bare URL on its own line.
+def _sidecar_payload_text(text: str, send_markdown: bool) -> str:
+ """The ``/send`` text: verbatim only when the sidecar will really use spectrum-ts' markdown builder.
- Every plain-text path here ends at iMessage, which auto-links bare URLs and
- nothing else, so discarding a link target makes the link unreachable — see
- the ``chooseSendFormat`` comment for why these payloads lose markdown at all.
+ ``chooseSendFormat`` routes markdown containing a raw URL through the verbatim ``text()`` builder
+ (the markdown builder's data detection 500s on those), and a plain send has no renderer at all, so
+ both are stripped here or iMessage shows literal ``**``/fences. Link targets survive as bare URLs:
+ iMessage auto-links those and nothing else.
"""
+ if send_markdown and not _SIDECAR_URL_RE.search(text or ""):
+ return text
return strip_markdown(text, keep_link_targets=True)
-def _sidecar_downgrades_to_text(text: str) -> bool:
- """True when the sidecar will route a markdown payload to the text builder.
-
- ``chooseSendFormat`` sends markdown containing a raw http(s) URL through
- spectrum-ts' ``text()`` builder, because the markdown builder's iMessage
- data detection 500s on those messages.
- """
- return bool(_SIDECAR_URL_RE.search(text or ""))
-
-
def _url_only_candidate(text: str) -> Optional[str]:
candidate = (text or "").strip()
if not re.fullmatch(r"https?://\S+", candidate, flags=re.IGNORECASE):
@@ -1321,7 +1314,7 @@ class PhotonAdapter(BasePlatformAdapter):
def format_message(self, content: str) -> str:
# Markdown passes through verbatim (sidecar markdown() builder); PHOTON_MARKDOWN=false strips.
- return content if _markdown_enabled() else _strip_for_imessage(content)
+ return content if _markdown_enabled() else strip_markdown(content, keep_link_targets=True)
@staticmethod
def _is_retryable_error(error: Optional[str]) -> bool:
@@ -1350,8 +1343,7 @@ class PhotonAdapter(BasePlatformAdapter):
"""No Markdown banner (replies are markdown or already-stripped plain text); bypass
richlink() so a rich-link outage doesn't strand a sendable URL."""
return await self._sidecar_send(
- chat_id, _strip_for_imessage(self.format_message(content))[: self.MAX_MESSAGE_LENGTH],
- richlink=False, markdown=False)
+ chat_id, self.format_message(content)[: self.MAX_MESSAGE_LENGTH], richlink=False, markdown=False)
async def _post_send(self, path: str, body: Dict[str, Any], *, structured: bool = False) -> SendResult:
"""POST a send-like body and wrap the outcome as a SendResult. ``structured`` carries
@@ -1379,13 +1371,9 @@ class PhotonAdapter(BasePlatformAdapter):
logger.warning("[photon] rich-link send failed, falling back to plain text: %s", rich_result.error)
markdown = False
send_markdown = markdown and _markdown_enabled()
- if send_markdown and _sidecar_downgrades_to_text(text):
- # spectrum-ts' markdown() degrades to readable plain text on its own;
- # text() does not, and ships the source verbatim. Strip before the
- # sidecar downgrades, or iMessage renders literal ** markers.
- # The format key stays: the sidecar owns the builder choice, and an
- # older sidecar without chooseSendFormat must keep rendering natively.
- text = _strip_for_imessage(text)
+ # The format key stays even when the text is stripped: the sidecar owns the builder choice,
+ # and an older sidecar without chooseSendFormat must keep rendering natively.
+ text = _sidecar_payload_text(text, send_markdown)
if len(text) > self.MAX_MESSAGE_LENGTH:
logger.warning("[photon] truncating outbound from %d to %d chars", len(text), self.MAX_MESSAGE_LENGTH)
text = text[: self.MAX_MESSAGE_LENGTH]
@@ -1552,8 +1540,10 @@ async def _standalone_send(
if rich_url:
_resp, data = await _post("/send-richlink", {"spaceId": chat_id, "url": rich_url})
if not data: # no URL-only message, or the rich-link send failed: plain text
- send_body: Dict[str, Any] = {"spaceId": chat_id, "text": message[:_MAX_MESSAGE_LENGTH]}
- if _markdown_enabled() and not rich_url:
+ send_markdown = _markdown_enabled() and not rich_url
+ send_body: Dict[str, Any] = {
+ "spaceId": chat_id, "text": _sidecar_payload_text(message, send_markdown)[:_MAX_MESSAGE_LENGTH]}
+ if send_markdown:
send_body["format"] = "markdown"
resp, data = await _post("/send", send_body)
if not data:
diff --git a/tests/gateway/test_strip_markdown_links.py b/tests/gateway/test_strip_markdown_links.py
index e6f316a51e8..f046118df5d 100644
--- a/tests/gateway/test_strip_markdown_links.py
+++ b/tests/gateway/test_strip_markdown_links.py
@@ -1,39 +1,9 @@
-"""``strip_markdown`` link handling.
-
-The default drops a link target (SMS, IRC, Feishu, QQ all rely on that);
-``keep_link_targets=True`` leaves the bare URL behind for platforms whose own
-data detection is the only thing that can re-linkify it.
-"""
-from __future__ import annotations
-
+"""``strip_markdown`` link handling: the default drops a link target (SMS, IRC, Feishu, QQ rely on it);
+``keep_link_targets=True`` leaves a bare http(s) URL for platforms whose data detection re-links it."""
from gateway.platforms.helpers import strip_markdown
-_LINK = "[Open the itinerary](https://example.com/i?tfs=CBwQ&hl=en)"
-
-
-def test_link_target_is_dropped_by_default() -> None:
- assert strip_markdown(f"see {_LINK} now") == "see Open the itinerary now"
-
-
-def test_keep_link_targets_puts_the_url_on_its_own_line() -> None:
- assert strip_markdown(_LINK, keep_link_targets=True) == (
- "Open the itinerary\nhttps://example.com/i?tfs=CBwQ&hl=en"
- )
-
-
-def test_keep_link_targets_does_not_duplicate_a_self_labelled_link() -> None:
- url = "https://example.com/x"
- assert strip_markdown(f"[{url}]({url})", keep_link_targets=True) == url
-
-
-def test_keep_link_targets_ignores_non_http_targets() -> None:
- """``mailto:``/relative targets are not auto-linked, so emitting them is noise."""
- text = "[mail](mailto:[email protected]) and [rel](/docs/page)"
- assert strip_markdown(text, keep_link_targets=True) == "mail and rel"
-
-def test_keep_link_targets_still_strips_inline_formatting() -> None:
- text = f"**Release 1.2.0**\n- `code` here\n{_LINK}"
- out = strip_markdown(text, keep_link_targets=True)
- assert "**" not in out and "`" not in out
- assert out.endswith("https://example.com/i?tfs=CBwQ&hl=en")
+def test_keep_link_targets_keeps_http_urls_only() -> None:
+ text = "see [Open it](https://example.com/i?x=1) or [mail](mailto:[email protected])"
+ assert strip_markdown(text) == "see Open it or mail"
+ assert strip_markdown(text, keep_link_targets=True) == "see Open it\nhttps://example.com/i?x=1 or mail"
diff --git a/tests/plugins/platforms/photon/test_markdown.py b/tests/plugins/platforms/photon/test_markdown.py
index 50e0b7041ff..5310a8df4f9 100644
--- a/tests/plugins/platforms/photon/test_markdown.py
+++ b/tests/plugins/platforms/photon/test_markdown.py
@@ -112,109 +112,19 @@ async def test_standalone_send_includes_markdown_format(
assert posted[0][1]["format"] == "markdown"
-_MD_WITH_URL = (
- "**Release 1.2.0** is out\n"
- "- **\u20ac5** off this month\n"
- "https://example.com/releases/1.2.0"
-)
-_MD_WITH_LINK = "**Release 1.2.0** is out\n[Read the notes](https://example.com/releases/1.2.0)"
-
-
@pytest.mark.asyncio
async def test_url_bearing_markdown_is_stripped_before_the_text_builder(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """A markdown payload the sidecar downgrades must not ship raw markers.
-
- ``chooseSendFormat`` routes markdown containing a raw URL through
- spectrum-ts' ``text()`` builder, which sends the source verbatim.
- """
+ """``chooseSendFormat`` sends markdown containing a URL through spectrum-ts' verbatim ``text()``
+ builder, so the adapter strips first, and a ``[label](url)`` link keeps a tappable bare URL."""
adapter = _make_adapter(monkeypatch)
calls = _capture_sidecar(adapter)
- await adapter.send("space-1", _MD_WITH_URL)
+ await adapter.send("space-1", "**Release 1.2.0** is out\n[Read the notes](https://example.com/notes)")
path, body = calls[-1]
assert path == "/send"
- # The format key is deliberately preserved: the sidecar owns the builder
- # choice (see test_rich_links.py). Only the payload changes.
- assert body["format"] == "markdown"
- assert "**" not in body["text"]
- # Stripping must not damage the parts iMessage still needs.
- assert "https://example.com/releases/1.2.0" in body["text"]
- assert "\u20ac5" in body["text"]
-
-
-async def test_url_free_markdown_still_renders_natively(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- adapter = _make_adapter(monkeypatch)
- calls = _capture_sidecar(adapter)
-
- await adapter.send("space-1", _MD)
-
- _, body = calls[-1]
- assert body["format"] == "markdown"
- assert body["text"] == _MD, "URL-free markdown must reach markdown() untouched"
-
-
-async def test_plain_fallback_strips_markdown(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The explicit fallback selects the text builder, so it must strip too."""
- adapter = _make_adapter(monkeypatch)
- calls = _capture_sidecar(adapter)
-
- await adapter._send_plain_fallback("space-1", _MD, reply_to=None, metadata=None)
-
- _, body = calls[-1]
- assert "format" not in body
- assert "**" not in body["text"]
- assert "`" not in body["text"]
-
-
-async def test_markdown_link_keeps_a_tappable_url(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A ``[label](url)`` link must not lose its URL on the way to iMessage.
-
- The URL inside ``](...)`` is enough for ``chooseSendFormat`` to pick the text
- builder, so this payload gets stripped — and iMessage auto-links bare URLs
- only. Dropping the target (the shared default) leaves the link unreachable.
- """
- adapter = _make_adapter(monkeypatch)
- calls = _capture_sidecar(adapter)
-
- await adapter.send("space-1", _MD_WITH_LINK)
-
- _, body = calls[-1]
- assert body["text"] == (
- "Release 1.2.0 is out\nRead the notes\nhttps://example.com/releases/1.2.0"
- )
-
-
-async def test_plain_fallback_keeps_link_urls(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- adapter = _make_adapter(monkeypatch)
- calls = _capture_sidecar(adapter)
-
- await adapter._send_plain_fallback("space-1", _MD_WITH_LINK, reply_to=None, metadata=None)
-
- _, body = calls[-1]
- assert "**" not in body["text"]
- assert "https://example.com/releases/1.2.0" in body["text"]
-
-
-def test_markdown_disabled_keeps_link_urls(monkeypatch: pytest.MonkeyPatch) -> None:
- """``PHOTON_MARKDOWN=false`` strips through the same iMessage-aware helper."""
- monkeypatch.setenv("PHOTON_MARKDOWN", "false")
- adapter = _make_adapter(monkeypatch)
-
- assert adapter.format_message(_MD_WITH_LINK) == (
- "Release 1.2.0 is out\nRead the notes\nhttps://example.com/releases/1.2.0"
- )
+ assert body["format"] == "markdown" # the sidecar owns the builder choice (test_rich_links.py)
+ assert "**" not in body["text"] and "](" not in body["text"]
+ assert "\nhttps://example.com/notes" in body["text"]