"""内置任务 AgentReply 测试:会话分区、落库、RPC 回复与失败提示。""" from __future__ import annotations import asyncio from datetime import datetime from pathlib import Path from typing import Any import pytest from bot042.channels.base import BaseChannel from bot042.channels.manager import ChannelManager from bot042.channels.models import ( ChannelMessage, ChannelSubject, InboundMessage, TextContent, ) from bot042.config import Settings from bot042.db import repo from bot042.flows import builtin from bot042.flows.builtin import ERROR_REPLY, RPC_SEND, AgentReply, ChannelServices from bot042.flows.bus import EventBus from bot042.flows.rpc import RpcHub from bot042.flows.scheduler import CN_TZ from bot042.flows.tasks import EventTrigger, RunStatus, TaskContext, TaskRunner class EchoChannel(BaseChannel): """测试渠道:任何 subject 都视为已登记,发送记录在内存。""" channel_type = "echo" def __init__(self) -> None: super().__init__(channel_id="c1") self.sent: list[str] = [] async def start(self) -> None: pass async def stop(self) -> None: pass def parse_inbound(self, raw_payload: Any) -> InboundMessage: assert isinstance(raw_payload, InboundMessage) return raw_payload def get_subject(self, subject_id: str) -> ChannelSubject | None: return ChannelSubject(subject_id=subject_id) async def _send_text(self, subject: ChannelSubject, text: str) -> None: self.sent.append(text) async def _send_content(self, subject: ChannelSubject, parts: list) -> None: pass async def _send_media(self, subject: ChannelSubject, media: Any) -> None: pass def _envelope( text: str, *, session: str | None = "s1", subject: str = "u1" ) -> ChannelMessage: message = InboundMessage( channel_id="c1", channel_type="echo", channel_session_id=session, channel_subject=ChannelSubject(subject_id=subject), content=[TextContent(text=text)], ) return ChannelMessage.of(message, session_key=session or "") def test_partition_key_matches_db_session_id() -> None: """分区键必须与会话历史使用的 session_id 一致。""" ctx = TaskContext( run_id="r1", task=AgentReply.name, event="channel.inbound", fired_at=datetime.now(CN_TZ), payload=_envelope("hi"), ) assert AgentReply.partition_key(ctx) == "s1" # 群聊:渠道锁键是发送者(user-a),历史会话键是群(chat-9),分区跟历史走 group = _envelope("hi", session="chat-9").model_copy( update={"session_key": "user-a", "subject_id": "user-a"} ) ctx2 = ctx.model_copy(update={"payload": group}) assert AgentReply.partition_key(ctx2) == "chat-9" # 没有平台会话 ID 时回退「渠道:主体」,与 run() 的落库表达式一致 ctx3 = ctx.model_copy(update={"payload": _envelope("hi", session=None)}) assert AgentReply.partition_key(ctx3) == "c1:u1" def test_db_session_id_property() -> None: """db_session_id 是落库与分区共用的唯一来源(消息本体与总线载荷一致)。""" group = _envelope("hi", session="chat-9") assert group.db_session_id == "chat-9" assert group.message.db_session_id == "chat-9" direct = _envelope("hi", session=None) assert direct.db_session_id == "c1:u1" assert direct.message.db_session_id == "c1:u1" def test_agent_reply_persists_and_replies_via_rpc( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: calls: list[tuple[str, list]] = [] async def fake_run_task( task, settings=None, history=None, *, cache=None, steering=None ): calls.append((task, list(history or []))) return {"messages": [{"role": "assistant", "content": "答:" + task}]} monkeypatch.setattr(builtin, "run_task", fake_run_task) async def _run() -> tuple[list[str], list[str], list[str]]: bus = EventBus() bus.bind_loop() hub = RpcHub(bus) manager = ChannelManager() channel = EchoChannel() await manager.add_channel(channel) await manager.start() _ = hub.serve(RPC_SEND, manager.rpc_send) services = ChannelServices( channels=manager, settings=Settings(), db=tmp_path / "bot.db", hub=hub, ) runner = TaskRunner(bus, deps=services) runner.register(AgentReply) _ = runner.add_task(AgentReply.name, EventTrigger(event="channel.inbound")) await runner.start() bus.emit("channel.inbound", _envelope("第一句")) bus.emit("channel.inbound", _envelope("第二句")) await runner.wait_idle(timeout=2) await bus.wait_for_complete() runs = runner.runs(AgentReply.name) keys = [run.key for run in runs] statuses = [run.status.value for run in runs] await runner.stop() hub.close() await manager.stop() return channel.sent, keys, statuses sent, keys, statuses = asyncio.run(_run()) assert sent == ["答:第一句", "答:第二句"] assert keys == ["s1", "s1"] assert statuses == ["succeeded", "succeeded"] # 第二轮上下文里有第一轮问答 assert calls[1][1] == [ {"role": "user", "content": "第一句"}, {"role": "assistant", "content": "答:第一句"}, ] rows = asyncio.run(repo.list_messages(tmp_path / "bot.db", session_id="s1")) assert [(r["role"], r["content"]) for r in rows] == [ ("user", "第一句"), ("assistant", "答:第一句"), ("user", "第二句"), ("assistant", "答:第二句"), ] def test_agent_reply_sends_error_hint_on_failure( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: async def boom(task, settings=None, history=None, *, cache=None): raise RuntimeError("agent down") monkeypatch.setattr(builtin, "run_task", boom) async def _run() -> tuple[list[str], list[RunStatus]]: bus = EventBus() bus.bind_loop() hub = RpcHub(bus) manager = ChannelManager() channel = EchoChannel() await manager.add_channel(channel) await manager.start() _ = hub.serve(RPC_SEND, manager.rpc_send) services = ChannelServices( channels=manager, settings=Settings(), db=tmp_path / "bot.db", hub=hub ) runner = TaskRunner(bus, deps=services) runner.register(AgentReply) _ = runner.add_task(AgentReply.name, EventTrigger(event="channel.inbound")) await runner.start() bus.emit("channel.inbound", _envelope("会失败")) await runner.wait_idle(timeout=2) await bus.wait_for_complete() statuses = [run.status for run in runner.runs(AgentReply.name)] await runner.stop() hub.close() await manager.stop() return channel.sent, statuses sent, statuses = asyncio.run(_run()) assert sent == [ERROR_REPLY] assert statuses == [RunStatus.FAILED]