test_agent_hub.py 62.7 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 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
import asyncio
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from fastapi.testclient import TestClient

from app.main import app as fastapi_app

# ── AgentHub 测试实例 ────────────────────────────────────────────
from app.config.settings import AgentConfig
from app.agent_core.active_session_service import ActiveSessionService
from app.agent_core.agent_hub import AgentHub, AgentHubError, _route_context_var, _background_tasks
from app.agent_core.memory import SessionMemory


def _extract_text(resp):
    """Extract text from ToolResponse (content blocks may be dicts or TextBlock)."""
    block = resp.content[0]
    if isinstance(block, dict):
        return block["text"]
    return block.text


async def _drain_background_tasks():
    """等待所有 fire-and-forget 后台任务完成(测试用)。"""
    tasks = list(_background_tasks)
    _background_tasks.clear()
    if tasks:
        await asyncio.gather(*tasks, return_exceptions=True)


# 测试用 agent keys(替代原来的 "main" / "meeting")
STEWARD_KEY = "agent_steward_test"
MEETING_KEY = "agent_meeting_test"


def _make_test_agents():
    """Create test agent configs matching the new AgentConfig structure."""
    return {
        STEWARD_KEY: AgentConfig(
            name="管家 Agent",
            code="11",
            prompt="你是智能助手,负责协调各个岗位Agent协作回答用户问题。",
            description="协调调度各子Agent,分析用户意图并分发任务",
            is_steward=True,
        ),
        MEETING_KEY: AgentConfig(
            name="会议Agent",
            code="17",
            prompt="你是会议纪要助手,职责包括处理会议纪要相关的任务。",
            description="会议录音转写、会议纪要生成与导出",
            skills=["meeting_minutes"],
            is_steward=False,
        ),
    }


def _make_test_hub(agents=None):
    """Create an AgentHub with mock config_loader and test agents."""
    mock_loader = MagicMock()
    mock_model_config = MagicMock()
    mock_model_config.model_name = "test-model"
    mock_model_config.api_key = "test-key"
    mock_model_config.api_base = "http://test"
    mock_loader.load_models.return_value = {"main": mock_model_config}
    mock_loader.load_skills_from_toolkit.return_value = {}

    session_service = ActiveSessionService()
    im_service = MagicMock()
    im_service.send_message = AsyncMock(return_value={"code": 200})

    return AgentHub(
        config_loader=mock_loader,
        session_service=session_service,
        im_service=im_service,
        preloaded_agents=agents or _make_test_agents(),
    )


test_hub = _make_test_hub()


def _make_mock_model_reply(text: str):
    """创建一个返回纯文本的 mock model,供 ReActAgent 内部调用。"""

    def _make_resp(blocks):
        r = MagicMock()
        r.content = blocks
        return r

    async def side_effect(*args, **kwargs):
        return _make_resp([{"type": "text", "text": text}])

    mock = AsyncMock(side_effect=side_effect)
    mock.stream = False  # 关键:让 ReActAgent 走非流式路径
    return mock


async def _noop_format(msgs):
    """透传 formatter,让 ReActAgent 直接传递 Msg 列表给 mock model。"""
    return msgs


def _override_get_agent_hub():
    return test_hub


def _override_get_message_gate():
    from unittest.mock import MagicMock, AsyncMock
    from app.agent_core.message_gate import MessageGate, GateDecision
    mock_gate = MagicMock(spec=MessageGate)
    mock_gate.evaluate = AsyncMock(return_value=None)
    # 让 evaluate 同步调用 agent_hub.process_message(模拟 actionable 分支)
    async def fake_evaluate(session_id, room_id, user_id, bot_id_mapping, messages=None, wait_seconds=6.0, **kwargs):
        text_parts = []
        file_url = None
        for msg in (messages or []):
            if msg.msg_type == "text":
                if msg.msg_content:
                    text_parts.append(msg.msg_content)
            else:
                if msg.msg_content and file_url is None:
                    file_url = msg.msg_content
        query = "\n".join(text_parts)
        await test_hub.process_message(
            session_id=session_id,
            room_id=room_id,
            user_id=user_id,
            user_query=query,
            file_url=file_url,
            allowed_agent_codes=None,
            bot_id_mapping=bot_id_mapping,
        )
    mock_gate.evaluate = AsyncMock(side_effect=fake_evaluate)
    return mock_gate


from app.api.v1.endpoints.agent_hub import get_agent_hub, get_message_gate

fastapi_app.dependency_overrides[get_agent_hub] = _override_get_agent_hub
fastapi_app.dependency_overrides[get_message_gate] = _override_get_message_gate

client = TestClient(fastapi_app)


# ── Helper - 构造新格式请求体 ──

def _make_request(
    query: str = "你好",
    agents: list = None,
    group_contact_id: str = "room_001",
    sender_id: str = "user_001",
    extra_messages: list = None,
) -> dict:
    """构造符合新 API 格式的请求体。session_id = group_contact_id。"""
    body = {
        "group": {
            "group_contact_id": group_contact_id,
            "group_name": "测试群",
            "bot_code": "test_bot",
        },
        "position": {
            "position_id": 1,
            "position_code": "store_sales",
            "position_name": "驻店销售岗",
        },
        "agents": agents or [{"agent_id": 17, "agent_name": "会议Agent"}],
        "messages": [
            {
                "msg_id": "m1",
                "msg_time": "2026-05-23T10:00:00Z",
                "sender_id": sender_id,
                "sender_name": "测试用户",
                "msg_type": "text",
                "msg_content": query,
                "payload": {},
            }
        ],
    }
    if extra_messages:
        body["messages"].extend(extra_messages)
    return body


def _get_session_messages(session_id: str) -> list:
    """Helper: 从 SessionStore 获取消息历史"""
    data = test_hub.session_service.store.get(session_id)
    if data:
        return data.get("conversation_history", [])
    return []


# ═══════════════════════════════════════════════════════════════════
# API 层集成测试 — POST /api/v1/chat/completions (新异步格式)
# ═══════════════════════════════════════════════════════════════════


