媒体功能是上一轮智能体自改代码时留下的 WIP(那轮步数耗尽被中断)。 本次把手头完成度较高的部分整理到可提交状态,并修掉其中两处判定 bug。 入站(已可用): - 新增 flows/media_input.py:附件先落盘再进上下文,小图内联为 base64, 大图与音视频退化为「路径 + 元信息」,附件级失败只降级为说明而不打断整轮 - processor 改用 prepare_inbound,文本 / 多模态输入据此决定发纯文本还是 content blocks 出站(骨架就位,尚未接线): - 新增 agent/outbox.py、channels/media.py(大小与类型校验、限长下载 / 读取) - 新增 send_image / send_file 工具、ChannelServices.send_content、 MessageEvent.content_event / media_event - 目前还没有任何调用方创建 MediaOutbox,因此这两个工具一律返回 「当前不在渠道会话中」;渠道侧的 _send_media 由各平台子类实现 修复: - prepare_inbound 不再塞「(无内容)」占位块:占位块会让 has_content 恒真, 空消息也能一路跑到 run_task,白烧一次模型调用 - 新增 PreparedInbound.is_multimodal 取代 len(blocks) > 1 的猜测: 「只有一张图、没有正文」时 blocks 只有 1 个,原逻辑会把附件丢掉 - 附件全部接收失败时回「附件未能接收:<原因>」,不再误报「空消息」 - 顺手清掉 ruff 告警(未用导入、__all__ 未排序、嵌套 if / with) 测试:test_processor 拆成三个用例(空消息 / 附件全失败 / 仅附件必须发 blocks,最后一条是防回潮的回归测试),全量 243 passed,ruff 全绿。
279 lines
9.9 KiB
Python
279 lines
9.9 KiB
Python
"""make_processor 测试:messages 历史、事件流与错误分支(stub run_task)。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from bot042.channels.models import (
|
|
ChannelSubject,
|
|
ImageContent,
|
|
InboundMessage,
|
|
MessageEventType,
|
|
TextContent,
|
|
)
|
|
from bot042.db import repo
|
|
from bot042.flows import processor as processor_mod
|
|
from bot042.flows.media_input import PreparedInbound
|
|
from bot042.flows.processor import make_processor
|
|
|
|
|
|
def _message(text: str, *, session: str = "cli", media: bool = False) -> InboundMessage:
|
|
content = []
|
|
if text:
|
|
content.append(TextContent(text=text))
|
|
if media:
|
|
content.append(ImageContent(url="https://img/x.png"))
|
|
return InboundMessage(
|
|
channel_id="cli",
|
|
channel_type="cli",
|
|
channel_subject=ChannelSubject(subject_id="local"),
|
|
channel_session_id=session,
|
|
content=content or [TextContent(text="")],
|
|
)
|
|
|
|
|
|
def _events(processor, message) -> list:
|
|
async def _collect() -> list:
|
|
return [event async for event in processor(message)]
|
|
|
|
return asyncio.run(_collect())
|
|
|
|
|
|
def test_processor_persists_and_reuses_history(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
calls: list[tuple[str, list]] = []
|
|
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None):
|
|
calls.append((task, list(history or [])))
|
|
return {"messages": [{"role": "assistant", "content": "答复:" + task}]}
|
|
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
db = tmp_path / "bot.db"
|
|
processor = make_processor(db=db)
|
|
|
|
events = _events(processor, _message("第一句"))
|
|
assert [e.type for e in events] == [
|
|
MessageEventType.TYPING,
|
|
MessageEventType.MESSAGE,
|
|
MessageEventType.COMPLETED,
|
|
]
|
|
assert events[1].content[0].text == "答复:第一句" # type: ignore[union-attr]
|
|
|
|
events = _events(processor, _message("第二句"))
|
|
assert events[1].content[0].text == "答复:第二句" # type: ignore[union-attr]
|
|
|
|
# 第二轮的历史包含第一轮问答
|
|
assert calls[0] == ("第一句", [])
|
|
assert calls[1][0] == "第二句"
|
|
assert calls[1][1] == [
|
|
{"role": "user", "content": "第一句"},
|
|
{"role": "assistant", "content": "答复:第一句"},
|
|
]
|
|
|
|
rows = asyncio.run(repo.list_messages(db, session_id="cli"))
|
|
assert [(r["role"], r["content"]) for r in rows] == [
|
|
("user", "第一句"),
|
|
("assistant", "答复:第一句"),
|
|
("user", "第二句"),
|
|
("assistant", "答复:第二句"),
|
|
]
|
|
sessions = asyncio.run(repo.list_sessions(db))
|
|
assert [s["id"] for s in sessions] == ["cli"]
|
|
|
|
|
|
def test_processor_session_isolated_per_key(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None):
|
|
return {"messages": [{"role": "assistant", "content": "ok"}]}
|
|
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
db = tmp_path / "bot.db"
|
|
processor = make_processor(db=db)
|
|
|
|
_events(processor, _message("a", session="s1"))
|
|
_events(processor, _message("b", session="s2"))
|
|
|
|
assert len(asyncio.run(repo.list_messages(db, session_id="s1"))) == 2
|
|
assert len(asyncio.run(repo.list_messages(db, session_id="s2"))) == 2
|
|
|
|
|
|
def test_processor_error_event_on_failure(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None):
|
|
raise RuntimeError("boom")
|
|
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
processor = make_processor(db=tmp_path / "bot.db")
|
|
|
|
events = _events(processor, _message("会失败"))
|
|
assert [e.type for e in events] == [MessageEventType.TYPING, MessageEventType.ERROR]
|
|
assert events[1].error == "处理消息时出错,请稍后再试。"
|
|
|
|
# 用户消息已落库,但没有助手回复
|
|
rows = asyncio.run(repo.list_messages(tmp_path / "bot.db", session_id="cli"))
|
|
assert [r["role"] for r in rows] == ["user"]
|
|
|
|
|
|
def test_processor_failed_turn_excluded_from_history(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
"""上一轮失败的悬空 user 消息不进上下文,但仍在库里留痕。"""
|
|
calls: list[list] = []
|
|
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None):
|
|
calls.append(list(history or []))
|
|
if task == "会失败":
|
|
raise RuntimeError("boom")
|
|
return {"messages": [{"role": "assistant", "content": "好的"}]}
|
|
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
db = tmp_path / "bot.db"
|
|
processor = make_processor(db=db)
|
|
|
|
_events(processor, _message("会失败"))
|
|
_events(processor, _message("再来一次"))
|
|
|
|
# 第二次的上下文里没有上一轮那条无回复的 user 消息
|
|
assert calls[1] == []
|
|
rows = asyncio.run(repo.list_messages(db, session_id="cli"))
|
|
assert [(r["role"], r["content"]) for r in rows] == [
|
|
("user", "会失败"),
|
|
("user", "再来一次"),
|
|
("assistant", "好的"),
|
|
]
|
|
|
|
|
|
def test_processor_empty_reply_not_persisted(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
"""空回复只展示占位文案,不写进 messages 表(避免污染后续上下文)。"""
|
|
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None):
|
|
return {"messages": [{"role": "assistant", "content": []}]}
|
|
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
db = tmp_path / "bot.db"
|
|
processor = make_processor(db=db)
|
|
|
|
events = _events(processor, _message("hi"))
|
|
assert events[1].content[0].text == "(无输出)" # type: ignore[union-attr]
|
|
rows = asyncio.run(repo.list_messages(db, session_id="cli"))
|
|
assert [(r["role"], r["content"]) for r in rows] == [("user", "hi")]
|
|
|
|
|
|
def test_processor_reuses_agent_cache(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
"""同一个处理器的多轮消息复用同一个 AgentCache。"""
|
|
seen: list[object] = []
|
|
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None):
|
|
seen.append(cache)
|
|
return {"messages": [{"role": "assistant", "content": "ok"}]}
|
|
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
processor = make_processor(db=tmp_path / "bot.db")
|
|
_events(processor, _message("a"))
|
|
_events(processor, _message("b"))
|
|
|
|
assert seen[0] is not None
|
|
assert seen[0] is seen[1]
|
|
|
|
|
|
def test_build_history_rules() -> None:
|
|
rows = [
|
|
{"role": "assistant", "content": "开场白"},
|
|
{"role": "user", "content": "第一问"},
|
|
{"role": "assistant", "content": "第一答"},
|
|
{"role": "user", "content": "无回复的残留"},
|
|
]
|
|
assert processor_mod.build_history(rows) == [
|
|
{"role": "user", "content": "第一问"},
|
|
{"role": "assistant", "content": "第一答"},
|
|
]
|
|
|
|
# 字符预算从新到旧累加,超预算的旧消息被丢弃
|
|
rows = [
|
|
{"role": "user", "content": "x" * 100},
|
|
{"role": "assistant", "content": "y" * 10},
|
|
{"role": "user", "content": "z" * 10},
|
|
{"role": "assistant", "content": "w" * 10},
|
|
]
|
|
assert processor_mod.build_history(rows, max_chars=30) == [
|
|
{"role": "user", "content": "z" * 10},
|
|
{"role": "assistant", "content": "w" * 10},
|
|
]
|
|
|
|
|
|
def test_processor_rejects_empty_message(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None): # pragma: no cover
|
|
raise AssertionError("不应执行任务")
|
|
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
processor = make_processor(db=tmp_path / "bot.db")
|
|
|
|
events = _events(processor, _message(""))
|
|
assert events[-1].type == MessageEventType.ERROR
|
|
assert "空消息" in (events[-1].error or "")
|
|
|
|
|
|
def test_processor_explains_unreadable_attachments(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
"""附件全部没接收成功:给附件级说明,不要含糊成「空消息」。"""
|
|
|
|
async def fake_prepare(message, *, root, **kwargs):
|
|
_ = message, root, kwargs
|
|
return PreparedInbound(text="", notes=["图片未接收:超过大小上限"])
|
|
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None): # pragma: no cover
|
|
raise AssertionError("不应执行任务")
|
|
|
|
monkeypatch.setattr(processor_mod, "prepare_inbound", fake_prepare)
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
processor = make_processor(db=tmp_path / "bot.db")
|
|
|
|
events = _events(processor, _message("", media=True))
|
|
assert events[-1].type == MessageEventType.ERROR
|
|
error = events[-1].error or ""
|
|
assert "附件未能接收" in error
|
|
assert "超过大小上限" in error
|
|
|
|
|
|
def test_processor_sends_blocks_for_attachment_only_message(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
"""只有一张图、没有正文时也必须发多模态块,否则附件被静默丢掉。"""
|
|
|
|
async def fake_prepare(message, *, root, **kwargs):
|
|
_ = message, root, kwargs
|
|
return PreparedInbound(
|
|
text="",
|
|
blocks=[
|
|
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}
|
|
],
|
|
)
|
|
|
|
seen: list[object] = []
|
|
|
|
async def fake_run_task(task, settings=None, history=None, *, cache=None):
|
|
seen.append(task)
|
|
return {"messages": [{"role": "assistant", "content": "看到了"}]}
|
|
|
|
monkeypatch.setattr(processor_mod, "prepare_inbound", fake_prepare)
|
|
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
|
|
processor = make_processor(db=tmp_path / "bot.db")
|
|
|
|
events = _events(processor, _message("", media=True))
|
|
assert isinstance(seen[0], list)
|
|
assert seen[0][0]["type"] == "image_url"
|
|
assert events[-1].type == MessageEventType.COMPLETED
|