Commit 439b92de by sunqi02 Committed by 胡悦

fix: SessionBuffer 入锁 + AgentHub 移出锁,消除并发覆盖风险

- MessageGate 新增 _extract_query_and_file_url() 静态方法
- _handle_actionable 签名改为接收预提取的 (query, file_url)
- evaluate() 锁内 clear_pending,锁外调 AgentHub
- MessageGate 新增 append_messages(),per-session 锁保护 buffer 追加
- endpoint 改用 append_messages() 替代裸 SessionBuffer.append()
- 更新 MessageGate 测试适配锁重构 + LLM 临时放行
- 新增 4 个 _extract_query_and_file_url 单元测试

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 2f397726
......@@ -127,13 +127,10 @@ async def chat(
if steward_bot_id:
bot_id_mapping[MOUTH_AGENT_CODE] = steward_bot_id
# 4. 追加消息到 buffer(在 BackgroundTask 之外,确保锁外追加)
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore
store = SessionStore()
buffer = SessionBuffer(store, session_id, session_service=agent_hub.session_service)
for msg in request.messages:
buffer.append(msg.model_dump())
# 4. 追加消息到 buffer(在 MessageGate per-session 锁内,确保并发安全)
await message_gate.append_messages(
session_id, [m.model_dump() for m in request.messages]
)
# 4.5 入口日志:记录本次请求的概要(不打印完整 payload,避免敏感信息泄露)
text_preview = (query[:80] + "…") if len(query) > 80 else query
......
......@@ -70,6 +70,17 @@ class MessageGate:
self._session_locks[session_id] = asyncio.Lock()
return self._session_locks[session_id]
async def append_messages(self, session_id: str, messages: List[Dict[str, Any]]) -> None:
"""追加消息到 session buffer,使用 per-session 锁保证并发安全。"""
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore
async with self._get_lock(session_id):
store = SessionStore()
buffer = SessionBuffer(store, session_id, session_service=self.session_service)
for msg in messages:
buffer.append(msg)
async def evaluate(
self,
session_id: str,
......@@ -119,6 +130,8 @@ class MessageGate:
self._running_tasks[session_id] = asyncio.current_task()
try:
actionable_args = None # (query, file_url) for lock-external AgentHub call
async with lock:
# 调试:记录锁获取时的 KV 状态
_kv_data = store.get(session_id) or {}
......@@ -156,16 +169,22 @@ class MessageGate:
buffer.clear_pending()
return
# pass
# pass: 锁内提取 query/file_url + clear_pending
query, file_url = self._extract_query_and_file_url(pending)
buffer.clear_pending()
actionable_args = (query, file_url)
# ── 锁外:AgentHub ReAct 循环不持锁 ──
if actionable_args:
query, file_url = actionable_args
await self._handle_actionable(
session_id=session_id,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending,
query=query,
file_url=file_url,
bot_id_mapping=bot_id_mapping,
)
buffer.clear_pending()
finally:
self._running_tasks.pop(session_id, None)
......@@ -173,31 +192,8 @@ class MessageGate:
self,
pending: List[Dict[str, Any]],
) -> "GateDecision":
"""调 LLM 判断当前消息是否需要激活助手。无历史上下文,只看当前消息。
Returns:
GateDecision with intent="chat" or "pass"
"""
merged_text = self._merge_text_from_pending(pending)
if not merged_text:
return GateDecision(intent="chat")
prompt = (
"你是助手激活识别器。判断当前消息是否需要AI助手响应。\n"
"- chat:打招呼、道谢、确认收到、纯社交寒暄、群友间对话 —— 助手沉默\n"
"- pass:提问、命令、文件处理、提到某Agent名称、需要协助 —— 激活助手\n"
"\n只输出 \"chat\" 或 \"pass\"。\n"
"\n当前消息:\n" + merged_text
)
messages = [{"role": "user", "content": prompt}]
response = await self.model(messages=messages)
text = self._extract_text(response).strip().lower()
logger.debug("[MessageGate] activation response: %s", text)
if text == "pass":
return GateDecision(intent="pass")
return GateDecision(intent="chat") # 兜底默认:chat
"""直接放行所有消息,跳过 LLM 意图分类。"""
return GateDecision(intent="pass")
async def _handle_chat(
self,
......@@ -240,6 +236,35 @@ class MessageGate:
parts.append(f"[文件: {mc}]")
return "\n".join(parts) if parts else ""
@staticmethod
def _extract_query_and_file_url(
pending: List[Dict[str, Any]],
) -> tuple:
"""从 pending 消息中提取 query 文本和 file_url。
在锁内调用,返回 (query, file_url),AgentHub 在锁外使用。
"""
query = MessageGate._merge_text_from_pending(pending)
# 安全网:从 text 消息中提取 URL,补齐可能丢弃的链接
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}"
# 提取 file_url(取第一个非 text 消息的 URL)
file_url = None
for m in pending:
if m.get("msg_type") != "text" and m.get("msg_content"):
file_url = m["msg_content"]
break
return query, file_url
async def _handle_casual(
self,
session_id: str,
......@@ -351,35 +376,15 @@ class MessageGate:
session_id: str,
room_id: str,
user_id: str,
decision: "GateDecision",
pending: List[Dict[str, Any]],
query: str,
file_url: Optional[str],
bot_id_mapping: Dict[str, str],
) -> None:
"""pass 分支:分发到 AgentHub。"""
query = self._merge_text_from_pending(pending)
"""pass 分支:分发到 AgentHub。query/file_url 由调用方在锁内预先提取。"""
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}"
# 提取 file_url(取第一个非 text 消息的 URL)
file_url = None
for m in pending:
if m.get("msg_type") != "text" and m.get("msg_content"):
file_url = m["msg_content"]
break
try:
await self.agent_hub.process_message(
session_id=session_id,
......
# SessionBuffer 入锁 + AgentHub 移出锁 实施计划
> **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 (`- [x]`) syntax for tracking.
**Goal:** 把 endpoint 的裸 buffer.append 收进 MessageGate session 锁内,同时把 AgentHub ReAct 移出锁,消除 pending_messages 并发覆盖风险。
**Architecture:** MessageGate 新增 `append_messages()` 方法与 `evaluate()` 共用 session 锁;`evaluate()` 锁内只做 buffer 读写(毫秒级),`AgentHub.process_message()` 移到锁外;endpoint 改一行调用。
**Tech Stack:** Python 3.11+ / asyncio / pytest-asyncio
**Spec:** `ai-workflow/Vibe coding for SQ/docs/superpowers/specs/2026-06-24-sessionbuffer-lock-design.md`
**涉及文件:**
- Modify: `app/service/message_gate.py`
- Modify: `app/api/v1/endpoints/agent_hub.py`
- Modify: `tests/test_message_gate.py`
---
### Task 1: AgentHub 调用移出锁 + 提取 query/file_url 方法
**Files:**
- Modify: `app/service/message_gate.py`
**目标:** 从 `_handle_actionable` 中抽出 query/file_url 提取逻辑为独立方法,改 `_handle_actionable` 签名为接收预提取的 query/file_url,`evaluate()` 锁内提取 + clear_pending,锁外调 AgentHub。三个改动原子提交。
- [x] **Step 1: 新增 `_extract_query_and_file_url()` 静态方法**
在 MessageGate 类中 `_handle_actionable` 上面新增:
```python
@staticmethod
def _extract_query_and_file_url(
pending: List[Dict[str, Any]],
) -> tuple:
"""从 pending 消息中提取 query 文本和 file_url。
在锁内调用,返回 (query, file_url),AgentHub 在锁外使用。
"""
query = MessageGate._merge_text_from_pending(pending)
# 安全网:从 text 消息中提取 URL,补齐可能丢弃的链接
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}"
# 提取 file_url(取第一个非 text 消息的 URL)
file_url = None
for m in pending:
if m.get("msg_type") != "text" and m.get("msg_content"):
file_url = m["msg_content"]
break
return query, file_url
```
- [x] **Step 2: 改造 `_handle_actionable` 签名为接收 query/file_url**
把 `_handle_actionable` 的 `decision` 和 `pending` 参数替换为 `query` 和 `file_url`,移除内部 query 提取逻辑:
```python
async def _handle_actionable(
self,
session_id: str,
room_id: str,
user_id: str,
query: str,
file_url: Optional[str],
bot_id_mapping: Dict[str, str],
) -> None:
"""pass 分支:分发到 AgentHub。query/file_url 由调用方在锁内预先提取。"""
if not query:
logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id)
return
try:
await self.agent_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,
)
except asyncio.CancelledError:
logger.info("[MessageGate] session=%s 任务被取消", session_id)
raise
except Exception:
logger.exception(
"[MessageGate] session=%s AgentHub.process_message 失败", session_id,
)
```
- [x] **Step 3: 修改 evaluate() — 锁内 clear_pending,锁外 AgentHub**
把 `async with lock:` 块内(行 121-168)替换为:锁内提取 query/file_url → clear_pending → 锁外调 AgentHub:
```python
try:
actionable_args = None # (query, file_url) for lock-external AgentHub call
async with lock:
_kv_data = store.get(session_id) or {}
_kv_history = _kv_data.get("conversation_history") or []
_kv_pending = _kv_data.get("pending_messages") or []
logger.info(
"[MessageGate] session=%s 获取锁,conversation_history 长度=%d,pending_messages 长度=%d",
session_id, len(_kv_history), len(_kv_pending),
)
if not buffer.has_text_message() and buffer.get_pending():
logger.info(
"[MessageGate] session=%s 无 text 消息,等待 %.1fs",
session_id, wait_seconds,
)
await asyncio.sleep(wait_seconds)
buffer = SessionBuffer(store, session_id, session_service=self.session_service)
pending = buffer.get_pending()
if not pending:
logger.warning("[MessageGate] session=%s buffer 为空,跳过", session_id)
return
decision = await self._classify_and_rewrite(pending=pending)
if decision.intent == "chat":
await self._handle_chat(
session_id=session_id,
pending=pending,
)
buffer.clear_pending()
return
# pass: 锁内提取 query/file_url + clear_pending
query, file_url = self._extract_query_and_file_url(pending)
buffer.clear_pending()
actionable_args = (query, file_url)
# ── 锁外:AgentHub ReAct 循环不持锁 ──
if actionable_args:
query, file_url = actionable_args
await self._handle_actionable(
session_id=session_id,
room_id=room_id,
user_id=user_id,
query=query,
file_url=file_url,
bot_id_mapping=bot_id_mapping,
)
finally:
self._running_tasks.pop(session_id, None)
```
- [x] **Step 4: Commit**
```bash
git add app/service/message_gate.py
git commit -m "refactor: AgentHub 调用移出 session 锁,锁内只做 buffer 操作
- 新增 _extract_query_and_file_url() 静态方法
- _handle_actionable 签名改为接收预提取的 (query, file_url)
- evaluate() 锁内 clear_pending,锁外调 AgentHub
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
```
---
### Task 2: MessageGate 新增 append_messages()
**Files:**
- Modify: `app/service/message_gate.py`
**目标:** 新增 `append_messages()` 方法,用 session 锁保护 buffer append,替代端点的裸追加。
- [x] **Step 1: 在 _get_lock 方法下方新增 append_messages**
```python
async def append_messages(self, session_id: str, messages: List[Dict[str, Any]]) -> None:
"""追加消息到 session buffer,使用 per-session 锁保证并发安全。"""
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore
async with self._get_lock(session_id):
store = SessionStore()
buffer = SessionBuffer(store, session_id, session_service=self.session_service)
for msg in messages:
buffer.append(msg)
```
- [x] **Step 2: Commit**
```bash
git add app/service/message_gate.py
git commit -m "feat: MessageGate 新增 append_messages(),加锁保护 buffer 追加
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
```
---
### Task 3: endpoint 改用 append_messages
**Files:**
- Modify: `app/api/v1/endpoints/agent_hub.py:130-136`
**目标:** 替换端点中裸 `SessionBuffer.append()` 为 `await message_gate.append_messages()`。
- [x] **Step 1: 替换 endpoint 中的 buffer 追加代码**
把 lines 130-136(`# 4. 追加消息到 buffer...` 到 `buffer.append(msg.model_dump())`)替换为:
```python
# 4. 追加消息到 buffer(在 MessageGate per-session 锁内,确保并发安全)
await message_gate.append_messages(
session_id, [m.model_dump() for m in request.messages]
)
```
删除不再需要的 `from app.service.session_buffer import SessionBuffer` 和 `from app.infrastructure.session_store import SessionStore` import(如果其他地方没用)。
- [x] **Step 2: Commit**
```bash
git add app/api/v1/endpoints/agent_hub.py
git commit -m "fix: endpoint 改用 MessageGate.append_messages(),消除并发覆盖风险
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
```
---
### Task 4: 更新测试 + 回归验证
**Files:**
- Modify: `tests/test_message_gate.py`
- [x] **Step 1: 新增 `test_extract_query_and_file_url_text_only`**
```python
def test_extract_query_and_file_url_text_only():
"""仅包含文本消息时,提取 query 且 file_url 为 None。"""
from app.service.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
```
- [x] **Step 2: 新增 `test_extract_query_and_file_url_with_file`**
```python
def test_extract_query_and_file_url_with_file():
"""混合文本+文件消息时,提取 query 和 file_url。"""
from app.service.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"
```
- [x] **Step 3: 新增 `test_extract_query_and_file_url_append_url`**
```python
def test_extract_query_and_file_url_append_url():
"""文本中已含 URL 时,不重复追加。"""
from app.service.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
```
- [x] **Step 4: 新增 `test_extract_query_and_file_url_empty`**
```python
def test_extract_query_and_file_url_empty():
"""空 pending 返回空 query。"""
from app.service.message_gate import MessageGate
query, file_url = MessageGate._extract_query_and_file_url([])
assert query == ""
assert file_url is None
```
- [x] **Step 5: 更新 `test_handle_actionable_calls_agent_hub` 适配新签名**
```python
@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()
call_kwargs = mock_agent_hub.process_message.call_args.kwargs
assert call_kwargs["user_query"] == "创建任务"
assert call_kwargs["file_url"] is None
```
- [x] **Step 6: 修复 `test_classify_returns_chat_for_empty_pending`**
`_classify_and_rewrite` 已改为直接返回 `pass`,更新断言:
```python
@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"
```
- [x] **Step 7: 修复 `test_classify_activation_returns_chat_by_default`**
同理:
```python
@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"
```
- [x] **Step 8: 删除 `test_classify_activation_model_called`**
该测试验证 LLM 被调用(`mock_model.assert_called_once()`),LLM 不再被调用,删除此测试函数。
- [x] **Step 9: 运行全部测试验证**
```bash
cd ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py tests/test_agent_hub.py -v
```
预期:全部通过。
- [x] **Step 10: Commit**
```bash
git add tests/test_message_gate.py
git commit -m "test: 更新 MessageGate 测试适配锁重构 + LLM 临时放行
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
```
---
### 验收清单
- [x] endpoint 不再直接创建 `SessionBuffer`,改为 `await message_gate.append_messages()`
- [x] `append_messages` 与 `evaluate` 共用同一把 per-session `asyncio.Lock`
- [x] AgentHub.process_message() 在 session 锁外执行
- [x] clear_pending() 在锁内、AgentHub 调用前执行
- [x] `_handle_actionable` 签名为 `(query, file_url, bot_id_mapping)`
- [x] `_running_tasks` busy 检测行为不变
- [x] 全部测试 `tests/test_message_gate.py` + `tests/test_agent_hub.py` 通过
......@@ -15,7 +15,7 @@
"sender_id": "",
"sender_name": "孙奇",
"msg_type": "text",
"msg_content": "课程涵盖哪些内容?",
"msg_content": "我想知道问界延保的价格",
"payload": {}
}
]
......
......@@ -27,7 +27,7 @@ def test_gate_decision_only_intent():
@pytest.mark.asyncio
async def test_classify_returns_chat_for_empty_pending():
"""空 pending → 返回 chat。"""
"""空 pending → 当前临时直接放行,返回 pass。"""
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
......@@ -37,50 +37,23 @@ async def test_classify_returns_chat_for_empty_pending():
model=MagicMock(),
)
decision = await gate._classify_and_rewrite(pending=[])
assert decision.intent == "chat"
@pytest.mark.asyncio
async def test_classify_activation_model_called():
"""LLM 返回 'pass' → GateDecision intent='pass'。"""
mock_model = AsyncMock()
mock_model_response = MagicMock()
mock_model_response.content = [{"type": "text", "text": "pass"}]
mock_model.return_value = mock_model_response
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=mock_model,
)
pending = [{"msg_type": "text", "msg_content": "帮我整理会议纪要"}]
decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "pass"
mock_model.assert_called_once()
@pytest.mark.asyncio
async def test_classify_activation_returns_chat_by_default():
"""LLM 返回未知内容 → 兜底 chat。"""
mock_model = AsyncMock()
mock_model_response = MagicMock()
mock_model_response.content = [{"type": "text", "text": "hello"}]
mock_model.return_value = mock_model_response
"""直接放行模式:返回 pass(临时跳过 LLM 分类)。"""
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=mock_model,
model=MagicMock(),
)
pending = [{"msg_type": "text", "msg_content": "谢谢大家"}]
decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "chat"
assert decision.intent == "pass"
@pytest.mark.asyncio
......@@ -119,7 +92,7 @@ async def test_handle_chat_adds_user_message_to_history():
@pytest.mark.asyncio
async def test_handle_actionable_calls_agent_hub():
"""_handle_actionable 调用 agent_hub.process_message。"""
"""_handle_actionable 用预提取的 query/file_url 调用 agent_hub.process_message。"""
mock_agent_hub = MagicMock()
mock_agent_hub.process_message = AsyncMock()
......@@ -131,16 +104,60 @@ async def test_handle_actionable_calls_agent_hub():
main_agent_key="11",
model=MagicMock(),
)
decision = GateDecision(intent="pass")
pending = [{"msg_type": "text", "msg_content": "创建任务"}]
await gate._handle_actionable(
session_id="test-session",
room_id="room-1",
user_id="user-1",
decision=decision,
pending=pending,
query="创建任务",
file_url=None,
bot_id_mapping={"11": "bot_main"},
)
mock_agent_hub.process_message.assert_called_once()
call_kwargs = mock_agent_hub.process_message.call_args.kwargs
assert call_kwargs["user_query"] == "创建任务"
assert call_kwargs["file_url"] is None
# ── _extract_query_and_file_url 单元测试 ──
def test_extract_query_and_file_url_text_only():
"""仅包含文本消息时,提取 query 且 file_url 为 None。"""
from app.service.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.service.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.service.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.service.message_gate import MessageGate
query, file_url = MessageGate._extract_query_and_file_url([])
assert query == ""
assert file_url is None
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!