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(tui): enable interactive team conversation with idle-watch round detection
haowenzhong11c722b8a0074
diff --git a/jiuwenswarm/cli/chat.py b/jiuwenswarm/cli/chat.pyindex 0141fde310..245965cb83 100644--- a/jiuwenswarm/cli/chat.py+++ b/jiuwenswarm/cli/chat.py@@ -16,6 +16,29 @@ import timeimport uuid as uuid_modulefrom pathlib import Path+# Importing ``readline`` transparently upgrades the builtin ``input()`` with+# line editing: left/right cursor movement, history, and correct multi-byte+# UTF-8 deletion (so backspacing a Chinese character removes the whole glyph+# instead of leaving a broken byte / raw escape sequences like ``^[[C``).+try:+ import readline+ _ = readline # side-effect import — CPython input() hooks into readline+except ImportError:+ # Windows lacks the ``readline`` module. Reconfigure stdin to UTF-8 so+ # that multi-byte characters (Chinese, Japanese, etc.) are read and+ # displayed correctly, and try ``pyreadline3`` (a drop-in ``readline``+ # replacement for Windows) when available.+ if sys.platform == "win32":+ try:+ sys.stdin.reconfigure(encoding="utf-8")+ except AttributeError:+ pass+ try:+ import pyreadline3+ _ = pyreadline3 # Windows readline replacement+ except ImportError:+ pass+from jiuwenswarm.cli._terminal import write_stderr, write_stdoutfrom jiuwenswarm.cli.gateway_client import GatewayClientfrom jiuwenswarm.cli.events import (@@ -376,6 +399,16 @@ async def _run_interactive_loop(# to members, etc.). Only chat.processing_status(is_processing=False)# or team.error should terminate the CLI stream.team_mode = request.get("params", {}).get("mode", "") in ("team", "team.plan", "code.team")+ # When the team leader replies with text but creates no tasks (e.g. a+ # simple greeting), the server's team-completion logic never fires+ # (is_team_completed() returns None for zero tasks), so the stream+ # never closes and processing_status(False) never arrives. We detect+ # this stall by watching for chat.final (leader reply) and then+ # waiting a short idle window; if no further events arrive, we treat+ # the round as complete and prompt the user.+ team_final_seen = False+ team_final_time: float = 0.0+ _team_round_idle_timeout = 3.0# In plan mode the agent may end its turn with a text question (without# calling ask_user or exit_plan_mode). In that case chat.final arrives# but the conversation isn't really done — the user needs to respond.@@ -472,12 +505,17 @@ async def _run_interactive_loop(return 130# Compute the remaining budget for the total deadline.+ # In team mode after the leader's chat.final, use a short idle+ # window to detect round-completion stall (no tasks created).if deadline is not None:remaining = deadline - time.monotonic()if remaining <= 0:logger.warning("response timed out")return 1cur_timeout = max(min(remaining, 0.3), 0.01)+ elif team_final_seen:+ elapsed = time.monotonic() - team_final_time+ cur_timeout = max(_team_round_idle_timeout - elapsed, 0.1)else:cur_timeout = recv_idle_timeout@@ -509,6 +547,40 @@ async def _run_interactive_loop(return 1continue+ # Team idle-watch: leader's chat.final seen and idle window+ # elapsed with no further events — server's team-completion+ # stalled (no tasks). Prompt for next message on TTY.+ if recv_task not in done and team_final_seen:+ team_final_seen = False+ if sys.stdin.isatty():+ renderer.clear_loading()+ if renderer.streamed_text and not renderer.streamed_text.endswith("\n"):+ write_stdout("\n")+ try:+ line = (await asyncio.to_thread(input, "\n> ")).strip()+ except EOFError:+ return 0+ if not line or line in ("/exit", "/quit", "/q"):+ return 0+ renderer.reset_streamed_text()+ await client.send_request({+ "type": "req",+ "id": f"chat-{uuid_module.uuid4().hex[:12]}",+ "method": "chat.send",+ "is_stream": True,+ "params": {+ "session_id": request["params"]["session_id"],+ "query": line,+ "mode": request["params"]["mode"],+ "cwd": request["params"].get("cwd", ""),+ "project_dir": request["params"].get("project_dir", ""),+ },+ })+ renderer.ensure_loading()+ continue+ # Non-TTY: no way to prompt, exit+ return 0+try:data = recv_task.result()except OSError:@@ -538,6 +610,13 @@ async def _run_interactive_loop(payload = data.get("payload", {})kind = event_kind(event_type)+ # Any event arriving during the team idle-watch window means+ # the team is still active (member tool calls, reasoning, etc.).+ # Reset the idle timer so we don't prematurely prompt the user.+ # chat.final re-arms it below.+ if team_final_seen and kind != "final":+ team_final_seen = False+if kind == "delta":renderer.handle_delta(payload)elif kind == "reasoning":@@ -555,6 +634,13 @@ async def _run_interactive_loop(renderer.handle_error(payload)return 1renderer.handle_final(payload)+ # In team mode, the leader's chat.final is a turn boundary+ # but not a terminal event. Start the idle-watch timer so+ # we can detect when the server's team-completion logic has+ # stalled (no tasks created → no processing_status(False)).+ if team_mode:+ team_final_seen = True+ team_final_time = time.monotonic()elif kind == "error":renderer.handle_error(payload)return 1@@ -668,6 +754,42 @@ async def _run_interactive_loop(return 1# leader reply or team control event — keep listeningcontinue+ # In team mode, a completed round (processing_status+ # is_processing=False / team.completed) is NOT the end of+ # the session — the team runtime is persistent and+ # inherently conversational. Treat round completion as a+ # turn boundary: prompt for the next message on TTY.+ if (+ team_mode+ and event_type == "chat.processing_status"+ and sys.stdin.isatty()+ ):+ team_final_seen = False+ renderer.clear_loading()+ if renderer.streamed_text and not renderer.streamed_text.endswith("\n"):+ write_stdout("\n")+ try:+ line = (await asyncio.to_thread(input, "\n> ")).strip()+ except EOFError:+ return 0+ if not line or line in ("/exit", "/quit", "/q"):+ return 0+ renderer.reset_streamed_text()+ await client.send_request({+ "type": "req",+ "id": f"chat-{uuid_module.uuid4().hex[:12]}",+ "method": "chat.send",+ "is_stream": True,+ "params": {+ "session_id": request["params"]["session_id"],+ "query": line,+ "mode": request["params"]["mode"],+ "cwd": request["params"].get("cwd", ""),+ "project_dir": request["params"].get("project_dir", ""),+ },+ })+ renderer.ensure_loading()+ continue# In plan mode, chat.final is only terminal if the agent# has exited plan mode (plan_exited=True) or this is an# approval-resume completion. Otherwise prompt for follow-up.@@ -857,10 +979,31 @@ def _print_connection_hint(url: str, args: argparse.Namespace) -> None:def run_chat(args: argparse.Namespace) -> int:+ error = _validate_args(args)+ if error is not None:+ return error++ is_team_mode = args.mode in ("team", "team.plan", "code.team")+if args.prompt:prompt = " ".join(args.prompt)elif not sys.stdin.isatty():prompt = sys.stdin.read().strip()+ elif is_team_mode:+ # Team runtime is persistent across conversation turns. Use+ # the same interactive loop model (single connection, multiple+ # follow-ups) that _run_interactive_loop already supports when+ # stdin is a TTY — we just need to prime it with the first line+ # instead of bouncing through _run_repl (which creates a fresh+ # connection per turn and loses team state).+ logger.info("Team mode — interactive persistent session.")+ logger.info("Type your prompt and press Enter. Ctrl+C to interrupt, /exit to exit.")+ try:+ prompt = input("> ").strip()+ except (EOFError, KeyboardInterrupt):+ return 0+ if not prompt:+ return 0else:return _run_repl(args)@@ -868,10 +1011,6 @@ def run_chat(args: argparse.Namespace) -> int:logger.error("no prompt provided and stdin is empty")return 2- error = _validate_args(args)- if error is not None:- return error-# Check for newly persisted dirs before sending the message,# so the user gets a chance to clean up from previous sessions._prompt_and_cleanup_dirs()