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): 只在补刀仍可能发生时挂起外层正文
n993577028d7da1e9e63ec
diff --git a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.pyindex 407f62d32f..41760abf04 100644--- a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py@@ -1557,9 +1557,20 @@ class TaskExecutionRail(DeepAgentRail):return Trueasync def _arm_todo_close_text_hold(self, ctx: AgentCallbackContext) -> None:- """Ask the adapter to buffer this call's outer text until we decide."""+ """Ask the adapter to buffer this call's outer text until we decide.++ Only arm while this call can still be discarded. After the nudge has+ been used, or on the last ReAct iteration, the text will be kept, so+ it should stream token by token. ``finish_reason=length`` is not+ known until the call returns, so a truncated turn is still held and+ released afterwards.+ """if self._todo_close_hold_pending or ctx.session is None:return+ if self._todo_close_nudge_used:+ return+ if self._is_last_react_iteration(ctx):+ returnif not self._started_in_progress_tasks():returnwrote = await self._write_todo_close_control(@@ -1574,15 +1585,24 @@ class TaskExecutionRail(DeepAgentRail):*,dropped: bool,) -> None:- """Drop already told the adapter to discard. Otherwise release."""+ """Drop already told the adapter to discard. Otherwise release.++ A failed release keeps the pending flag. The next model call must not+ send another hold: that frame would drop the text still sitting in the+ adapter. A later successful release flushes it. A failed drop still+ clears the flag so the next hold discards the buffer; releasing on+ that failure would put the discarded draft into the open task segment.+ """if not self._todo_close_hold_pending:return- self._todo_close_hold_pending = Falseif dropped or ctx.session is None:+ self._todo_close_hold_pending = Falsereturn- await self._write_todo_close_control(+ wrote = await self._write_todo_close_control(ctx.session, TODO_CLOSE_RELEASE_STREAM_TYPE,)+ if wrote:+ self._todo_close_hold_pending = Falseasync def _write_todo_close_control(self, session: Any, stream_type: str) -> bool:try:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex b0073ed4c3..dcc581e916 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -21321,8 +21321,12 @@ class JiuWenSwarmDeepAdapter:if _skip:continue# First chunk handed back by the runner: records the time to- # first token for this round.- if not first_chunk_seen:+ # first token for this round. Hold/drop/release are internal+ # and are written before the model streams, so they must not+ # count as the first token.+ if not first_chunk_seen and not is_todo_close_control(+ str(getattr(chunk, "type", "") or "")+ ):first_chunk_seen = Trueserver_logger.info("[AgentServer] runner streaming first chunk: session_id=%s request_id=%s"@@ -21402,15 +21406,18 @@ class JiuWenSwarmDeepAdapter:continuechunk_type = chunk.type- control = todo_close_hold.on_control(chunk_type)- if control == "arm" or control == "drop":+ foreign_output = False+ if chunk_type == "llm_output":+ foreign_output = _is_foreign_stream_source(chunk.payload)+ close_action = todo_close_hold.decide(+ chunk_type, foreign=foreign_output,+ )+ if close_action == "skip":continue- if control == "release" or todo_close_hold.should_flush_for(chunk_type):- if control != "release":- todo_close_hold.disarm()+ if close_action in ("flush_skip", "flush_pass"):for held_chunk in _take_todo_close_chunks():yield held_chunk- if control == "release":+ if close_action == "flush_skip":continueif chunk_type == "llm_usage":logger.info(f"[JiuWenSwarmDeepAdapter] llm_usage chunk: {chunk}")@@ -21493,9 +21500,7 @@ class JiuWenSwarmDeepAdapter:is_complete=False,)accumulated_reasoning = ""- if todo_close_hold.should_buffer(- _is_foreign_stream_source(chunk.payload)- ):+ if close_action == "buffer":todo_close_hold.push(delta_payload)continuehas_streamed_content = Truediff --git a/jiuwenswarm/server/runtime/agent_adapter/todo_close_text_hold.py b/jiuwenswarm/server/runtime/agent_adapter/todo_close_text_hold.pyindex 2197b77ea8..c5118a5706 100644--- a/jiuwenswarm/server/runtime/agent_adapter/todo_close_text_hold.py+++ b/jiuwenswarm/server/runtime/agent_adapter/todo_close_text_hold.py@@ -44,6 +44,28 @@ class TodoCloseTextHold:self.armed = Falseself._payloads: list[dict[str, Any]] = []+ def decide(self, chunk_type: str, *, foreign: bool = False) -> str:+ """What the adapter should do with this chunk.++ ``skip``: control frame already applied, do not forward.+ ``flush_skip``: release; emit the buffer and do not forward the frame.+ ``flush_pass``: a commit frame arrived before release; emit the buffer,+ then process this frame.+ ``buffer``: outer ``llm_output`` while armed.+ ``pass``: forward immediately, including child streams.+ """+ control = self.on_control(chunk_type)+ if control in ("arm", "drop"):+ return "skip"+ if control == "release":+ return "flush_skip"+ if self.should_flush_for(chunk_type):+ self.disarm()+ return "flush_pass"+ if chunk_type == "llm_output" and self.should_buffer(foreign):+ return "buffer"+ return "pass"+def on_control(self, chunk_type: str) -> str:"""Apply a control frame.diff --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 4bbc59db2b..359f837e5f 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@@ -79,6 +79,12 @@ async def test_text_only_ending_attaches_one_todo_close_nudge() -> None:await rail.after_model_call(ctx)assert len(ctx.inputs.response.tool_calls) == 1+ ctx.session.events.clear()+ follow = _text_ctx("补刀已经用过,这段应该直接流式发出。")+ follow.session = ctx.session+ await rail.before_model_call(follow)+ assert ctx.session.events == []+@pytest.mark.asyncioasync def test_truncated_text_does_not_attach_nudge() -> None:@@ -106,10 +112,12 @@ async def test_last_react_iteration_does_not_attach_nudge() -> None:ctx = _text_ctx("最后一轮正文")ctx.inputs.react_iteration = 15+ await rail.before_model_call(ctx)await rail.after_model_call(ctx)assert ctx.inputs.response.tool_calls == []assert rail._todo_close_nudge_used is False+ assert ctx.session.events == []@pytest.mark.asyncio@@ -128,6 +136,55 @@ async def test_text_only_ending_keeps_real_tool_calls() -> None:assert ctx.session.events == ["todo_close_hold", "todo_close_release"]+class _ReleaseFails(_FakeSession):+ async def write_stream(self, schema: object) -> None:+ if str(getattr(schema, "type", "")) == "todo_close_release":+ raise RuntimeError("stream down")+ await super().write_stream(schema)+++class _DropFails(_FakeSession):+ async def write_stream(self, schema: object) -> None:+ if str(getattr(schema, "type", "")) == "todo_close_drop":+ raise RuntimeError("stream down")+ await super().write_stream(schema)+++async def test_failed_release_keeps_hold_pending() -> None:+ rail = _rail_with_open_task()+ session = _ReleaseFails()+ existing = ToolCall(+ id="call-1", type="function", name="read_file", arguments="{}",+ )+ ctx = _text_ctx("进度说明", tool_calls=[existing])+ ctx.session = session++ await rail.before_model_call(ctx)+ await rail.after_model_call(ctx)++ assert rail._todo_close_hold_pending is True+ assert session.events == ["todo_close_hold"]++ await rail.before_model_call(ctx)+ assert session.events == ["todo_close_hold"]+++async def test_failed_drop_does_not_release() -> None:+ rail = _rail_with_open_task()+ session = _DropFails()+ ctx = _text_ctx("这段应该作废。")+ ctx.session = session++ await rail.before_model_call(ctx)+ await rail.after_model_call(ctx)++ assert rail._todo_close_nudge_used is True+ assert rail._todo_close_hold_pending is False+ assert session.events == ["todo_close_hold"]++@pytest.mark.asyncioasync def test_text_only_ending_skipped_without_open_task() -> None:rail = TaskExecutionRail()diff --git a/tests/unit_tests/agentserver/test_todo_close_text_hold.py b/tests/unit_tests/agentserver/test_todo_close_text_hold.pyindex f7c67b0f93..c2e765c063 100644--- a/tests/unit_tests/agentserver/test_todo_close_text_hold.py+++ b/tests/unit_tests/agentserver/test_todo_close_text_hold.py@@ -49,6 +49,72 @@ def test_second_hold_discards_unreleased_text() -> None:assert hold.armed is True+def _replay(chunks: list[tuple[str, str, bool]]) -> list[str]:+ """Apply the adapter's decide() and return forwarded delta texts."""+ hold = TodoCloseTextHold()+ forwarded: list[str] = []++ def _flush() -> None:+ forwarded.extend(+ str(payload.get("content") or "") for payload in hold.take()+ )++ for chunk_type, content, foreign in chunks:+ action = hold.decide(chunk_type, foreign=foreign)+ if action == "skip":+ continue+ if action in ("flush_skip", "flush_pass"):+ _flush()+ if action == "flush_skip":+ continue+ if action == "buffer":+ hold.push({"event_type": "chat.delta", "content": content})+ continue+ if chunk_type == "llm_output":+ forwarded.append(content)+ _flush()+ return forwarded+++def test_drop_sequence_does_not_forward_text() -> None:+ forwarded = _replay([+ ("todo_close_hold", "", False),+ ("llm_output", "草稿", False),+ ("llm_output", "还在写", False),+ ("todo_close_drop", "", False),+ ])+ assert forwarded == []+++def test_release_sequence_forwards_text_once_and_answer_is_deduped() -> None:+ forwarded = _replay([+ ("todo_close_hold", "", False),+ ("llm_output", "留下的进度", False),+ ("todo_close_release", "", False),+ ])+ assert forwarded == ["留下的进度"]+ answer = OutputSchema(+ type="answer",+ index=0,+ payload={"output": {"output": "留下的进度"}},+ )+ parsed = JiuWenSwarmDeepAdapter._parse_stream_chunk(+ answer,+ _has_streamed_content=True,+ _streamed_text="留下的进度",+ )+ assert parsed == {"event_type": "chat.final", "content": ""}+++def test_foreign_llm_output_is_not_buffered() -> None:+ forwarded = _replay([+ ("todo_close_hold", "", False),+ ("llm_output", "子流正文", True),+ ("todo_close_drop", "", False),+ ])+ assert forwarded == ["子流正文"]++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"}),