class TestChatCompletionsAPI:
    def test_returns_200_with_new_format(self):
        """新格式请求 → 立即返回 200 + session_id (=group_contact_id)"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                resp = client.post(
                    "/api/v1/chat/completions",
                    json=_make_request(group_contact_id="sess_api_001", query="你好"),
                )

                assert resp.status_code == 200
                data = resp.json()["data"]
                assert data["status"] == "ok"
                assert data["session_id"] == "sess_api_001"

    def test_session_created_from_group_contact_id(self):
        """group_contact_id → session_id + room_id, 会话被创建"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                resp = client.post(
                    "/api/v1/chat/completions",
                    json=_make_request(
                        query="测试",
                        group_contact_id="grp_room_99",
                    ),
                )

                assert resp.status_code == 200
                data = resp.json()["data"]
                assert data["session_id"] == "grp_room_99"
                session_data = test_hub.session_service.store.get("grp_room_99")
                assert session_data is not None
                assert session_data["room_id"] == "grp_room_99"

    def test_user_id_from_last_message_sender(self):
        """user_id 从 messages 最后一条消息的 sender_id 推导"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                resp = client.post(
                    "/api/v1/chat/completions",
                    json=_make_request(
                        group_contact_id="sess_api_003",
                        query="你好",
                        extra_messages=[
                            {
                                "msg_id": "m2",
                                "msg_time": "2026-05-23T10:01:00Z",
                                "sender_id": "user_last",
                                "sender_name": "最后发言者",
                                "msg_type": "text",
                                "msg_content": "第二条消息",
                                "payload": {},
                            }
                        ],
                    ),
                )

                assert resp.status_code == 200
                messages = _get_session_messages("sess_api_003")
                assert len(messages) >= 1

    def test_image_message_extracts_file_url(self):
        """image 类型消息的 msg_content 作为图片 URL 传给 Agent"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("我看到了一张图片")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                resp = client.post(
                    "/api/v1/chat/completions",
                    json={
                        "group": {"group_contact_id": "sess_img_001"},
                        "messages": [
                            {
                                "msg_id": "m1",
                                "msg_time": "2026-05-23T10:00:00Z",
                                "sender_id": "user_001",
                                "msg_type": "text",
                                "msg_content": "这张图片是什么",
                                "payload": {},
                            },
                            {
                                "msg_id": "m2",
                                "msg_time": "2026-05-23T10:00:01Z",
                                "sender_id": "user_001",
                                "msg_type": "image",
                                "msg_content": "https://oss.example.com/img/photo.jpg",
                                "payload": {},
                            },
                        ],
                    },
                )

                assert resp.status_code == 200

    def test_agents_filter_allowed_codes(self):
        """agents 数组中的 agent_id 映射为 allowed_agent_codes"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                resp = client.post(
                    "/api/v1/chat/completions",
                    json=_make_request(
                        group_contact_id="sess_agent_filter",
                        query="你好",
                        agents=[{"agent_id": 17, "agent_name": "会议Agent"}],
                    ),
                )

                assert resp.status_code == 200

    def test_missing_messages_returns_400(self):
        """缺少 messages 字段 → 400"""
        resp = client.post(
            "/api/v1/chat/completions",
            json={"group": {"group_contact_id": "grp_no_msg"}},
        )
        assert resp.status_code == 400

    def test_empty_messages_returns_400(self):
        """空 messages 数组 → 400"""
        resp = client.post(
            "/api/v1/chat/completions",
            json={
                "group": {"group_contact_id": "grp_empty_msg"},
                "messages": [],
            },
        )
        assert resp.status_code == 400

    def test_image_only_messages_returns_200(self):
        """只有 image 消息没有 text → 200(MessageGate 会等待文本或追问)"""
        resp = client.post(
            "/api/v1/chat/completions",
            json={
                "group": {"group_contact_id": "grp_img_only"},
                "messages": [
                    {
                        "msg_id": "m1",
                        "msg_time": "2026-05-23T10:00:00Z",
                        "sender_id": "user_001",
                        "msg_type": "image",
                        "msg_content": "https://example.com/img.jpg",
                        "payload": {},
                    },
                ],
            },
        )
        assert resp.status_code == 200

    def test_missing_group_contact_id_returns_400(self):
        """不传 group.group_contact_id → 400"""
        resp = client.post(
            "/api/v1/chat/completions",
            json={
                "messages": [
                    {
                        "msg_id": "m1",
                        "msg_time": "2026-05-23T10:00:00Z",
                        "sender_id": "u1",
                        "msg_type": "text",
                        "msg_content": "你好",
                        "payload": {},
                    }
                ],
            },
        )
        assert resp.status_code == 400

    def test_agents_without_name(self):
        """agents 不含 agent_name → 不报错"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                resp = client.post(
                    "/api/v1/chat/completions",
                    json={
                        "group": {"group_contact_id": "grp_no_name"},
                        "agents": [{"agent_id": 17}],
                        "messages": [
                            {
                                "msg_id": "m1",
                                "msg_time": "2026-05-23T10:00:00Z",
                                "sender_id": "u1",
                                "msg_type": "text",
                                "msg_content": "你好",
                                "payload": {},
                            }
                        ],
                    },
                )
                assert resp.status_code == 200

    def test_agents_with_bot_id_and_steward(self):
        """agents 含 bot_id 和 is_steward → 正确接收"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                resp = client.post(
                    "/api/v1/chat/completions",
                    json={
                        "group": {"group_contact_id": "grp_steward"},
                        "agents": [
                            {"agent_id": 17, "bot_id": "bot_001", "is_steward": True},
                            {"agent_id": 102, "bot_id": "bot_002", "is_steward": False},
                        ],
                        "messages": [
                            {
                                "msg_id": "m1",
                                "msg_time": "2026-05-23T10:00:00Z",
                                "sender_id": "u1",
                                "msg_type": "text",
                                "msg_content": "你好",
                                "payload": {},
                            }
                        ],
                    },
                )
                assert resp.status_code == 200


# ═══════════════════════════════════════════════════════════════════
# PostReplyHook 单元测试
# ═══════════════════════════════════════════════════════════════════


class TestPostReplyHook:
    @pytest.mark.asyncio
    async def test_strips_thinking_blocks_before_send(self):
        from app.hooks.post_reply import PostReplyHook

        mock_im = AsyncMock()
        mock_im.send_message.return_value = {"code": 200}

        hook = PostReplyHook(im_service=mock_im)

        await hook.execute(
            {
                "agent_name": STEWARD_KEY,
                "response_content": "正常回复<thinking>内部思考</thinking>继续回复",
                "room_id": "room_001",
                "mentioned_list": ["user_001"],
                "bot_id_mapping": {STEWARD_KEY: "bot_steward_001"},
            }
        )

        sent = mock_im.send_message.call_args[1]["content"]
        assert "<thinking>" not in sent
        assert "正常回复" in sent
        assert "继续回复" in sent

    @pytest.mark.asyncio
    async def test_skips_when_agent_name_missing(self):
        from app.hooks.post_reply import PostReplyHook

        mock_im = AsyncMock()
        hook = PostReplyHook(im_service=mock_im)

        result = await hook.execute(
            {"response_content": "内容", "room_id": "room_001"}
        )

        assert result is None
        mock_im.send_message.assert_not_called()

    @pytest.mark.asyncio
    async def test_skips_when_response_content_missing(self):
        from app.hooks.post_reply import PostReplyHook

        mock_im = AsyncMock()
        hook = PostReplyHook(im_service=mock_im)

        result = await hook.execute(
            {"agent_name": STEWARD_KEY, "room_id": "room_001"}
        )

        assert result is None
        mock_im.send_message.assert_not_called()

    @pytest.mark.asyncio
    async def test_skips_for_unmapped_agent(self):
        from app.hooks.post_reply import PostReplyHook

        mock_im = AsyncMock()
        hook = PostReplyHook(im_service=mock_im)

        result = await hook.execute(
            {
                "agent_name": "unknown_agent",
                "response_content": "回复",
                "room_id": "room_001",
                "mentioned_list": [],
                "bot_id_mapping": {},
            }
        )

        assert result is None
        mock_im.send_message.assert_not_called()

    @pytest.mark.asyncio
    async def test_skips_when_content_empty_after_strip(self):
        from app.hooks.post_reply import PostReplyHook

        mock_im = AsyncMock()
        hook = PostReplyHook(im_service=mock_im)

        result = await hook.execute(
            {
                "agent_name": STEWARD_KEY,
                "response_content": "<thinking>只有思考</thinking>",
                "room_id": "room_001",
                "mentioned_list": [],
                "bot_id_mapping": {STEWARD_KEY: "bot_steward_001"},
            }
        )

        assert result is None
        mock_im.send_message.assert_not_called()


# ═══════════════════════════════════════════════════════════════════
# AgentHub 路由逻辑测试(直接调用 process_message)
# ═══════════════════════════════════════════════════════════════════


class TestAgentHubRouting:
    @pytest.mark.asyncio
    async def test_process_message_returns_routing_metadata(self):
        """验证返回结构包含所有必需字段"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复内容")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                result = await test_hub.process_message(
                    session_id="sess_meta_001",
                    room_id="room_001",
                    user_id="user_001",
                    user_query="测试问题",
                )

                assert "session_id" in result
                assert result["response_agent_code"] == STEWARD_KEY
                assert result["routing_reason"] == "default"
                assert result["response_content"] == "回复内容"
                assert isinstance(result["processing_time_ms"], float)
                assert result["processing_time_ms"] >= 0

    @pytest.mark.asyncio
    async def test_preserves_session_across_calls(self):
        """同一 session_id 多次调用,消息累积在同一 session"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                sid = "sess_persist_001"
                await test_hub.process_message(
                    session_id=sid, room_id="r1", user_id="u1", user_query="Q1"
                )
                await test_hub.process_message(
                    session_id=sid, room_id="r1", user_id="u1", user_query="Q2"
                )

                messages = _get_session_messages(sid)
                assert len(messages) == 4  # 2 user + 2 assistant

    @pytest.mark.asyncio
    async def test_default_routing_to_steward(self):
        """未指定 agent → 路由到 steward"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好,我是智能助手")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                result = await test_hub.process_message(
                    session_id="sess_route_001",
                    room_id="room_001",
                    user_id="user_001",
                    user_query="你好",
                )

                assert result["response_agent_code"] == STEWARD_KEY
                assert result["routing_reason"] == "default"
                assert len(result["response_content"]) > 0

    @pytest.mark.asyncio
    async def test_mention_routing_always_steward(self):
        """即使传入 mentioned_agent_code,也始终路由到 steward"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("已为你整理会议纪要")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                result = await test_hub.process_message(
                    session_id="sess_route_002",
                    room_id="room_001",
                    user_id="user_001",
                    user_query="整理会议纪要",
                    mentioned_agent_code="meeting",
                )

                assert result["response_agent_code"] == STEWARD_KEY
                assert result["routing_reason"] == "default"

    @pytest.mark.asyncio
    async def test_no_sticky_routing(self):
        """不再粘性继承 agent,每次始终路由 steward"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("会议纪要内容")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                sid = "sess_route_003"
                r1 = await test_hub.process_message(
                    session_id=sid,
                    room_id="room_001",
                    user_id="user_001",
                    user_query="查会议纪要",
                    mentioned_agent_code="meeting",
                )
                assert r1["response_agent_code"] == STEWARD_KEY

                r2 = await test_hub.process_message(
                    session_id=sid,
                    room_id="room_001",
                    user_id="user_001",
                    user_query="再查一个",
                )
                assert r2["response_agent_code"] == STEWARD_KEY
                assert r2["routing_reason"] == "default"

    @pytest.mark.asyncio
    async def test_messages_accumulate(self):
        """同一 session 多次请求,消息累积"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复内容")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                sid = "sess_accumulate"
                for i in range(3):
                    await test_hub.process_message(
                        session_id=sid,
                        room_id="room_001",
                        user_id="user_001",
                        user_query=f"问题{i + 1}",
                    )

                messages = _get_session_messages(sid)
                assert len(messages) == 6  # 3 user + 3 assistant

    @pytest.mark.asyncio
    async def test_channel_default_value(self):
        """channel 字段默认为 wechat_group"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                await test_hub.process_message(
                    session_id="sess_channel",
                    room_id="room_001",
                    user_id="user_001",
                    user_query="测试",
                )

                session_data = test_hub.session_service.store.get("sess_channel")
                assert session_data is not None
                assert session_data["channel"] == "wechat_group"

    @pytest.mark.asyncio
    async def test_image_url_appended_to_query(self):
        """file_url 不为空时,图片 URL 追加到 query 中"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("我看到图片了")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                result = await test_hub.process_message(
                    session_id="sess_img",
                    room_id="room_001",
                    user_id="user_001",
                    user_query="这张图片是什么",
                    file_url="https://oss.example.com/img/photo.jpg",
                )

                assert result["response_content"] is not None

    @pytest.mark.asyncio
    async def test_file_url_appended_as_attachment(self):
        """file_url 不为空时,agent_hub 应使用"附件"格式追加到 query(兼容音频/视频等非图片)"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                result = await test_hub.process_message(
                    session_id="sess_file",
                    room_id="room_001",
                    user_id="user_001",
                    user_query="请帮我总结会议",
                    file_url="https://oss.example.com/audio.mp3",
                )
                # 验证 process_message 跑通
                assert result["response_content"] == "收到"
                # 验证拼接逻辑:file_url 被加到 query
                # 抽取出 _build_main_prompt 实际内容包含 user_query,确保 input 流转
                # 简易检查:session store 中应该有 user 消息
                msgs = _get_session_messages("sess_file")
                assert any("请帮我总结会议" in m.get("content", "") for m in msgs)

    @pytest.mark.asyncio
    async def test_allowed_agent_codes_still_routes_steward(self):
        """allowed_agent_codes 不影响路由(始终 steward),仅影响 prompt 中 advertised 的子 agent"""
        with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                result = await test_hub.process_message(
                    session_id="sess_restricted",
                    room_id="room_001",
                    user_id="user_001",
                    user_query="整理会议纪要",
                    mentioned_agent_code="meeting",
                    allowed_agent_codes=[],
                )

                assert result["response_agent_code"] == STEWARD_KEY
                assert result["routing_reason"] == "default"


