mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-23 14:04:41 +00:00
fix(feishu): keep a card's markdown image from failing every update (#8423)
* fix(feishu): keep a card's markdown image from failing every update
A card markdown element only renders a markdown image whose target is an
uploaded `image_key`. An answer that carries `` therefore made Feishu
reject the card with 230099 / 11310 ("the card contains images but no imagekey is
passed in"), and because the same card is patched for each streamed snapshot,
every later update failed too: the reply stopped at the text sent before the
image marker (#8407).
Rewrite the marker as a link before the card is built, which keeps the
reference and its target in a form the element renders. Fenced blocks and
inline code spans stay literal, since a card shows them as code and rewriting
what they contain would misreport the answer.
The rewrite only removes a character, so a card that already fit Feishu's
30 KB body limit still does.
* fix(feishu): rewrite the button card's text and stay literal in an open fence
Review follow-ups on the card markdown rewrite.
The clarification button card builds its own JSON and is delivered with
`raw_card_content=True`, so it never passed through `_build_card_content`: an
agent-authored question carrying `` would still be rejected with
230099 / 11310. `build_button_card` now applies the same rewrite to the text it
puts in its markdown element (imported inside the function, since feishu.py
imports that module).
A snapshot streamed before its closing fence arrives has an open block at the
end, and the closed-fence pattern did not see it, so a marker inside that block
was rewritten in the transient snapshot and then shown as a link in what had
been code. What follows an unterminated opener is now left literal.
This commit is contained in:
parent
8a6eb9c898
commit
477c8e04ec
@ -157,6 +157,61 @@ FEISHU_MAX_CARDS_PER_REPLY = 10
|
||||
_CARD_TRUNCATION_MARKER = "\n\n... (truncated)"
|
||||
_CARD_CONTINUES_MARKER = "\n\n…"
|
||||
_LONE_SURROGATE = re.compile("[\ud800-\udfff]")
|
||||
|
||||
# A markdown image marker, rewritten for the card so Feishu never sees one.
|
||||
_MARKDOWN_IMAGE = re.compile(r"!\[(?P<alt>[^\]]*)\]\((?P<target>[^)\s]*)[^)]*\)")
|
||||
_FENCED_CODE = re.compile(r"(?ms)^[ \t]*(?P<fence>`{3,}|~{3,})[^\n]*\n.*?^[ \t]*(?P=fence)[ \t]*$")
|
||||
_INLINE_CODE_SPAN = re.compile(r"`[^`\n]*`")
|
||||
# A fence a streamed snapshot cut open: what follows its opener is still code.
|
||||
_UNCLOSED_FENCE = re.compile(r"(?m)^[ \t]*(?P<fence>`{3,}|~{3,})[^\n]*$")
|
||||
|
||||
|
||||
def _rewrite_outside_inline_code(chunk: str, rewrite: Callable[[str], str]) -> str:
|
||||
"""Apply *rewrite* to the parts of *chunk* that are not inline code spans."""
|
||||
out: list[str] = []
|
||||
cursor = 0
|
||||
for span in _INLINE_CODE_SPAN.finditer(chunk):
|
||||
out.append(rewrite(chunk[cursor : span.start()]))
|
||||
out.append(span.group(0))
|
||||
cursor = span.end()
|
||||
out.append(rewrite(chunk[cursor:]))
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _card_markdown(text: str) -> str:
|
||||
"""Rewrite the markdown a Feishu card cannot render.
|
||||
|
||||
A card markdown element only accepts a markdown image whose target is an
|
||||
uploaded ``image_key``. A URL target makes Feishu reject every update of that
|
||||
card with 230099 / 11310 ("the card contains images but no imagekey is passed
|
||||
in"), which is how a reply carrying ```` loses the rest of its
|
||||
streamed text. Dropping the marker keeps the reference, and its link, in a
|
||||
form the card renders. Code stays literal: a fenced block renders as code
|
||||
there, and rewriting what it shows would misreport the answer.
|
||||
"""
|
||||
if "})", chunk)
|
||||
|
||||
out: list[str] = []
|
||||
cursor = 0
|
||||
for fenced in _FENCED_CODE.finditer(text):
|
||||
out.append(_rewrite_outside_inline_code(text[cursor : fenced.start()], as_link))
|
||||
out.append(fenced.group(0))
|
||||
cursor = fenced.end()
|
||||
|
||||
tail = text[cursor:]
|
||||
# A snapshot streamed before its closing fence arrives has an open block at the
|
||||
# end; that content is code too, so what follows the opener stays literal.
|
||||
open_fence = _UNCLOSED_FENCE.search(tail)
|
||||
literal_from = open_fence.start() if open_fence else len(tail)
|
||||
out.append(_rewrite_outside_inline_code(tail[:literal_from], as_link))
|
||||
out.append(tail[literal_from:])
|
||||
return "".join(out)
|
||||
|
||||
|
||||
# Characters JSON escapes, measured after the second escape: ``"`` is ``\\\"``.
|
||||
_ESCAPED_CARD_CHAR_BYTES = {'"': 4, "\\": 4, "\b": 3, "\f": 3, "\n": 3, "\r": 3, "\t": 3}
|
||||
|
||||
@ -999,7 +1054,7 @@ class FeishuChannel(Channel):
|
||||
card = {
|
||||
"config": {"wide_screen_mode": True, "update_multi": True},
|
||||
# Unpaired surrogates cannot be encoded as UTF-8.
|
||||
"elements": [{"tag": "markdown", "content": _LONE_SURROGATE.sub("\ufffd", text)}],
|
||||
"elements": [{"tag": "markdown", "content": _card_markdown(_LONE_SURROGATE.sub("\ufffd", text))}],
|
||||
}
|
||||
# ASCII escapes would make each CJK character 6 bytes instead of 3.
|
||||
return json.dumps(card, ensure_ascii=False)
|
||||
|
||||
@ -123,7 +123,12 @@ class ClarificationCardRequest:
|
||||
|
||||
def build_button_card(request: ClarificationCardRequest) -> str:
|
||||
"""Render the clarification as a Feishu interactive card with one button per option."""
|
||||
# Imported here because feishu.py imports this module, and the markdown rewrite
|
||||
# lives beside the card it was written for.
|
||||
from app.channels.feishu import _card_markdown
|
||||
|
||||
content = f"{request.context}\n\n{request.question}" if request.context else request.question
|
||||
content = _card_markdown(content)
|
||||
card = {
|
||||
"config": {"wide_screen_mode": True, "update_multi": True},
|
||||
"header": {"title": {"tag": "plain_text", "content": "需要你的选择"}},
|
||||
|
||||
@ -18,6 +18,7 @@ from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody,
|
||||
from lark_oapi.core.json import JSON
|
||||
|
||||
from app.channels.feishu import FEISHU_CARD_MAX_BYTES, FEISHU_MAX_CARDS_PER_REPLY, FeishuChannel, _card_text_bytes, _split_card_text
|
||||
from app.channels.feishu_card_interaction import ClarificationCardRequest, build_button_card
|
||||
from app.channels.message_bus import MessageBus, OutboundMessage
|
||||
from app.channels.store import JsonChannelStore
|
||||
|
||||
@ -223,3 +224,68 @@ async def test_reply_without_running_card_and_push_without_source_split_too(feis
|
||||
assert api.rejected == []
|
||||
assert "".join(api.cards[card_id] for _, card_id in api.replies) == answer
|
||||
assert "".join(text for _, text in api.created) == answer
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("text", "expected", "keeps_its_marker"),
|
||||
[
|
||||
# Feishu only accepts a markdown image whose target is an uploaded image_key;
|
||||
# a URL target fails the whole card with 230099 / 11310 (#8407).
|
||||
("see  here", "see [chart](https://x.io/a.png) here", False),
|
||||
("", "[only](https://x.io/a.png)", False),
|
||||
(" and ", "[a](k) and [b](k2)", False),
|
||||
# A title inside the marker is not part of the link target Feishu gets.
|
||||
(' tail', "[a](https://x.io/a.png) tail", False),
|
||||
# Text without an image marker is untouched.
|
||||
("plain answer", "plain answer", False),
|
||||
# Code renders literally in a card, so the shown source must not change.
|
||||
("inline `` keeps its marker", "inline `` keeps its marker", True),
|
||||
("```\n\n```", "```\n\n```", True),
|
||||
# A snapshot streamed before the closing fence arrives keeps its open block literal.
|
||||
("```\n", "```\n", True),
|
||||
("```\n\n```\ntail ", "```\n\n```\ntail [c](d)", True),
|
||||
],
|
||||
)
|
||||
async def test_card_content_never_sends_a_markdown_image_feishu_cannot_resolve(text: str, expected: str, keeps_its_marker: bool):
|
||||
rendered = json.loads(FeishuChannel._build_card_content(text))["elements"][0]["content"]
|
||||
|
||||
assert rendered == expected
|
||||
# An unrendered marker inside code is literal text, not an image element.
|
||||
assert ("",
|
||||
options=("Alpha", "Beta"),
|
||||
option_ids=("o1", "o2"),
|
||||
callback_token="token",
|
||||
context="context ",
|
||||
)
|
||||
|
||||
card = json.loads(build_button_card(request))
|
||||
|
||||
markdown = next(element for element in card["elements"] if element["tag"] == "markdown")
|
||||
assert markdown["content"] == ("context [x](https://example.invalid/x.png)\n\nPick [chart](https://example.invalid/chart.png)")
|
||||
assert "![" not in markdown["content"]
|
||||
|
||||
|
||||
async def test_card_answer_with_an_image_url_still_fits_the_body_limit():
|
||||
"""An answer carrying an image URL keeps its link and stays within the card body limit."""
|
||||
answer = (
|
||||
"""Look at this:
|
||||

|
||||
"""
|
||||
+ "中文" * 200
|
||||
)
|
||||
|
||||
card = FeishuChannel._build_card_content(answer)
|
||||
|
||||
rendered = json.loads(card)["elements"][0]["content"]
|
||||
assert "![chart]" not in rendered
|
||||
assert "[chart](https://example.invalid/chart.png)" in rendered
|
||||
request = PatchMessageRequest.builder().message_id("card").request_body(PatchMessageRequestBody.builder().content(card).build()).build()
|
||||
assert _body_bytes(request) <= FEISHU_CARD_MAX_BYTES
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user