Commit 583a1897 by sunqi02 Committed by 胡悦

feat(message-gate): scaffold MessageGate service class

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent bb53542a
"""MessageGate 服务 - API 层和 AgentHub 之间的意图门控层。
详见设计文档: docs/superpowers/specs/2026-06-01-message-gate-design.md
"""
from __future__ import annotations
import asyncio
import logging
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from app.config.loader import ConfigLoader
from app.hooks.post_reply import PostReplyHook
from app.service.active_session_service import ActiveSessionService
logger = logging.getLogger(__name__)
@dataclass
class GateDecision:
"""MessageGate 评估后输出的决策结果。"""
intent: str # actionable | casual | incomplete | ignore
rewritten_query: Optional[str] = None
reply: Optional[str] = None
cancel: bool = False # 暂未使用,Phase 2 启用
class MessageGate:
"""消息门控层 - 等待/分类/重写/调度。"""
def __init__(
self,
config_loader: ConfigLoader,
session_service: ActiveSessionService,
post_reply_hook: PostReplyHook,
agent_hub: Any, # AgentHub 实例,避免循环 import
main_agent_key: str,
) -> None:
self.config_loader = config_loader
self.session_service = session_service
self.post_reply_hook = post_reply_hook
self.agent_hub = agent_hub
self.main_agent_key = main_agent_key
# 运行时状态
self._session_locks: Dict[str, asyncio.Lock] = {}
self._running_tasks: Dict[str, asyncio.Task] = {}
# 每次 evaluate 调用时由 endpoint 注入的 bot_id_mapping
self._current_bot_id_mapping: Dict[str, str] = {}
def _get_lock(self, session_id: str) -> asyncio.Lock:
if session_id not in self._session_locks:
self._session_locks[session_id] = asyncio.Lock()
return self._session_locks[session_id]
async def evaluate(
self,
session_id: str,
room_id: str,
user_id: str,
bot_id_mapping: Dict[str, str],
messages: List[Dict[str, Any]] = None,
wait_seconds: float = 6.0,
) -> None:
"""评估入口:等待、分类、重写、分发。"""
raise NotImplementedError
\ No newline at end of file \ No newline at end of file
"""MessageGate 激活识别测试。""" """MessageGate 服务的单元测试。"""
import pytest import pytest
from unittest.mock import MagicMock, AsyncMock from unittest.mock import MagicMock, AsyncMock
from app.agent_core.message_gate import MessageGate, GateDecision from app.service.message_gate import MessageGate, GateDecision
def test_message_gate_can_be_constructed(): def test_message_gate_can_be_constructed():
"""MessageGate 应能通过依赖注入的方式构造。""" """MessageGate 应能通过依赖注入的方式构造。"""
gate = MessageGate( config_loader = MagicMock()
config_loader=MagicMock(), session_service = MagicMock()
session_service=MagicMock(), post_reply_hook = MagicMock()
post_reply_hook=MagicMock(), agent_hub = MagicMock()
agent_hub=MagicMock(), main_agent_key = "main"
main_agent_key="11",
model=MagicMock(),
)
assert gate is not None
def test_gate_decision_only_intent():
"""GateDecision 只有 intent 字段。"""
d = GateDecision(intent="chat")
assert d.intent == "chat"
assert not hasattr(d, "rewritten_query")
assert not hasattr(d, "reply")
@pytest.mark.asyncio
async def test_classify_returns_chat_for_empty_pending():
"""空 pending → 当前临时直接放行,返回 pass。"""
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
decision = await gate._classify_and_rewrite(pending=[])
assert decision.intent == "pass"
@pytest.mark.asyncio
async def test_classify_activation_returns_chat_by_default():
"""直接放行模式:返回 pass(临时跳过 LLM 分类)。"""
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
pending = [{"msg_type": "text", "msg_content": "谢谢大家"}]
decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "pass"
@pytest.mark.asyncio
async def test_handle_chat_adds_user_message_to_history():
"""_handle_chat 追加用户消息到 conversation_history。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
sid = "test-chat-session"
# SessionMemory.add() 要求 session 已存在
store.set(sid, {"conversation_history": [], "intent_session": ""})
mock_session_service = MagicMock()
mock_session_service.save_to_db = MagicMock()
gate = MessageGate( gate = MessageGate(
config_loader=MagicMock(), config_loader=config_loader,
session_service=mock_session_service, session_service=session_service,
post_reply_hook=MagicMock(), post_reply_hook=post_reply_hook,
agent_hub=MagicMock(), agent_hub=agent_hub,
main_agent_key="11", main_agent_key=main_agent_key,
model=MagicMock(),
)
pending = [{"msg_type": "text", "msg_content": "好的"}]
await gate._handle_chat(session_id=sid, pending=pending)
data = store.get(sid)
history = data.get("conversation_history", [])
assert len(history) == 1
assert history[0]["role"] == "user"
assert history[0]["content"] == "好的"
mock_session_service.save_to_db.assert_called_once_with(sid)
@pytest.mark.asyncio
async def test_handle_actionable_calls_agent_hub():
"""_handle_actionable 用预提取的 query/file_url 调用 agent_hub.process_message。"""
mock_agent_hub = MagicMock()
mock_agent_hub.process_message = AsyncMock()
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=mock_agent_hub,
main_agent_key="11",
model=MagicMock(),
)
await gate._handle_actionable(
session_id="test-session",
room_id="room-1",
user_id="user-1",
query="创建任务",
file_url=None,
bot_id_mapping={"11": "bot_main"},
) )
mock_agent_hub.process_message.assert_called_once() assert gate is not None
call_kwargs = mock_agent_hub.process_message.call_args.kwargs assert gate.config_loader is config_loader
assert call_kwargs["user_query"] == "创建任务" assert gate.session_service is session_service
assert call_kwargs["file_url"] is None assert gate.agent_hub is agent_hub
# ── _extract_query_and_file_url 单元测试 ──
def test_extract_query_and_file_url_text_only():
"""仅包含文本消息时,提取 query 且 file_url 为 None。"""
from app.agent_core.message_gate import MessageGate
pending = [{"msg_type": "text", "msg_content": "帮我整理纪要"}]
query, file_url = MessageGate._extract_query_and_file_url(pending)
assert query == "帮我整理纪要"
assert file_url is None
def test_extract_query_and_file_url_with_file():
"""混合文本+文件消息时,提取 query 和 file_url。"""
from app.agent_core.message_gate import MessageGate
pending = [
{"msg_type": "text", "msg_content": "分析这份报表"},
{"msg_type": "file", "msg_content": "https://oss.example.com/report.xlsx"},
]
query, file_url = MessageGate._extract_query_and_file_url(pending)
assert "分析这份报表" in query
assert file_url == "https://oss.example.com/report.xlsx"
def test_extract_query_and_file_url_append_url():
"""文本中已含 URL 时,不重复追加。"""
from app.agent_core.message_gate import MessageGate
pending = [
{"msg_type": "text", "msg_content": "看下这个 https://example.com/doc"},
]
query, file_url = MessageGate._extract_query_and_file_url(pending)
assert "https://example.com/doc" in query
assert query.count("https://example.com/doc") == 1
assert file_url is None
def test_extract_query_and_file_url_empty():
"""空 pending 返回空 query。"""
from app.agent_core.message_gate import MessageGate
query, file_url = MessageGate._extract_query_and_file_url([])
assert query == ""
assert file_url is None
@pytest.mark.asyncio
async def test_handle_busy_writes_to_intent_session():
"""_handle_busy 写入 intent_session 且不污染 conversation_history。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
sid = "test-busy-session"
store.set(sid, {"conversation_history": [], "intent_session": []})
mock_post_reply = MagicMock()
mock_post_reply.execute = AsyncMock()
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=mock_post_reply,
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
pending = [{"msg_type": "text", "msg_content": "帮我查一下"}]
await gate._handle_busy(
session_id=sid,
room_id="room-1",
user_id="user-1",
pending=pending,
bot_id_mapping={"11": "bot_main"},
)
data = store.get(sid)
# 不污染 conversation_history
assert data["conversation_history"] == []
# 写入 intent_session
assert len(data["intent_session"]) == 1
assert data["intent_session"][0]["role"] == "user"
assert data["intent_session"][0]["content"] == "帮我查一下"
# 发送了 BUSY_REPLY
mock_post_reply.execute.assert_called_once()
call_context = mock_post_reply.execute.call_args[0][0]
assert "正在执行任务中" in call_context["response_content"]
@pytest.mark.asyncio
async def test_handle_busy_accumulates_in_intent_session():
"""多次 busy 调用应累积消息到 intent_session。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
sid = "test-busy-accum"
store.set(sid, {"conversation_history": [], "intent_session": []})
mock_post_reply = MagicMock()
mock_post_reply.execute = AsyncMock()
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=mock_post_reply,
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
await gate._handle_busy(sid, "room", "u1",
[{"msg_type": "text", "msg_content": "第一条"}],
{"11": "bot"})
await gate._handle_busy(sid, "room", "u1",
[{"msg_type": "text", "msg_content": "第二条"}],
{"11": "bot"})
data = store.get(sid) def test_gate_decision_dataclass_defaults():
assert len(data["intent_session"]) == 2 """GateDecision 默认字段正确。"""
assert data["intent_session"][0]["content"] == "第一条" d = GateDecision(intent="ignore")
assert data["intent_session"][1]["content"] == "第二条" assert d.intent == "ignore"
assert data["conversation_history"] == [] assert d.rewritten_query is None
assert d.reply is None
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!