# ═══════════════════════════════════════════════════════════════════
# 协作层集成测试 — call_sub_agent 串行链
# ═══════════════════════════════════════════════════════════════════


class TestCollaboration:
    """Serial chain collaboration integration tests — simulate multi-call ReAct with call_sub_agent."""

    @pytest.mark.asyncio
    async def test_serial_chain_two_sub_agents(self):
        """Simulate: model calls meeting → then task → then returns integrated result."""
        responses = [
            [{"type": "tool_use", "id": "call_1", "name": "call_sub_agent",
              "input": {"agent_code": MEETING_KEY, "instruction": "整理纪要"}}],
            [{"type": "tool_use", "id": "call_2", "name": "call_sub_agent",
              "input": {"agent_code": "unknown_task", "instruction": "提取待办"}}],
            [{"type": "text", "text": "已整理纪要并提取待办:1.提交方案 2.确认预算"}],
        ]

        call_count = [0]

        def _make_resp(blocks):
            r = MagicMock()
            r.content = blocks
            return r

        async def model_side_effect(*args, **kwargs):
            idx = min(call_count[0], len(responses) - 1)
            result = _make_resp(responses[idx])
            call_count[0] += 1
            return result

        async def mock_sub_call(agent_code, instruction):
            if agent_code == MEETING_KEY:
                return "纪要: 讨论了Q2预算和团队调整"
            elif agent_code == "unknown_task":
                return "待办: 1.提交Q2预算 2.人员调整方案"
            return ""

        model_mock = AsyncMock(side_effect=model_side_effect)
        model_mock.stream = False

        with patch.object(test_hub, 'model', new=model_mock):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)):
                    result = await test_hub.process_message(
                        session_id="sess_collab_001",
                        room_id="room_001",
                        user_id="u1",
                        user_query="整理纪要并提取待办",
                    )
                    assert "已整理" in result["response_content"]

    @pytest.mark.asyncio
    async def test_max_iterations_limit(self):
        """Loop exceeding 10 iterations — ReActAgent generates summary, no exception."""
        tool_call_blocks = [
            {"type": "tool_use", "id": "call_x", "name": "call_sub_agent",
             "input": {"agent_code": MEETING_KEY, "instruction": "x"}}
        ]

        async def model_side_effect(prompt, tools=None, **kwargs):
            r = MagicMock()
            if tools is None:
                r.content = [{"type": "text", "text": "已达最大迭代次数,总结当前情况。"}]
            else:
                r.content = tool_call_blocks
            return r

        async def mock_sub_call(*args, **kwargs):
            return "result"

        model_mock_2 = AsyncMock(side_effect=model_side_effect)
        model_mock_2.stream = False

        with patch.object(test_hub, 'model', new=model_mock_2):
            with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)):
                    result = await test_hub.process_message(
                        session_id="sess_limit_001",
                        room_id="room_001",
                        user_id="u1",
                        user_query="test",
                    )
                    assert result["response_content"] is not None
                    assert len(result["response_content"]) > 0


