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(chat): chat CLI plan mode interactive question and approval flow

haowenzhong11c97656605eb
diff --git a/jiuwenswarm/cli/chat.py b/jiuwenswarm/cli/chat.py
index fce5dca11f..026cba41e8 100644
--- a/jiuwenswarm/cli/chat.py
+++ b/jiuwenswarm/cli/chat.py
@@ -37,6 +37,15 @@ VALID_MODES = frozenset({
"agent.plan", "agent.fast", "code.plan", "code.normal", "code.team", "team",
})
+# Sources that require the answer to be sent via ``chat.send`` (streaming) to
+# resume the paused agent task. Other sources use ``chat.user_answer``.
+_INTERRUPT_RESUME_SOURCES = frozenset({
+ "confirm_interrupt",
+ "permission_interrupt",
+ "ask_user_interrupt",
+ "evolution_interrupt",
+})
+
def resolve_mode(raw: str) -> str:
normalized = raw.strip().lower()
@@ -197,6 +206,25 @@ 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")
+ # 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.
+ # We track plan_exited (set when plan.mode_exited is received) to
+ # distinguish "agent finished implementing after approval" from "agent
+ # ended turn with text, waiting for user follow-up".
+ plan_mode = request.get("params", {}).get("mode", "") in ("code.plan", "agent.plan")
+ plan_exited = False
+ # When we send an interrupt-resume answer (chat.send with source), the
+ # previous stream's trailing chat.final / processing_status(False) may
+ # still arrive. We skip terminal events until the resumed stream sends
+ # its own processing_status(False).
+ awaiting_resume = False
+ # Tracks whether we just sent a plan-approval answer (source=confirm_interrupt
+ # with exit_plan_mode). When True, the next chat.final is the completion of
+ # the approved plan execution — do NOT prompt for follow-up. plan.mode_exited
+ # arrives as a separate push AFTER the stream finishes, so plan_exited would
+ # still be False when chat.final hits.
+ _approval_resume = False
loop = asyncio.get_running_loop()
@@ -327,30 +355,106 @@ async def _run_interactive_loop(
elif kind == "interactive":
renderer.clear_loading()
if sys.stdin.isatty():
- write_stderr(
- f"\n[{event_type}] "
- f"{payload.get('question') or payload.get('message', 'Input needed')}\n"
- )
- answer = input("> ").strip()
+ source = str(payload.get("source") or "").strip()
+ request_id = str(payload.get("request_id") or "").strip()
+ questions = payload.get("questions") or []
+
+ # Collect all options across questions for input mapping
+ all_options: list[dict] = []
+ # Display question(s) and options
+ if isinstance(questions, list) and questions:
+ for q in questions:
+ header = q.get("header", "Input needed")
+ question_text = q.get("question", "")
+ options = q.get("options") or []
+ write_stderr(f"\n[{header}] {question_text}\n")
+ if isinstance(options, list) and options:
+ for i, opt in enumerate(options, 1):
+ label = opt.get("label", "")
+ desc = opt.get("description", "")
+ write_stderr(
+ f" {i}. {label}"
+ + (f" — {desc}" if desc else "")
+ + "\n"
+ )
+ all_options.append(opt)
+ else:
+ write_stderr(
+ f"\n[{event_type}] "
+ f"{payload.get('question') or payload.get('message', 'Input needed')}\n"
+ )
+
+ answer = (await asyncio.to_thread(input, "> ")).strip()
+ # Map numeric input or label text to the option's value.
+ # E.g. "1" → "approve", "Approve" → "approve", "批准" → "approve"
+ selected = answer
+ if all_options:
+ # Try numeric index (1-based)
+ if answer.isdigit():
+ idx = int(answer) - 1
+ if 0 <= idx < len(all_options):
+ selected = str(all_options[idx].get("value") or all_options[idx].get("label") or answer)
+ # Try matching label (case-insensitive)
+ if selected == answer:
+ for opt in all_options:
+ label = str(opt.get("label") or "")
+ if label and label.lower() == answer.lower():
+ selected = str(opt.get("value") or label)
+ break
+ answers = [{"selected_options": [selected], "custom_input": answer}]
+
try:
- await client.send_request({
- "type": "req",
- "id": f"answer-{uuid_module.uuid4().hex[:12]}",
- "method": "chat.user_answer",
- "is_stream": False,
- "params": {
- "session_id": request["params"]["session_id"],
- "answer": answer,
- "request_id": payload.get("request_id", ""),
- },
- })
+ if source in _INTERRUPT_RESUME_SOURCES and request_id:
+ # Interrupt resume: send via chat.send (streaming)
+ # to resume the paused agent task. Using
+ # chat.user_answer here would NOT resume the task.
+ awaiting_resume = True
+ if source == "confirm_interrupt":
+ _approval_resume = True
+ await client.send_request({
+ "type": "req",
+ "id": f"answer-{uuid_module.uuid4().hex[:12]}",
+ "method": "chat.send",
+ "is_stream": True,
+ "params": {
+ "session_id": request["params"]["session_id"],
+ "query": "",
+ "request_id": request_id,
+ "answers": answers,
+ "source": source,
+ "mode": request["params"]["mode"],
+ },
+ })
+ else:
+ await client.send_request({
+ "type": "req",
+ "id": f"answer-{uuid_module.uuid4().hex[:12]}",
+ "method": "chat.user_answer",
+ "is_stream": False,
+ "params": {
+ "session_id": request["params"]["session_id"],
+ "answers": answers,
+ "request_id": request_id,
+ },
+ })
except ConnectionError:
return 0
else:
logger.error("interactive input required but stdin is not a TTY: %s", event_type)
return 4
+ elif event_type == "plan.mode_exited":
+ # Agent exited plan mode (user approved). Subsequent
+ # chat.final is a real terminal event.
+ plan_exited = True
if is_terminal_event(event_type, payload):
+ # After sending an interrupt-resume answer, the previous
+ # stream's trailing chat.final / processing_status(False)
+ # may arrive. Skip them — the resumed stream will send its
+ # own terminal events.
+ if awaiting_resume:
+ awaiting_resume = False
+ continue
# In team mode, chat.final (leader reply) is not terminal —
# the team keeps working after the leader responds. Only
# processing_status(is_processing=False) or team.error ends
@@ -361,6 +465,44 @@ async def _run_interactive_loop(
return 1
# leader reply or team control event — keep listening
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.
+ _follow_up_in_plan = (
+ plan_mode and not plan_exited and not _approval_resume
+ )
+ if _follow_up_in_plan and event_type == "chat.final" and 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
+ # Send follow-up message and continue streaming.
+ # Reset the renderer's streamed text so the next
+ # response starts fresh.
+ 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", ""),
+ },
+ })
+ # After sending the follow-up, the previous stream's
+ # trailing chat.final / processing_status(False) may
+ # still arrive. Skip them and wait for the new stream.
+ awaiting_resume = True
+ continue
renderer.clear_loading()
if renderer.streamed_text and not renderer.streamed_text.endswith("\n"):
write_stdout("\n")
diff --git a/jiuwenswarm/cli/render.py b/jiuwenswarm/cli/render.py
index d7f805353c..9d74c7ceeb 100644
--- a/jiuwenswarm/cli/render.py
+++ b/jiuwenswarm/cli/render.py
@@ -80,6 +80,10 @@ class HumanRenderer:
def spinner_idx(self) -> int:
return self._spinner_idx
+ def reset_streamed_text(self) -> None:
+ """Reset the accumulated streamed text for a new response turn."""
+ self._streamed_text = ""
+
def clear_loading(self) -> None:
if not self._loading:
return