diff --git a/CHANGELOG.md b/CHANGELOG.md index 136280774b..9aa8b93524 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ ## [Unreleased] +### 修复 +- 定时 Agent 任务不再把普通工具调用前的过程说明拼入最终推送和合成历史;保留团队 `ask_agent` 分派话术,错误或等待审批时不推送未完成的文本(#2384)。 + ## [1.0.3b8] - 2026-11-27 ### 新增 diff --git a/src/octop/infra/cron/delivery.py b/src/octop/infra/cron/delivery.py index d0d7cfdbe3..72e21084f5 100644 --- a/src/octop/infra/cron/delivery.py +++ b/src/octop/infra/cron/delivery.py @@ -17,6 +17,7 @@ from octop.infra.db.repos.threads import ThreadRow from octop.infra.gateway.process import build_harness_request from octop.infra.gateway.process.message_keys import COMPOSER_CTX_KEY, build_composer_context +from octop.infra.gateway.process.response_mode import withhold_pretool_stream_chunks from octop.infra.gateway.process.usage_record import UsageTracker, record_turn_usage from octop.infra.gateway.threads import ThreadRegistry from octop.infra.history.projection import TurnHistoryTracker, message_inputs @@ -248,6 +249,7 @@ async def _deliver_agent( usage = UsageTracker() parts: list[str] = [] interaction_required = False + error_message: str | None = None saw_tool_call = False emitted_tool_error_ids: set[str] = set() try: @@ -260,7 +262,8 @@ async def _deliver_agent( HitlSessionPolicy(mode="allow_all"), ) with write_scope(allowed=False), policy: - async for chunk in self._agent_manager.stream(command.agent_id, request): + stream = self._agent_manager.stream(command.agent_id, request) + async for chunk in withhold_pretool_stream_chunks(stream): tracker.observe(chunk) usage.observe(chunk) kind = chunk.get("type") @@ -278,6 +281,12 @@ async def _deliver_agent( parts.append(str(chunk.get("content") or chunk.get("text") or "")) elif kind == "hitl_required": interaction_required = True + elif kind == "error": + error_message = str( + chunk.get("message") or chunk.get("content") or "cron agent run failed" + ) + if error_message: + raise RuntimeError(error_message) if interaction_required: raise RuntimeError("cron agent run requires user interaction") outbound = strip_thinking("".join(parts)).strip() diff --git a/src/octop/infra/gateway/process/response_mode.py b/src/octop/infra/gateway/process/response_mode.py index 0a98269272..db0a1d7034 100644 --- a/src/octop/infra/gateway/process/response_mode.py +++ b/src/octop/infra/gateway/process/response_mode.py @@ -44,6 +44,100 @@ def qq_channel_response_mode(config: dict[str, Any]) -> ChannelResponseMode: return "invoke" +async def withhold_pretool_stream_chunks( + chunks: AsyncIterator[dict[str, Any]], + *, + keep_for_tools: frozenset[str] = frozenset({"ask_agent"}), +) -> AsyncIterator[dict[str, Any]]: + """Withhold raw text until its tool batch or final-answer boundary is known. + + Only a batch consisting entirely of allowed tools keeps its lead-in text. + Control/state chunks pass through unchanged, so consumers can still track + usage and canonical checkpoint messages without accumulating discarded text. + """ + pending: list[dict[str, Any]] = [] + call_names: dict[str, str] = {} + call_ids: dict[str, str] = {} + result_names: set[str] = set() + seen_results: set[str] = set() + saw_result = False + + def keep_pending() -> bool: + names = set(call_names.values()) | result_names + return not names or (saw_result and names <= keep_for_tools) + + try: + async for chunk in chunks: + kind = chunk.get("type") + if kind in {"error", "hitl_required"}: + pending.clear() + yield chunk + return + + if saw_result and kind in {"token", "delta", "tool_call_chunk"}: + if keep_pending(): + for held in pending: + yield held + pending.clear() + call_names.clear() + call_ids.clear() + result_names.clear() + saw_result = False + + if kind in {"token", "delta"}: + pending.append(chunk) + continue + + if kind == "tool_call_chunk": + call_id = str(chunk.get("id") or "") + index = chunk.get("index") + key = str(index) if index is not None else call_id or "0" + call_names[key] = call_names.get(key, "") + str(chunk.get("name") or "") + if call_id: + call_ids[call_id] = key + elif kind == "tool_result": + messages = chunk.get("messages") + if isinstance(messages, list) and messages: + for message in messages: + if isinstance(message, dict): + call_id = str(message.get("tool_call_id") or "") + name = str(message.get("name") or "") + role = message.get("type") or message.get("role") + else: + call_id = str(getattr(message, "tool_call_id", None) or "") + name = str(getattr(message, "name", None) or "") + role = getattr(message, "type", None) + if not call_id and role != "tool": + continue + if call_id and ( + call_id in seen_results or (call_ids and call_id not in call_ids) + ): + continue + if call_id: + seen_results.add(call_id) + result_key = call_ids.get(call_id) + if result_key is None and not call_ids and len(call_names) == 1: + result_key = next(iter(call_names)) + if name: + result_names.add(name) + if result_key is not None: + call_names[result_key] = name + elif not call_names: + result_names.add("") # An unknown tool cannot preserve narration. + saw_result = True + else: + if chunk.get("name") or not call_names: + result_names.add(str(chunk.get("name") or "")) + saw_result = True + yield chunk + + if keep_pending(): + for held in pending: + yield held + finally: + await close_event_stream(chunks) + + async def collapse_to_invoke_response( events: AsyncIterator[MessageEvent], ) -> AsyncIterator[MessageEvent]: @@ -205,6 +299,7 @@ def _invoke_processor(message: InboundMessage) -> AsyncIterator[MessageEvent]: "normalize_channel_response_mode", "processor_for_response_mode", "qq_channel_response_mode", + "withhold_pretool_stream_chunks", "withhold_weixin_stream_preamble", "wrap_weixin_stream_processor", ] diff --git a/tests/unit/cron/test_cron_delivery.py b/tests/unit/cron/test_cron_delivery.py index 538dc6aeff..7b8b36ec7d 100644 --- a/tests/unit/cron/test_cron_delivery.py +++ b/tests/unit/cron/test_cron_delivery.py @@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest -from langchain_core.messages import AIMessage, HumanMessage +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage from octop.infra.agents.security.hitl_session import HitlSessionPolicy, HitlSessionPolicyStore from octop.infra.cron.delivery import CronDeliveryCommand, CronDeliveryService @@ -514,6 +514,157 @@ async def _stream(_aid: str, _request: dict): assert gateway.push_session_text.await_args.args[1] == "最终学习内容" +@pytest.mark.parametrize("tool_name", ["current_time", "ask_agent"]) +@pytest.mark.parametrize("token_type", ["token", "delta"]) +@pytest.mark.asyncio +async def test_agent_delivers_only_final_text_except_team_dispatch( + tool_name: str, token_type: str +) -> None: + session = _session(channel_type="weixin") + preamble = "I'll gather the current time. " + final = "晚间中文摘要。" + + async def stream(_aid: str, _request: dict): + yield {"type": token_type, "content": preamble} + yield {"type": "tool_call_chunk", "name": tool_name, "index": 0, "id": "call-1"} + yield { + "type": "tool_result", + "messages": [ToolMessage(content="ok", name=tool_name, tool_call_id="call-1")], + } + yield {"type": token_type, "content": final} + + manager = MagicMock() + manager.stream = stream + manager.get_row.return_value = None + manager.merge_turn_mcp_servers.return_value = None + gateway = MagicMock() + gateway.run_in_session = _run_locked + gateway.require_session.return_value = session + gateway.push_session_text = AsyncMock() + service = CronDeliveryService(gateway=gateway, agent_manager=manager, repos=MagicMock()) + + await service.deliver(_command(task_type="agent")) + + gateway.push_session_text.assert_awaited_once_with( + session, preamble + final if tool_name == "ask_agent" else final, title_source="记得喝水" + ) + + +@pytest.mark.asyncio +async def test_agent_filtered_history_does_not_duplicate_checkpoint_answer(tmp_path: Path) -> None: + db, session = _seed_dashboard_thread(tmp_path, thread_id="thr_filtered") + preamble = "I'll gather the current time. " + final = "晚间中文摘要。" + plan = AIMessage( + id="plan-1", + content=preamble, + tool_calls=[{"name": "current_time", "id": "call-1", "args": {}}], + ) + result = ToolMessage(id="tool-1", content="18:00", name="current_time", tool_call_id="call-1") + answer = AIMessage(id="answer-1", content=final) + + async def stream(_aid: str, request: dict): + human = HumanMessage(id="human-1", content=request["messages"][0].content) + yield {"type": "token", "content": preamble} + yield {"type": "tool_call_chunk", "name": "current_time", "id": "call-1", "index": 0} + yield {"type": "tool_result", "messages": [result]} + yield {"type": "reasoning", "content": "private reasoning"} + yield {"type": "token", "content": final} + yield {"type": "state_snapshot", "data": {"messages": [human, plan, result, answer]}} + yield {"type": "usage", "usage": {"input_tokens": 10, "output_tokens": 5}} + + manager = MagicMock() + manager.stream = stream + manager.get_row.return_value = None + manager.merge_turn_mcp_servers.return_value = None + gateway = MagicMock() + gateway.run_in_session = _run_locked + gateway.require_session.return_value = session + gateway.push_session_text = AsyncMock() + gateway.notify_dashboard_push = AsyncMock() + repos = MagicMock() + repos.user_repo = UserRepo(db) + repos.thread_message_repo = ThreadMessageRepo(db) + service = CronDeliveryService(gateway=gateway, agent_manager=manager, repos=repos) + + try: + await service.deliver(_command(task_type="agent", session_key=session.session_key)) + gateway.push_session_text.assert_awaited_once_with(session, final, title_source="记得喝水") + gateway.notify_dashboard_push.assert_awaited_once_with(session, "a1", final) + rows, _ = repos.thread_message_repo.page(session.thread_id, limit=20) + assert [row.message_id for row in rows] == ["human-1", "plan-1", "tool-1", "answer-1"] + assert plan.content == preamble + assert plan.tool_calls[0]["name"] == "current_time" + assert repos.usage_repo.record.call_args.kwargs["input_tokens"] == 10 + assert repos.usage_repo.record.call_args.kwargs["output_tokens"] == 5 + finally: + db.close() + + +@pytest.mark.parametrize("terminal", ["error", "hitl_required"]) +@pytest.mark.parametrize("after_dispatch", [False, True]) +@pytest.mark.asyncio +async def test_agent_terminal_event_never_pushes_partial_reply( + terminal: str, after_dispatch: bool +) -> None: + session = _session(channel_type="weixin") + closed = False + + async def stream(_aid: str, _request: dict): + nonlocal closed + try: + if after_dispatch: + yield {"type": "token", "content": "dispatch"} + yield {"type": "tool_call_chunk", "name": "ask_agent", "id": "call-1"} + yield { + "type": "tool_result", + "messages": [ + ToolMessage(content="ok", name="ask_agent", tool_call_id="call-1") + ], + } + yield {"type": "token", "content": "unconfirmed pending text"} + yield {"type": terminal, "message": "run failed"} + pytest.fail("terminal event must close the producer") + finally: + closed = True + + manager = MagicMock() + manager.stream = stream + manager.get_row.return_value = None + manager.merge_turn_mcp_servers.return_value = None + gateway = MagicMock() + gateway.run_in_session = _run_locked + gateway.require_session.return_value = session + gateway.push_session_text = AsyncMock() + repos = MagicMock() + service = CronDeliveryService(gateway=gateway, agent_manager=manager, repos=repos) + + with pytest.raises(RuntimeError, match="run failed" if terminal == "error" else "interaction"): + await service.deliver(_command(task_type="agent")) + + assert closed + gateway.push_session_text.assert_not_awaited() + projected = repos.thread_message_repo.append_if_ready.call_args.args[1] + assert all("unconfirmed pending text" not in item.message_json for item in projected) + + +@pytest.mark.asyncio +async def test_text_cron_preserves_literal_process_like_text() -> None: + session = _session(channel_type="weixin") + manager = MagicMock() + gateway = MagicMock() + gateway.run_in_session = _run_locked + gateway.require_session.return_value = session + gateway.push_session_text = AsyncMock() + prompt = "I'll start by checking the time. 这是预设的提醒原文。" + service = CronDeliveryService(gateway=gateway, agent_manager=manager, repos=MagicMock()) + + await service.deliver(_command(task_type="text", prompt=prompt)) + + gateway.push_session_text.assert_awaited_once_with(session, prompt, title_source=prompt) + manager.stream.assert_not_called() + + @pytest.mark.asyncio async def test_delivery_binds_channel_to_latest_conversation(tmp_path: Path) -> None: db = SqlitePool(tmp_path / "octop.db") @@ -877,9 +1028,10 @@ async def _stream(_aid: str, _request: dict): gateway.push_session_text.assert_not_awaited() page, _has_more = ThreadMessageRepo(db).page("thr_fail", limit=10) - assert [row.role for row in page] == ["human", "ai"] + # An interrupted run still records its prompt, but unconfirmed narration + # must not become a synthetic final answer in history. + assert [row.role for row in page] == ["human"] assert "记得喝水" in page[0].message_json - assert "先查一下" in page[1].message_json titled = ThreadRepo(db).get("thr_fail") assert titled is not None assert titled.title == "喝水提醒" diff --git a/tests/unit/gateway/test_response_mode.py b/tests/unit/gateway/test_response_mode.py index 2d23f54091..e7524b407e 100644 --- a/tests/unit/gateway/test_response_mode.py +++ b/tests/unit/gateway/test_response_mode.py @@ -4,8 +4,10 @@ import asyncio from collections.abc import AsyncIterator +from typing import Any import pytest +from langchain_core.messages import ToolMessage from octop_gateway.models import ( FileContent, InboundMessage, @@ -20,11 +22,290 @@ normalize_channel_response_mode, processor_for_response_mode, qq_channel_response_mode, + withhold_pretool_stream_chunks, withhold_weixin_stream_preamble, wrap_weixin_stream_processor, ) +def _raw_call(name: str, index: int = 0, call_id: str = "call-1") -> dict[str, Any]: + return {"type": "tool_call_chunk", "name": name, "index": index, "id": call_id} + + +def _raw_result(name: str | None, call_id: str = "call-1") -> dict[str, Any]: + return { + "type": "tool_result", + "messages": [ToolMessage(content="ok", name=name, tool_call_id=call_id)], + } + + +def _raw_text(text: str) -> dict[str, Any]: + return {"type": "token", "content": text, "node": "agent_main"} + + +@pytest.mark.parametrize( + "chunks,expected", + [ + pytest.param( + [_raw_text("English final"), {"type": "delta", "text": "中文"}], + "English final中文", + id="no-tools", + ), + pytest.param( + [ + _raw_text("progress"), + _raw_call("current_time"), + _raw_result("current_time"), + _raw_text("final"), + ], + "final", + id="ordinary-tool", + ), + pytest.param( + [ + _raw_text("first"), + _raw_call("ls"), + _raw_result("ls"), + _raw_text("second"), + _raw_call("cronjob_list", call_id="call-2"), + _raw_result("cronjob_list", "call-2"), + _raw_text("final"), + ], + "final", + id="successive-tools", + ), + pytest.param( + [ + _raw_text("dispatch"), + _raw_call("ask_agent"), + _raw_result("ask_agent"), + _raw_text("final"), + ], + "dispatchfinal", + id="team-dispatch", + ), + pytest.param( + [ + _raw_text("dispatch"), + _raw_call("ask_"), + _raw_call("agent", call_id=""), + _raw_result(None), + _raw_text("final"), + ], + "dispatchfinal", + id="fragmented-name", + ), + pytest.param( + [ + _raw_text("dispatch"), + _raw_call("ask_"), + _raw_result("ask_agent"), + _raw_text("final"), + ], + "dispatchfinal", + id="result-completes-name", + ), + pytest.param( + [ + _raw_text("progress"), + _raw_call("ask_agent"), + _raw_call("ls", index=1, call_id="call-2"), + _raw_result("ask_agent"), + _raw_result("ls", "call-2"), + _raw_text("final"), + ], + "final", + id="mixed-parallel-tools", + ), + pytest.param( + [ + _raw_text("progress"), + _raw_call("ask_agent"), + _raw_call("ls", index=1, call_id="call-2"), + _raw_result(None, "call-2"), + _raw_result(None), + _raw_text("final"), + ], + "final", + id="parallel-result-ids", + ), + pytest.param( + [_raw_text("progress"), _raw_result("ls"), _raw_text("final")], + "final", + id="result-without-call-chunks", + ), + pytest.param( + [ + _raw_text("dispatch"), + {"type": "tool_result", "name": "ask_agent"}, + _raw_text("final"), + ], + "dispatchfinal", + id="chunk-name-fallback", + ), + pytest.param( + [_raw_text("progress"), {"type": "tool_result"}, _raw_text("final")], + "final", + id="unknown-tool", + ), + pytest.param( + [ + _raw_text("progress"), + _raw_call("ls"), + _raw_result("ls"), + _raw_text("final"), + _raw_result("ls"), + ], + "final", + id="result-replay-after-answer", + ), + pytest.param( + [ + _raw_text("dispatch"), + _raw_call("ask_agent"), + _raw_result("ask_agent"), + _raw_call("ls", call_id="call-2"), + _raw_result("ls", "call-2"), + _raw_text("final"), + ], + "dispatchfinal", + id="preserve-approved-dispatch", + ), + pytest.param([_raw_text("progress"), _raw_call("ls")], "", id="unfinished-tool-call"), + pytest.param( + [ + _raw_text("progress"), + _raw_call("ask_agent"), + _raw_result("ask_agent"), + {"type": "error", "message": "failed"}, + ], + "", + id="error-clears-pending-dispatch", + ), + pytest.param( + [_raw_text("progress"), {"type": "hitl_required", "request": {}}], + "", + id="hitl-clears-pending", + ), + pytest.param( + [ + _raw_text("progress"), + _raw_call("ask_agent"), + { + "type": "tool_result", + "messages": [ + {"role": "tool", "name": "ls", "tool_call_id": "historical"}, + {"role": "tool", "name": "ask_agent", "tool_call_id": "call-1"}, + ], + }, + _raw_text("final"), + ], + "progressfinal", + id="history-replay-alongside-live-result", + ), + pytest.param( + [ + _raw_text("dispatch"), + {"type": "tool_call_chunk", "id": "call-1", "name": "ask_"}, + {"type": "tool_call_chunk", "id": "call-1", "name": "agent"}, + _raw_result(None), + _raw_text("final"), + ], + "dispatchfinal", + id="id-without-index", + ), + ], +) +@pytest.mark.asyncio +async def test_raw_stream_withholds_each_pretool_segment( + chunks: list[dict[str, Any]], expected: str +) -> None: + async def stream(): + for chunk in chunks: + yield chunk + + output = [chunk async for chunk in withhold_pretool_stream_chunks(stream())] + + assert ( + "".join( + str(c.get("content") or c.get("text") or "") + for c in output + if c["type"] in {"token", "delta"} + ) + == expected + ) + original_control = [c for c in chunks if c["type"] not in {"token", "delta"}] + output_control = [c for c in output if c["type"] not in {"token", "delta"}] + assert len(output_control) == len(original_control) + assert all(a is b for a, b in zip(output_control, original_control, strict=True)) + + +@pytest.mark.parametrize("terminal", ["error", "hitl_required", "cancel"]) +@pytest.mark.asyncio +async def test_raw_preamble_filter_closes_source(terminal: str) -> None: + closed = False + + async def stream(): + nonlocal closed + try: + yield _raw_text("pending") + yield {"type": terminal} + await asyncio.Event().wait() + finally: + closed = True + + filtered = withhold_pretool_stream_chunks(stream()) + assert (await anext(filtered))["type"] == terminal + await close_event_stream(filtered) + assert closed + + +@pytest.mark.asyncio +async def test_raw_preamble_filter_resolves_name_without_streamed_call_id() -> None: + async def stream(): + yield _raw_text("dispatch") + yield _raw_call("ask_", call_id="") + yield _raw_result("ask_agent") + yield _raw_text("final") + + output = [c async for c in withhold_pretool_stream_chunks(stream())] + assert [c["content"] for c in output if c["type"] == "token"] == ["dispatch", "final"] + + +@pytest.mark.asyncio +async def test_raw_preamble_filter_keeps_parallel_team_dispatch() -> None: + async def stream(): + yield _raw_text("dispatch") + yield _raw_call("ask_", call_id="call-1") + yield _raw_call("ask_", index=1, call_id="call-2") + yield _raw_call("agent", call_id="") + yield _raw_call("agent", index=1, call_id="") + yield _raw_result(None, "call-2") + yield _raw_result(None, "call-1") + yield _raw_text("final") + + output = [c async for c in withhold_pretool_stream_chunks(stream())] + assert [c["content"] for c in output if c["type"] == "token"] == ["dispatch", "final"] + + +@pytest.mark.asyncio +async def test_raw_preamble_filter_passes_usage_reasoning_and_state_unchanged() -> None: + control = [ + {"type": "usage", "usage": {"output_tokens": 10}}, + {"type": "reasoning", "content": "private"}, + {"type": "state_snapshot", "data": {"messages": []}}, + ] + + async def stream(): + yield _raw_text("answer") + for chunk in control: + yield chunk + + output = [chunk async for chunk in withhold_pretool_stream_chunks(stream())] + assert output[:-1] == control + assert output[-1]["content"] == "answer" + + async def _events(*events: MessageEvent) -> AsyncIterator[MessageEvent]: for event in events: yield event