# ── Tests for sub_model (thinking control) ──


def test_agent_hub_has_sub_model_with_low_temperature():
    """AgentHub 应创建 sub_model 实例,temperature=0.2。"""
    hub = _make_test_hub()
    # sub_model 应存在,且 generate_kwargs["temperature"] == 0.2
    assert hasattr(hub, "sub_model")
    assert hub.sub_model is not None
    assert hub.sub_model.generate_kwargs.get("temperature") == 0.2


@pytest.mark.asyncio
async def test_call_sub_agent_uses_sub_model():
    """_call_sub_agent 创建的 ReActAgent 应使用 sub_model 而非 main model。"""
    from agentscope.agent import ReActAgent

    hub = _make_test_hub()
    _token = _route_context_var.set({
        "room_id": "room_001", "user_id": "user_001", "bot_id_mapping": {},
        "session_id": "sess_test_001",
        "call_count": 0,
    })
    captured_model = None

    real_init = ReActAgent.__init__

    def capture_init(self, *args, **kwargs):
        nonlocal captured_model
        captured_model = kwargs.get("model")
        real_init(self, *args, **kwargs)
        # 把 reply 替换为 AsyncMock 避免真实模型调用
        self.reply = AsyncMock(return_value=MagicMock())

    try:
        with patch.object(ReActAgent, "__init__", new=capture_init):
            await hub._call_sub_agent(MEETING_KEY, "test instruction")
    finally:
        _route_context_var.reset(_token)

    # ReActAgent 应被创建,model 应该是 sub_model
    assert captured_model is not None
    assert captured_model is hub.sub_model
    # 不应是 main model
    assert captured_model is not hub.model


# ── Tests for prompt assembly (hardcoded guides removed, now in DB prompt) ──


def test_main_prompt_no_hardcoded_guides():
    """_build_main_prompt 不应包含硬编码的 DISPATCH_GUIDE 和 THINKING_GUIDE。"""
    hub = _make_test_hub()
    prompt = hub._build_main_prompt()
    assert "调度规则" not in prompt
    assert "思考风格" not in prompt
    # 但不影响 steward.prompt 和 soul_guide 的正常拼接
    assert "你是智能助手" in prompt
    assert "说人话" in prompt


def test_sub_agent_prompt_no_hardcoded_guides():
    """_build_sub_agent_prompt 不应包含硬编码的 DISPATCH_GUIDE 和 THINKING_GUIDE。"""
    hub = _make_test_hub()
    prompt = hub._build_sub_agent_prompt(MEETING_KEY)
    assert "调度规则" not in prompt
    assert "思考风格" not in prompt
    assert "你是会议纪要助手" in prompt
    assert "说人话" in prompt


