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(goal): keep user-round chat.final; demote only in-flight goal attempts
wncbdj769563f2f4c2
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 82d6ad9412..b2169ede29 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -802,6 +802,10 @@ class JiuWenSwarmDeepAdapter:# (e.g., supplement while previous task still winding down) don't# prematurely remove the entry when the first task finishes.self._active_session_ids: Counter[str] = Counter()+ # Provenance of assistant text currently forwarded on the shared+ # interaction stream. A late user-round chat.final must not be demoted+ # just because a goal round already became active.+ self._stream_content_run_kind: str | None = None# In-flight asyncio tasks per session (stream/non-stream agent runs).self._session_agent_tasks: dict[str, set[asyncio.Task[Any]]] = {}self._task_planning_rail: TaskPlanningRail | None = None@@ -5662,22 +5666,88 @@ class JiuWenSwarmDeepAdapter:return Truereturn self._goal_record_is_active()+ def _should_demote_goal_intermediate_final(self) -> bool:+ """Whether an attempt-boundary ``chat.final`` must become intermediate.++ Demote only when GoalRecord is still ACTIVE **and** the text being+ closed belonged to a **goal** round.++ Prefer ``_stream_content_run_kind`` (stamped while forwarding deltas)+ over the live ``active_round``: a user-round final can still be in the+ queue after the scheduler has already started the next goal round.+ Falling back to ``_has_active_goal_round()`` covers goal attempts that+ emit a final with no prior delta on this consumer.+ """+ if not self._goal_record_is_active():+ return False+ content_kind = self._stream_content_run_kind+ if content_kind is not None:+ return content_kind == "goal"+ return self._has_active_goal_round()++ def _current_interaction_run_kind(self) -> str | None:+ if self._instance is None or not self._instance_interaction_started():+ return None+ active = self._instance.active_round+ if active is None:+ return None+ kind = getattr(active, "run_kind", None)+ if kind is None:+ return None+ return str(getattr(kind, "value", kind))++ def _begin_visible_chat_content(self) -> dict[str, Any] | None:+ """Stamp content provenance; inject a bubble-split final on user→goal.++ When the shared stream switches from user-round text to goal-round text+ without a terminal ``chat.final`` in between, emit an empty final so the+ frontend can ``stopStreaming`` and open a new bubble.+ """+ kind = self._current_interaction_run_kind()+ prev = self._stream_content_run_kind+ boundary: dict[str, Any] | None = None+ if prev == "user" and kind == "goal":+ boundary = {"event_type": "chat.final", "content": ""}+ self._stream_content_run_kind = None+ if kind is not None:+ self._stream_content_run_kind = kind+ return boundary+def _adapt_goal_intermediate_final(self, parsed: dict | None) -> dict | None:if not isinstance(parsed, dict):return parsedif parsed.get("event_type") != "chat.final":return parsed- # Demote only while the GoalRecord remains ACTIVE. Do not key off an- # in-flight goal round: user cancel pauses the record first, then- # aborts the round — finals during unwind must stay terminal so the- # frontend can close the dialog.- if not self._goal_record_is_active():+ if not self._should_demote_goal_intermediate_final():return parsedadapted = dict(parsed)adapted["event_type"] = "chat.delta"adapted["goal_intermediate"] = Truereturn adapted+ def _should_emit_stream_end_chat_final(+ self,+ *,+ had_assistant_output: bool,+ emitted_terminal_chat_final: bool,+ ) -> bool:+ """Whether the host must synthesize a terminal ``chat.final``.++ pause→clear (and similar) cancels the in-flight goal round so the+ interaction iterator ends normally, but often without a model+ ``chat.final``. Gateway Goal streams also skip+ ``processing_status=false``.++ Emit even when no assistant tokens were forwarded yet: the frontend+ may already be ``isProcessing`` from goal.set before the first+ delta/reasoning arrives; without a final the stop control stays stuck.+ ``had_assistant_output`` is retained for call-site/tests but ignored.+ """+ del had_assistant_output # intentionally unused; see docstring+ if emitted_terminal_chat_final:+ return False+ return not self._goal_record_is_active()+@staticmethoddef _resolve_input_dispatch_mode(params: Any) -> InputDispatchMode | None:"""Map host ``input_mode`` / ``runtime_mode`` onto OpenJiuwen dispatch mode.@@ -7742,6 +7812,8 @@ class JiuWenSwarmDeepAdapter:has_streamed_content = Falseaccumulated_text = ""accumulated_reasoning = ""+ had_assistant_output = False+ emitted_terminal_chat_final = Falseusage_accumulator = {"input_tokens": 0,"output_tokens": 0,@@ -7765,6 +7837,15 @@ class JiuWenSwarmDeepAdapter:emitted_ask_user_request_ids.add(request_id)return False+ def note_chat_payload(payload: dict[str, Any]) -> dict[str, Any]:+ nonlocal had_assistant_output, emitted_terminal_chat_final+ event_type = payload.get("event_type")+ if event_type in ("chat.delta", "chat.reasoning", "chat.final"):+ had_assistant_output = True+ if event_type == "chat.final":+ emitted_terminal_chat_final = True+ return payload+cron_context_tokens = self._bind_runtime_cron_context(channel_id=request.channel_id,session_id=request.session_id,@@ -8052,6 +8133,19 @@ class JiuWenSwarmDeepAdapter:_debug_logger.feed(chunk)if not (hasattr(chunk, "type") and hasattr(chunk, "payload")):parsed = self._parse_stream_chunk(chunk)+ # Only stamp provenance / inject split on new visible deltas.+ # A late user-round chat.final must keep the prior content kind.+ if isinstance(parsed, dict) and parsed.get("event_type") == "chat.delta":+ boundary = self._begin_visible_chat_content()+ if boundary is not None:+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=note_chat_payload(boundary),+ is_complete=False,+ )+ # Boundary closes the user bubble only; goal segment follows.+ emitted_terminal_chat_final = Falseparsed = self._adapt_goal_intermediate_final(parsed)if parsed is not None:if should_skip_duplicate_ask_user(parsed):@@ -8060,7 +8154,7 @@ class JiuWenSwarmDeepAdapter:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={"event_type": "chat.delta", "content": accumulated_text},+ payload=note_chat_payload({"event_type": "chat.delta", "content": accumulated_text}),is_complete=False,)accumulated_text = ""@@ -8068,17 +8162,19 @@ class JiuWenSwarmDeepAdapter:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={+ payload=note_chat_payload({"event_type": "chat.reasoning","content": accumulated_reasoning,- },+ }),is_complete=False,)accumulated_reasoning = ""+ if parsed.get("event_type") == "chat.final":+ self._stream_content_run_kind = Noneyield AgentResponseChunk(request_id=rid,channel_id=cid,- payload=parsed,+ payload=note_chat_payload(parsed),is_complete=False,)continue@@ -8120,10 +8216,19 @@ class JiuWenSwarmDeepAdapter:)if reasoning_payload is None:continue+ boundary = self._begin_visible_chat_content()+ if boundary is not None:+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=note_chat_payload(boundary),+ is_complete=False,+ )+ emitted_terminal_chat_final = Falseyield AgentResponseChunk(request_id=rid,channel_id=cid,- payload=reasoning_payload,+ payload=note_chat_payload(reasoning_payload),is_complete=False,)continue@@ -8142,17 +8247,26 @@ class JiuWenSwarmDeepAdapter:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={+ payload=note_chat_payload({"event_type": "chat.reasoning","content": accumulated_reasoning,- },+ }),is_complete=False,)accumulated_reasoning = ""+ boundary = self._begin_visible_chat_content()+ if boundary is not None:+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=note_chat_payload(boundary),+ is_complete=False,+ )+ emitted_terminal_chat_final = Falseyield AgentResponseChunk(request_id=rid,channel_id=cid,- payload=delta_payload,+ payload=note_chat_payload(delta_payload),is_complete=False,)continue@@ -8162,7 +8276,7 @@ class JiuWenSwarmDeepAdapter:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={"event_type": "chat.delta", "content": accumulated_text},+ payload=note_chat_payload({"event_type": "chat.delta", "content": accumulated_text}),is_complete=False,)accumulated_text = ""@@ -8170,10 +8284,10 @@ class JiuWenSwarmDeepAdapter:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={+ payload=note_chat_payload({"event_type": "chat.reasoning","content": accumulated_reasoning,- },+ }),is_complete=False,)accumulated_reasoning = ""@@ -8183,10 +8297,12 @@ class JiuWenSwarmDeepAdapter:if parsed is not None:if should_skip_duplicate_ask_user(parsed):continue+ if parsed.get("event_type") == "chat.final":+ self._stream_content_run_kind = Noneyield AgentResponseChunk(request_id=rid,channel_id=cid,- payload=parsed,+ payload=note_chat_payload(parsed),is_complete=False,)continue@@ -8195,10 +8311,12 @@ class JiuWenSwarmDeepAdapter:if parsed is not None:if should_skip_duplicate_ask_user(parsed):continue+ if parsed.get("event_type") == "chat.final":+ self._stream_content_run_kind = Noneyield AgentResponseChunk(request_id=rid,channel_id=cid,- payload=parsed,+ payload=note_chat_payload(parsed),is_complete=False,)continue@@ -8207,7 +8325,7 @@ class JiuWenSwarmDeepAdapter:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={"event_type": "chat.delta", "content": accumulated_text},+ payload=note_chat_payload({"event_type": "chat.delta", "content": accumulated_text}),is_complete=False,)accumulated_text = ""@@ -8215,7 +8333,7 @@ class JiuWenSwarmDeepAdapter:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={"event_type": "chat.reasoning", "content": accumulated_reasoning},+ payload=note_chat_payload({"event_type": "chat.reasoning", "content": accumulated_reasoning}),is_complete=False,)accumulated_reasoning = ""@@ -8224,32 +8342,59 @@ class JiuWenSwarmDeepAdapter:if parsed is not None:if should_skip_duplicate_ask_user(parsed):continue+ if parsed.get("event_type") == "chat.final":+ self._stream_content_run_kind = Noneyield AgentResponseChunk(request_id=rid,channel_id=cid,- payload=parsed,+ payload=note_chat_payload(parsed),is_complete=False,)if accumulated_text:- # Same rule as _adapt_goal_intermediate_final: only keep the- # host flush as delta while GoalRecord is still ACTIVE.- final_event_type = (- "chat.delta"- if self._goal_record_is_active()- else "chat.final"- )+ # Same rule as _adapt_goal_intermediate_final: demote host+ # flush only when the flushed text belonged to a goal round.+ if self._should_demote_goal_intermediate_final():+ flush_payload: dict[str, Any] = {+ "event_type": "chat.delta",+ "content": accumulated_text,+ "goal_intermediate": True,+ }+ else:+ flush_payload = {+ "event_type": "chat.final",+ "content": accumulated_text,+ }+ self._stream_content_run_kind = Noneyield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={"event_type": final_event_type, "content": accumulated_text},+ payload=note_chat_payload(flush_payload),is_complete=False,)if accumulated_reasoning:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={"event_type": "chat.reasoning", "content": accumulated_reasoning},+ payload=note_chat_payload({"event_type": "chat.reasoning", "content": accumulated_reasoning}),+ is_complete=False,+ )++ # pause→clear (and similar): round cancelled, iterator ends without+ # a model chat.final. Synthesize a real final so the frontend can+ # stopStreaming; do not demote.+ if self._should_emit_stream_end_chat_final(+ had_assistant_output=had_assistant_output,+ emitted_terminal_chat_final=emitted_terminal_chat_final,+ ):+ self._stream_content_run_kind = None+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=note_chat_payload({+ "event_type": "chat.final",+ "content": "",+ }),is_complete=False,)diff --git a/tests/unit_tests/agentserver/test_goal_runtime_adapter.py b/tests/unit_tests/agentserver/test_goal_runtime_adapter.pyindex 24d24375c3..86dc29e6d9 100644--- a/tests/unit_tests/agentserver/test_goal_runtime_adapter.py+++ b/tests/unit_tests/agentserver/test_goal_runtime_adapter.py@@ -90,6 +90,7 @@ def _adapter(goal_manager: _FakeGoals) -> JiuWenSwarmDeepAdapter:adapter = JiuWenSwarmDeepAdapter.__new__(JiuWenSwarmDeepAdapter)adapter._instance = SimpleNamespace(goal_manager=goal_manager)adapter._is_session_scoped_adapter = True+ adapter._stream_content_run_kind = Nonereturn adapter@@ -316,10 +317,14 @@ async def test_command_goal_unary_response_stays_rpc_payload() -> None:assert response.payload["message"] == "No goal in this session."-def test_active_goal_demotes_intermediate_chat_final_to_delta() -> None:+def test_active_goal_demotes_goal_round_chat_final_to_delta() -> None:+ """Goal multi-attempt middle: demote final so the frontend does not split."""goals = _FakeGoals()goals.record = GoalRecord.create(session_id="session-1", objective="ship the feature")adapter = _adapter(goals)+ adapter._instance.active_round = SimpleNamespace(run_kind="goal")+ adapter._instance.interaction_started = True+ adapter._stream_content_run_kind = "goal"payload = adapter._adapt_goal_intermediate_final({"event_type": "chat.final", "content": "attempt output"}@@ -332,6 +337,76 @@ def test_active_goal_demotes_intermediate_chat_final_to_delta() -> None:}+def test_active_goal_keeps_user_round_chat_final_terminal() -> None:+ """User answer finishes while Goal is still ACTIVE: keep real chat.final."""+ goals = _FakeGoals()+ goals.record = GoalRecord.create(session_id="session-1", objective="ship the feature")+ adapter = _adapter(goals)+ adapter._instance.active_round = SimpleNamespace(run_kind="user")+ adapter._instance.interaction_started = True+ adapter._stream_content_run_kind = "user"++ payload = adapter._adapt_goal_intermediate_final(+ {"event_type": "chat.final", "content": "ordinary answer"}+ )++ assert payload == {+ "event_type": "chat.final",+ "content": "ordinary answer",+ }+++def test_late_user_final_stays_terminal_after_goal_round_started() -> None:+ """Provenance beats live active_round when user final arrives late."""+ goals = _FakeGoals()+ goals.record = GoalRecord.create(session_id="session-1", objective="ship the feature")+ adapter = _adapter(goals)+ adapter._instance.active_round = SimpleNamespace(run_kind="goal")+ adapter._instance.interaction_started = True+ adapter._stream_content_run_kind = "user"++ payload = adapter._adapt_goal_intermediate_final(+ {"event_type": "chat.final", "content": "ordinary answer"}+ )++ assert payload == {+ "event_type": "chat.final",+ "content": "ordinary answer",+ }+++def test_user_to_goal_content_injects_bubble_split_final() -> None:+ goals = _FakeGoals()+ goals.record = GoalRecord.create(session_id="session-1", objective="ship the feature")+ adapter = _adapter(goals)+ adapter._instance.active_round = SimpleNamespace(run_kind="goal")+ adapter._instance.interaction_started = True+ adapter._stream_content_run_kind = "user"++ boundary = adapter._begin_visible_chat_content()++ assert boundary == {"event_type": "chat.final", "content": ""}+ assert adapter._stream_content_run_kind == "goal"+++def test_active_goal_keeps_chat_final_when_no_goal_round_in_flight() -> None:+ """Between user end and next Goal start, do not demote (no goal round)."""+ goals = _FakeGoals()+ goals.record = GoalRecord.create(session_id="session-1", objective="ship the feature")+ adapter = _adapter(goals)+ adapter._instance.active_round = None+ adapter._instance.interaction_started = True++ payload = adapter._adapt_goal_intermediate_final(+ {"event_type": "chat.final", "content": "ordinary answer"}+ )++ assert payload == {+ "event_type": "chat.final",+ "content": "ordinary answer",+ }++def test_interrupt_resume_dispatch_injects_even_without_output_lease() -> None:"""Permission answers must send_input when Goal already holds the lease."""assert JiuWenSwarmDeepAdapter._is_interrupt_resume_dispatch(@@ -480,3 +555,49 @@ def test_web_channel_does_not_treat_goal_slash_as_intent() -> None:params={"query": "/goal set write a report"},)assert JiuWenSwarmDeepAdapter._structured_goal_op_from_request(req) is None+++def test_stream_end_synthesizes_final_after_goal_cleared() -> None:+ """pause→clear ends the iterator without a final; host must synthesize one."""+ goals = _FakeGoals()+ adapter = _adapter(goals)+ goals.record = None++ assert adapter._should_emit_stream_end_chat_final(+ had_assistant_output=True,+ emitted_terminal_chat_final=False,+ )+++def test_stream_end_synthesizes_final_even_before_assistant_tokens() -> None:+ """Goal.set may be processing before the first delta; clear still needs a final."""+ goals = _FakeGoals()+ adapter = _adapter(goals)+ goals.record = None++ assert adapter._should_emit_stream_end_chat_final(+ had_assistant_output=False,+ emitted_terminal_chat_final=False,+ )+++def test_stream_end_skips_final_when_goal_still_active() -> None:+ goals = _FakeGoals()+ goals.record = GoalRecord.create(session_id="session-1", objective="ship")+ adapter = _adapter(goals)++ assert not adapter._should_emit_stream_end_chat_final(+ had_assistant_output=True,+ emitted_terminal_chat_final=False,+ )+++def test_stream_end_skips_final_when_already_emitted() -> None:+ goals = _FakeGoals()+ adapter = _adapter(goals)+ goals.record = None++ assert not adapter._should_emit_stream_end_chat_final(+ had_assistant_output=True,+ emitted_terminal_chat_final=True,+ )