JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(todo): 未关闭任务段上的模型正文先挂起,作废再丢
n993577028bfb9f1f055fa
diff --git a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.pyindex 83d10d9bf6..407f62d32f 100644--- a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py@@ -40,9 +40,15 @@ from jiuwenswarm.agents.harness.common.tools.todo_resume import (remember_turn_user_query,snapshot_includes_persistent_todos,)-from jiuwenswarm.common.tool_display import build_tool_display_name+from jiuwenswarm.common.todo_generation import todo_item_generation_tokenfrom jiuwenswarm.common.todo_snapshot import overlay_serial_todo_statuses+from jiuwenswarm.common.tool_display import build_tool_display_namefrom jiuwenswarm.common.utils import logger+from jiuwenswarm.server.runtime.agent_adapter.todo_close_text_hold import (+ TODO_CLOSE_DROP_STREAM_TYPE,+ TODO_CLOSE_HOLD_STREAM_TYPE,+ TODO_CLOSE_RELEASE_STREAM_TYPE,+)_ACTIVE_TASK_ID: ContextVar[str | None] = ContextVar("active_task_id", default=None@@ -1372,6 +1378,8 @@ class TaskExecutionRail(DeepAgentRail):# 同一次 invoke 只拦一次纯文本收尾。模型仍不改状态就放行,# 不伪造 completed,也不把未完成项全部 cancelled。self._todo_close_nudge_used: bool = False+ # 本轮模型调用已经通知适配器挂起外层正文。after 必须 drop 或 release。+ self._todo_close_hold_pending: bool = Falsedef set_skill_turbo_request_metadata(self, metadata: dict | None) -> None:"""注入当前请求 metadata 副本,供 before_tool_call 解析请求级工作区。"""@@ -1458,6 +1466,7 @@ class TaskExecutionRail(DeepAgentRail):self._todo_complete_deferred = set()self._todo_start_deferred = set()self._todo_close_nudge_used = False+ self._todo_close_hold_pending = Falseself._tool_start_times = {}_ACTIVE_TASK_ID.set(None)if isinstance(ctx.inputs, InvokeInputs):@@ -1479,6 +1488,7 @@ class TaskExecutionRail(DeepAgentRail):async def before_model_call(self, ctx: AgentCallbackContext) -> None:"""Bind task_id before LLM calls."""self._bind_context_to_in_progress_task()+ await self._arm_todo_close_text_hold(ctx)async def after_model_call(self, ctx: AgentCallbackContext) -> None:"""Hold a text-only ending while a started todo is still in_progress.@@ -1490,6 +1500,11 @@ class TaskExecutionRail(DeepAgentRail):is replaced with an instruction to call todo_modify. A secondtext-only response in the same invoke is left alone.+ ``llm_output`` is already on the session stream by the time this+ hook runs. ``before_model_call`` asks the adapter to hold that text+ when a started todo is open; attaching the nudge drops it, and every+ other ending releases it.+Not applied when the model output was truncated (``finish_reason````length``): the truncation retry persists this assistant messagewithout a matching tool result. Not applied on the last ReAct@@ -1497,22 +1512,34 @@ class TaskExecutionRail(DeepAgentRail):paths (deepresearch direct display and similar) never reach thishook and stay on their existing end behavior."""+ dropped = False+ try:+ dropped = self._attach_todo_close_nudge(ctx)+ if dropped and self._todo_close_hold_pending:+ await self._write_todo_close_control(+ ctx.session, TODO_CLOSE_DROP_STREAM_TYPE,+ )+ finally:+ await self._finish_todo_close_text_hold(ctx, dropped=dropped)++ def _attach_todo_close_nudge(self, ctx: AgentCallbackContext) -> bool:+ """Replace one text-only ending with the internal todo_modify call."""if self._todo_close_nudge_used or ctx.session is None:- return+ return Falseresponse = getattr(ctx.inputs, "response", None)if response is None or getattr(response, "tool_calls", None):- return+ return Falseif str(getattr(response, "finish_reason", "") or "") == "length":- return+ return Falseif self._is_last_react_iteration(ctx):- return+ return Falsecontent = str(getattr(response, "content", None) or "").strip()if not content:- return+ return Falseopen_tasks = self._started_in_progress_tasks()if not open_tasks:- return- # 流式正文已经推给前端。历史里留下这段字会让下一轮当成已经送达。+ return False+ # 历史里留下这段字会让下一轮当成已经送达。适配器还没下发挂起的流式块。response.content = ""response.tool_calls = [ToolCall(@@ -1527,6 +1554,53 @@ class TaskExecutionRail(DeepAgentRail):"[TaskExecutionRail] todo close nudge: open=%s",[raw_id for raw_id, _task in open_tasks],)+ return True++ async def _arm_todo_close_text_hold(self, ctx: AgentCallbackContext) -> None:+ """Ask the adapter to buffer this call's outer text until we decide."""+ if self._todo_close_hold_pending or ctx.session is None:+ return+ if not self._started_in_progress_tasks():+ return+ wrote = await self._write_todo_close_control(+ ctx.session, TODO_CLOSE_HOLD_STREAM_TYPE,+ )+ if wrote:+ self._todo_close_hold_pending = True++ async def _finish_todo_close_text_hold(+ self,+ ctx: AgentCallbackContext,+ *,+ dropped: bool,+ ) -> None:+ """Drop already told the adapter to discard. Otherwise release."""+ if not self._todo_close_hold_pending:+ return+ self._todo_close_hold_pending = False+ if dropped or ctx.session is None:+ return+ await self._write_todo_close_control(+ ctx.session, TODO_CLOSE_RELEASE_STREAM_TYPE,+ )++ async def _write_todo_close_control(self, session: Any, stream_type: str) -> bool:+ try:+ await session.write_stream(+ OutputSchema(+ type=stream_type,+ index=0,+ payload={"result_type": "control"},+ )+ )+ except Exception:+ logger.warning(+ "[TaskExecutionRail] todo close control %s failed",+ stream_type,+ exc_info=True,+ )+ return False+ return Truedef _is_last_react_iteration(self, ctx: AgentCallbackContext) -> bool:"""True when this model call is the final ReAct iteration."""@@ -1548,7 +1622,9 @@ class TaskExecutionRail(DeepAgentRail):resume clears ``_todo_started`` / ``_active_tasks`` in``before_invoke``, while ``todo.json`` and the already-open frontendsegment remain. Fall back to in-progress rows on disk so a text-only- resume still gets the nudge.+ resume still gets the nudge. Unstamped legacy rows+ (``generation_token`` missing) are not this turn's work and are+ skipped."""found: list[tuple[str, dict[str, Any]]] = []seen: set[str] = set()@@ -1570,6 +1646,8 @@ class TaskExecutionRail(DeepAgentRail):continueif str(task.get("status", "")).lower() != "in_progress":continue+ if todo_item_generation_token(task) is None:+ continuefound.append((raw_id, task))return founddiff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 4fb86726e9..b0073ed4c3 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -129,6 +129,10 @@ from jiuwenswarm.server.runtime.agent_adapter.statusline_setup_agent import (STATUSLINE_SETUP_AGENT_TYPE,build_statusline_setup_agent_config,)+from jiuwenswarm.server.runtime.agent_adapter.todo_close_text_hold import (+ TodoCloseTextHold,+ is_todo_close_control,+)from jiuwenswarm.agents.harness.common.tools.deepresearch import (get_deepresearch_tools,@@ -21255,6 +21259,35 @@ class JiuWenSwarmDeepAdapter:# has either handed the message over or attached to a running round.runner_stream_started_at = time.monotonic()first_chunk_seen = False+ todo_close_hold = TodoCloseTextHold()++ def _take_todo_close_chunks() -> list[AgentResponseChunk]:+ """下发挂起的外层正文。drop 过的块不在这里。"""+ nonlocal emitted_terminal_chat_final, has_streamed_content+ payloads = todo_close_hold.take()+ if not payloads:+ return []+ chunks: list[AgentResponseChunk] = []+ boundary = self._begin_visible_chat_content(+ stream_is_user_originated+ )+ if boundary is not None:+ chunks.append(AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=note_chat_payload(boundary),+ is_complete=False,+ ))+ emitted_terminal_chat_final = False+ for payload in payloads:+ chunks.append(AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=note_chat_payload(payload),+ is_complete=False,+ ))+ has_streamed_content = True+ return chunks# A plain user-chat consumer stream (not a command.goal / attach-goal# stream). Only these may be hijacked by a goal round before the user# round produces its first visible token; used to allow a bubble@@ -21369,6 +21402,16 @@ class JiuWenSwarmDeepAdapter:continuechunk_type = chunk.type+ control = todo_close_hold.on_control(chunk_type)+ if control == "arm" or control == "drop":+ continue+ if control == "release" or todo_close_hold.should_flush_for(chunk_type):+ if control != "release":+ todo_close_hold.disarm()+ for held_chunk in _take_todo_close_chunks():+ yield held_chunk+ if control == "release":+ continueif chunk_type == "llm_usage":logger.info(f"[JiuWenSwarmDeepAdapter] llm_usage chunk: {chunk}")usage_meta = (@@ -21439,7 +21482,6 @@ class JiuWenSwarmDeepAdapter:if delta_payload is None:continue_propagate_stream_source_id(chunk.payload, delta_payload)- has_streamed_content = Trueif accumulated_reasoning:yield AgentResponseChunk(request_id=rid,@@ -21451,6 +21493,12 @@ class JiuWenSwarmDeepAdapter:is_complete=False,)accumulated_reasoning = ""+ if todo_close_hold.should_buffer(+ _is_foreign_stream_source(chunk.payload)+ ):+ todo_close_hold.push(delta_payload)+ continue+ has_streamed_content = Trueboundary = self._begin_visible_chat_content(stream_is_user_originated)if boundary is not None:yield AgentResponseChunk(@@ -21666,6 +21714,9 @@ class JiuWenSwarmDeepAdapter:# ask_user 暂停中为 True 跳过;in-place 续跑后为 False 放行(此时# 轮次已正常完成/取消,flush 与合成 final 必须发出,否则前端悬挂)。# hitl_pending_stream 只反映"本轮出过 ask_user 卡片",不随续跑复位。+ if not suppress_stream_after_hitl:+ for held_chunk in _take_todo_close_chunks():+ yield held_chunkif accumulated_text and not suppress_stream_after_hitl:# Same rule as _adapt_goal_intermediate_final: demote host# flush only when the flushed text belonged to a goal round.@@ -22542,6 +22593,9 @@ class JiuWenSwarmDeepAdapter:chunk_type = chunk.typepayload = chunk.payload+ if is_todo_close_control(chunk_type):+ return None+if chunk_type == "steering_consumed":# Only the root/leader receipt may divide the user's main# conversation. A member's private input is not root input.diff --git a/jiuwenswarm/server/runtime/agent_adapter/todo_close_text_hold.py b/jiuwenswarm/server/runtime/agent_adapter/todo_close_text_hold.pynew file mode 100644index 0000000000..2197b77ea8--- /dev/null+++ b/jiuwenswarm/server/runtime/agent_adapter/todo_close_text_hold.py@@ -0,0 +1,95 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Hold outer-model chat text while a started todo is still open.++``llm_output`` is written to the session stream before ``after_model_call``.+When that hook replaces the turn with the todo-close nudge, those chunks+must not be forwarded: the frontend would keep them inside the open task+segment. The rail emits hold / drop / release around the model call; this+buffer is what the adapter applies.+"""++from __future__ import annotations++from typing import Any++from jiuwenswarm.common.utils import logger++TODO_CLOSE_HOLD_STREAM_TYPE = "todo_close_hold"+TODO_CLOSE_DROP_STREAM_TYPE = "todo_close_drop"+TODO_CLOSE_RELEASE_STREAM_TYPE = "todo_close_release"++# 这些帧说明本轮模型输出已经定案,挂起的正文可以下发。+# 补刀作废走 drop,不会落到这里。+TODO_CLOSE_COMMIT_CHUNK_TYPES = frozenset({+ "tool_call",+ "answer",+ "task.complete",+})+++def is_todo_close_control(chunk_type: str) -> bool:+ """True for the rail's hold / drop / release frames."""+ return chunk_type in (+ TODO_CLOSE_HOLD_STREAM_TYPE,+ TODO_CLOSE_DROP_STREAM_TYPE,+ TODO_CLOSE_RELEASE_STREAM_TYPE,+ )+++class TodoCloseTextHold:+ """Buffer one model call's outer chat deltas until the rail decides."""++ def __init__(self) -> None:+ self.armed = False+ self._payloads: list[dict[str, Any]] = []++ def on_control(self, chunk_type: str) -> str:+ """Apply a control frame.++ Returns ``arm``, ``drop``, ``release``, or ``""``.+ A second hold drops whatever the previous call never released.+ """+ if chunk_type == TODO_CLOSE_HOLD_STREAM_TYPE:+ self._replace_hold()+ return "arm"+ if chunk_type == TODO_CLOSE_DROP_STREAM_TYPE:+ self._payloads.clear()+ self.armed = False+ return "drop"+ if chunk_type == TODO_CLOSE_RELEASE_STREAM_TYPE:+ self.armed = False+ return "release"+ return ""++ def should_buffer(self, foreign: bool) -> bool:+ """Outer-model text is held. Child streams keep flowing."""+ if foreign:+ return False+ return self.armed++ def push(self, payload: dict[str, Any]) -> None:+ self._payloads.append(payload)++ def should_flush_for(self, chunk_type: str) -> bool:+ """Commit frames flush text when the release frame was missed."""+ if chunk_type not in TODO_CLOSE_COMMIT_CHUNK_TYPES:+ return False+ return bool(self._payloads)++ def disarm(self) -> None:+ self.armed = False++ def take(self) -> list[dict[str, Any]]:+ payloads = self._payloads+ self._payloads = []+ return payloads++ def _replace_hold(self) -> None:+ if self._payloads:+ logger.warning(+ "[TodoCloseTextHold] replaced %d unreleased chat payload(s)",+ len(self._payloads),+ )+ self._payloads.clear()+ self.armed = Truediff --git a/tests/unit_tests/agentserver/rails/test_task_execution_todo_close_nudge.py b/tests/unit_tests/agentserver/rails/test_task_execution_todo_close_nudge.pyindex 14c6ed4bf9..4bbc59db2b 100644--- a/tests/unit_tests/agentserver/rails/test_task_execution_todo_close_nudge.py+++ b/tests/unit_tests/agentserver/rails/test_task_execution_todo_close_nudge.py@@ -22,11 +22,14 @@ from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (class _FakeSession:+ def __init__(self) -> None:+ self.events: list[str] = []+def get_session_id(self) -> str:return "sess-1"async def write_stream(self, schema: object) -> None:- return None+ self.events.append(str(getattr(schema, "type", "")))def _rail_with_open_task() -> TaskExecutionRail:@@ -62,6 +65,7 @@ async def test_text_only_ending_attaches_one_todo_close_nudge() -> None:rail = _rail_with_open_task()ctx = _text_ctx("流程在此暂停,请上传源文件。")+ await rail.before_model_call(ctx)await rail.after_model_call(ctx)calls = ctx.inputs.response.tool_callsassert len(calls) == 1@@ -69,6 +73,8 @@ async def test_text_only_ending_attaches_one_todo_close_nudge() -> None:assert str(calls[0].id).startswith(TODO_CLOSE_NUDGE_ID_PREFIX)assert ctx.inputs.response.content == ""assert rail._todo_close_nudge_used is True+ assert ctx.session.events == ["todo_close_hold", "todo_close_drop"]+ assert rail._todo_close_hold_pending is Falseawait rail.after_model_call(ctx)assert len(ctx.inputs.response.tool_calls) == 1@@ -80,11 +86,13 @@ async def test_truncated_text_does_not_attach_nudge() -> None:ctx = _text_ctx("正文被截断")ctx.inputs.response.finish_reason = "length"+ await rail.before_model_call(ctx)await rail.after_model_call(ctx)assert ctx.inputs.response.tool_calls == []assert ctx.inputs.response.content == "正文被截断"assert rail._todo_close_nudge_used is False+ assert ctx.session.events == ["todo_close_hold", "todo_close_release"]@pytest.mark.asyncio@@ -112,10 +120,12 @@ async def test_text_only_ending_keeps_real_tool_calls() -> None:)ctx = _text_ctx("同时改状态", tool_calls=[existing])+ await rail.before_model_call(ctx)await rail.after_model_call(ctx)assert ctx.inputs.response.tool_calls == [existing]assert rail._todo_close_nudge_used is False+ assert ctx.session.events == ["todo_close_hold", "todo_close_release"]@pytest.mark.asyncio@@ -238,13 +248,14 @@ async def test_stream_rail_does_not_emit_todo_close_nudge(monkeypatch) -> None:@pytest.mark.asyncio-async def test_text_only_resume_nudges_disk_in_progress_without_memory() -> None:+async def test_text_only_resume_nudges_stamped_disk_in_progress() -> None:rail = TaskExecutionRail()rail._todo_map = {"env": {"id": "env","content": "环境预检","status": "in_progress",+ "generation_token": "gen-1",},}ctx = _text_ctx("问答之后直接说明卡点。")@@ -256,12 +267,39 @@ async def test_text_only_resume_nudges_disk_in_progress_without_memory() -> Noneassert str(calls[0].id).startswith(TODO_CLOSE_NUDGE_ID_PREFIX)+async def test_unstamped_legacy_in_progress_does_not_nudge() -> None:+ rail = TaskExecutionRail()+ rail._todo_map = {+ "legacy": {+ "id": "legacy",+ "content": "上一问留下的步骤",+ "status": "in_progress",+ },+ "current": {+ "id": "current",+ "content": "这一问的步骤",+ "status": "pending",+ "generation_token": "gen-1",+ },+ }+ ctx = _text_ctx("新问题直接回答。")++ await rail.before_model_call(ctx)+ await rail.after_model_call(ctx)++ assert ctx.inputs.response.tool_calls == []+ assert ctx.session.events == []++@pytest.mark.asyncioasync def test_before_invoke_resets_nudge_budget() -> None:rail = _rail_with_open_task()rail._todo_close_nudge_used = True+ rail._todo_close_hold_pending = Truectx = SimpleNamespace(session=None, inputs=object(), extra={})await rail.before_invoke(ctx)assert rail._todo_close_nudge_used is False+ assert rail._todo_close_hold_pending is Falsediff --git a/tests/unit_tests/agentserver/test_todo_close_text_hold.py b/tests/unit_tests/agentserver/test_todo_close_text_hold.pynew file mode 100644index 0000000000..f7c67b0f93--- /dev/null+++ b/tests/unit_tests/agentserver/test_todo_close_text_hold.py@@ -0,0 +1,56 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from openjiuwen.core.session.stream import OutputSchema++from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+)+from jiuwenswarm.server.runtime.agent_adapter.todo_close_text_hold import (+ TodoCloseTextHold,+)+++def test_hold_drops_text_and_release_returns_it() -> None:+ hold = TodoCloseTextHold()+ dropped = OutputSchema(type="todo_close_drop", index=0, payload={})+ released = OutputSchema(type="todo_close_release", index=0, payload={})++ assert hold.on_control("todo_close_hold") == "arm"+ assert hold.should_buffer(False) is True+ assert hold.should_buffer(True) is False+ hold.push({"event_type": "chat.delta", "content": "草稿"})+ assert hold.on_control(dropped.type) == "drop"+ assert hold.take() == []+ assert hold.should_buffer(False) is False++ assert hold.on_control("todo_close_hold") == "arm"+ hold.push({"event_type": "chat.delta", "content": "留下"})+ assert hold.on_control(released.type) == "release"+ assert hold.take() == [{"event_type": "chat.delta", "content": "留下"}]+++def test_commit_frame_flushes_when_release_was_missed() -> None:+ hold = TodoCloseTextHold()+ hold.on_control("todo_close_hold")+ hold.push({"event_type": "chat.delta", "content": "进度"})+ assert hold.should_flush_for("llm_usage") is False+ assert hold.should_flush_for("tool_call") is True+ hold.disarm()+ assert hold.take() == [{"event_type": "chat.delta", "content": "进度"}]+ assert hold.should_buffer(False) is False+++def test_second_hold_discards_unreleased_text() -> None:+ hold = TodoCloseTextHold()+ hold.on_control("todo_close_hold")+ hold.push({"event_type": "chat.delta", "content": "作废"})+ assert hold.on_control("todo_close_hold") == "arm"+ assert hold.take() == []+ assert hold.armed is True+++def test_parse_stream_chunk_drops_todo_close_control() -> None:+ parsed = JiuWenSwarmDeepAdapter._parse_stream_chunk(+ OutputSchema(type="todo_close_drop", index=0, payload={"result_type": "control"}),+ )+ assert parsed is None