mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(feishu): keep links and code blocks from rich-text posts (#8574)
* fix(feishu): keep links and code blocks from rich-text posts A Feishu message with a hyperlink or a code block arrives as a post. The parser kept only text/at elements and attachment placeholders, so `a` and `code_block` elements were dropped and the agent got the question without the link or the code. Render a link as [text](url), or the bare URL when the text is the URL, and a code block as a fenced block tagged with its language, using a fence longer than any backtick run in the code. * fix(feishu): start a post code block on its own line and escape link labels A code block that shares a paragraph with text was space-joined into one line, where its opening fence does not start a block. Emit it as its own paragraph instead. Escape brackets and backslashes in a link label so a "]" cannot end the link text early, and put a URL with parentheses or spaces in <...>. --------- Co-authored-by: HYYAlex <232531662+HYYAlex@users.noreply.github.com>
This commit is contained in:
parent
336b3d3527
commit
3a2ebca717
@ -311,6 +311,31 @@ def _append_post_file_placeholders(text: str, count: int) -> str:
|
||||
return "\n\n".join(paragraphs)
|
||||
|
||||
|
||||
def _post_link_text(element: dict) -> str:
|
||||
"""Render a post ``a`` element as a Markdown link, keeping its label and URL."""
|
||||
label = element.get("text") if isinstance(element.get("text"), str) else ""
|
||||
href = element.get("href") if isinstance(element.get("href"), str) else ""
|
||||
if not (label and href) or label == href:
|
||||
return href or label
|
||||
# Escape brackets so a "]" in the label cannot end the link text early, and
|
||||
# put a URL with parentheses or spaces in <...>, where it needs no escaping.
|
||||
label = re.sub(r"[\\\[\]]", lambda match: "\\" + match.group(), label)
|
||||
destination = f"<{href}>" if re.search(r"[\s()]", href) else href
|
||||
return f"[{label}]({destination})"
|
||||
|
||||
|
||||
def _post_code_block_text(element: dict) -> str:
|
||||
"""Render a post ``code_block`` element as a fenced block that the code's own backticks cannot close."""
|
||||
code = element.get("text")
|
||||
if not isinstance(code, str) or not code.strip():
|
||||
return ""
|
||||
language = element.get("language")
|
||||
info = language.lower() if isinstance(language, str) and re.fullmatch(r"[\w+#.-]+", language) else ""
|
||||
fence = "`" * max(3, max((len(run) for run in re.findall(r"`+", code)), default=0) + 1)
|
||||
code = code.rstrip("\n")
|
||||
return f"{fence}{info}\n{code}\n{fence}"
|
||||
|
||||
|
||||
class FeishuChannel(Channel):
|
||||
"""Feishu/Lark IM channel using the ``lark-oapi`` WebSocket client.
|
||||
|
||||
@ -2184,6 +2209,19 @@ class FeishuChannel(Channel):
|
||||
text_value = element.get("text", "")
|
||||
if text_value:
|
||||
paragraph_text_parts.append(text_value)
|
||||
elif element.get("tag") == "a":
|
||||
link_text = _post_link_text(element)
|
||||
if link_text:
|
||||
paragraph_text_parts.append(link_text)
|
||||
elif element.get("tag") == "code_block":
|
||||
code_block_text = _post_code_block_text(element)
|
||||
if code_block_text:
|
||||
# A fence must start its own line, so the block
|
||||
# becomes its own paragraph.
|
||||
if paragraph_text_parts:
|
||||
text_paragraphs.append(" ".join(paragraph_text_parts))
|
||||
paragraph_text_parts.clear()
|
||||
text_paragraphs.append(code_block_text)
|
||||
elif element.get("tag") == "img":
|
||||
image_key = element.get("image_key")
|
||||
if isinstance(image_key, str) and image_key:
|
||||
|
||||
@ -1283,6 +1283,91 @@ def test_feishu_post_with_text_and_top_level_files_extracts_attachments():
|
||||
assert mock_make_inbound.call_args[1]["files"] == [{"file_key": "file_inv_a"}, {"file_key": "file_inv_b"}, {"file_key": "file_po"}]
|
||||
|
||||
|
||||
def test_feishu_post_keeps_links_and_code_blocks():
|
||||
"""Feishu sends a message with a hyperlink or a code block as a post with ``a`` and ``code_block`` elements."""
|
||||
channel = FeishuChannel(MessageBus(), {"app_id": "test", "app_secret": "test"})
|
||||
url = "https://docs.python.org/3/library/functions.html#sum"
|
||||
event = _make_post_event(
|
||||
{
|
||||
"title": "",
|
||||
"content": [
|
||||
[{"tag": "text", "text": "Why does this raise TypeError?", "style": []}],
|
||||
[{"tag": "code_block", "language": "PYTHON", "text": 'print(sum(["3"]))\n'}],
|
||||
[{"tag": "text", "text": "See", "style": []}, {"tag": "a", "href": url, "text": url, "style": []}],
|
||||
[
|
||||
{"tag": "text", "text": "Compare", "style": ["bold"]},
|
||||
{"tag": "a", "href": "https://example.com/a", "text": "plan A", "style": []},
|
||||
{"tag": "text", "text": "and", "style": []},
|
||||
{"tag": "a", "href": "https://example.com/b", "text": "plan B", "style": []},
|
||||
],
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
mock_make_inbound = MagicMock()
|
||||
m.setattr(channel, "_make_inbound", mock_make_inbound)
|
||||
channel._on_message(event)
|
||||
|
||||
mock_make_inbound.assert_called_once()
|
||||
assert mock_make_inbound.call_args[1]["text"] == "\n\n".join(
|
||||
[
|
||||
"Why does this raise TypeError?",
|
||||
'```python\nprint(sum(["3"]))\n```',
|
||||
f"See {url}",
|
||||
"Compare [plan A](https://example.com/a) and [plan B](https://example.com/b)",
|
||||
]
|
||||
)
|
||||
assert mock_make_inbound.call_args[1]["files"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("element", "expected"),
|
||||
[
|
||||
({"tag": "a", "href": "https://example.com"}, "https://example.com"),
|
||||
({"tag": "a", "text": "label only"}, "label only"),
|
||||
({"tag": "a", "text": "", "href": None}, ""),
|
||||
({"tag": "a", "text": "[bug] a]b \\", "href": "https://example.com"}, "[\\[bug\\] a\\]b \\\\](https://example.com)"),
|
||||
({"tag": "a", "text": "Python", "href": "https://en.wikipedia.org/wiki/Python_(language"}, "[Python](<https://en.wikipedia.org/wiki/Python_(language>)"),
|
||||
({"tag": "code_block", "text": "x = 1"}, "```\nx = 1\n```"),
|
||||
({"tag": "code_block", "language": "GO", "text": "``` and ````"}, "`````go\n``` and ````\n`````"),
|
||||
({"tag": "code_block", "language": "bad\nlanguage", "text": "x = 1"}, "```\nx = 1\n```"),
|
||||
({"tag": "code_block", "language": "PYTHON", "text": " \n"}, ""),
|
||||
],
|
||||
)
|
||||
def test_feishu_post_link_and_code_block_edge_cases(element, expected):
|
||||
"""A code fence outlasts the code's own backticks; elements without content add nothing."""
|
||||
channel = FeishuChannel(MessageBus(), {"app_id": "test", "app_secret": "test"})
|
||||
event = _make_post_event({"content": [[{"tag": "text", "text": "Before"}], [element]]})
|
||||
|
||||
parsed = channel._parse_message_event(event)
|
||||
|
||||
assert parsed is not None
|
||||
assert parsed.text == ("Before\n\n" + expected if expected else "Before")
|
||||
|
||||
|
||||
def test_feishu_post_code_block_inside_a_paragraph_starts_on_its_own_line():
|
||||
"""A fence only opens a block at the start of a line, so text around the code becomes separate paragraphs."""
|
||||
channel = FeishuChannel(MessageBus(), {"app_id": "test", "app_secret": "test"})
|
||||
event = _make_post_event(
|
||||
{
|
||||
"content": [
|
||||
[
|
||||
{"tag": "text", "text": "Run"},
|
||||
{"tag": "code_block", "language": "BASH", "text": "make test"},
|
||||
{"tag": "text", "text": "and see"},
|
||||
{"tag": "a", "href": "https://example.com/log", "text": "the log"},
|
||||
]
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
parsed = channel._parse_message_event(event)
|
||||
|
||||
assert parsed is not None
|
||||
assert parsed.text == "Run\n\n```bash\nmake test\n```\n\nand see [the log](https://example.com/log)"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("code", ["bind-code", None])
|
||||
async def test_feishu_post_connect_reads_only_the_caption(monkeypatch, code):
|
||||
|
||||
@ -59,6 +59,10 @@ Feishu desktop posts can include a caption and files. Commands use the caption,
|
||||
and a command that starts a chat turn, such as `/goal <condition>`, passes the
|
||||
files to that turn.
|
||||
|
||||
Links and code blocks in a Feishu rich-text post reach the agent as Markdown: a
|
||||
link as `[text](url)`, or the bare URL when its text is the URL, and a code block
|
||||
as a fenced block tagged with its language.
|
||||
|
||||
**Configuration in `config.yaml`:**
|
||||
|
||||
Discord's `channels.discord.allowed_guilds` accepts one positive numeric guild
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user