Commit fee500a3 by sunqi02

传入更改

1 parent db5a2ce4
# 消息发送重构 & 内容保留 实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 修复 rewritten_query 丢失原文 + 子 Agent 用自己的 bot 发 post_reply + 主 Agent 条件静默
**Architecture:** 3 处修改,2 个文件。message_gate.py 的 `_handle_actionable` 合并原文和重写指令。agent_hub.py 的 `_call_sub_agent` 增加 post_reply 发送;`process_message` 用 ctx 计数器控制主 Agent 静默。
**Tech Stack:** Python 3.12+ / AgentScope / pytest + pytest-asyncio + unittest.mock
---
## File Map
| 文件 | 修改内容 | 职责 |
|------|---------|------|
| `app/service/message_gate.py` | 新增 `_merge_text_from_pending`,修改 `_handle_actionable` | 保留原文 |
| `app/service/agent_hub.py` | 修改 `process_message`、`_call_sub_agent`、`_make_call_sub_agent_tool` | 子 Agent 发 post_reply + 主 Agent 静默 |
| `tests/test_message_gate.py` | 新增测试方法 | 验证原文合并逻辑 |
| `tests/test_agent_hub.py` | 新增测试方法 | 验证 post_reply 发送 + 静默逻辑 |
---
### Task 1: MessageGate — 提取文本辅助方法
**文件:**
- Modify: `app/service/message_gate.py`(新增静态方法)
- Test: `tests/test_message_gate.py`
- [ ] **Step 1: 新增 `_merge_text_from_pending` 静态方法**
在 `MessageGate` 类中添加(放在 `_extract_text` 静态方法附近):
```python
@staticmethod
def _merge_text_from_pending(pending: List[Dict[str, Any]]) -> str:
"""从 pending 列表中提取文本,与 _classify_and_rewrite 拼 merged_text 逻辑一致。"""
parts = []
for m in pending:
mt = m.get("msg_type", "")
mc = m.get("msg_content", "")
if mt == "text" and mc:
parts.append(mc)
elif mc:
parts.append(f"[文件: {mc}]")
return "\n".join(parts) if parts else ""
```
- [ ] **Step 2: 写测试 — `_merge_text_from_pending`**
在 `tests/test_message_gate.py` 中添加:
```python
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 == "有效内容"
```
- [ ] **Step 3: 运行测试验证通过**
```bash
cd ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py::TestMergeTextFromPending -v
```
- [ ] **Step 4: Commit**
```bash
git add app/service/message_gate.py tests/test_message_gate.py
git commit -m "feat: add _merge_text_from_pending helper for extracting text from pending messages"
```
---
### Task 2: MessageGate — `_handle_actionable` 合并原文
**文件:**
- Modify: `app/service/message_gate.py` — `_handle_actionable()`(line 471-485)
- Test: `tests/test_message_gate.py`
- [ ] **Step 1: 修改 `_handle_actionable` 的 query 构造逻辑**
将现有代码(line 471-485):
```python
query = decision.rewritten_query or ""
if not query:
logger.warning(...)
return
# 安全网:从 text 消息中提取 URL...
URL_RE = re.compile(...)
for m in pending:
...
```
替换为:
```python
rewritten = decision.rewritten_query or ""
original = self._merge_text_from_pending(pending)
if original and original not in rewritten:
query = f"{rewritten}\n\n---\n{original}"
elif rewritten:
query = rewritten
else:
query = original
if not query:
logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id)
return
# 安全网:从 text 消息中提取 URL,补齐 rewritten_query 可能丢弃的链接
# 只补 text 类型(用户主动写的 URL),不补 file/image 类型的历史残留链接
URL_RE = re.compile(r'https?://[^\s<>"{}|\\^`\[\]]+')
for m in pending:
if m.get("msg_type") != "text":
continue
mc = m.get("msg_content", "")
for url in URL_RE.findall(mc):
if url not in query:
query = f"{query}\n{url}"
```
- [ ] **Step 2: 写测试 — rewritten_query 与原文合并**
在 `tests/test_message_gate.py` 中 `TestMessageGateClassification` 类(或新建 `TestHandleActionable`)添加:
```python
@pytest.mark.asyncio
async def test_handle_actionable_preserves_original_text(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="请将上面提供的对话记录整理成会议纪要",
)
# 直接测试 _handle_actionable 调用了 agent_hub.process_message 并传了合并后的 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(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(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 == "请总结这个录音"
```
- [ ] **Step 3: 运行测试验证通过**
```bash
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v -k "handle_actionable"
```
- [ ] **Step 4: Commit**
```bash
git add app/service/message_gate.py tests/test_message_gate.py
git commit -m "fix: preserve original text content in _handle_actionable when rewritten_query loses it"
```
---
### Task 3: AgentHub — call_count 计数器
**文件:**
- Modify: `app/service/agent_hub.py` — `process_message()` + `_make_call_sub_agent_tool()`
- Test: `tests/test_agent_hub.py`
- [ ] **Step 1: `process_message` 初始化 call_count**
在 `process_message()` 中,修改 `_current_route_ctx` 初始化(当前 line 376-378):
```python
# 当前
self._current_route_ctx = dict(
room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {},
)
# 改为
self._current_route_ctx = dict(
room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {},
call_count=0,
)
```
- [ ] **Step 2: `_make_call_sub_agent_tool` 闭包内递增计数器**
在 `call_sub_agent` 函数体内,调用 `_call_sub_agent` 之前添加(当前 `_make_call_sub_agent_tool` line 623-653):
```python
async def call_sub_agent(agent_code: str = "", instruction: str = "") -> ToolResponse:
# ...现有参数校验逻辑不变...
# 新增:递增调用计数
ctx = getattr(self, "_current_route_ctx", None)
if ctx:
ctx["call_count"] = ctx.get("call_count", 0) + 1
result = await self._call_sub_agent(agent_code, instruction)
return ToolResponse(
content=[TextBlock(type="text", text=result)]
)
```
- [ ] **Step 3: 写测试 — call_count 递增**
在 `tests/test_agent_hub.py` 中添加:
```python
class TestCallSubAgentCounter:
"""测试 call_sub_agent 调用计数。"""
def test_call_count_initialized_in_route_ctx(self):
"""_current_route_ctx 初始化后 call_count 为 0。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=0,
)
assert hub._current_route_ctx["call_count"] == 0
@pytest.mark.asyncio
async def test_call_count_increments_in_tool(self):
"""call_sub_agent 工具调用后计数器 +1。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=0,
)
# patch _call_sub_agent 避免真实创建 ReActAgent
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="测试指令")
assert hub._current_route_ctx["call_count"] == 1
```
- [ ] **Step 4: 运行测试验证通过**
```bash
PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestCallSubAgentCounter -v
```
- [ ] **Step 5: Commit**
```bash
git add app/service/agent_hub.py tests/test_agent_hub.py
git commit -m "feat: add call_count counter to track sub_agent invocations per request"
```
---
### Task 4: AgentHub — `_call_sub_agent` 增加 post_reply
**文件:**
- Modify: `app/service/agent_hub.py` — `_call_sub_agent()`(line 524-551)
- Test: `tests/test_agent_hub.py`
- [ ] **Step 1: 在 `_call_sub_agent` 返回前发送 post_reply**
```python
async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
"""通过 ReActAgent 调用子 Agent。"""
if agent_code not in self.agents:
valid = [c for c, a in self.agents.items() if not a.is_steward]
return (
f"错误:子 Agent '{agent_code}' 不存在。"
f"可用调用码: {valid}"
)
sub_prompt = self._build_sub_agent_prompt(agent_code)
sub_memory = InMemoryMemory()
sub_agent = ReActAgent(
name=agent_code,
sys_prompt=sub_prompt,
model=self.sub_model,
formatter=self.formatter,
toolkit=self.agent_toolkits.get(agent_code, self.toolkit),
memory=sub_memory,
max_iters=10,
)
# 为子 Agent 注册 IM hook(post_reasoning → thinking 摘要)
ctx = self._current_route_ctx
self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])
response = await sub_agent.reply(Msg("user", instruction, "user"))
response_text = response.get_text_content()
# 新增:子 Agent 用自己的 bot 账号发送最终回复
try:
await self.post_reply_hook.execute({
"agent_name": agent_code,
"response_content": response_text,
"room_id": ctx["room_id"],
"mentioned_list": [ctx["user_id"]],
"bot_id_mapping": ctx["bot_id_mapping"],
})
except Exception:
logger.warning(
"[子Agent IM 发送失败] agent=%s room=%s(不影响推理流程)",
agent_code, ctx.get("room_id"), exc_info=True,
)
return response_text
```
- [ ] **Step 2: 写测试 — 子 Agent post_reply 发送**
在 `tests/test_agent_hub.py` 中添加:
```python
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()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
call_count=0,
)
mock_reply = _make_mock_model_reply("会议纪要已生成")
# 必须同时 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):
result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
assert "会议纪要已生成" in result
# 验证 post_reply_hook.execute 被调用
hub.post_reply_hook.execute.assert_called()
call_kwargs = hub.post_reply_hook.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()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
call_count=0,
)
hub.post_reply_hook.execute = AsyncMock(side_effect=Exception("IM down"))
mock_reply = _make_mock_model_reply("会议纪要已生成")
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, "处理会议录音")
# 结果正常返回
assert "会议纪要已生成" in result
```
- [ ] **Step 3: 运行测试验证通过**
```bash
PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestSubAgentPostReply -v
```
- [ ] **Step 4: Commit**
```bash
git add app/service/agent_hub.py tests/test_agent_hub.py
git commit -m "feat: sub-agent sends post_reply through its own bot account"
```
---
### Task 5: AgentHub — 主 Agent 条件静默
**文件:**
- Modify: `app/service/agent_hub.py` — `process_message()`结尾 line 466-479
- Test: `tests/test_agent_hub.py`
- [ ] **Step 1: 修改 `process_message` 的 post_reply 发送条件**
将现有的 post_reply 发送(line 466-479):
```python
# Send via hook — failure non-fatal, only log
try:
await self.post_reply_hook.execute({
"agent_name": target_agent,
"response_content": response_content,
"room_id": room_id,
"mentioned_list": [user_id],
"bot_id_mapping": bot_id_mapping or {},
})
except Exception:
logger.warning(...)
```
替换为:
```python
# Send via hook — failure non-fatal, only log
# 1 次 call_sub_agent 时跳过:子 Agent 已用自己的 bot 发送回复
if self._current_route_ctx.get("call_count", 0) != 1:
try:
await self.post_reply_hook.execute({
"agent_name": target_agent,
"response_content": response_content,
"room_id": room_id,
"mentioned_list": [user_id],
"bot_id_mapping": bot_id_mapping or {},
})
except Exception:
logger.warning(
"[最终回复 IM 发送失败] agent=%s session=%s room=%s",
target_agent, session_id, room_id, exc_info=True,
)
else:
logger.info(
"[主Agent 静默] call_count=1,子 Agent 已发送回复,跳过主 Agent post_reply"
)
```
- [ ] **Step 2: 写测试 — 条件静默**
在 `tests/test_agent_hub.py` 中 `TestSubAgentPostReply` 类添加:
```python
def test_main_agent_silent_when_call_count_is_1(self):
"""1 次 call_sub_agent 时,主 Agent 不发 post_reply。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=1,
)
# 模拟 process_message 结尾的判断逻辑
call_count = hub._current_route_ctx.get("call_count", 0)
assert call_count == 1
# 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 正常发送。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=0,
)
call_count = hub._current_route_ctx.get("call_count", 0)
assert call_count == 0
should_send = call_count != 1
assert should_send is True
def test_main_agent_sends_when_call_count_is_2(self):
"""2+ 次 call_sub_agent 时,主 Agent 正常发综合回复。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=2,
)
call_count = hub._current_route_ctx.get("call_count", 0)
assert call_count == 2
should_send = call_count != 1
assert should_send is True
```
- [ ] **Step 3: 运行测试验证通过**
```bash
PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestSubAgentPostReply -v
```
- [ ] **Step 4: Commit**
```bash
git add app/service/agent_hub.py tests/test_agent_hub.py
git commit -m "feat: main agent stays silent when exactly one sub_agent was called"
```
---
### Task 6: 全量回归测试
- [ ] **Step 1: 跑全部测试确认无回归**
```bash
cd ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/ -v --tb=short
```
- [ ] **Step 2: 确认所有测试通过后,检查测试覆盖**
```bash
PYTHONPATH=. python -m pytest tests/ -v --tb=short 2>&1 | tail -5
```
预期:全部 pass,无 FAIL。
---
### Task 7: 手动验证清单
以下通过实际发送请求验证(需要启动服务):
- [ ] **场景 1:大段文本 → 原文不丢失**
发送包含长文本的消息,确认 AgentHub 收到的 user_query 包含完整原文
- [ ] **场景 2:1 次 call_sub_agent → 子 Agent 用自己的 bot 发**
发送会议纪要请求,确认子 Agent 的 bot 发了 thinking 摘要 + 最终回复,主 Agent 未发最终回复
- [ ] **场景 3:0 次 call_sub_agent → 主 Agent 正常发**
发送简单问候,确认主 Agent 正常发送回复
- [ ] **场景 4:2 次 call_sub_agent → 主 Agent 发综合回复**
发送需要多个子 Agent 协作的请求,确认主 Agent 发综合回复
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!