test_message_gate.py 18.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
"""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 不注入


class TestMergeTextFromPending:
    """测试 _merge_text_from_pending 辅助方法。"""

    def test_text_messages_concatenated(self):
        from app.service.message_gate import MessageGate
        pending = [
            {"msg_type": "text", "msg_content": "第一行"},
            {"msg_type": "text", "msg_content": "第二行"},
        ]
        result = MessageGate._merge_text_from_pending(pending)
        assert result == "第一行\n第二行"

    def test_non_text_tagged_as_file(self):
        from app.service.message_gate import MessageGate
        pending = [
            {"msg_type": "file", "msg_content": "https://example.com/audio.wav"},
        ]
        result = MessageGate._merge_text_from_pending(pending)
        assert result == "[文件: https://example.com/audio.wav]"

    def test_mixed_text_and_file(self):
        from app.service.message_gate import MessageGate
        pending = [
            {"msg_type": "text", "msg_content": "请总结这个录音"},
            {"msg_type": "audio", "msg_content": "https://example.com/audio.wav"},
        ]
        result = MessageGate._merge_text_from_pending(pending)
        assert "请总结这个录音" in result
        assert "[文件: https://example.com/audio.wav]" in result

    def test_empty_pending(self):
        from app.service.message_gate import MessageGate
        result = MessageGate._merge_text_from_pending([])
        assert result == ""

    def test_empty_content_skipped(self):
        from app.service.message_gate import MessageGate
        pending = [
            {"msg_type": "text", "msg_content": ""},
            {"msg_type": "text", "msg_content": "有效内容"},
        ]
        result = MessageGate._merge_text_from_pending(pending)
        assert result == "有效内容"


class TestHandleActionableContentPreservation:
    """测试 _handle_actionable 的原文合并逻辑。"""

    @pytest.mark.asyncio
    async def test_handle_actionable_preserves_original_text(self, message_gate_with_deps):
        """rewritten_query 使用指代时,原文应被合并到 query 中。"""
        gate = message_gate_with_deps
        pending = [
            {"msg_type": "text", "msg_content": "130行的转写文本内容..."},
        ]
        decision = GateDecision(
            intent="actionable",
            rewritten_query="请将上面提供的对话记录整理成会议纪要",
        )

        await gate._handle_actionable(
            session_id="sess_test",
            room_id="room1",
            user_id="u1",
            decision=decision,
            pending=pending,
            bot_id_mapping={"agent_meeting": "bot_123"},
        )

        call_args = gate.agent_hub.process_message.call_args
        query = call_args.kwargs["user_query"]
        assert "请将上面提供的对话记录整理成会议纪要" in query
        assert "130行的转写文本内容..." in query

    @pytest.mark.asyncio
    async def test_handle_actionable_no_duplicate_when_rewritten_contains_original(self, message_gate_with_deps):
        """rewritten_query 已包含原文时,不重复拼接。"""
        gate = message_gate_with_deps
        pending = [
            {"msg_type": "text", "msg_content": "你好"},
        ]
        decision = GateDecision(
            intent="actionable",
            rewritten_query="你好,请帮我查一下天气",
        )

        await gate._handle_actionable(
            session_id="sess_test",
            room_id="room1",
            user_id="u1",
            decision=decision,
            pending=pending,
            bot_id_mapping={},
        )

        call_args = gate.agent_hub.process_message.call_args
        query = call_args.kwargs["user_query"]
        assert query.count("你好") == 1

    @pytest.mark.asyncio
    async def test_handle_actionable_empty_rewritten_uses_original(self, message_gate_with_deps):
        """rewritten_query 为空时,用原文兜底。"""
        gate = message_gate_with_deps
        pending = [
            {"msg_type": "text", "msg_content": "请总结这个录音"},
        ]
        decision = GateDecision(intent="actionable", rewritten_query="")

        await gate._handle_actionable(
            session_id="sess_test",
            room_id="room1",
            user_id="u1",
            decision=decision,
            pending=pending,
            bot_id_mapping={},
        )

        call_args = gate.agent_hub.process_message.call_args
        query = call_args.kwargs["user_query"]
        assert query == "请总结这个录音"