Skip to content

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(team): handle team follow-up delivery races

min_gitcodeb46a0a890ebd
diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
index 8887ba7761..e95d74d47c 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
@@ -8,6 +8,7 @@ import asyncio
import logging
import os
import time
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, AsyncIterator
@@ -90,6 +91,9 @@ _STREAM_TRACE_ENV_KEY = "JIUWENSWARM_TEAM_STREAM_TRACE"
# streaming so the frontend only receives leader output.
_HIDE_TEAMMATE_ENV_KEY = "JIUWENSWARM_TEAM_HIDE_TEAMMATE"
_DEBUG_PREFIX = "/debug"
+_FOLLOWUP_INTERACT_RETRY_TIMEOUT_SEC = 1.0
+_FOLLOWUP_INTERACT_RACE_WAIT_TIMEOUT_SEC = 3.0
+_FOLLOWUP_INTERACT_POLL_INTERVAL_SEC = 0.05
def _team_hide_teammate_enabled() -> bool:
@@ -106,6 +110,56 @@ _INTERACT_REASON_ERROR_MAP: dict[str, str] = {
}
+def _is_followup_delivery_boundary_reason(reason: str | None) -> bool:
+ """Return whether follow-up delivery likely hit a runtime boundary."""
+ normalized = str(reason or "")
+ if normalized in {"gate_closed", "not_active"}:
+ return True
+ return normalized.startswith("deliver_to_leader_failed:")
+
+
+async def _retry_followup_interact_until_ready(
+ team_manager: Any,
+ session_id: str,
+ query: Any,
+ *,
+ timeout_sec: float = _FOLLOWUP_INTERACT_RETRY_TIMEOUT_SEC,
+ poll_interval_sec: float = _FOLLOWUP_INTERACT_POLL_INTERVAL_SEC,
+) -> tuple[bool, str | None]:
+ """Retry follow-up interact while the runtime boundary may still settle."""
+ deadline = time.monotonic() + max(0.0, timeout_sec)
+ sleep_sec = max(0.01, poll_interval_sec)
+ last_reason: str | None = None
+ while time.monotonic() < deadline:
+ await asyncio.sleep(sleep_sec)
+ success, reason = await team_manager.interact(session_id, query)
+ if success:
+ return True, None
+ last_reason = reason
+ if not _is_followup_delivery_boundary_reason(reason):
+ return False, reason
+ return False, last_reason
+
+
+async def _wait_for_team_first_request_condition(
+ team_manager: Any,
+ session_id: str,
+ *,
+ timeout_sec: float = _FOLLOWUP_INTERACT_RACE_WAIT_TIMEOUT_SEC,
+ poll_interval_sec: float = _FOLLOWUP_INTERACT_POLL_INTERVAL_SEC,
+) -> bool:
+ """Wait until the canonical first-request condition becomes true."""
+ if not await _team_session_has_runtime(team_manager, session_id):
+ return True
+ deadline = time.monotonic() + max(0.0, timeout_sec)
+ sleep_sec = max(0.01, poll_interval_sec)
+ while time.monotonic() < deadline:
+ await asyncio.sleep(sleep_sec)
+ if not await _team_session_has_runtime(team_manager, session_id):
+ return True
+ return not await _team_session_has_runtime(team_manager, session_id)
+
+
def _strip_directive(query: str, prefix: str) -> tuple[str, bool]:
"""Strip a leading slash directive from a query string.
@@ -130,6 +184,109 @@ def _extract_query_directives(query: str) -> tuple[str, bool, bool]:
return query, hide_dm, debug
+@dataclass(slots=True)
+class _FirstTeamRequestPreparation:
+ """Result of first-request preprocessing."""
+
+ recovered_runtime: bool
+ query: Any
+ hide_dm: bool
+ debug: bool
+ error_chunks: list[AgentResponseChunk] | None = None
+
+
+async def _prepare_first_team_request(
+ *,
+ team_manager: Any,
+ session_id: str,
+ channel_id: str | None,
+ request_id: str,
+ query: Any,
+) -> _FirstTeamRequestPreparation:
+ """Apply first-request preprocessing shared by cold starts and fallback starts."""
+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput
+
+ hide_dm = False
+ debug = False
+
+ if isinstance(query, InteractiveInput):
+ wait_for_resumable = getattr(team_manager, "wait_for_resumable_runtime", None)
+ restored = False
+ if callable(wait_for_resumable):
+ try:
+ restored = bool(await wait_for_resumable(session_id))
+ except Exception as exc:
+ logger.warning(
+ "[TeamHelpers] waiting for resumable runtime failed: "
+ "channel_id=%s session_id=%s error=%s",
+ _resolve_channel_id(channel_id),
+ session_id,
+ exc,
+ )
+ if restored or await _team_session_has_runtime(team_manager, session_id):
+ logger.info(
+ "[TeamHelpers] interactive input recovered paused team runtime: "
+ "channel_id=%s session_id=%s",
+ _resolve_channel_id(channel_id),
+ session_id,
+ )
+ return _FirstTeamRequestPreparation(
+ recovered_runtime=True,
+ query=query,
+ hide_dm=hide_dm,
+ debug=debug,
+ )
+
+ logger.warning(
+ "[TeamHelpers] interactive input ignored because no active team runtime exists: "
+ "channel_id=%s session_id=%s",
+ _resolve_channel_id(channel_id),
+ session_id,
+ )
+ error_chunks = [
+ AgentResponseChunk(
+ request_id=request_id,
+ channel_id=channel_id,
+ payload={
+ "event_type": "chat.error",
+ "error": "Team runtime is not active, please restart the task",
+ },
+ is_complete=False,
+ ),
+ _team_processing_done_chunk(request_id, channel_id, session_id),
+ AgentResponseChunk(
+ request_id=request_id,
+ channel_id=channel_id,
+ payload=None,
+ is_complete=True,
+ ),
+ ]
+ return _FirstTeamRequestPreparation(
+ recovered_runtime=False,
+ query=query,
+ hide_dm=hide_dm,
+ debug=debug,
+ error_chunks=error_chunks,
+ )
+
+ query, hide_dm, debug = _extract_query_directives(str(query or ""))
+ if hide_dm or debug:
+ logger.info(
+ "[TeamHelpers] query directives captured for first team request: "
+ "channel_id=%s session_id=%s hide_dm=%s debug=%s",
+ _resolve_channel_id(channel_id),
+ session_id,
+ hide_dm,
+ debug,
+ )
+ return _FirstTeamRequestPreparation(
+ recovered_runtime=False,
+ query=query,
+ hide_dm=hide_dm,
+ debug=debug,
+ )
+
+
def sync_team_identity_metadata(
*,
channel_id: str | None,
@@ -916,6 +1073,60 @@ def _team_spec_skills_dir(team_spec: Any) -> str:
return str(team_home(team_name) / "team-workspace" / "skills")
+async def _start_team_stream_round(
+ *,
+ channel_id: str | None,
+ session_id: str,
+ request_id: str,
+ team_manager: Any,
+ team_name: str,
+ team_spec: Any,
+ query: str,
+ hide_dm: bool = False,
+ debug: bool = False,
+ source: str = "first",
+) -> asyncio.Queue:
+ """Start a team stream round and register its waiter queue."""
+ # Sync team observability with current config before streaming.
+ # Runner.run_agent_team_streaming auto-attaches handlers when
+ # is_initialized() is True; this call ensures init/shutdown
+ # matches the latest config toggle.
+ from jiuwenswarm.agents.harness.team.team_manager import sync_team_observability
+
+ sync_team_observability()
+ await team_manager.prepare_runtime_activation(session_id, team_name)
+ request_queue: asyncio.Queue = asyncio.Queue()
+ waiter_key = (_resolve_channel_id(channel_id), session_id)
+ if waiter_key not in _pending_waiters:
+ _pending_waiters[waiter_key] = []
+ _pending_waiters[waiter_key].append((request_id, request_queue))
+ logger.info(
+ "[TeamHelpers] %s team request: channel_id=%s session_id=%s",
+ source,
+ waiter_key[0],
+ session_id,
+ )
+
+ stream_envs: dict[str, Any] = {}
+ if hide_dm:
+ stream_envs["hide_dm"] = True
+ if debug:
+ stream_envs[_STREAM_TRACE_ENV_KEY] = "1"
+ round_id = increment_session_round_count(session_id)
+ stream_task = asyncio.create_task(
+ _consume_stream_with_query(
+ channel_id,
+ session_id,
+ team_spec,
+ query,
+ round_id=round_id,
+ envs=stream_envs or None,
+ )
+ )
+ team_manager.register_stream_task(session_id, stream_task)
+ return request_queue
+
+
async def process_team_message_stream(
request: Any,
inputs: dict[str, Any],
@@ -955,66 +1166,24 @@ async def process_team_message_stream(
hide_dm = False
debug = False
if is_first_request:
- from openjiuwen.core.session.interaction.interactive_input import InteractiveInput
-
- if isinstance(query, InteractiveInput):
- wait_for_resumable = getattr(team_manager, "wait_for_resumable_runtime", None)
- restored = False
- if callable(wait_for_resumable):
- try:
- restored = bool(await wait_for_resumable(session_id))
- except Exception as exc:
- logger.warning(
- "[TeamHelpers] waiting for resumable runtime failed: "
- "channel_id=%s session_id=%s error=%s",
- _resolve_channel_id(channel_id),
- session_id,
- exc,
- )
- if restored or await _team_session_has_runtime(team_manager, session_id):
- is_first_request = False
- logger.info(
- "[TeamHelpers] interactive input recovered paused team runtime: "
- "channel_id=%s session_id=%s",
- _resolve_channel_id(channel_id),
- session_id,
- )
- else:
- logger.warning(
- "[TeamHelpers] interactive input ignored because no active team runtime exists: "
- "channel_id=%s session_id=%s",
- _resolve_channel_id(channel_id),
- session_id,
- )
- yield AgentResponseChunk(
- request_id=rid,
- channel_id=channel_id,
- payload={
- "event_type": "chat.error",
- "error": "Team runtime is not active, please restart the task",
- },
- is_complete=False,
- )
- yield _team_processing_done_chunk(rid, channel_id, session_id)
- yield AgentResponseChunk(
- request_id=rid,
- channel_id=channel_id,
- payload=None,
- is_complete=True,
- )
- return
+ preparation = await _prepare_first_team_request(
+ team_manager=team_manager,
+ session_id=session_id,
+ channel_id=channel_id,
+ request_id=rid,
+ query=query,
+ )
+ if preparation.error_chunks is not None:
+ for chunk in preparation.error_chunks:
+ yield chunk
+ return
+ if preparation.recovered_runtime:
+ is_first_request = False
else:
- query, hide_dm, debug = _extract_query_directives(str(query or ""))
+ query = preparation.query
query_text = query if isinstance(query, str) else ""
- if hide_dm or debug:
- logger.info(
- "[TeamHelpers] query directives captured for first team request: "
- "channel_id=%s session_id=%s hide_dm=%s debug=%s",
- _resolve_channel_id(channel_id),
- session_id,
- hide_dm,
- debug,
- )
+ hide_dm = preparation.hide_dm
+ debug = preparation.debug
try:
request_metadata = dict(request.metadata or {})
@@ -1061,8 +1230,10 @@ async def process_team_message_stream(
team_name = team_spec.team_name
team_skills_dir = _team_spec_skills_dir(team_spec)
ensure_ready = getattr(team_manager, "ensure_team_shared_skills_ready_for_session", None)
+ shared_skills_ready_prepared = False
if is_first_request and callable(ensure_ready):
ensure_ready(session_id, team_spec)
+ shared_skills_ready_prepared = True
slash_result = await _handle_team_slash_command(
channel_id,
@@ -1126,43 +1297,8 @@ async def process_team_message_stream(
return
try:
- if is_first_request:
- # Sync team observability with current config before streaming.
- # Runner.run_agent_team_streaming auto-attaches handlers when
- # is_initialized() is True; this call ensures init/shutdown
- # matches the latest config toggle.
- from jiuwenswarm.agents.harness.team.team_manager import sync_team_observability
- sync_team_observability()
- await team_manager.prepare_runtime_activation(session_id, team_name)
- request_queue = asyncio.Queue()
- waiter_key = (_resolve_channel_id(channel_id), session_id)
- if waiter_key not in _pending_waiters:
- _pending_waiters[waiter_key] = []
- _pending_waiters[waiter_key].append((rid, request_queue))
- logger.info(
- "[TeamHelpers] first team request: channel_id=%s session_id=%s",
- waiter_key[0],
- session_id,
- )
-
- stream_envs: dict[str, Any] = {}
- if hide_dm:
- stream_envs["hide_dm"] = True
- if debug:
- stream_envs[_STREAM_TRACE_ENV_KEY] = "1"
- round_id = increment_session_round_count(session_id)
- stream_task = asyncio.create_task(
- _consume_stream_with_query(
- channel_id,
- session_id,
- team_spec,
- query,
- round_id=round_id,
- envs=stream_envs or None,
- )
- )
- team_manager.register_stream_task(session_id, stream_task)
- else:
+ first_request_source = "first"
+ if not is_first_request:
logger.info(
"[TeamHelpers] follow-up team request: channel_id=%s session_id=%s",
_resolve_channel_id(channel_id),
@@ -1178,17 +1314,100 @@ async def process_team_message_stream(
reason,
_safe_query_preview(query),
)
- error_msg = _INTERACT_REASON_ERROR_MAP.get(reason or "",
- "Failed to send message, please try again later")
- yield AgentResponseChunk(
- request_id=rid,
- channel_id=channel_id,
- payload={
- "event_type": "chat.error",
- "error": error_msg,
- },
- is_complete=False,
+ if _is_followup_delivery_boundary_reason(reason):
+ success, reason = await _retry_followup_interact_until_ready(
+ team_manager,
+ session_id,
+ query,
+ )
+ if not success and _is_followup_delivery_boundary_reason(reason):
+ first_request_ready = await _wait_for_team_first_request_condition(
+ team_manager,
+ session_id,
+ )
+ if first_request_ready:
+ preparation = await _prepare_first_team_request(
+ team_manager=team_manager,
+ session_id=session_id,
+ channel_id=channel_id,
+ request_id=rid,
+ query=query,
+ )
+ if preparation.error_chunks is not None:
+ for chunk in preparation.error_chunks:
+ yield chunk
+ return
+ is_first_request = not preparation.recovered_runtime
+ if is_first_request:
+ first_request_source = "follow-up fallback"
+ query = preparation.query
+ hide_dm = preparation.hide_dm
+ debug = preparation.debug
+ logger.info(
+ "[TeamHelpers] follow-up interact reclassified by first-request condition: "
+ "channel_id=%s session_id=%s reason=%s",
+ _resolve_channel_id(channel_id),
+ session_id,
+ reason,
+ )
+ else:
+ reason = reason or "gate_closed"
+ if not success and not is_first_request:
+ error_msg = _INTERACT_REASON_ERROR_MAP.get(
+ reason or "",
+ "Failed to send message, please try again later",
+ )
+ yield AgentResponseChunk(
+ request_id=rid,
+ channel_id=channel_id,
+ payload={
+ "event_type": "chat.error",
+ "error": error_msg,
+ },
+ is_complete=False,
+ )
+ yield AgentResponseChunk(
+ request_id=rid,
+ channel_id=channel_id,
+ payload=None,
+ is_complete=True,
+ )
+ return
+
+ if not is_first_request:
+ if _is_cron_request_id(rid):
+ request_queue = asyncio.Queue()
+ waiter_key = (_resolve_channel_id(channel_id), session_id)
+ _pending_waiters.setdefault(waiter_key, []).append((rid, request_queue))
+ logger.info(
+ "[TeamHelpers] cron follow-up team request waits for round: "
+ "channel_id=%s session_id=%s request_id=%s",
+ waiter_key[0],
+ session_id,
+ rid,
)
+ round_state = new_cron_team_round_state()
+ try:
+ async for event in _wait_for_cron_team_round_events(
+ request_queue=request_queue,
+ round_state=round_state,
+ request_id=rid,
+ channel_id=channel_id,
+ session_id=session_id,
+ ):
+ yield AgentResponseChunk(
+ request_id=rid,
+ channel_id=channel_id,
+ payload=event,
+ is_complete=False,
+ )
+ finally:
+ waiters = _pending_waiters.get(waiter_key, [])
+ _pending_waiters[waiter_key] = [
+ (req_id, queue) for req_id, queue in waiters if req_id != rid
+ ]
+ if not _pending_waiters.get(waiter_key, []):
+ _pending_waiters.pop(waiter_key, None)
yield AgentResponseChunk(
request_id=rid,
channel_id=channel_id,
@@ -1197,39 +1416,33 @@ async def process_team_message_stream(
)
return
- if _is_cron_request_id(rid):
- request_queue = asyncio.Queue()
- waiter_key = (_resolve_channel_id(channel_id), session_id)
- _pending_waiters.setdefault(waiter_key, []).append((rid, request_queue))
logger.info(
- "[TeamHelpers] cron follow-up team request waits for round: "
+ "[TeamHelpers] follow-up request submitted without waiter: "
"channel_id=%s session_id=%s request_id=%s",
- waiter_key[0],
+ _resolve_channel_id(channel_id),
session_id,
rid,
)
- round_state = new_cron_team_round_state()
- try:
- async for event in _wait_for_cron_team_round_events(
- request_queue=request_queue,
- round_state=round_state,
- request_id=rid,
- channel_id=channel_id,
- session_id=session_id,
- ):
- yield AgentResponseChunk(
- request_id=rid,
- channel_id=channel_id,
- payload=event,
- is_complete=False,
- )
- finally:
- waiters = _pending_waiters.get(waiter_key, [])
- _pending_waiters[waiter_key] = [
- (req_id, queue) for req_id, queue in waiters if req_id != rid
- ]
- if not _pending_waiters.get(waiter_key, []):
- _pending_waiters.pop(waiter_key, None)
+ # NOTE: do NOT emit is_processing=False here.
+ # A follow-up request only enqueues the query into the running
+ # team stream; the actual LLM work still happens inside
+ # _consume_stream_with_query. The real "round complete" signal
+ # will be broadcast by that background stream once team.completed
+ # arrives, and forwarded to the frontend via the long-lived
+ # waiter that was registered by the first request.
+ # The deferred placeholder below tells the Gateway not to
+ # auto-emit is_processing=False when this short stream ends,
+ # which prevents the frontend from flashing
+ # "finished -> wait -> running again" before the LLM replies.
+ yield AgentResponseChunk(
+ request_id=rid,
+ channel_id=channel_id,
+ payload={
+ "event_type": "chat.processing_status_deferred",
+ "session_id": session_id,
+ },
+ is_complete=False,
+ )
yield AgentResponseChunk(
request_id=rid,
channel_id=channel_id,
@@ -1238,39 +1451,22 @@ async def process_team_message_stream(
)
return
- logger.info(
- "[TeamHelpers] follow-up request submitted without waiter: channel_id=%s session_id=%s request_id=%s",
- _resolve_channel_id(channel_id),
- session_id,
- rid,
- )
- # NOTE: do NOT emit is_processing=False here.
- # A follow-up request only enqueues the query into the running
- # team stream; the actual LLM work still happens inside
- # _consume_stream_with_query. The real "round complete" signal
- # will be broadcast by that background stream once team.completed
- # arrives, and forwarded to the frontend via the long-lived
- # waiter that was registered by the first request.
- # The deferred placeholder below tells the Gateway not to
- # auto-emit is_processing=False when this short stream ends,
- # which prevents the frontend from flashing
- # "finished -> wait -> running again" before the LLM replies.
- yield AgentResponseChunk(
- request_id=rid,
+ if is_first_request:
+ if callable(ensure_ready) and not shared_skills_ready_prepared:
+ ensure_ready(session_id, team_spec)
+ shared_skills_ready_prepared = True
+ request_queue = await _start_team_stream_round(
channel_id=channel_id,
- payload={
- "event_type": "chat.processing_status_deferred",
- "session_id": session_id,
- },
- is_complete=False,
- )
- yield AgentResponseChunk(
+ session_id=session_id,
request_id=rid,
- channel_id=channel_id,
- payload=None,
- is_complete=True,
+ team_manager=team_manager,
+ team_name=team_name,
+ team_spec=team_spec,
+ query=query,
+ hide_dm=hide_dm,
+ debug=debug,
+ source=first_request_source,
)
- return
try:
if _is_cron_request_id(rid) and request_queue is not None:
diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.py
index d3df852389..69fec3f42a 100644
--- a/tests/unit_tests/agentserver/test_team_helpers.py
+++ b/tests/unit_tests/agentserver/test_team_helpers.py
@@ -1291,6 +1291,332 @@ async def test_process_team_message_stream_emits_deferred_marker_for_followup(mo
assert chunks[1].is_complete is True
+async def test_process_team_message_stream_retries_followup_while_native_starts(monkeypatch):
+ class _FakeManager(_InactiveTeamRuntimeManagerMixin):
+ interact_calls: list[tuple[str, str]] = []
+
+ @staticmethod
+ def has_stream_task(session_id: str) -> bool:
+ assert session_id == "sess-team-followup-starting"
+ return True
+
+ @staticmethod
+ async def get_swarm_enriched_team_spec(**kwargs):
+ return SimpleNamespace(team_name="unit-team")
+
+ @classmethod
+ async def interact(cls, session_id: str, query: str):
+ cls.interact_calls.append((session_id, query))
+ return (
+ False,
+ "deliver_to_leader_failed:[123023] deepagent runtime error, "
+ "reason: NativeHarness not started.",
+ )
+
+ async def _fake_retry(team_manager: object, session_id: str, query: str):
+ assert team_manager is not None
+ _FakeManager.interact_calls.append((session_id, f"retry:{query}"))
+ return True, None
+
+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())
+ monkeypatch.setattr(team_helpers, "_retry_followup_interact_until_ready", _fake_retry)
+
+ request = SimpleNamespace(
+ session_id="sess-team-followup-starting",
+ request_id="req-team-followup-starting",
+ channel_id="web",
+ metadata=None,
+ params={"mode": "team"},
+ )
+
+ chunks = []
+ async for chunk in team_helpers.process_team_message_stream(
+ request,
+ {"query": "启动中追问"},
+ object(),
+ ):
+ chunks.append(chunk)
+
+ assert _FakeManager.interact_calls == [
+ ("sess-team-followup-starting", "启动中追问"),
+ ("sess-team-followup-starting", "retry:启动中追问"),
+ ]
+ assert chunks[0].payload == {
+ "event_type": "chat.processing_status_deferred",
+ "session_id": "sess-team-followup-starting",
+ }
+ assert chunks[-1].is_complete is True
+
+
+async def test_process_team_message_stream_restarts_round_after_shutdown_race(monkeypatch):
+ captured: dict[str, Any] = {}
+
+ class _FakeManager(_InactiveTeamRuntimeManagerMixin):
+ interact_calls: list[tuple[str, str]] = []
+ skills_ready_calls: list[tuple[str, str]] = []
+ stream_active = True
+
+ @classmethod
+ def has_stream_task(cls, session_id: str) -> bool:
+ assert session_id == "sess-team-followup-stopped"
+ return cls.stream_active
+
+ @staticmethod
+ async def get_swarm_enriched_team_spec(**kwargs):
+ return SimpleNamespace(team_name="unit-team", enable_swarmflow=False)
+
+ @classmethod
+ async def interact(cls, session_id: str, query: str):
+ cls.interact_calls.append((session_id, query))
+ return (
+ False,
+ "deliver_to_leader_failed:[123023] deepagent runtime error, "
+ "reason: NativeHarness already stopped.",
+ )
+
+ @classmethod
+ def ensure_team_shared_skills_ready_for_session(cls, session_id: str, team_spec: object):
+ cls.skills_ready_calls.append((session_id, team_spec.team_name))
+
+ @staticmethod
+ async def prepare_runtime_activation(session_id: str, team_name: str):
+ captured["prepared"] = (session_id, team_name)
+
+ @staticmethod
+ def register_stream_task(session_id: str, task: object) -> None:
+ captured["registered"] = session_id
+
+ async def _fake_wait_first_request(team_manager: object, session_id: str, **kwargs) -> bool:
+ assert team_manager is not None
+ assert session_id == "sess-team-followup-stopped"
+ _FakeManager.stream_active = False
+ return True
+
+ async def _fake_retry(team_manager: object, session_id: str, query: str):
+ assert team_manager is not None
+ assert session_id == "sess-team-followup-stopped"
+ assert query
+ return (
+ False,
+ "deliver_to_leader_failed:[123023] deepagent runtime error, "
+ "reason: NativeHarness already stopped.",
+ )
+
+ async def _fake_consume_stream_with_query(
+ channel_id: str | None,
+ session_id: str,
+ spec: object,
+ query: str,
+ *,
+ round_id: int,
+ envs: dict | None = None,
+ ) -> None:
+ _ = channel_id, spec, envs
+ captured["consumed"] = (session_id, query, round_id)
+
+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())
+ monkeypatch.setattr(team_helpers, "_retry_followup_interact_until_ready", _fake_retry)
+ monkeypatch.setattr(
+ team_helpers,
+ "_wait_for_team_first_request_condition",
+ _fake_wait_first_request,
+ )
+ monkeypatch.setattr(team_helpers, "increment_session_round_count", lambda session_id: 7)
+ monkeypatch.setattr(team_helpers, "_consume_stream_with_query", _fake_consume_stream_with_query)
+
+ request = SimpleNamespace(
+ session_id="sess-team-followup-stopped",
+ request_id="req-team-followup-stopped",
+ channel_id="web",
+ metadata=None,
+ params={"mode": "team"},
+ )
+
+ chunks = []
+ async for chunk in team_helpers.process_team_message_stream(
+ request,
+ {"query": "查询杭州天气"},
+ object(),
+ ):
+ chunks.append(chunk)
+ await asyncio.sleep(0)
+
+ assert _FakeManager.interact_calls == [
+ ("sess-team-followup-stopped", "查询杭州天气"),
+ ]
+ assert _FakeManager.skills_ready_calls == [
+ ("sess-team-followup-stopped", "unit-team"),
+ ]
+ assert captured["prepared"] == ("sess-team-followup-stopped", "unit-team")
+ assert captured["registered"] == "sess-team-followup-stopped"
+ assert captured["consumed"] == ("sess-team-followup-stopped", "查询杭州天气", 7)
+ assert chunks[-1].is_complete is True
+ assert not any(
+ chunk.payload
+ and chunk.payload.get("error") == "Failed to send message, please try again later"
+ for chunk in chunks
+ )
+
+
+async def test_process_team_message_stream_fallback_reuses_first_request_directives(monkeypatch):
+ captured: dict[str, Any] = {}
+
+ class _FakeManager(_InactiveTeamRuntimeManagerMixin):
+ interact_calls: list[tuple[str, str]] = []
+ stream_active = True
+
+ @classmethod
+ def has_stream_task(cls, session_id: str) -> bool:
+ assert session_id == "sess-team-followup-directives"
+ return cls.stream_active
+
+ @staticmethod
+ async def get_swarm_enriched_team_spec(**kwargs):
+ return SimpleNamespace(team_name="unit-team", enable_swarmflow=False)
+
+ @classmethod
+ async def interact(cls, session_id: str, query: str):
+ cls.interact_calls.append((session_id, query))
+ return False, "gate_closed"
+
+ @staticmethod
+ async def prepare_runtime_activation(session_id: str, team_name: str):
+ captured["prepared"] = (session_id, team_name)
+
+ @staticmethod
+ def register_stream_task(session_id: str, task: object) -> None:
+ captured["registered"] = session_id
+
+ async def _fake_retry(team_manager: object, session_id: str, query: str):
+ assert team_manager is not None
+ assert session_id == "sess-team-followup-directives"
+ assert query == "/hide_dm /debug weather"
+ return False, "gate_closed"
+
+ async def _fake_wait_first_request(team_manager: object, session_id: str, **kwargs) -> bool:
+ assert team_manager is not None
+ assert session_id == "sess-team-followup-directives"
+ _FakeManager.stream_active = False
+ return True
+
+ async def _fake_consume_stream_with_query(
+ channel_id: str | None,
+ session_id: str,
+ spec: object,
+ query: str,
+ *,
+ round_id: int,
+ envs: dict | None = None,
+ ) -> None:
+ _ = channel_id, spec
+ captured["consumed"] = (session_id, query, round_id, envs)
+
+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())
+ monkeypatch.setattr(team_helpers, "_retry_followup_interact_until_ready", _fake_retry)
+ monkeypatch.setattr(
+ team_helpers,
+ "_wait_for_team_first_request_condition",
+ _fake_wait_first_request,
+ )
+ monkeypatch.setattr(team_helpers, "increment_session_round_count", lambda session_id: 9)
+ monkeypatch.setattr(team_helpers, "_consume_stream_with_query", _fake_consume_stream_with_query)
+
+ request = SimpleNamespace(
+ session_id="sess-team-followup-directives",
+ request_id="req-team-followup-directives",
+ channel_id="web",
+ metadata=None,
+ params={"mode": "team"},
+ )
+
+ chunks = []
+ async for chunk in team_helpers.process_team_message_stream(
+ request,
+ {"query": "/hide_dm /debug weather"},
+ object(),
+ ):
+ chunks.append(chunk)
+ await asyncio.sleep(0)
+
+ assert _FakeManager.interact_calls == [
+ ("sess-team-followup-directives", "/hide_dm /debug weather"),
+ ]
+ assert captured["prepared"] == ("sess-team-followup-directives", "unit-team")
+ assert captured["registered"] == "sess-team-followup-directives"
+ assert captured["consumed"][:3] == ("sess-team-followup-directives", "weather", 9)
+ stream_envs = captured["consumed"][3]
+ assert stream_envs["hide_dm"] is True
+ assert stream_envs["JIUWENSWARM_TEAM_STREAM_TRACE"] == "1"
+ assert chunks[-1].is_complete is True
+
+
+async def test_process_team_message_stream_reports_error_when_shutdown_race_wait_times_out(monkeypatch):
+ class _FakeManager(_InactiveTeamRuntimeManagerMixin):
+ @staticmethod
+ def has_stream_task(session_id: str) -> bool:
+ assert session_id == "sess-team-followup-timeout"
+ return True
+
+ @staticmethod
+ async def get_swarm_enriched_team_spec(**kwargs):
+ return SimpleNamespace(team_name="unit-team")
+
+ @staticmethod
+ async def interact(session_id: str, query: str):
+ assert session_id == "sess-team-followup-timeout"
+ assert query == "还在收尾"
+ return False, "gate_closed"
+
+ @staticmethod
+ async def prepare_runtime_activation(session_id: str, team_name: str):
+ raise AssertionError("timed-out shutdown race should not start a new stream")
+
+ async def _fake_wait_first_request(team_manager: object, session_id: str, **kwargs) -> bool:
+ assert team_manager is not None
+ assert session_id == "sess-team-followup-timeout"
+ return False
+
+ async def _fake_retry(team_manager: object, session_id: str, query: str):
+ assert team_manager is not None
+ assert session_id == "sess-team-followup-timeout"
+ assert query
+ return False, "gate_closed"
+
+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())
+ monkeypatch.setattr(team_helpers, "_retry_followup_interact_until_ready", _fake_retry)
+ monkeypatch.setattr(
+ team_helpers,
+ "_wait_for_team_first_request_condition",
+ _fake_wait_first_request,
+ )
+
+ request = SimpleNamespace(
+ session_id="sess-team-followup-timeout",
+ request_id="req-team-followup-timeout",
+ channel_id="web",
+ metadata=None,
+ params={"mode": "team"},
+ )
+
+ chunks = []
+ async for chunk in team_helpers.process_team_message_stream(
+ request,
+ {"query": "还在收尾"},
+ object(),
+ ):
+ chunks.append(chunk)
+
+ assert chunks[0].payload == {
+ "event_type": "chat.error",
+ "error": "Team is shutting down, please try again later",
+ }
+ assert chunks[-1].is_complete is True
+
+
@pytest.mark.anyio
async def test_process_team_message_stream_passes_interactive_input_to_followup(monkeypatch):
from openjiuwen.core.session.interaction.interactive_input import InteractiveInput