Commit dff977c5 by sunqi02 Committed by 胡悦

refactor(message-gate): fix review issues - remove race condition, dead code, unused imports

- Remove _current_bot_id_mapping instance variable, pass bot_id_mapping as parameter instead (race condition fix)
- Remove dead _process_message_async function from agent_hub.py
- Remove unused SessionMemory import in _classify_and_rewrite
- Update close() to cancel running tasks before clearing
- Remove unused messages parameter from evaluate()
- Remove dead _dispatch_to_agent_hub mock in test

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 05e86c4f
......@@ -137,34 +137,6 @@ async def chat(
return {"status": "ok", "session_id": session_id}
async def _process_message_async(
agent_hub: AgentHub,
session_id: str,
room_id: str,
user_id: str,
user_query: str,
file_url: Optional[str],
allowed_agent_codes: Optional[list],
bot_id_mapping: Optional[dict] = None,
):
"""后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try:
await agent_hub.process_message(
session_id=session_id,
room_id=room_id,
user_id=user_id,
user_query=user_query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
bot_id_mapping=bot_id_mapping,
)
except Exception:
logger.exception(
"Agent 后台处理失败: session=%s user=%s query=%s",
session_id, user_id, user_query[:50],
)
async def _process_message_async_via_gate(
agent_hub: AgentHub,
message_gate: MessageGate,
......@@ -181,7 +153,6 @@ async def _process_message_async_via_gate(
room_id=room_id,
user_id=user_id,
bot_id_mapping=bot_id_mapping or {},
messages=messages,
)
except Exception:
logger.exception("MessageGate 评估失败,尝试兜底")
......
......@@ -46,8 +46,6 @@ class MessageGate:
# 运行时状态
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] = {}
# 模型:优先使用注入的(测试场景),否则从配置加载
if model is not None:
......@@ -76,7 +74,6 @@ class MessageGate:
room_id: str,
user_id: str,
bot_id_mapping: Dict[str, str],
messages: List[Dict[str, Any]] = None,
wait_seconds: float = 6.0,
) -> None:
"""评估入口:等待、分类、重写、分发。
......@@ -86,12 +83,8 @@ class MessageGate:
room_id: 房间 ID
user_id: 用户 ID
bot_id_mapping: 由 endpoint 注入的 agent_key → bot_id 映射
messages: 原始消息列表(已由 endpoint 追加到 buffer,留空)
wait_seconds: 等待窗口(默认 6 秒,测试时可缩短)
"""
# 注入当前调用上下文
self._current_bot_id_mapping = bot_id_mapping
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore
......@@ -129,7 +122,7 @@ class MessageGate:
decision = await self._classify_and_rewrite(
session_id=session_id,
pending=pending,
agent_codes=list(self._current_bot_id_mapping.keys()),
agent_codes=list(bot_id_mapping.keys()),
)
# 步骤 8:根据 intent 分支
......@@ -146,6 +139,7 @@ class MessageGate:
user_id=user_id,
decision=decision,
pending=pending,
bot_id_mapping=bot_id_mapping,
)
buffer.clear_pending()
return
......@@ -157,7 +151,7 @@ class MessageGate:
user_id=user_id,
decision=decision,
pending=pending,
bot_id_mapping=self._current_bot_id_mapping,
bot_id_mapping=bot_id_mapping,
)
buffer.clear_pending()
......@@ -168,8 +162,6 @@ class MessageGate:
agent_codes: Optional[List[str]] = None,
) -> "GateDecision":
"""调 LLM 进行意图分类 + query 重写。"""
from app.service.memory import SessionMemory
# 合并文本
merged_text = "\n".join(
m.get("msg_content", "")
......@@ -287,6 +279,7 @@ class MessageGate:
user_id: str,
decision: "GateDecision",
pending: List[Dict[str, Any]],
bot_id_mapping: Dict[str, str],
) -> None:
"""casual 分支:直接发 IM 回复,并记录 user + assistant 到 history。"""
if not decision.reply:
......@@ -306,7 +299,7 @@ class MessageGate:
"response_content": decision.reply,
"room_id": room_id,
"mentioned_list": [user_id],
"bot_id_mapping": self._current_bot_id_mapping,
"bot_id_mapping": bot_id_mapping,
})
async def _handle_actionable(
......@@ -359,6 +352,8 @@ class MessageGate:
task.add_done_callback(lambda t: self._running_tasks.pop(session_id, None))
async def close(self) -> None:
"""清理资源(Phase 1 简化版)。"""
"""清理资源:取消运行中的任务并清空状态。"""
for task in list(self._running_tasks.values()):
task.cancel()
self._running_tasks.clear()
self._session_locks.clear()
\ No newline at end of file
......@@ -60,7 +60,6 @@ def message_gate_with_deps():
main_agent_key="main",
model=mock_model,
)
gate._current_bot_id_mapping = {"main": "bot-001"}
return gate
......@@ -82,7 +81,6 @@ async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps):
intent="actionable",
rewritten_query="请分析文件 [url]",
))
gate._dispatch_to_agent_hub = AsyncMock()
# 追加 file 消息到 buffer
from app.infrastructure.session_store import SessionStore
......@@ -100,7 +98,6 @@ async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps):
room_id="r1",
user_id="u1",
bot_id_mapping={"main": "bot-001"},
messages=[],
)
# 等待 0.01s 后分类被调用
assert gate._classify_and_rewrite.await_count == 1
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!