test_message_gate.py 14.1 KB
"""MessageGate 服务的单元测试。"""
import pytest
from unittest.mock import MagicMock, AsyncMock
from app.service.message_gate import MessageGate, GateDecision


def test_message_gate_can_be_constructed():
    """MessageGate 应能通过依赖注入的方式构造。"""
    config_loader = MagicMock()
    session_service = MagicMock()
    post_reply_hook = MagicMock()
    agent_hub = MagicMock()
    main_agent_key = "main"

    gate = MessageGate(
        config_loader=config_loader,
        session_service=session_service,
        post_reply_hook=post_reply_hook,
        agent_hub=agent_hub,
        main_agent_key=main_agent_key,
        model=MagicMock(),  # 提供 mock model 避免真实加载 models.json
    )

    assert gate is not None
    assert gate.config_loader is config_loader
    assert gate.session_service is session_service
    assert gate.agent_hub is agent_hub


def test_gate_decision_dataclass_defaults():
    """GateDecision 默认字段正确。"""
    d = GateDecision(intent="ignore")
    assert d.intent == "ignore"
    assert d.rewritten_query is None
    assert d.reply is None


import asyncio
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import clear_default_store_for_tests


@pytest.fixture
def message_gate_with_deps():
    """构造一个带假依赖的 MessageGate。"""
    config_loader = MagicMock()
    session_service = MagicMock()
    post_reply_hook = MagicMock()
    post_reply_hook.execute = AsyncMock()
    agent_hub = MagicMock()
    agent_hub.process_message = AsyncMock()
    agent_hub.agents = {}  # MessageGate._classify_and_rewrite 会读写此属性

    # 提供 mock model,避免真实加载 models.json
    mock_model = MagicMock()
    gate = MessageGate(
        config_loader=config_loader,
        session_service=session_service,
        post_reply_hook=post_reply_hook,
        agent_hub=agent_hub,
        main_agent_key="main",
        model=mock_model,
    )
    return gate


@pytest.mark.asyncio
async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps):
    """纯 file 消息应等待(用 monkey-patched 短等待避免测试慢)。"""
    gate = message_gate_with_deps

    # 用 0.1 秒等待代替 6 秒
    from app.service import message_gate as mg_module
    original_sleep = mg_module.asyncio.sleep
    async def fast_sleep(_):
        await original_sleep(0.01)
    mg_module.asyncio.sleep = fast_sleep

    try:
        # 模拟 LLM 返回 actionable(patch 内部方法)
        gate._classify_and_rewrite = AsyncMock(return_value=GateDecision(
            intent="actionable",
            rewritten_query="请分析文件 [url]",
        ))

        # 追加 file 消息到 buffer
        from app.infrastructure.session_store import SessionStore
        clear_default_store_for_tests()
        store = SessionStore()
        buffer = SessionBuffer(store, "sess_001")
        buffer.append({
            "msg_id": "m1", "msg_type": "file",
            "msg_content": "https://example.com/audio.mp3",
            "sender_id": "u1", "msg_time": "t",
        })

        await gate.evaluate(
            session_id="sess_001",
            room_id="r1",
            user_id="u1",
            bot_id_mapping={"main": "bot-001"},
        )
        # 等待 0.01s 后分类被调用
        assert gate._classify_and_rewrite.await_count == 1
    finally:
        mg_module.asyncio.sleep = original_sleep


@pytest.mark.asyncio
async def test_classify_casual_intent(message_gate_with_deps, monkeypatch):
    """_classify_and_rewrite 应正确解析 LLM 返回的 casual JSON。"""
    gate = message_gate_with_deps

    # Mock OpenAIChatModel 返回 casual JSON
    fake_response_text = '{"intent": "casual", "reply": "早~"}'
    gate.model = AsyncMock(return_value=MagicMock(
        content=[{"type": "text", "text": fake_response_text}]
    ))

    pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "早上好",
                "sender_id": "u1", "msg_time": "t"}]
    decision = await gate._classify_and_rewrite(
        session_id="sess_001",
        pending=pending,
        agent_codes=["11", "14"],
    )
    assert decision.intent == "casual"
    assert decision.reply == "早~"


@pytest.mark.asyncio
async def test_classify_actionable_with_rewrite(message_gate_with_deps):
    """actionable 分类应包含 rewritten_query。"""
    gate = message_gate_with_deps
    fake_response_text = '{"intent": "actionable", "rewritten_query": "请总结这个文件"}'
    gate.model = AsyncMock(return_value=MagicMock(
        content=[{"type": "text", "text": fake_response_text}]
    ))

    pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "帮我总结",
                "sender_id": "u1", "msg_time": "t"}]
    decision = await gate._classify_and_rewrite(
        session_id="sess_001",
        pending=pending,
        agent_codes=["11"],
    )
    assert decision.intent == "actionable"
    assert decision.rewritten_query == "请总结这个文件"