# ── Tests for soul_guide injection ──


def test_main_prompt_includes_soul_guide():
    """_build_main_prompt 输出应包含 soul/agent.md 的回复风格内容。"""
    hub = _make_test_hub()
    prompt = hub._build_main_prompt()
    assert "说人话" in prompt
    assert "微信适配" in prompt


def test_sub_agent_prompt_includes_soul_guide():
    """_build_sub_agent_prompt 输出应包含 soul/agent.md 的回复风格内容。"""
    hub = _make_test_hub()
    prompt = hub._build_sub_agent_prompt(MEETING_KEY)
    assert "说人话" in prompt
    assert "微信适配" in prompt


# ── Tests for thinking summarization ──


@pytest.mark.asyncio
async def test_summarize_thinking_calls_model():
    """任意长度 thinking 都应调用 thinking_summary_model 摘要化。"""
    hub = _make_test_hub()
    short = "正在处理"
    mock_response = MagicMock()
    mock_response.content = [{"type": "text", "text": "处理中"}]
    hub.thinking_summary_model = AsyncMock(return_value=mock_response)
    hub.formatter.format = AsyncMock(return_value=[{"role": "user", "content": short}])

    result = await hub._summarize_thinking(short)
    assert hub.thinking_summary_model.called
    assert result == "处理中"


@pytest.mark.asyncio
async def test_summarize_thinking_long_text_calls_model():
    """长 thinking 应调用 thinking_summary_model 摘要化。"""
    hub = _make_test_hub()
    long_text = "用户需要我根据提供的音频文件生成会议纪要。根据系统提示,我需要使用 meeting_minutes 技能来处理这个任务。让我先查看 meeting_minutes 技能的 SKILL.md 文件。"
    mock_response = MagicMock()
    mock_response.content = [{"type": "text", "text": "正在生成会议纪要"}]
    hub.thinking_summary_model = AsyncMock(return_value=mock_response)
    hub.formatter.format = AsyncMock(return_value=[{"role": "user", "content": long_text}])

    result = await hub._summarize_thinking(long_text)
    assert hub.thinking_summary_model.called
    assert "会议纪要" in result


@pytest.mark.asyncio
async def test_hook_summarizes_thinking_before_send():
    """hook 应在发送 IM 前对长 thinking 调用摘要化。"""
    from app.agent_core.agent_hub import _im_post_reasoning_hook

    mock_im = AsyncMock()
    mock_im.send_message.return_value = {"code": 200}
    mock_summarize = AsyncMock(return_value="正在处理会议纪要")

    mock_agent = MagicMock()
    mock_agent.name = MEETING_KEY
    mock_agent.memory = MagicMock()
    mock_agent.memory.get_memory = AsyncMock(return_value=[])

    mock_output = MagicMock()
    mock_output.content = [{"type": "thinking", "thinking": "这条思考过程非常长," * 10}]

    await _im_post_reasoning_hook(
        mock_agent, {}, mock_output,
        im_service=mock_im,
        room_id="room_001",
        user_id="user_001",
        bot_id_mapping={MEETING_KEY: "bot_001"},
        summarize_thinking=mock_summarize,
    )

    # 让 fire-and-forget 后台任务执行完再断言
    await _drain_background_tasks()
    mock_summarize.assert_called_once()
    sent_content = mock_im.send_message.call_args[1]["content"]
    assert sent_content == "正在处理会议纪要"


@pytest.mark.asyncio
async def test_hook_summarizes_even_short_thinking():
    """即使是短 thinking,也应走摘要化(不直接暴露内部推理)。"""
    from app.agent_core.agent_hub import _im_post_reasoning_hook

    mock_im = AsyncMock()
    mock_im.send_message.return_value = {"code": 200}
    mock_summarize = AsyncMock(return_value="正在处理")

    mock_agent = MagicMock()
    mock_agent.name = MEETING_KEY
    mock_agent.memory = MagicMock()
    mock_agent.memory.get_memory = AsyncMock(return_value=[])

    mock_output = MagicMock()
    mock_output.content = [{"type": "thinking", "thinking": "正在处理"}]

    await _im_post_reasoning_hook(
        mock_agent, {}, mock_output,
        im_service=mock_im,
        room_id="room_001",
        user_id="user_001",
        bot_id_mapping={MEETING_KEY: "bot_001"},
        summarize_thinking=mock_summarize,
    )

    # 让 fire-and-forget 后台任务执行完再断言
    await _drain_background_tasks()


@pytest.mark.asyncio
async def test_hook_skips_after_call_sub_agent_result():
    """call_sub_agent 工具结果后的 post_reasoning 应跳过 IM 发送。"""
    from app.agent_core.agent_hub import _im_post_reasoning_hook

    mock_im = AsyncMock()
    mock_summarize = AsyncMock()

    mock_agent = MagicMock()
    mock_agent.name = MEETING_KEY
    # post_reasoning 触发时 memory[-1] 已是本轮 reasoning 输出,
    # call_sub_agent 的 tool_result 在上轮 _acting() 写入,位于 memory[-2]
    mock_tool_result = MagicMock()
    mock_tool_result.content = [
        {"type": "tool_result", "id": "call_123", "name": "call_sub_agent", "output": "会议纪要已生成"}
    ]
    mock_current_reasoning = MagicMock()
    mock_current_reasoning.content = []
    mock_agent.memory = MagicMock()
    mock_agent.memory.get_memory = AsyncMock(
        return_value=[mock_tool_result, mock_current_reasoning]
    )

    mock_output = MagicMock()
    mock_output.content = [{"type": "thinking", "thinking": "收到结果,整合回复用户"}]

    result = await _im_post_reasoning_hook(
        mock_agent, {}, mock_output,
        im_service=mock_im,
        room_id="room_001",
        user_id="user_001",
        bot_id_mapping={MEETING_KEY: "bot_001"},
        summarize_thinking=mock_summarize,
    )

    # 应直接返回 None,不发送 IM
    assert result is None
    mock_im.send_message.assert_not_called()
    mock_summarize.assert_not_called()


