"""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.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_and_media( 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 "") events = _events(processor, _message("", media=True)) assert events[-1].type == MessageEventType.ERROR assert "仅支持文本" in (events[-1].error or "")