@pytest.mark.asyncio
async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps):
    """actionable 分支应直接 await AgentHub.process_message。"""
    gate = message_gate_with_deps
    gate.agent_hub.process_message = AsyncMock()

    await gate._handle_actionable(
        session_id="sess_001",
        room_id="r1",
        user_id="u1",
        decision=GateDecision(intent="actionable", rewritten_query="请分析文件"),
        pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "url",
                  "sender_id": "u1", "msg_time": "t"}],
        bot_id_mapping={"main": "bot-001"},
    )

    gate.agent_hub.process_message.assert_awaited_once()


@pytest.mark.asyncio
async def test_actionable_extracts_file_url_from_file_type(message_gate_with_deps):
    """file 类型消息的 msg_content 应被提取为 file_url 传给 AgentHub。"""
    gate = message_gate_with_deps
    gate.agent_hub.process_message = AsyncMock()

    await gate._handle_actionable(
        session_id="sess_002",
        room_id="r1",
        user_id="u1",
        decision=GateDecision(intent="actionable", rewritten_query="请总结会议"),
        pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "https://oss.example.com/audio.mp3",
                  "sender_id": "u1", "msg_time": "t"}],
        bot_id_mapping={"main": "bot-001"},
    )

    gate.agent_hub.process_message.assert_awaited_once()
    # 验证 file_url 参数正确传递
    call_kwargs = gate.agent_hub.process_message.call_args.kwargs
    assert call_kwargs.get("file_url") == "https://oss.example.com/audio.mp3"


@pytest.mark.asyncio
async def test_actionable_still_extracts_image_url(message_gate_with_deps):
    """image 类型消息的 msg_content 也应被提取为 file_url(向后兼容)。"""
    gate = message_gate_with_deps
    gate.agent_hub.process_message = AsyncMock()

    await gate._handle_actionable(
        session_id="sess_003",
        room_id="r1",
        user_id="u1",
        decision=GateDecision(intent="actionable", rewritten_query="这是什么图片"),
        pending=[{"msg_id": "m1", "msg_type": "image", "msg_content": "https://oss.example.com/img.jpg",
                  "sender_id": "u1", "msg_time": "t"}],
        bot_id_mapping={"main": "bot-001"},
    )

    call_kwargs = gate.agent_hub.process_message.call_args.kwargs
    assert call_kwargs.get("file_url") == "https://oss.example.com/img.jpg"


@pytest.mark.asyncio
async def test_incomplete_sends_reply_and_preserves_buffer(message_gate_with_deps):
    """incomplete 分支应发 IM 追问,且不清空 buffer。"""
    gate = message_gate_with_deps

    from app.infrastructure.session_store import SessionStore
    from app.infrastructure.session_store import clear_default_store_for_tests
    clear_default_store_for_tests()
    store = SessionStore()
    buffer = SessionBuffer(store, "sess_inc")
    buffer.append({
        "msg_id": "m1", "msg_type": "file",
        "msg_content": "https://example.com/audio.mp3",
        "sender_id": "u1", "msg_time": "t",
    })

    await gate._handle_incomplete(
        session_id="sess_inc",
        room_id="r1",
        user_id="u1",
        decision=GateDecision(intent="incomplete", reply="这文件是用来做什么的?"),
        pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "https://example.com/audio.mp3",
                  "sender_id": "u1", "msg_time": "t"}],
        bot_id_mapping={"main": "bot-001"},
    )

    # IM 追问被发送
    gate.post_reply_hook.execute.assert_awaited_once()
    call_args = gate.post_reply_hook.execute.call_args[0][0]
    assert call_args["response_content"] == "这文件是用来做什么的?"

    # buffer 未被清空(evaluate 里 incomplete 分支不清空)
    remaining = buffer.get_pending()
    assert len(remaining) == 1


@pytest.mark.asyncio
async def test_classify_file_only_as_incomplete(message_gate_with_deps):
    """file-only 消息应被 LLM 分类为 incomplete。"""
    gate = message_gate_with_deps
    fake_response_text = '{"intent": "incomplete", "reply": "这段录音需要转文字,还是做摘要?"}'
    gate.model = AsyncMock(return_value=MagicMock(
        content=[{"type": "text", "text": fake_response_text}]
    ))

    pending = [{"msg_id": "m1", "msg_type": "file", "msg_content": "https://example.com/audio.mp3",
                "sender_id": "u1", "msg_time": "t"}]
    decision = await gate._classify_and_rewrite(
        session_id="sess_file_only",
        pending=pending,
        agent_codes=["main"],
    )
    assert decision.intent == "incomplete"
    assert decision.reply == "这段录音需要转文字,还是做摘要?"

    # 验证发给 LLM 的 merged_text 带了类型标注
    call_args = gate.model.call_args
    messages = call_args[1]["messages"] if "messages" in call_args[1] else call_args[0][0]
    user_content = messages[1]["content"]
    assert "[文件:" in user_content