class TestCallSubAgentCounter:
    """测试 call_sub_agent 调用计数。"""

    def test_call_count_initialized_in_route_ctx(self):
        """_route_context_var 初始化后 call_count 为 0。"""
        token = _route_context_var.set(dict(
            room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
        ))
        try:
            ctx = _route_context_var.get()
            assert ctx["call_count"] == 0
        finally:
            _route_context_var.reset(token)

    @pytest.mark.asyncio
    async def test_call_count_increments_in_tool(self):
        """call_sub_agent 工具调用后计数器 +1。"""
        hub = _make_test_hub()
        token = _route_context_var.set(dict(
            room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
        ))
        try:
            with patch.object(hub, '_call_sub_agent', new=AsyncMock(return_value="子Agent结果")):
                tool = hub._make_call_sub_agent_tool()
                await tool(agent_code=MEETING_KEY, instruction="测试指令")
            ctx = _route_context_var.get()
            assert ctx["call_count"] == 1
        finally:
            _route_context_var.reset(token)

    @pytest.mark.asyncio
    async def test_dedup_rejects_repeated_agent_code(self):
        """同一 agent_code 第二次调用返回去重错误。"""
        hub = _make_test_hub()
        token = _route_context_var.set(dict(
            room_id="r1", user_id="u1", bot_id_mapping={},
            call_count=0, called_agents=set(),
        ))
        try:
            with patch.object(hub, '_call_sub_agent', new=AsyncMock(return_value="子Agent结果")):
                tool = hub._make_call_sub_agent_tool()
                # 第一次调用成功
                r1 = await tool(agent_code=MEETING_KEY, instruction="测试指令")
                assert "错误" not in r1.content[0].get("text", "")
                ctx = _route_context_var.get()
                assert ctx["call_count"] == 1
                assert MEETING_KEY in ctx["called_agents"]

                # 第二次调用同一 agent_code → 去重拒绝
                r2 = await tool(agent_code=MEETING_KEY, instruction="再试一次")
                assert "已被调用过" in r2.content[0].get("text", "")
                # call_count 不变
                assert ctx["call_count"] == 1
        finally:
            _route_context_var.reset(token)

    @pytest.mark.asyncio
    async def test_dedup_allows_different_agent_code(self):
        """不同 agent_code 不受去重影响。"""
        hub = _make_test_hub()
        # 找另一个非 steward 的 agent code
        sub_keys = [k for k in hub.agents if not hub.agents[k].is_steward and k != MEETING_KEY]
        if not sub_keys:
            pytest.skip("需要至少两个不同的子Agent")
        other_key = sub_keys[0]

        token = _route_context_var.set(dict(
            room_id="r1", user_id="u1", bot_id_mapping={},
            call_count=0, called_agents=set(),
        ))
        try:
            with patch.object(hub, '_call_sub_agent', new=AsyncMock(return_value="子Agent结果")):
                tool = hub._make_call_sub_agent_tool()
                r1 = await tool(agent_code=MEETING_KEY, instruction="任务一")
                r2 = await tool(agent_code=other_key, instruction="任务二")
                assert "已被调用过" not in r2.content[0].get("text", "")
                ctx = _route_context_var.get()
                assert ctx["call_count"] == 2
        finally:
            _route_context_var.reset(token)


class TestSubAgentPostReply:
    """测试子 Agent 独立发送 post_reply。"""

    @pytest.mark.asyncio
    async def test_call_sub_agent_sends_post_reply(self):
        """_call_sub_agent 应通过 post_reply_hook 发送子 Agent 回复。"""
        hub = _make_test_hub()
        token = _route_context_var.set(dict(
            room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
            session_id="sess_test_002", call_count=0,
        ))

        # post_reply_hook.execute 是真实方法,用 AsyncMock(wraps=...) 包装以跟踪调用
        mock_execute = AsyncMock(wraps=hub.post_reply_hook.execute)

        mock_reply = _make_mock_model_reply("会议纪要已生成")
        try:
            # 必须同时 patch sub_model 和 thinking_summary_model:
            # thinking_summary_model 在 __init__ 时赋值为 sub_model 引用,
            # post_reasoning hook 会调 _summarize_thinking → thinking_summary_model
            with patch.object(hub, 'sub_model', new=mock_reply):
                with patch.object(hub, 'thinking_summary_model', new=mock_reply):
                    with patch.object(hub.post_reply_hook, 'execute', new=mock_execute):
                        result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
                        # 在 with 块内让后台任务执行,确保 mock_execute 仍生效
                        await _drain_background_tasks()
        finally:
            _route_context_var.reset(token)

        assert "会议纪要已生成" in result

        # 验证 post_reply_hook.execute 被调用
        mock_execute.assert_called()
        call_kwargs = mock_execute.call_args[0][0]
        assert call_kwargs["agent_name"] == MEETING_KEY
        assert "会议纪要已生成" == call_kwargs["response_content"]
        assert call_kwargs["bot_id_mapping"][MEETING_KEY] == "bot_meeting"

    @pytest.mark.asyncio
    async def test_call_sub_agent_post_reply_failure_non_fatal(self):
        """post_reply 发送失败不影响子 Agent 返回结果。"""
        hub = _make_test_hub()
        token = _route_context_var.set(dict(
            room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
            session_id="sess_test_003", call_count=0,
        ))
        hub.post_reply_hook.execute = AsyncMock(side_effect=Exception("IM down"))

        mock_reply = _make_mock_model_reply("会议纪要已生成")
        try:
            with patch.object(hub, 'sub_model', new=mock_reply):
                with patch.object(hub, 'thinking_summary_model', new=mock_reply):
                    result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
        finally:
            _route_context_var.reset(token)

        # 结果正常返回
        assert "会议纪要已生成" in result

    def test_main_agent_silent_when_call_count_is_1(self):
        """1 次 call_sub_agent 时,主 Agent 不发 post_reply。"""
        call_count = 1
        should_send = call_count != 1
        assert should_send is False

    def test_main_agent_sends_when_call_count_is_0(self):
        """0 次 call_sub_agent 时,主 Agent 正常发送。"""
        call_count = 0
        should_send = call_count == 0
        assert should_send is True

    def test_main_agent_sends_when_call_count_is_2(self):
        """2+ 次 call_sub_agent 时,主 Agent 正常发综合回复。"""
        call_count = 2
        assert call_count >= 1


import asyncio

# ── 自调用防护 & 子Agent 消息持久化测试 ──────────────────────────

