fix(telegram): wait for final streaming edit interval

Wait once for the remaining message edit interval during Agent finalization, without bypassing Telegram 429 cooldown or replaying confirmed text.

Refs #7124
This commit is contained in:
jxxghp
2026-10-22 08:25:25 +08:00
parent 9d534d1954
commit cc2e02793e
6 changed files with 167 additions and 30 deletions

View File

@@ -256,10 +256,13 @@ async def test_streaming_start_waits_for_concurrent_stop_final_flush() -> None:
flush_started = asyncio.Event()
release_flush = asyncio.Event()
async def blocking_flush() -> None:
async def blocking_flush(*, final: bool = False) -> None:
"""
把最终刷新停留在生命周期锁内,验证新启动等待。
:param final: 是否执行停止阶段的最终刷新
"""
assert final
flush_started.set()
await release_flush.wait()

View File

@@ -15,7 +15,7 @@ from app.domain.metainfo import MetaInfo
from app.modules.telegram.botapi import TelegramApiError, TelegramNetworkError
from app.modules.telegram.module import TelegramModule
from app.modules.telegram.telegram import Telegram
from app.schemas.message import Message, MessageResponse
from app.schemas.message import Message
from app.schemas.types import MediaType, NotificationChannel
@@ -45,11 +45,27 @@ def telegram():
@pytest.mark.asyncio
async def test_agent_fallback_skips_progress_during_telegram_edit_interval(telegram, monkeypatch):
@pytest.mark.parametrize("partial_answer, trailing_tool", [(False, False), (True, False), (True, True)])
async def test_agent_final_edit_waits_during_telegram_edit_interval(
telegram, monkeypatch, partial_answer, trailing_tool,
):
"""
真实 Telegram 两秒编辑间隔触发回退时,已发送统计不能随最终答案再发一次。
真实 Telegram 两秒编辑间隔内收尾时,应等待并把完整答案编辑回原消息。
"""
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: 100.0)
now = [100.0]
waits = []
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
def advance(seconds):
"""
记录并推进 Telegram 编辑等待,保持用例离线且无需真实延时。
:param seconds: 等待秒数
"""
waits.append(seconds)
now[0] += seconds
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
telegram.bot.send_rich_message.return_value = {
"message_id": 101, "chat": {"id": "fake_chat_id"},
}
@@ -57,35 +73,53 @@ async def test_agent_fallback_skips_progress_during_telegram_edit_interval(teleg
handler._channel = NotificationChannel.Telegram.value
handler._source = "bot"
handler._streaming_enabled = True
handler._original_message_id = "question"
module = TelegramModule()
module._channel = NotificationChannel.Telegram
monkeypatch.setattr(module, "get_configs", lambda: {"bot": SimpleNamespace(name="bot")})
monkeypatch.setattr(module, "get_instance", lambda _name: telegram)
monkeypatch.setattr(module, "check_message", lambda *_args: True)
monkeypatch.setattr(module, "get_notification_targets", lambda _message: None)
async def dispatch(func, *args, **kwargs):
"""
保留真实 Telegram 发送及限频逻辑,只隔离宿主模块路由和远端 Bot API。
"""
if func.__name__ == "send_direct_message":
message = args[0]
result = telegram.send_msg(title="", text=message.text, rich_message=message.rich_message)
return MessageResponse(source="bot", **result)
return module.send_direct_message(args[0])
if func.__name__ == "edit_message":
return telegram.edit_msg(
chat_id=kwargs["chat_id"], message_id=kwargs["message_id"],
text=kwargs["text"],
rich_message=kwargs["metadata"]["telegram_rich_message"],
)
return module.edit_message(**kwargs)
return True
monkeypatch.setattr("app.agent.callback.run_in_threadpool", dispatch)
handler.record_tool_call("execute_command", tool_kwargs={"command": "capture"})
handler.thinking_started()
await handler._flush_messages()
handler.emit("截图已发送。")
handler.emit("| 剧名 | 简介 |\n| --- | --- |\n" + "| 示例 | 推荐理由 |\n" * 8)
if partial_answer:
now[0] += 2.0
await handler._flush_messages()
handler.emit("\n其中这些剧集评价最稳。\n\n要继续搜索吗?")
if trailing_tool:
handler.record_tool_call("read_file", tool_kwargs={"file_path": "result.txt"})
handler.flush_pending_tool_summary()
expected_text = handler._buffer
all_sent, _ = await handler.stop_streaming()
all_sent, final_text = await handler.stop_streaming()
assert not all_sent
assert await handler.take() == "截图已发送。"
assert all_sent
assert waits == [2.0]
assert await handler.take() == ""
telegram.bot.send_rich_message.assert_called_once()
telegram.bot.edit_message_text.assert_not_called()
assert telegram.bot.edit_message_text.call_count == (2 if partial_answer else 1)
assert telegram.bot.edit_message_text.call_args.kwargs["message_id"] == 101
rich_html = telegram.bot.edit_message_text.call_args.kwargs["rich_message"]["html"]
assert "<table>" in rich_html
assert rich_html.count("<td>推荐理由</td>") == 8
assert "要继续搜索吗?" in rich_html
assert final_text == expected_text
assert "要继续搜索吗?" in final_text
assert "思考中" not in final_text
@pytest.mark.parametrize("url", [None, "", " ", 123, False])

View File

@@ -279,7 +279,8 @@ class TestEditMsgFallsBackToPlainText:
assert result is False
client._api.edit_message_text.assert_called_once()
def test_429_cooldown_skips_follow_up_edits(self, monkeypatch):
@pytest.mark.parametrize("wait_for_interval", [False, True])
def test_429_cooldown_skips_follow_up_edits(self, monkeypatch, wait_for_interval):
"""
同一聊天的冷却期内后续编辑不应再触碰 Bot API。
"""
@@ -293,7 +294,12 @@ class TestEditMsgFallsBackToPlainText:
assert client.edit_msg(chat_id="chat", message_id=5, text="正文", rich_message="# 结果") is False
now[0] += 10
assert client.edit_msg(chat_id="chat", message_id=5, text="更新", rich_message="# 更新") is False
with patch("app.modules.telegram.telegram.time.sleep") as sleep_mock:
assert client.edit_msg(
chat_id="chat", message_id=5, text="更新", rich_message="# 更新",
wait_for_interval=wait_for_interval,
) is False
sleep_mock.assert_not_called()
assert client._api.edit_message_text.call_count == 1
now[0] += 8
client._api.edit_message_text.side_effect = None
@@ -301,6 +307,41 @@ class TestEditMsgFallsBackToPlainText:
assert client.edit_msg(chat_id="chat", message_id=5, text="更新", rich_message="# 更新") is True
assert client._api.edit_message_text.call_count == 2
@pytest.mark.parametrize("interruption", ["429", "edit"])
def test_final_edit_rechecks_cooldown_and_interval_after_one_wait(self, monkeypatch, interruption):
"""
等待期间出现聊天冷却或同消息并发编辑时,不追加请求或无限延长等待。
"""
client = _make_client()
now = [100.0]
waits = []
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
client._api.edit_message_text.return_value = {"message_id": 5}
assert client.edit_msg(chat_id="chat", message_id=5, text="首帧", rich_message="# 首帧") is True
def interrupt_wait(seconds):
"""
在虚拟等待结束时模拟其他请求带来的状态变化。
:param seconds: 本次等待秒数
"""
waits.append(seconds)
now[0] += seconds
if interruption == "429":
client._mark_rate_limit(
"chat", TelegramApiError("editMessageText", "Too Many Requests", 429, {"retry_after": 17}),
)
else:
assert client.edit_msg(chat_id="chat", message_id=5, text="并发编辑") is True
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", interrupt_wait)
assert client.edit_msg(
chat_id="chat", message_id=5, text="完整正文", rich_message="# 完整正文",
wait_for_interval=True,
) is False
assert waits == [TELEGRAM_EDIT_MIN_INTERVAL_SECONDS]
assert client._api.edit_message_text.call_count == (1 if interruption == "429" else 2)
def test_successful_edits_are_throttled_and_latest_text_wins(self, monkeypatch):
"""
最小编辑间隔内只保留最新一次刷新,解除后发送当前文本。
@@ -318,6 +359,34 @@ class TestEditMsgFallsBackToPlainText:
assert client.edit_msg(chat_id="chat", message_id=5, text="最新", rich_message="# 最新") is True
assert client._api.edit_message_text.call_count == 2
def test_final_edit_waits_for_message_interval(self, monkeypatch):
"""
收尾编辑应等待消息级间隔,确保完整正文覆盖原消息。
"""
client = _make_client()
now = [100.0]
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
def advance(seconds):
"""
用虚拟时钟推进消息级编辑间隔。
:param seconds: 等待秒数
"""
now[0] += seconds
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
client._api.edit_message_text.return_value = {"message_id": 5}
assert client.edit_msg(chat_id="chat", message_id=5, text="首帧", rich_message="# 首帧") is True
assert client.edit_msg(
chat_id="chat", message_id=5, text="完整正文", rich_message="# 完整正文",
wait_for_interval=True,
) is True
assert client._api.edit_message_text.call_count == 2
assert now[0] == 100.0 + TELEGRAM_EDIT_MIN_INTERVAL_SECONDS
assert "完整正文" in client._api.edit_message_text.call_args.kwargs["rich_message"]["html"]
class TestFallbackDisablesMarkdownV2:
"""