@pytest.mark.asyncio
async def test_classify_task_without_resource_is_incomplete(message_gate_with_deps):
    """纯文字 '帮我整理会议纪要' 无文件 → incomplete(不能复用历史链接)。"""
    gate = message_gate_with_deps

    from app.config.settings import AgentConfig
    gate.agent_hub.agents = {
        "agent_meeting": AgentConfig(
            name="会议Agent", code="17",
            prompt="你是广联数科的会议纪要助手,职责包括:音频转写、会议纪要整理。",
            is_steward=False, skills=["meeting_minutes"],
        ),
    }

    fake_response = '{"intent": "incomplete", "reply": "请提供需要处理的音频文件"}'
    gate.model = AsyncMock(return_value=MagicMock(
        content=[{"type": "text", "text": fake_response}]
    ))

    pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "帮我整理成会议纪要",
                "sender_id": "u1", "msg_time": "t"}]
    decision = await gate._classify_and_rewrite(
        session_id="sess_002",
        pending=pending,
        agent_codes=["agent_meeting"],
    )
    assert decision.intent == "incomplete"
    assert "音频" in (decision.reply or "")

    # 验证 system prompt 注入了 agent 职责
    call_args = gate.model.call_args
    messages = call_args[1]["messages"] if "messages" in call_args[1] else call_args[0][0]
    system_content = messages[0]["content"]
    assert "音频转写" in system_content


@pytest.mark.asyncio
async def test_classify_actionable_with_resource_present(message_gate_with_deps):
    """有文件+意图 → actionable(文件在文本消息中作为 URL)。"""
    gate = message_gate_with_deps

    from app.config.settings import AgentConfig
    gate.agent_hub.agents = {
        "agent_meeting": AgentConfig(
            name="会议Agent", code="17",
            prompt="你是广联数科的会议纪要助手,职责包括:音频转写。",
            is_steward=False, skills=["meeting_minutes"],
        ),
    }

    fake_response = '{"intent": "actionable", "rewritten_query": "将音频转文字并整理会议纪要"}'
    gate.model = AsyncMock(return_value=MagicMock(
        content=[{"type": "text", "text": fake_response}]
    ))

    pending = [
        {"msg_id": "m1", "msg_type": "text", "msg_content": "https://example.com/audio.mp3",
         "sender_id": "u1", "msg_time": "t"},
        {"msg_id": "m2", "msg_type": "text", "msg_content": "帮我整理成会议纪要",
         "sender_id": "u1", "msg_time": "t"},
    ]
    decision = await gate._classify_and_rewrite(
        session_id="sess_003",
        pending=pending,
        agent_codes=["agent_meeting"],
    )
    assert decision.intent == "actionable"
    assert "音频" in (decision.rewritten_query or "")


@pytest.mark.asyncio
async def test_steward_agent_excluded_from_prompt(message_gate_with_deps):
    """is_steward=True 的主 agent 不注入 system prompt。"""
    gate = message_gate_with_deps

    from app.config.settings import AgentConfig
    gate.agent_hub.agents = {
        "agent_main": AgentConfig(
            name="管家Agent", code="11",
            prompt="你是管家,负责协调各岗位Agent。",
            is_steward=True, skills=[],
        ),
        "agent_meeting": AgentConfig(
            name="会议Agent", code="17",
            prompt="会议纪要助手,职责:音频转写。",
            is_steward=False, skills=["meeting_minutes"],
        ),
    }

    fake_response = '{"intent": "incomplete", "reply": "请提供音频文件"}'
    gate.model = AsyncMock(return_value=MagicMock(
        content=[{"type": "text", "text": fake_response}]
    ))

    pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "帮我整理纪要",
                "sender_id": "u1", "msg_time": "t"}]
    await gate._classify_and_rewrite(
        session_id="sess_004",
        pending=pending,
        agent_codes=["agent_main", "agent_meeting"],
    )

    # 验证 system prompt 不含管家 agent 的 prompt
    call_args = gate.model.call_args
    messages = call_args[1]["messages"] if "messages" in call_args[1] else call_args[0][0]
    system_content = messages[0]["content"]
    assert "音频转写" in system_content           # 子 agent 注入
    assert "协调各岗位" not in system_content     # 主 agent 不注入