class TestSelfCallGuard:
    """验证 _call_sub_agent 的自调用防护和子Agent消息落地。"""

    def test_rejects_steward_self_call(self):
        """主Agent 不允许调用自己的 code → 返回错误提示。"""
        hub = _make_test_hub()
        steward_key = hub._find_steward_key()
        result = asyncio.run(hub._call_sub_agent(steward_key, "测试指令"))
        assert "不允许主Agent自调用" in result
        assert "发言人Agent" in result

    def test_rejects_unknown_agent(self):
        """调用不存在的 agent code → 返回错误提示。"""
        hub = _make_test_hub()
        result = asyncio.run(hub._call_sub_agent("nonexistent_999", "测试指令"))
        assert "不存在" in result

    def test_save_tool_interactions_tool_use(self):
        """tool_use → role=assistant, name=assistant, 保留 Block 结构。"""
        from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
        clear_default_store_for_tests()
        store = SessionStore()
        sid = "test-default-agent-code"
        store.set(sid, {"conversation_history": []})
        mem = SessionMemory(sid, store)

        fake_msg = MagicMock()
        fake_msg.content = [
            {"type": "tool_use", "id": "toolu_001", "name": "read_file",
             "input": {"file_path": "test.txt"}},
        ]
        AgentHub._save_tool_interactions(mem, [fake_msg])

        history = store.get(sid).get("conversation_history", [])
        assert len(history) == 1
        assert history[0]["role"] == "assistant"
        assert history[0]["name"] == "assistant"
        assert history[0]["content"] == [{
            "type": "tool_use", "id": "toolu_001", "name": "read_file",
            "input": {"file_path": "test.txt"},
        }]

    def test_save_tool_interactions_tool_result(self):
        """tool_result → role=system, name=system, 保留 Block 结构。"""
        from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
        clear_default_store_for_tests()
        store = SessionStore()
        sid = "test-no-default-code"
        store.set(sid, {"conversation_history": []})
        mem = SessionMemory(sid, store)

        fake_msg = MagicMock()
        fake_msg.content = [
            {"type": "tool_result", "id": "toolu_001", "name": "read_file",
             "output": "文件内容..."},
        ]
        AgentHub._save_tool_interactions(mem, [fake_msg])

        history = store.get(sid).get("conversation_history", [])
        assert len(history) == 1
        assert history[0]["role"] == "system"
        assert history[0]["name"] == "system"
        assert history[0]["content"] == [{
            "type": "tool_result", "id": "toolu_001", "name": "read_file",
            "output": "文件内容...",
        }]


class TestMessageShielding:
    """验证主Agent 消息屏蔽逻辑。"""

    def test_call_count_zero_sends_reply(self):
        """call_count == 0 → 需正常发送和存 DB。"""
        ctx = {"call_count": 0}
        assert ctx["call_count"] == 0

    def test_call_count_one_shields_reply(self):
        """call_count >= 1 → 不发送、不存 DB。"""
        ctx = {"call_count": 1}
        assert ctx["call_count"] >= 1

    def test_call_count_multi_shields_reply(self):
        """call_count >= 2 → 同样不发送、不存 DB。"""
        ctx = {"call_count": 3}
        assert ctx["call_count"] >= 1


# ── 并发会话隔离测试 ──

