From a05387a33924bacb95f537aa5e1128f5366df79f Mon Sep 17 00:00:00 2001 From: taide05 Date: Tue, 21 Jul 2026 17:46:18 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=20EventBus=20sub?= =?UTF-8?q?scribe=20/=20unsubscribe=20/=20emit=20/=20flush=5Fevents?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用 hasattr 懒初始化而非 __init__,各方法独立检查属性存在 asyncio.QueueFull 用 pass 静默丢弃,不中断 Agent 循环 payload 展开到事件顶层,减少嵌套层级 --- app/core/event_bus.py | 57 +++++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/app/core/event_bus.py b/app/core/event_bus.py index 160ad68..494aeeb 100644 --- a/app/core/event_bus.py +++ b/app/core/event_bus.py @@ -1,29 +1,33 @@ +"""事件总线。 + +Agent 循环过程中每发生一件事就通过 EventBus 推送出去, +订阅者(如 SSE 连接)收到事件后推给前端。 +""" + from __future__ import annotations import asyncio -import json from datetime import datetime, timezone from typing import Any -from uuid import UUID from app.core.event_types import EventType class EventBus: - def __init__(self): - self._subscribers: dict[str, list[asyncio.Queue]] = {} - self._pending_events: list[dict] = [] - def subscribe(self, session_id: str, queue: asyncio.Queue): + def subscribe(self, session_id: str, queue: asyncio.Queue) -> None: + if not hasattr(self,"_subscribers"): + self._subscribers = {} if session_id not in self._subscribers: self._subscribers[session_id] = [] self._subscribers[session_id].append(queue) - def unsubscribe(self, session_id: str, queue: asyncio.Queue): + def unsubscribe(self, session_id: str, queue: asyncio.Queue) -> None: + if not hasattr(self, "_subscribers"): + return if session_id in self._subscribers: - subs = self._subscribers[session_id] - if queue in subs: - subs.remove(queue) + if queue in self._subscribers[session_id]: + self._subscribers[session_id].remove(queue) async def emit( self, @@ -31,38 +35,39 @@ async def emit( session_id: str, event_type: EventType, payload: dict[str, Any], - ): + ) -> None: event_data = { "node_id": str(node_id), "session_id": str(session_id), - "type": event_type.value, - **payload, - "timestamp": datetime.now(timezone.utc).isoformat(), + "type": event_type.value, # EventType 是 str enum, .value 拿字符串 + **payload, # payload 的键值展开到事件顶层的其余字段 + "timestamp": datetime.now(timezone.utc).isoformat() } - - self._pending_events.append({ - "session_id": session_id, - "node_id": node_id, - "event_type": event_type.value, - "payload": payload, - }) - - for queue in self._subscribers.get(session_id, []): + if not hasattr(self,"_pending_events"): + self._pending_events = [] + self._pending_events.append(event_data) + if not hasattr(self,"_subscribers"): + return + for queue in self._subscribers.get(session_id,[]): try: queue.put_nowait(event_data) except asyncio.QueueFull: pass def flush_events(self) -> list[dict]: - events = self._pending_events.copy() - self._pending_events.clear() - return events + if not hasattr(self,"_pending_events"): + return [] + result = self._pending_events + self._pending_events = [] + return result +# ─── 全局单例(已给,直接用)───────────────────────────── _global_event_bus: EventBus | None = None def get_event_bus() -> EventBus: + """获取全局唯一的 EventBus 实例。""" global _global_event_bus if _global_event_bus is None: _global_event_bus = EventBus() From 45b8cf155c7873e02994ca631926aab3178b6fc7 Mon Sep 17 00:00:00 2001 From: taide05 Date: Tue, 21 Jul 2026 21:23:11 +0800 Subject: [PATCH 2/2] feat: implement ReAct agent loop with tool execution and fallback Co-Authored-By: Claude Opus 4.7 --- app/core/agent_loop.py | 215 +++++++++++++++------------------- app/core/event_bus.py | 2 +- tests/manual_smoke_test.py | 2 +- tests/unit/test_agent_loop.py | 155 +++++++++++++++++++++--- tests/unit/test_event_bus.py | 162 +++++++++++++++++++++++++ 5 files changed, 399 insertions(+), 137 deletions(-) create mode 100644 tests/unit/test_event_bus.py diff --git a/app/core/agent_loop.py b/app/core/agent_loop.py index 4deedf5..17aebb3 100644 --- a/app/core/agent_loop.py +++ b/app/core/agent_loop.py @@ -1,9 +1,14 @@ +"""ReAct Agent 主循环。 + +Thought → Action → Observation 循环是 Agent 的心脏。 +这个文件是你的第三个实现目标,也是三个文件中最复杂的一个。 +""" + from __future__ import annotations import json import time -from dataclasses import dataclass, field -from uuid import UUID, uuid4 +from dataclasses import dataclass from app.core.agent_config import AgentConfig from app.core.event_bus import EventBus, get_event_bus @@ -11,12 +16,8 @@ from app.core.llm_client import LLMClient, LLMError from app.core.tool_registry import ToolRegistry, ToolExecutionError, ToolNotFoundError -DEFAULT_SYSTEM_PROMPT = ( - "You are a helpful AI assistant with access to tools. " - "Use tools when you need to look up information or perform calculations. " - "After using tools, synthesize the results into a clear answer. " - "If a tool returns an error, try a different approach or explain the issue to the user." -) + +# ─── 数据结构 ─────────────────────────────────────────── @dataclass @@ -33,20 +34,31 @@ class LoopState: def _build_tool_call_message(tool_calls: list[dict], content: str | None) -> dict: openai_tool_calls = [] for tc in tool_calls: - openai_tool_calls.append({ - "id": tc["id"], - "type": "function", - "function": { - "name": tc["name"], - "arguments": json.dumps(tc["arguments"], ensure_ascii=False), - }, - }) - msg: dict = {"role": "assistant", "content": content, "tool_calls": openai_tool_calls} - return msg - + openai_tool_calls.append( + { + "id":tc["id"], + "type":"function", + "function":{ + "name":tc["name"], + "arguments":json.dumps(tc["arguments"],ensure_ascii=False) + } + } + ) + result_dict_cm = { + "role":"assistant", + "content":content, + "tool_calls":openai_tool_calls + } + return result_dict_cm def _build_tool_result_message(tool_call_id: str, result_str: str) -> dict: - return {"role": "tool", "tool_call_id": tool_call_id, "content": result_str} + result_dict_rs = { + "role":"tool", + "tool_call_id":tool_call_id, + "content":result_str + } + return result_dict_rs +# ─── 主函数:你要实现的 ──────────────────────────────────── async def run_agent_loop( @@ -58,114 +70,79 @@ async def run_agent_loop( node_id: str = "", event_bus: EventBus | None = None, ) -> LoopState: - event_bus = event_bus or get_event_bus() - tools_schema = await tools.get_all_as_openai_schema() + if event_bus is None: + event_bus = get_event_bus() + schema = await tools.get_all_as_openai_schema() state = LoopState( - session_id=session_id, - node_id=node_id, - messages=list(messages), + session_id = session_id, + node_id = node_id, + messages = list(messages) ) - - for iteration in range(1, config.max_iterations + 1): + for iteration in range(1,config.max_iterations + 1): state.iteration = iteration - try: - response = await llm.chat(state.messages, tools_schema) - except LLMError as e: - state.error = str(e) + response = await llm.chat(state.messages,schema) + if response.thinking: + await event_bus.emit(node_id,session_id,EventType.THINKING,{"content":response.thinking,"iteration":iteration}) + if response.content: + await event_bus.emit(node_id,session_id,EventType.TEXT,{"content":response.content,"iteration":iteration,"is_final":not bool(response.tool_calls)}) + if not response.tool_calls: + state.final_answer = response.content + state.should_stop = True + state.messages.append({"role":"assistant","content":response.content}) + break + else: + assistant = _build_tool_call_message(response.tool_calls,response.content) + state.messages.append(assistant) + for tc in response.tool_calls: + tool_call_id = tc["id"] + tool_name = tc["name"] + arguments = tc["arguments"] + await event_bus.emit(node_id,session_id,EventType.TOOL_CALL,{ + "tool_call_id":tool_call_id, + "tool_name":tool_name, + "arguments":arguments, + "iteration":iteration, + }) + start_time = time.monotonic() + try: + result = await tools.execute(tool_name,arguments) + result_str = json.dumps(result,ensure_ascii=False) + duration_ms = int((time.monotonic() - start_time) * 1000) + await event_bus.emit(node_id,session_id,EventType.TOOL_RESULT,{ + "tool_call_id":tool_call_id, + "tool_name":tool_name, + "result":result, + "duration_ms":duration_ms, + "is_error":False, + }) + except (ToolExecutionError,ToolNotFoundError) as e: + result_str = json.dumps({"error":str(e)}) + duration_ms = int((time.monotonic() - start_time) * 1000) + await event_bus.emit(node_id,session_id,EventType.TOOL_RESULT,{ + "tool_call_id":tool_call_id, + "tool_name":tool_name, + "result":{"error":str(e)}, + "duration_ms":duration_ms, + "is_error":True, + }) + state.messages.append(_build_tool_result_message(tool_call_id,result_str)) + except LLMError as exc: + state.error = str(exc) state.should_stop = True - await event_bus.emit(node_id, session_id, EventType.ERROR, { - "message": str(e), - "iteration": iteration, - }) break - - if response.thinking: - await event_bus.emit(node_id, session_id, EventType.THINKING, { - "content": response.thinking, - "iteration": iteration, - }) - - if response.content: - await event_bus.emit(node_id, session_id, EventType.TEXT, { - "content": response.content, - "iteration": iteration, - "is_final": not bool(response.tool_calls), - }) - - if not response.tool_calls: - state.final_answer = response.content - state.should_stop = True - state.messages.append({"role": "assistant", "content": response.content}) - await event_bus.emit(node_id, session_id, EventType.STATUS, { - "status": "completed", - "message": "Agent finished", - "stop_reason": StopReason.FINISH.value, - "iterations": iteration, - }) - break - - assistant_msg = _build_tool_call_message(response.tool_calls, response.content) - state.messages.append(assistant_msg) - - for tc in response.tool_calls: - tool_call_id = tc["id"] - tool_name = tc["name"] - arguments = tc["arguments"] - - await event_bus.emit(node_id, session_id, EventType.TOOL_CALL, { - "tool_call_id": tool_call_id, - "tool_name": tool_name, - "arguments": arguments, - "iteration": iteration, - }) - - start_time = time.monotonic() - try: - result = await tools.execute(tool_name, arguments) - duration_ms = int((time.monotonic() - start_time) * 1000) - await event_bus.emit(node_id, session_id, EventType.TOOL_RESULT, { - "tool_call_id": tool_call_id, - "tool_name": tool_name, - "result": result, - "duration_ms": duration_ms, - "is_error": False, - }) - result_str = json.dumps(result, ensure_ascii=False) - except (ToolExecutionError, ToolNotFoundError) as e: - duration_ms = int((time.monotonic() - start_time) * 1000) - result_str = json.dumps({"error": str(e)}) - await event_bus.emit(node_id, session_id, EventType.TOOL_RESULT, { - "tool_call_id": tool_call_id, - "tool_name": tool_name, - "result": {"error": str(e)}, - "duration_ms": duration_ms, - "is_error": True, - }) - - state.messages.append(_build_tool_result_message(tool_call_id, result_str)) - else: - state.should_stop = True - await event_bus.emit(node_id, session_id, EventType.STATUS, { - "status": "completed", - "message": f"Reached max iterations ({config.max_iterations})", - "stop_reason": StopReason.MAX_ITERATIONS.value, - "iterations": iteration, - }) - - state.messages.append({ - "role": "user", - "content": "Maximum steps reached. Summarize what you found so far and give your best answer.", + state.should_stop = True + await event_bus.emit(node_id,session_id,EventType.STATUS,{ + "status":"completed", + "message":f"Reached max iterations({config.max_iterations})", + "stop_reason":StopReason.MAX_ITERATIONS.value, + "iterations":config.max_iterations }) + state.messages.append({"role":"user","content":"Maximum steps reached. Summarize what you found so far and give your best answer."}) try: fallback = await llm.chat(state.messages) state.final_answer = fallback.content - await event_bus.emit(node_id, session_id, EventType.TEXT, { - "content": fallback.content, - "is_final": True, - }) - except LLMError: + except LLMError as exc: state.final_answer = "Agent reached iteration limit but could not produce a summary." - - return state + return state \ No newline at end of file diff --git a/app/core/event_bus.py b/app/core/event_bus.py index 494aeeb..97598a1 100644 --- a/app/core/event_bus.py +++ b/app/core/event_bus.py @@ -71,4 +71,4 @@ def get_event_bus() -> EventBus: global _global_event_bus if _global_event_bus is None: _global_event_bus = EventBus() - return _global_event_bus + return _global_event_bus \ No newline at end of file diff --git a/tests/manual_smoke_test.py b/tests/manual_smoke_test.py index 1e1c9fb..d3be190 100644 --- a/tests/manual_smoke_test.py +++ b/tests/manual_smoke_test.py @@ -73,7 +73,7 @@ async def test_agent_loop_with_tool(): print(f" Answer: {state.final_answer[:200]}...") events = event_bus.flush_events() - event_types = [e["event_type"] for e in events] + event_types = [e["type"] for e in events] print(f" Event types: {event_types}") assert state.final_answer is not None assert "tool_call" in event_types, f"Expected tool_call event, got {event_types}" diff --git a/tests/unit/test_agent_loop.py b/tests/unit/test_agent_loop.py index 6596f54..3042d6b 100644 --- a/tests/unit/test_agent_loop.py +++ b/tests/unit/test_agent_loop.py @@ -1,28 +1,41 @@ +"""agent_loop.py 的测试。运行方式:pytest tests/unit/test_agent_loop.py -v""" + from unittest.mock import AsyncMock import pytest -import pytest_asyncio from app.core.agent_config import AgentConfig -from app.core.agent_loop import run_agent_loop +from app.core.agent_loop import run_agent_loop, LoopState from app.core.event_bus import EventBus -from app.core.llm_client import LLMResponse +from app.core.llm_client import LLMResponse, LLMError from app.core.tool_registry import ToolDefinition, ToolRegistry -async def _calc_fn(expr): - return {"result": eval(expr)} +# ─── 辅助 ────────────────────────────────────────────────── + +async def _calc_fn(expr: str): + return eval(expr) + + +async def _search_fn(query: str): + return {"results": [f"Result for {query}"]} -@pytest_asyncio.fixture +async def _fail_fn(**kwargs): + raise RuntimeError("tool error") + + +@pytest.fixture def mock_llm(): + """LLM 直接返回文本,不调工具。""" llm = AsyncMock() llm.chat.return_value = LLMResponse(content="The answer is 4.", tool_calls=[]) return llm -@pytest_asyncio.fixture +@pytest.fixture def mock_llm_with_tool(): + """LLM 第一轮调工具,第二轮返回文本。""" llm = AsyncMock() llm.chat.side_effect = [ LLMResponse( @@ -34,31 +47,60 @@ def mock_llm_with_tool(): return llm -@pytest_asyncio.fixture +@pytest.fixture +def mock_llm_max_iterations(): + """LLM 一直调工具,超过 max_iterations。""" + llm = AsyncMock() + llm.chat.return_value = LLMResponse( + tool_calls=[{"id": "call_1", "name": "calc", "arguments": {"expr": "1+1"}}], + ) + return llm + + +@pytest.fixture +def mock_llm_error(): + """LLM 调用失败。""" + llm = AsyncMock() + llm.chat.side_effect = LLMError("API error") + return llm + + +@pytest.fixture async def registry(): reg = ToolRegistry() - tool = ToolDefinition( - name="calc", - description="Calculate", + await reg.register(ToolDefinition( + name="calc", description="Calculate an expression", parameters={"type": "object", "properties": {"expr": {"type": "string"}}, "required": ["expr"]}, fn=_calc_fn, - ) - await reg.register(tool) + )) + await reg.register(ToolDefinition( + name="search", description="Search the web", + parameters={"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}, + fn=_search_fn, + )) + await reg.register(ToolDefinition( + name="fail_tool", description="Always fails", + parameters={"type": "object", "properties": {}}, + fn=_fail_fn, + )) return reg -@pytest_asyncio.fixture +@pytest.fixture def event_bus(): return EventBus() -@pytest_asyncio.fixture +@pytest.fixture def config(): return AgentConfig(max_iterations=5) +# ─── 基本流程 ────────────────────────────────────────────── + @pytest.mark.asyncio async def test_simple_no_tool_response(mock_llm, registry, event_bus, config): + """LLM 不调工具直接返回文本 → 1 轮结束。""" messages = [{"role": "user", "content": "What is 2+2?"}] state = await run_agent_loop(messages, mock_llm, registry, config, event_bus=event_bus) assert state.final_answer == "The answer is 4." @@ -68,16 +110,97 @@ async def test_simple_no_tool_response(mock_llm, registry, event_bus, config): @pytest.mark.asyncio async def test_single_tool_call(mock_llm_with_tool, registry, event_bus, config): + """LLM 调一次工具后返回文本 → 2 轮结束。""" messages = [{"role": "user", "content": "Calculate 2+2"}] state = await run_agent_loop(messages, mock_llm_with_tool, registry, config, event_bus=event_bus) assert state.final_answer == "The result is 4." assert state.iteration == 2 +# ─── 工具异常处理 ────────────────────────────────────────── + +@pytest.mark.asyncio +async def test_tool_error_reported_to_llm(registry, event_bus, config): + """工具执行失败 → 错误信息应作为 tool result 返回给 LLM。""" + llm = AsyncMock() + llm.chat.side_effect = [ + LLMResponse( + tool_calls=[{"id": "c1", "name": "fail_tool", "arguments": {}}], + ), + LLMResponse(content="The tool failed, let me try differently.", tool_calls=[]), + ] + messages = [{"role": "user", "content": "Use fail_tool"}] + state = await run_agent_loop(messages, llm, registry, config, event_bus=event_bus) + assert state.final_answer is not None + # 第二轮调用时 messages 应包含工具错误信息 + second_call_messages = llm.chat.call_args_list[1][0][0] + tool_results = [m for m in second_call_messages if m["role"] == "tool"] + assert len(tool_results) == 1 + + +# ─── max_iterations 兜底 ─────────────────────────────────── + +@pytest.mark.asyncio +async def test_max_iterations_reached(mock_llm_max_iterations, registry, event_bus): + """达到 max_iterations 后应停止并尝试总结。""" + config = AgentConfig(max_iterations=3) + messages = [{"role": "user", "content": "Keep calculating"}] + state = await run_agent_loop(messages, mock_llm_max_iterations, registry, config, event_bus=event_bus) + assert state.iteration >= 3 + assert state.should_stop is True + + +# ─── LLM 调用异常 ────────────────────────────────────────── + +@pytest.mark.asyncio +async def test_llm_error_stops_loop(mock_llm_error, registry, event_bus, config): + """LLM 调用失败 → 应直接中断循环并设置 error 字段。""" + messages = [{"role": "user", "content": "Hello"}] + state = await run_agent_loop(messages, mock_llm_error, registry, config, event_bus=event_bus) + assert state.error is not None + assert state.should_stop is True + + +# ─── 事件发送 ────────────────────────────────────────────── + @pytest.mark.asyncio async def test_events_emitted(mock_llm, registry, event_bus, config): + """正常流程应发送事件。""" messages = [{"role": "user", "content": "Hello"}] await run_agent_loop(messages, mock_llm, registry, config, "s1", "n1", event_bus) events = event_bus.flush_events() - event_types = [e["event_type"] for e in events] + event_types = [e["type"] for e in events] assert "text" in event_types or "status" in event_types + + +# ─── 多工具调用 ──────────────────────────────────────────── + +@pytest.mark.asyncio +async def test_multiple_tool_calls_in_one_turn(registry, event_bus, config): + """一轮中 LLM 返回多个 tool_calls → 每个都应执行。""" + llm = AsyncMock() + llm.chat.side_effect = [ + LLMResponse( + tool_calls=[ + {"id": "c1", "name": "calc", "arguments": {"expr": "1+1"}}, + {"id": "c2", "name": "search", "arguments": {"query": "test"}}, + ], + ), + LLMResponse(content="Done.", tool_calls=[]), + ] + messages = [{"role": "user", "content": "Calc and search"}] + state = await run_agent_loop(messages, llm, registry, config, event_bus=event_bus) + assert state.final_answer == "Done." + + +# ─── 消息历史累积 ───────────────────────────────────────── + +@pytest.mark.asyncio +async def test_messages_accumulate(mock_llm_with_tool, registry, event_bus, config): + """每轮对话应追加到 messages 中。""" + messages = [{"role": "user", "content": "Calc 2+2"}] + state = await run_agent_loop(messages, mock_llm_with_tool, registry, config, event_bus=event_bus) + # messages 应包含: user + assistant(with tool_call) + tool_result + assistant(final) + roles = [m["role"] for m in state.messages] + assert "tool" in roles + assert roles.count("assistant") >= 2 diff --git a/tests/unit/test_event_bus.py b/tests/unit/test_event_bus.py new file mode 100644 index 0000000..a2247e3 --- /dev/null +++ b/tests/unit/test_event_bus.py @@ -0,0 +1,162 @@ +"""event_bus.py 的测试。运行方式:pytest tests/unit/test_event_bus.py -v""" + +import asyncio + +import pytest + +from app.core.event_bus import EventBus, get_event_bus +from app.core.event_types import EventType + + +# ─── subscribe + emit ────────────────────────────────── + +@pytest.mark.asyncio +async def test_emit_delivers_to_subscriber(): + """订阅后 emit 应把事件推送到队列。""" + bus = EventBus() + q = asyncio.Queue(maxsize=10) + bus.subscribe("s1", q) + + await bus.emit("n1", "s1", EventType.TEXT, {"content": "hello"}) + + event = q.get_nowait() + assert event["node_id"] == "n1" + assert event["session_id"] == "s1" + assert event["type"] == "text" + assert event["content"] == "hello" + assert "timestamp" in event + + +@pytest.mark.asyncio +async def test_emit_to_multiple_subscribers(): + """同一 session 的多个队列都应收到事件。""" + bus = EventBus() + q1 = asyncio.Queue(maxsize=10) + q2 = asyncio.Queue(maxsize=10) + bus.subscribe("s1", q1) + bus.subscribe("s1", q2) + + await bus.emit("n1", "s1", EventType.STATUS, {"status": "ok"}) + + assert not q1.empty() + assert not q2.empty() + assert q1.get_nowait()["status"] == "ok" + assert q2.get_nowait()["status"] == "ok" + + +@pytest.mark.asyncio +async def test_different_sessions_isolated(): + """A session 的事件不应推送到 B session 的队列。""" + bus = EventBus() + q_a = asyncio.Queue(maxsize=10) + q_b = asyncio.Queue(maxsize=10) + bus.subscribe("a", q_a) + bus.subscribe("b", q_b) + + await bus.emit("n1", "a", EventType.TEXT, {"content": "only for a"}) + + assert not q_a.empty() + assert q_b.empty() # B 不应收到 + + +@pytest.mark.asyncio +async def test_emit_no_subscribers_does_not_raise(): + """没有订阅者时 emit 不应抛异常。""" + bus = EventBus() + await bus.emit("n1", "no_one", EventType.TEXT, {"content": "nobody"}) + + +@pytest.mark.asyncio +async def test_emit_full_queue_graceful(): + """队列满时 emit 应静默丢弃,不抛异常、不阻塞。""" + bus = EventBus() + q = asyncio.Queue(maxsize=1) # 容量 1 + bus.subscribe("s1", q) + + await bus.emit("n1", "s1", EventType.TEXT, {"seq": 1}) + # 队列已满,这次 emit 应静默丢弃 + await bus.emit("n1", "s1", EventType.TEXT, {"seq": 2}) + + event = q.get_nowait() + assert event["seq"] == 1 # 第一条在,第二条丢了 + + +# ─── unsubscribe ──────────────────────────────────────── + +@pytest.mark.asyncio +async def test_unsubscribe_stops_events(): + """取消订阅后不再收到事件。""" + bus = EventBus() + q = asyncio.Queue(maxsize=10) + bus.subscribe("s1", q) + bus.unsubscribe("s1", q) + + await bus.emit("n1", "s1", EventType.TEXT, {"content": "should not arrive"}) + + assert q.empty() + + +@pytest.mark.asyncio +async def test_unsubscribe_nonexistent_does_not_raise(): + """取消不存在的订阅不应抛异常。""" + bus = EventBus() + q = asyncio.Queue(maxsize=10) + bus.unsubscribe("no_session", q) # 不抛异常 + bus.subscribe("s1", asyncio.Queue(maxsize=10)) + bus.unsubscribe("s1", q) # session 存在但 queue 未订阅,也不抛异常 + + +@pytest.mark.asyncio +async def test_unsubscribe_removes_only_specified_queue(): + """取消一个队列不影响同一 session 的其他队列。""" + bus = EventBus() + q1 = asyncio.Queue(maxsize=10) + q2 = asyncio.Queue(maxsize=10) + bus.subscribe("s1", q1) + bus.subscribe("s1", q2) + bus.unsubscribe("s1", q1) + + await bus.emit("n1", "s1", EventType.TEXT, {"content": "hi"}) + + assert q1.empty() + assert not q2.empty() + + +# ─── payload 展开 ─────────────────────────────────────── + +@pytest.mark.asyncio +async def test_emit_payload_spread_into_event(): + """payload 的键应展开到事件的顶层。""" + bus = EventBus() + q = asyncio.Queue(maxsize=10) + bus.subscribe("s1", q) + + await bus.emit("n1", "s1", EventType.TOOL_RESULT, { + "tool_name": "search", + "result": "found", + "duration_ms": 150, + }) + + event = q.get_nowait() + assert event["tool_name"] == "search" + assert event["result"] == "found" + assert event["duration_ms"] == 150 + assert event["type"] == "tool_result" + + +# ─── flush_events ─────────────────────────────────────── + +def test_flush_events_returns_list(): + """flush_events 应返回 list。""" + bus = EventBus() + result = bus.flush_events() + assert isinstance(result, list) + + +# ─── get_event_bus 全局单例 ───────────────────────────── + +def test_get_event_bus_returns_singleton(): + """多次调用返回同一个实例。""" + b1 = get_event_bus() + b2 = get_event_bus() + assert b1 is b2