class TestConcurrentSessions:
    """并发会话隔离:验证子Agent room_id 不串群(回归验证 race condition)。"""

    @pytest.mark.asyncio
    async def test_concurrent_sessions_no_room_contamination(self):
        """并发会话:两个会话都触发 call_sub_Agent,回复应发到各自房间。"""
        hub = test_hub
        post_replies = []
        model_call_count = [0]
        mock_sub = _make_mock_model_reply("子Agent处理结果")

        async def track(data):
            post_replies.append((data["room_id"], data["agent_name"]))

        async def model_side_effect(*args, **kwargs):
            """Both sessions return tool_use (idx<2), then text (idx>=2).
            First call yields to let the other session overwrite _current_route_ctx."""
            idx = model_call_count[0]
            model_call_count[0] += 1
            r = MagicMock()
            if idx < 2:  # First model call for BOTH sessions: both trigger call_sub_agent
                r.content = [{"type": "tool_use", "id": "call_1", "name": "call_sub_agent",
                              "input": {"agent_code": MEETING_KEY, "instruction": "处理"}}]
                if idx == 0:
                    await asyncio.sleep(0.1)  # Yield: let other session overwrite ctx
            else:  # Second model call for BOTH sessions: text reply
                r.content = [{"type": "text", "text": "完成"}]
            return r

        model_mock = AsyncMock(side_effect=model_side_effect)
        model_mock.stream = False

        with patch.object(hub, 'model', new=model_mock):
            with patch.object(hub, 'sub_model', new=mock_sub):
                with patch.object(hub, 'thinking_summary_model', new=mock_sub):
                    with patch.object(hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
                        with patch.object(hub.post_reply_hook, 'execute', new=AsyncMock(side_effect=track)):
                            await asyncio.gather(
                                hub.process_message(
                                    session_id="sess_A", room_id="room_A",
                                    user_id="u1", user_query="Q1",
                                ),
                                hub.process_message(
                                    session_id="sess_B", room_id="room_B",
                                    user_id="u2", user_query="Q2",
                                ),
                            )

        # 验证子Agent回复的房间隔离
        # Without isolation: 两个子Agent 回复都去同一个房间(最后一个设置 ctx 的房间)
        # With isolation: 各去各的房间
        sub_agent_rooms = {room for room, name in post_replies if name == MEETING_KEY}
        assert len(sub_agent_rooms) >= 2, (
            f"两个子Agent 回复发到同一房间!存在串群 Bug: {sub_agent_rooms}\n"
            f"全部 post_replies: {post_replies}"
        )


class TestReadPendingMessagesTool:
    """read_pending_messages 工具行为测试"""

    @pytest.mark.asyncio
    async def test_read_returns_messages(self):
        """工具能读取 intent_session 中的消息"""
        hub = _make_test_hub()
        session_id = "sess_read_test"
        hub.session_service.get_or_create_session(
            session_id=session_id, room_id="r1"
        )

        data = hub.session_service.store.get(session_id)
        data["intent_session"] = [
            {"role": "user", "content": "消息1"},
            {"role": "user", "content": "消息2"},
        ]
        hub.session_service.store.set(session_id, data)

        token = _route_context_var.set({"session_id": session_id, "call_count": 0})
        try:
            tool_fn = hub._make_read_pending_messages_tool()
            result = await tool_fn()
            assert result is not None
            text = _extract_text(result)
            assert "2 条新消息" in text
            assert "消息1" in text
            assert "消息2" in text
        finally:
            _route_context_var.reset(token)

    @pytest.mark.asyncio
    async def test_read_clears_intent_session(self):
        """工具读取后清空 intent_session"""
        hub = _make_test_hub()
        session_id = "sess_read_clear"
        hub.session_service.get_or_create_session(
            session_id=session_id, room_id="r1"
        )

        data = hub.session_service.store.get(session_id)
        data["intent_session"] = [
            {"role": "user", "content": "消息"},
        ]
        hub.session_service.store.set(session_id, data)

        token = _route_context_var.set({"session_id": session_id, "call_count": 0})
        try:
            tool_fn = hub._make_read_pending_messages_tool()
            await tool_fn()

            after = hub.session_service.store.get(session_id)
            assert after["intent_session"] == []
        finally:
            _route_context_var.reset(token)

    @pytest.mark.asyncio
    async def test_read_when_empty_returns_no_new_messages(self):
        """intent_session 为空时返回'无新消息'"""
        hub = _make_test_hub()
        session_id = "sess_read_empty"
        hub.session_service.get_or_create_session(
            session_id=session_id, room_id="r1"
        )

        token = _route_context_var.set({"session_id": session_id, "call_count": 0})
        try:
            tool_fn = hub._make_read_pending_messages_tool()
            result = await tool_fn()
            text = _extract_text(result)
            assert "无新消息" in text
        finally:
            _route_context_var.reset(token)

    @pytest.mark.asyncio
    async def test_read_when_no_context_returns_no_new_messages(self):
        """无路由上下文时返回'无新消息'"""
        hub = _make_test_hub()
        tool_fn = hub._make_read_pending_messages_tool()
        result = await tool_fn()
        text = _extract_text(result)
        assert "无新消息" in text


# ═══════════════════════════════════════════════════════════════════
# post_observe intent_session 注入测试
# ═══════════════════════════════════════════════════════════════════


class TestPostObserveIntentHook:
    """post_observe intent_session 注入测试"""

    @pytest.mark.asyncio
    async def test_hook_injects_when_intent_nonempty(self):
        """intent_session 非空时 hook 注入到 memory"""
        hub = _make_test_hub()
        session_id = "sess_hook_inject"
        hub.session_service.get_or_create_session(
            session_id=session_id, room_id="r1"
        )

        # 预置 intent_session
        data = hub.session_service.store.get(session_id)
        data["intent_session"] = [
            {"role": "user", "content": "hook测试消息"},
        ]
        hub.session_service.store.set(session_id, data)

        from agentscope.agent import ReActAgent
        from agentscope.memory import InMemoryMemory
        from agentscope.message import Msg
        from functools import partial

        from app.agent_core.agent_hub import _post_observe_intent_hook
        from app.agent_core.memory import SessionMemory

        memory = InMemoryMemory()
        agent = ReActAgent(
            name="test_agent",
            sys_prompt="test",
            model=hub.model,
            formatter=hub.formatter,
            toolkit=hub.toolkit,
            memory=memory,
            max_iters=1,
        )

        session_memory = SessionMemory(
            session_id=session_id,
            store=hub.session_service.store,
        )
        agent.register_instance_hook(
            "post_observe", "intent_check",
            partial(
                _post_observe_intent_hook,
                store=hub.session_service.store,
                session_id=session_id,
                session_memory=session_memory,
            ),
        )

        await agent.observe(Msg("user", "dummy", "user"))

        # Verify injected into InMemoryMemory
        mem_msgs = await agent.memory.get_memory()
        assert any("hook测试消息" in str(m.content) for m in mem_msgs)

        # Verify intent_session cleared
        after = hub.session_service.store.get(session_id)
        assert after["intent_session"] == []

        # Verify injected into conversation_history
        history = after.get("conversation_history", [])
        assert any("hook测试消息" in str(h) for h in history)

    @pytest.mark.asyncio
    async def test_hook_skips_when_intent_empty(self):
        """intent_session 为空时 hook 跳过"""
        hub = _make_test_hub()
        session_id = "sess_hook_skip"
        hub.session_service.get_or_create_session(
            session_id=session_id, room_id="r1"
        )

        from agentscope.agent import ReActAgent
        from agentscope.memory import InMemoryMemory
        from agentscope.message import Msg
        from functools import partial

        from app.agent_core.agent_hub import _post_observe_intent_hook
        from app.agent_core.memory import SessionMemory

        memory = InMemoryMemory()
        agent = ReActAgent(
            name="test_agent",
            sys_prompt="test",
            model=hub.model,
            formatter=hub.formatter,
            toolkit=hub.toolkit,
            memory=memory,
            max_iters=1,
        )

        session_memory = SessionMemory(
            session_id=session_id,
            store=hub.session_service.store,
        )
        agent.register_instance_hook(
            "post_observe", "intent_check",
            partial(
                _post_observe_intent_hook,
                store=hub.session_service.store,
                session_id=session_id,
                session_memory=session_memory,
            ),
        )

        await agent.observe(Msg("user", "dummy", "user"))

        mem_msgs = await agent.memory.get_memory()
        assert all("系统检测到" not in str(m.content) for m in mem_msgs)

    @pytest.mark.asyncio
    async def test_tool_read_then_hook_skips(self):
        """read_pending_messages 工具执行后 intent_session 已空,hook 跳过"""
        hub = _make_test_hub()
        session_id = "sess_hook_read_chain"
        hub.session_service.get_or_create_session(
            session_id=session_id, room_id="r1"
        )

        data = hub.session_service.store.get(session_id)
        data["intent_session"] = [
            {"role": "user", "content": "工具已消费"},
        ]
        hub.session_service.store.set(session_id, data)

        # 模拟工具调用(读取并清空)
        d = hub.session_service.store.get(session_id)
        d["intent_session"] = []
        hub.session_service.store.set(session_id, d)

        from agentscope.agent import ReActAgent
        from agentscope.memory import InMemoryMemory
        from agentscope.message import Msg
        from functools import partial

        from app.agent_core.agent_hub import _post_observe_intent_hook
        from app.agent_core.memory import SessionMemory

        session_memory = SessionMemory(
            session_id=session_id,
            store=hub.session_service.store,
        )

        agent = ReActAgent(
            name="test_agent",
            sys_prompt="test",
            model=hub.model,
            formatter=hub.formatter,
            toolkit=hub.toolkit,
            memory=InMemoryMemory(),
            max_iters=1,
        )
        agent.register_instance_hook(
            "post_observe", "intent_check",
            partial(
                _post_observe_intent_hook,
                store=hub.session_service.store,
                session_id=session_id,
                session_memory=session_memory,
            ),
        )

        await agent.observe(Msg("user", "dummy", "user"))

        after = hub.session_service.store.get(session_id)
        assert after["intent_session"] == []
        history = after.get("conversation_history", [])
        assert all("系统检测到" not in str(h) for h in history)