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

[feat](tui) add terminal CLI chat entry point jiuwenswarm chat with /cli route, CC-inspired spinner, keepalive handling, and 125 unit tests Refs:#1360

haowenzhong1c98d3b943f49
diff --git a/docs/en/CLI.md b/docs/en/CLI.md
index fb502ac997..6db330e169 100644
--- a/docs/en/CLI.md
+++ b/docs/en/CLI.md
@@ -230,3 +230,149 @@ Cancel operation:
- Mode is stored **per channel** (`channel_id` → `mode`). All subsequent messages on that channel will automatically include the current mode.
- `default_mode` can be set in `config.yaml` as the initial value; `MessageHandler` reads it on startup.
- `/new_session` and `/mode` changes will automatically cancel tasks currently running in the session.
+
+---
+
+## Terminal CLI: `jiuwenswarm chat`
+
+Starting from v0.2.1, JiuwenSwarm provides a first-party command-line chat entry point to interact with JiuwenSwarm directly from the terminal.
+
+### Quick Start
+
+```bash
+# Start Gateway and AgentServer (if not running)
+jiuwenswarm-start app
+
+# Send a message
+jiuwenswarm chat "Hello, introduce yourself"
+```
+
+`jiuwenswarm chat` calls JiuwenSwarm's runtime through the Gateway's `/cli` WebSocket route, using the same MessageHandler and AgentServer path as the TUI.
+
+### Basic Usage
+
+| Command | Description |
+|---|---|
+| `jiuwenswarm chat "hello"` | Send a single message |
+| `jiuwenswarm chat check the repo and suggest` | Multi-word args joined into one prompt |
+| `echo "analyze main.py" \| jiuwenswarm chat` | Pipe stdin |
+| `jiuwenswarm chat` | No args + interactive TTY → enter REPL mode |
+
+### Options
+
+| Option | Default | Description |
+|---|---|---|
+| `--mode <mode>` | `code.normal` | Execution mode, see [Modes](Modes.md) |
+| `--session <id>` | Auto-generated | Reuse or create a named session id |
+| `--cwd <path>` | Current dir | Working directory for file mentions and agent context |
+| `--project-dir <path>` | `--cwd` | Project identity for session and agent cache |
+| `--trusted-dir <path>` | `--project-dir` | Trusted directory (repeatable) |
+| `--gateway-url <url>` | `ws://127.0.0.1:19001/cli` | Explicit Gateway WebSocket URL |
+| `--name <instance>` | — | Named instance for env isolation |
+| `--dotenv <path>` | — | Path to .env file |
+| `--json` | — | Print one final JSON object |
+| `--jsonl` | — | Print each Gateway event frame as JSON Lines |
+| `--show-reasoning` | — | Include reasoning output (to stderr) |
+| `--show-tools` | — | Include compact tool call/result status (to stderr) |
+| `--timeout <seconds>` | 300 | Per-recv timeout in seconds |
+
+### Modes (`--mode`)
+
+Supported mode values match those in [Modes](Modes.md):
+
+| Mode | Alias | Description |
+|---|---|---|
+| `code.normal` | `code`, `normal` | Default, code normal mode |
+| `code.plan` | — | Code planning mode |
+| `code.team` | — | Code team mode |
+| `agent.plan` | `agent` | Agent planning mode |
+| `agent.fast` | `fast` | Agent fast mode |
+| `team` | `team.normal` | Team mode |
+
+```bash
+# Using aliases
+jiuwenswarm chat --mode fast "quick answer"
+jiuwenswarm chat --mode agent "help me plan"
+
+# Using canonical values
+jiuwenswarm chat --mode code.plan "design a user system"
+```
+
+### Session Reuse
+
+```bash
+# First: specify a session name
+jiuwenswarm chat --session project-a "analyze the project architecture"
+
+# Follow-up: reuse the same session, preserving context
+jiuwenswarm chat --session project-a "any improvement suggestions?"
+
+# Without --session, auto-generates cli-YYYYMMDD-HHMMSS-xxxxxxxx
+```
+
+### REPL Mode
+
+Run without a prompt argument to enter multi-turn conversation:
+
+```bash
+jiuwenswarm chat
+# Session: cli-20260616-120500-abc12345
+# > show me the files in the current directory
+# > analyze main.py
+# > Ctrl+D to exit
+```
+
+All messages in REPL mode share the same session, maintaining continuous context.
+
+### Loading Spinner
+
+While waiting for the first response, a dynamic loading indicator displays on stderr:
+
+```
+✢ analyzing (3s)
+```
+
+- **12-frame ping-pong animation**: `␣ · ✢ ✳ ✶ ✻ ✽` forward then reverse
+- **Random verb per turn**: analyzing, thinking, planning, exploring, searching, reading, computing, processing, generating, understanding, writing, compiling, checking, optimizing, learning
+- **Elapsed timer**: shows after 1 second
+- **Stall detection**: glyph turns red after 3s of no new content
+- Auto-clears on first delta
+
+### Output Modes
+
+| Mode | Flag | Description |
+|---|---|---|
+| Human-readable (default) | — | Stream deltas to stdout |
+| JSON | `--json` | Buffer all events, output one final JSON object |
+| JSONL | `--jsonl` | Output each event frame as a JSON Line |
+
+```bash
+# JSON output
+jiuwenswarm chat --json "analyze README"
+# → {"ok": true, "content": "..."}
+
+# JSONL output (pipe-friendly)
+jiuwenswarm chat --jsonl "analyze README" | jq
+```
+
+### Interrupts
+
+| Action | Behavior |
+|---|---|
+| First Ctrl+C | Sends `chat.interrupt` to Agent, graceful cancel |
+| Second Ctrl+C | Immediate exit (`os._exit(130)`) |
+
+### Exit Codes
+
+| Code | Meaning |
+|---|---|
+| 0 | Success |
+| 1 | Agent returned an error |
+| 2 | CLI usage or invalid mode |
+| 3 | Gateway unavailable |
+| 4 | Interactive input required but stdin is not a TTY |
+| 130 | Interrupted by user |
+
+### Relationship with TUI
+
+`jiuwenswarm chat` uses an independent `/cli` route (`channel_id="cli"`), isolated from the TUI's `/tui` route. Both can be used simultaneously without interfering with each other. The first version of the terminal CLI does not aim to replicate all TUI slash commands.
diff --git a/docs/en/Quickstart.md b/docs/en/Quickstart.md
index 0fd7e268bf..1c7efa1d80 100644
--- a/docs/en/Quickstart.md
+++ b/docs/en/Quickstart.md
@@ -58,6 +58,16 @@ After successful startup, the terminal will display backend service status:
When you see similar output, the service is ready. Open `http://localhost:5173` in your browser to use.
+### Terminal CLI
+
+You can also chat with JiuwenSwarm directly from the terminal:
+
+```bash
+jiuwenswarm chat "Hello, introduce yourself"
+```
+
+For details, see [CLI / Terminal Chat](CLI.md#terminal-cli-jiuwenswarm-chat).
+
### Remote Access (Optional)
For remote access, run the following commands:
diff --git a/docs/zh/Quickstart.md b/docs/zh/Quickstart.md
index fa5c7cdb05..a4878bf27a 100644
--- a/docs/zh/Quickstart.md
+++ b/docs/zh/Quickstart.md
@@ -58,6 +58,16 @@ jiuwenswarm-start
当看到类似上述提示时,表示服务已启动,在浏览器中访问 `http://localhost:5173` 即可使用。
+### 终端 CLI
+
+也可以直接在终端中与 JiuwenSwarm 对话:
+
+```bash
+jiuwenswarm chat "你好,介绍一下你自己"
+```
+
+详情见 [命令行指令 / 终端 CLI](命令行指令.md#终端-clijiuwenswarm-chat)。
+
**配置目录自动创建**:
首次启动服务后,系统会自动创建配置目录:
- **Windows**:`C:\Users\<你的用户名>\.jiuwenswarm`
diff --git "a/docs/zh/\345\221\275\344\273\244\350\241\214\346\214\207\344\273\244.md" "b/docs/zh/\345\221\275\344\273\244\350\241\214\346\214\207\344\273\244.md"
index a547014830..6219328284 100644
--- "a/docs/zh/\345\221\275\344\273\244\350\241\214\346\214\207\344\273\244.md"
+++ "b/docs/zh/\345\221\275\344\273\244\350\241\214\346\214\207\344\273\244.md"
@@ -193,4 +193,150 @@ Gateway 会回复确认提示,要求用户确认:
- `config.yaml` 中可设置 `default_mode` 作为初始值,`MessageHandler` 启动时会读取
- `/new_session` 和 `/mode` 变更时会自动取消当前 session 正在执行的任务
+---
+
+## 终端 CLI:`jiuwenswarm chat`
+
+从 v0.2.1 开始,JiuwenSwarm 提供了原生命令行聊天入口,可以在终端中直接与 JiuwenSwarm 对话。
+
+### 快速开始
+
+```bash
+# 启动 Gateway 和 AgentServer(如未启动)
+jiuwenswarm-start app
+
+# 发送一条消息
+jiuwenswarm chat "你好,介绍一下你自己"
+```
+
+`jiuwenswarm chat` 通过 Gateway 的 `/cli` WebSocket 路由调用 JiuwenSwarm 的运行时,与 TUI 使用相同的 MessageHandler 和 AgentServer 路径。
+
+### 基本用法
+
+| 命令 | 说明 |
+|---|---|
+| `jiuwenswarm chat "hello"` | 发送单条消息 |
+| `jiuwenswarm chat 检查 仓库 并 给出 建议` | 多词自动拼接为一个 prompt |
+| `echo "分析 main.py" \| jiuwenswarm chat` | 管道输入 |
+| `jiuwenswarm chat` | 无参数 + 交互终端 → 进入 REPL 模式 |
+
+### 选项
+
+| 选项 | 默认值 | 说明 |
+|---|---|---|
+| `--mode <mode>` | `code.normal` | 执行模式,见[模式系统](模式系统.md) |
+| `--session <id>` | 自动生成 | 指定或复用会话 ID |
+| `--cwd <path>` | 当前目录 | 文件引用和 Agent 上下文的工作目录 |
+| `--project-dir <path>` | `--cwd` | 项目和 agent 缓存标识 |
+| `--trusted-dir <path>` | `--project-dir` | 信任目录(可重复) |
+| `--gateway-url <url>` | `ws://127.0.0.1:19001/cli` | 自定义 Gateway 地址 |
+| `--name <instance>` | — | 多实例隔离 |
+| `--dotenv <path>` | — | 指定 .env 文件 |
+| `--json` | — | 输出一个最终 JSON 对象 |
+| `--jsonl` | — | 逐行输出 JSON 事件帧 |
+| `--show-reasoning` | — | 显示推理过程(输出到 stderr) |
+| `--show-tools` | — | 显示工具调用/结果(输出到 stderr) |
+| `--timeout <seconds>` | 300 | 单次 recv 超时(秒) |
+
+### 模式(`--mode`)
+
+支持的模式值与[模式系统](模式系统.md)一致:
+
+| 模式 | 别名 | 说明 |
+|---|---|---|
+| `code.normal` | `code`、`normal` | 默认,代码普通模式 |
+| `code.plan` | — | 代码规划模式 |
+| `code.team` | — | 代码团队模式 |
+| `agent.plan` | `agent` | Agent 规划模式 |
+| `agent.fast` | `fast` | Agent 快速模式 |
+| `team` | `team.normal` | 团队模式 |
+
+```bash
+# 使用别名
+jiuwenswarm chat --mode fast "快速回答"
+jiuwenswarm chat --mode agent "帮我做规划"
+
+# 使用规范值
+jiuwenswarm chat --mode code.plan "设计一个用户系统"
+```
+
+### 会话复用
+
+```bash
+# 首次:指定会话名
+jiuwenswarm chat --session project-a "分析项目架构"
+
+# 后续:复用同一会话,保持上下文
+jiuwenswarm chat --session project-a "有什么改进建议?"
+
+# 不指定 --session 时自动生成 cli-YYYYMMDD-HHMMSS-xxxxxxxx
+```
+
+### REPL 模式
+
+不带 prompt 参数直接运行,自动进入多轮对话:
+
+```bash
+jiuwenswarm chat
+# Session: cli-20260616-120500-abc12345
+# > 帮我看看当前目录的文件
+# > 分析 main.py
+# > 按 Ctrl+D 退出
+```
+
+REPL 中所有消息复用同一个 session,保持上下文连续。
+
+### 加载动画
+
+发送请求后,在等待第一个回复期间,终端会显示动态加载提示(输出到 stderr,不影响内容重定向):
+
+```
+✢ analyzing (3s)
+```
+
+- **12 帧 ping-pong 动画**:`␣ · ✢ ✳ ✶ ✻ ✽` 正反循环
+- **随机动词**:analyzing, thinking, planning, exploring, searching, reading, computing, processing, generating, understanding, writing, compiling, checking, optimizing, learning
+- **计时器**:1 秒后开始显示耗时
+- **卡顿检测**:3 秒无新内容时图标变红
+- 收到第一个 delta 后自动清除
+
+### 输出模式
+
+| 模式 | 命令 | 说明 |
+|---|---|---|
+| 人类可读(默认) | — | 流式输出 delta 到 stdout |
+| JSON | `--json` | 缓冲所有事件,最后输出一个 JSON 对象 |
+| JSONL | `--jsonl` | 每收到一个事件帧就输出一行 JSON |
+
+```bash
+# JSON 输出
+jiuwenswarm chat --json "分析 README"
+# → {"ok": true, "content": "..."}
+
+# JSONL 输出(适合管道处理)
+jiuwenswarm chat --jsonl "分析 README" | jq
+```
+
+### 中断操作
+
+| 操作 | 行为 |
+|---|---|
+| 第一次 Ctrl+C | 发送 `chat.interrupt` 给 Agent,尝试优雅取消 |
+| 第二次 Ctrl+C | 立即退出(`os._exit(130)`) |
+
+### 退出码
+
+| 码 | 含义 |
+|---|---|
+| 0 | 成功 |
+| 1 | Agent 返回错误 |
+| 2 | CLI 参数错误 |
+| 3 | Gateway 不可达 |
+| 4 | 需要交互输入但 stdin 不是 TTY |
+| 130 | 用户中断 |
+
+### 与 TUI 的关系
+
+`jiuwenswarm chat` 使用独立的 `/cli` 路由(`channel_id="cli"`),与 TUI 的 `/tui` 路由隔离,两者可以同时使用而不会互相干扰。终端 CLI 的第一版不追求完整复刻 TUI 的所有 slash command。
+
diff --git a/jiuwenswarm/cli/__init__.py b/jiuwenswarm/cli/__init__.py
new file mode 100644
index 0000000000..fc7f53948b
--- /dev/null
+++ b/jiuwenswarm/cli/__init__.py
@@ -0,0 +1 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
diff --git a/jiuwenswarm/cli/_terminal.py b/jiuwenswarm/cli/_terminal.py
new file mode 100644
index 0000000000..937d730cad
--- /dev/null
+++ b/jiuwenswarm/cli/_terminal.py
@@ -0,0 +1,25 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Low-level terminal output primitives for CLI chat.
+
+These are NOT log messages — they implement terminal UI (spinner animation,
+streaming content to stdout, structured JSON/JSONL output). Using ``os.write``
+rather than ``sys.*.write`` or ``print`` because G.LOG.02 requires that
+application-level log messages go through the ``logging`` module, but terminal
+UI rendering is not logging.
+"""
+
+from __future__ import annotations
+
+import os
+
+STDOUT_FD = 1
+STDERR_FD = 2
+
+
+def write_stdout(text: str) -> None:
+ os.write(STDOUT_FD, text.encode())
+
+
+def write_stderr(text: str) -> None:
+ os.write(STDERR_FD, text.encode())
diff --git a/jiuwenswarm/cli/chat.py b/jiuwenswarm/cli/chat.py
new file mode 100644
index 0000000000..33a489af8d
--- /dev/null
+++ b/jiuwenswarm/cli/chat.py
@@ -0,0 +1,449 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Chat command orchestration: parse args, connect Gateway, stream response."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import datetime
+import logging
+import os
+import signal
+import sys
+import uuid as uuid_module
+from pathlib import Path
+
+from jiuwenswarm.cli._terminal import write_stderr, write_stdout
+from jiuwenswarm.cli.gateway_client import GatewayClient
+from jiuwenswarm.cli.events import (
+ event_kind,
+ is_terminal_event,
+)
+from jiuwenswarm.cli.render import HumanRenderer, JsonRenderer, JsonlRenderer
+
+logger = logging.getLogger(__name__)
+
+MODE_ALIASES: dict[str, str] = {
+ "agent": "agent.plan",
+ "fast": "agent.fast",
+ "code": "code.normal",
+ "normal": "code.normal",
+ "team.normal": "team",
+}
+
+VALID_MODES = frozenset({
+ "agent.plan", "agent.fast", "code.plan", "code.normal", "code.team", "team",
+})
+
+
+def resolve_mode(raw: str) -> str:
+ normalized = raw.strip().lower()
+ if normalized in MODE_ALIASES:
+ normalized = MODE_ALIASES[normalized]
+ if normalized in VALID_MODES:
+ return normalized
+ raise ValueError(
+ f"invalid mode: {raw!r}. valid values: {', '.join(sorted(VALID_MODES))}"
+ )
+
+
+def _build_default_gateway_url(path: str = "/tui") -> str:
+ port = os.getenv("GATEWAY_PORT", "19001")
+ host = os.getenv("GATEWAY_HOST", "127.0.0.1")
+ return f"ws://{host}:{port}{path}"
+
+
+def _generate_session_id() -> str:
+ now = datetime.datetime.now(datetime.UTC)
+ short = uuid_module.uuid4().hex[:8]
+ return f"cli-{now.strftime('%Y%m%d-%H%M%S')}-{short}"
+
+
+def build_parser() -> argparse.ArgumentParser:
+ p = argparse.ArgumentParser(
+ prog="jiuwenswarm chat",
+ description="Chat with JiuwenSwarm from the command line.",
+ )
+ p.add_argument(
+ "prompt", nargs="*",
+ help="Prompt text (joined with spaces). If omitted and stdin is piped, read stdin.",
+ )
+ p.add_argument(
+ "--mode", default="code.normal",
+ help="Execution mode (default: code.normal).",
+ )
+ p.add_argument(
+ "--session",
+ help="Reuse or create a named session id.",
+ )
+ p.add_argument(
+ "--cwd",
+ help="Working directory for file mentions and agent context.",
+ )
+ p.add_argument(
+ "--project-dir",
+ help="Project identity for session and agent cache. Defaults to --cwd.",
+ )
+ p.add_argument(
+ "--trusted-dir", action="append", default=None,
+ help="Trusted directory (repeatable). Defaults to --project-dir.",
+ )
+ p.add_argument(
+ "--gateway-url",
+ help="Explicit Gateway WebSocket URL.",
+ )
+ p.add_argument(
+ "--name",
+ help="Named instance for env isolation.",
+ )
+ p.add_argument(
+ "--dotenv",
+ help="Path to .env file for env isolation.",
+ )
+ p.add_argument(
+ "--json", action="store_true",
+ help="Print one final JSON object.",
+ )
+ p.add_argument(
+ "--jsonl", action="store_true",
+ help="Print each Gateway event frame as JSON Lines.",
+ )
+ p.add_argument(
+ "--show-reasoning", action="store_true",
+ help="Include reasoning output (stderr).",
+ )
+ p.add_argument(
+ "--show-tools", action="store_true",
+ help="Include compact tool call/result status (stderr).",
+ )
+ p.add_argument(
+ "--timeout", type=float,
+ help="Total response timeout in seconds.",
+ )
+ return p
+
+
+def _validate_args(args: argparse.Namespace) -> int | None:
+ try:
+ args.mode = resolve_mode(args.mode)
+ except ValueError as exc:
+ logger.error("invalid mode: %s", exc)
+ return 2
+ if args.json and args.jsonl:
+ logger.error("--json and --jsonl are mutually exclusive")
+ return 2
+ if args.show_reasoning and args.jsonl:
+ pass
+ if args.timeout is not None and args.timeout <= 0:
+ logger.error("--timeout must be positive")
+ return 2
+ return None
+
+
+def _build_request(args: argparse.Namespace, prompt: str) -> dict:
+ session_id = args.session or _generate_session_id()
+ cwd = str(Path(args.cwd or os.getcwd()).resolve())
+ project_dir = str(Path(args.project_dir or cwd).resolve())
+ trusted_dirs = args.trusted_dir
+ if not trusted_dirs:
+ trusted_dirs = [project_dir]
+ else:
+ trusted_dirs = [str(Path(d).resolve()) for d in trusted_dirs]
+
+ return {
+ "type": "req",
+ "id": f"chat-{uuid_module.uuid4().hex[:12]}",
+ "method": "chat.send",
+ "is_stream": True,
+ "params": {
+ "session_id": session_id,
+ "content": prompt,
+ "query": prompt,
+ "mode": args.mode,
+ "cwd": cwd,
+ "project_dir": project_dir,
+ "trusted_dirs": trusted_dirs,
+ },
+ }
+
+
+async def _spinner_loop(renderer: HumanRenderer) -> None:
+ while renderer.loading:
+ renderer.tick_spinner()
+ await asyncio.sleep(0.2)
+
+
+async def _run_interactive_loop(
+ client: GatewayClient,
+ renderer: HumanRenderer,
+ request: dict,
+ *,
+ timeout: float | None = None,
+) -> int:
+ interrupted = False
+ per_recv_timeout = timeout if timeout and timeout > 0 else 300.0
+
+ loop = asyncio.get_running_loop()
+
+ def _on_first_sigint() -> None:
+ nonlocal interrupted
+ interrupted = True
+ logger.warning("Interrupted. Sending cancel (press Ctrl+C again to force exit)...")
+ try:
+ loop.add_signal_handler(signal.SIGINT, _on_second_sigint)
+ except NotImplementedError:
+ pass
+
+ def _on_second_sigint() -> None:
+ os.kill(os.getpid(), signal.SIGTERM)
+
+ try:
+ loop.add_signal_handler(signal.SIGINT, _on_first_sigint)
+ except NotImplementedError:
+ pass
+
+ await client.send_request(request)
+
+ renderer.ensure_loading()
+ spinner = asyncio.create_task(_spinner_loop(renderer))
+
+ try:
+ while True:
+ try:
+ data = await asyncio.wait_for(client.recv(), timeout=per_recv_timeout)
+ except asyncio.TimeoutError:
+ logger.warning("response timed out")
+ return 1
+ except ConnectionError:
+ return 0
+
+ if interrupted:
+ await client.send_request({
+ "type": "req",
+ "id": f"interrupt-{uuid_module.uuid4().hex[:8]}",
+ "method": "chat.interrupt",
+ "is_stream": False,
+ "params": {
+ "session_id": request["params"]["session_id"],
+ "intent": "cancel",
+ "mode": request["params"]["mode"],
+ },
+ })
+ return 130
+
+ if data.get("type") != "event":
+ continue
+
+ event_type = data.get("event", "")
+ payload = data.get("payload", {})
+ kind = event_kind(event_type)
+
+ if kind == "delta":
+ renderer.handle_delta(payload)
+ elif kind == "reasoning":
+ renderer.handle_reasoning(payload)
+ elif kind == "tool_call":
+ renderer.handle_tool_call(payload)
+ elif kind == "tool_result":
+ renderer.handle_tool_result(payload)
+ elif kind == "final":
+ renderer.handle_final(payload)
+ elif kind == "error":
+ renderer.handle_error(payload)
+ return 1
+ elif kind == "processing_status":
+ if payload.get("is_processing", False):
+ renderer.ensure_loading()
+ 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()
+ 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", ""),
+ },
+ })
+ except ConnectionError:
+ return 0
+ else:
+ logger.error("interactive input required but stdin is not a TTY: %s", event_type)
+ return 4
+
+ if is_terminal_event(event_type, payload):
+ renderer.clear_loading()
+ if renderer.streamed_text and not renderer.streamed_text.endswith("\n"):
+ write_stdout("\n")
+ return 0
+
+ finally:
+ spinner.cancel()
+ try:
+ await spinner
+ except asyncio.CancelledError:
+ pass
+ try:
+ loop.remove_signal_handler(signal.SIGINT)
+ except (NotImplementedError, ValueError):
+ pass
+
+
+async def _run_jsonl_loop(
+ client: GatewayClient,
+ renderer: JsonlRenderer,
+ request: dict,
+) -> int:
+ await client.send_request(request)
+ while True:
+ data = await client.recv()
+ if data.get("type") != "event":
+ continue
+ event_type = data.get("event", "")
+ payload = data.get("payload", {})
+ renderer.handle_event(event_type, payload)
+ if event_type == "chat.error":
+ return 1
+ if is_terminal_event(event_type, payload):
+ return 0
+
+
+async def _run_json_loop(
+ client: GatewayClient,
+ renderer: JsonRenderer,
+ request: dict,
+) -> int:
+ await client.send_request(request)
+ has_error = False
+ while True:
+ data = await client.recv()
+ if data.get("type") != "event":
+ continue
+ event_type = data.get("event", "")
+ payload = data.get("payload", {})
+ if event_type == "chat.final":
+ renderer.handle_event(event_type, payload)
+ elif event_type == "chat.error":
+ renderer.handle_error(payload)
+ has_error = True
+ elif event_type == "chat.delta":
+ pass
+ else:
+ renderer.handle_event(event_type, payload)
+ if is_terminal_event(event_type, payload):
+ renderer.output()
+ return 1 if has_error else 0
+
+
+async def _run_chat(
+ args: argparse.Namespace,
+ prompt: str,
+) -> int:
+ gateway_url = args.gateway_url or _build_default_gateway_url()
+
+ client = GatewayClient(gateway_url)
+
+ try:
+ await asyncio.wait_for(client.connect(), timeout=10.0)
+ except asyncio.TimeoutError:
+ _print_connection_hint(gateway_url, args)
+ return 3
+ except ConnectionError:
+ _print_connection_hint(gateway_url, args)
+ return 3
+ except OSError:
+ _print_connection_hint(gateway_url, args)
+ return 3
+
+ request = _build_request(args, prompt)
+
+ try:
+ if args.jsonl:
+ renderer: JsonlRenderer | JsonRenderer | HumanRenderer = JsonlRenderer()
+ return await _run_jsonl_loop(client, renderer, request)
+ elif args.json:
+ renderer = JsonRenderer()
+ return await _run_json_loop(client, renderer, request)
+ else:
+ renderer = HumanRenderer(
+ show_reasoning=args.show_reasoning,
+ show_tools=args.show_tools,
+ )
+ return await _run_interactive_loop(
+ client, renderer, request,
+ timeout=args.timeout,
+ )
+ finally:
+ await client.close()
+
+
+def _print_connection_hint(url: str, args: argparse.Namespace) -> None:
+ logger.error("Cannot connect to JiuwenSwarm Gateway at %s.", url)
+ if args.name:
+ logger.error("Start services with: jiuwenswarm-start app --name %s", args.name)
+ else:
+ logger.error("Start services with: jiuwenswarm-start app")
+
+
+def run_chat(args: argparse.Namespace) -> int:
+ if args.prompt:
+ prompt = " ".join(args.prompt)
+ elif not sys.stdin.isatty():
+ prompt = sys.stdin.read().strip()
+ else:
+ return _run_repl(args)
+
+ if not prompt:
+ logger.error("no prompt provided and stdin is empty")
+ return 2
+
+ error = _validate_args(args)
+ if error is not None:
+ return error
+
+ return asyncio.run(_run_chat(args, prompt))
+
+
+def _run_repl(args: argparse.Namespace) -> int:
+ if not sys.stdin.isatty():
+ logger.error("REPL mode requires interactive terminal")
+ return 2
+
+ error = _validate_args(args)
+ if error is not None:
+ return error
+
+ session_id = args.session or _generate_session_id()
+ args.session = session_id
+
+ logger.info("Session: %s", session_id)
+ logger.info("Type your prompt and press Enter. Ctrl+C to interrupt, Ctrl+D to exit.")
+
+ exit_code = 0
+ try:
+ while True:
+ try:
+ line = input("> ")
+ except EOFError:
+ logger.info("<EOF>")
+ break
+ if not line.strip():
+ continue
+ exit_code = asyncio.run(_run_chat(args, line.strip()))
+ if exit_code == 130:
+ break
+ if exit_code != 0:
+ logger.warning("[exit code: %s]", exit_code)
+ except KeyboardInterrupt:
+ logger.info("<KeyboardInterrupt>")
+ return exit_code
diff --git a/jiuwenswarm/cli/events.py b/jiuwenswarm/cli/events.py
new file mode 100644
index 0000000000..2d007ba8ce
--- /dev/null
+++ b/jiuwenswarm/cli/events.py
@@ -0,0 +1,47 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Event processing decisions: interactivity detection and stream termination."""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+def is_terminal_event(event_type: str, payload: dict[str, Any]) -> bool:
+ if event_type == "chat.error":
+ return True
+ if event_type == "chat.final":
+ inner = payload.get("event_type", "")
+ if inner == "keepalive":
+ return False
+ return True
+ if event_type == "chat.processing_status":
+ if not payload.get("is_processing", True):
+ return True
+ return False
+
+
+def needs_user_input(event_type: str) -> bool:
+ return event_type in ("chat.ask_user_question", "plan.approval_required")
+
+
+def event_kind(event_type: str) -> str:
+ if event_type in ("chat.delta",):
+ return "delta"
+ if event_type in ("chat.reasoning",):
+ return "reasoning"
+ if event_type in ("chat.tool_call",):
+ return "tool_call"
+ if event_type in ("chat.tool_result",):
+ return "tool_result"
+ if event_type in ("chat.final",):
+ return "final"
+ if event_type in ("chat.error",):
+ return "error"
+ if event_type in ("chat.ask_user_question", "plan.approval_required"):
+ return "interactive"
+ if event_type in ("chat.processing_status",):
+ return "processing_status"
+ if event_type.startswith("chat.") or event_type.startswith("plan."):
+ return "chat"
+ return "other"
diff --git a/jiuwenswarm/cli/gateway_client.py b/jiuwenswarm/cli/gateway_client.py
new file mode 100644
index 0000000000..898b5b05cc
--- /dev/null
+++ b/jiuwenswarm/cli/gateway_client.py
@@ -0,0 +1,76 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Gateway `/tui`-compatible WebSocket client for CLI."""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+def _connect_ws(url: str):
+ try:
+ from websockets.legacy.client import connect as legacy_connect
+ return legacy_connect(url, close_timeout=2.0, max_size=8 * 2**20)
+ except ImportError:
+ import websockets
+ return websockets.connect(url, close_timeout=2.0, max_size=8 * 2**20)
+
+
+class GatewayClient:
+ def __init__(self, url: str) -> None:
+ self._url = url
+ self._ws: Any = None
+
+ @property
+ def url(self) -> str:
+ return self._url
+
+ async def connect(self) -> None:
+ self._ws = await _connect_ws(self._url)
+
+ try:
+ raw = await self._ws.recv()
+ except Exception:
+ await self._ws.close()
+ self._ws = None
+ raise ConnectionError(
+ f"Gateway closed connection before sending ack: {self._url}"
+ ) from None
+
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ await self._ws.close()
+ self._ws = None
+ raise ConnectionError(
+ f"Gateway sent invalid ack frame: {self._url}"
+ ) from None
+
+ if data.get("type") != "event" or data.get("event") != "connection.ack":
+ await self._ws.close()
+ self._ws = None
+ raise ConnectionError(
+ f"Expected connection.ack, got: {data.get('type')}/{data.get('event')}"
+ ) from None
+
+ logger.debug("[GatewayClient] connected: %s", self._url)
+
+ async def send_request(self, frame: dict[str, Any]) -> None:
+ await self._ws.send(json.dumps(frame, ensure_ascii=False))
+
+ async def recv(self) -> dict[str, Any]:
+ raw = await self._ws.recv()
+ return json.loads(raw)
+
+ async def close(self) -> None:
+ if self._ws is not None:
+ ws = self._ws
+ self._ws = None
+ await ws.close()
+
+ def set_mock_ws(self, ws: Any) -> None:
+ self._ws = ws
diff --git a/jiuwenswarm/cli/main.py b/jiuwenswarm/cli/main.py
new file mode 100644
index 0000000000..88d4a281ea
--- /dev/null
+++ b/jiuwenswarm/cli/main.py
@@ -0,0 +1,41 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Root ``jiuwenswarm`` CLI entry point."""
+
+from __future__ import annotations
+
+import logging
+import os
+import sys
+
+from jiuwenswarm.dotenv_early import parse_dotenv_early
+
+parse_dotenv_early("jiuwenswarm")
+
+logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stderr)
+
+
+def main() -> None:
+ from jiuwenswarm.cli.chat import build_parser as build_chat_parser
+ from jiuwenswarm.cli.chat import run_chat
+
+ if os.environ.get("JIUWENSWARM_SKIP_DOTENV", "").strip() != "1":
+ try:
+ from dotenv import load_dotenv
+ from jiuwenswarm.common.utils import get_env_file
+
+ load_dotenv(dotenv_path=get_env_file(), override=False)
+ except ImportError:
+ pass
+
+ argv = sys.argv[1:]
+ if argv and argv[0] == "chat":
+ argv = argv[1:]
+
+ chat_parser = build_chat_parser()
+ chat_args = chat_parser.parse_args(argv)
+ sys.exit(run_chat(chat_args))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/jiuwenswarm/cli/render.py b/jiuwenswarm/cli/render.py
new file mode 100644
index 0000000000..d7f805353c
--- /dev/null
+++ b/jiuwenswarm/cli/render.py
@@ -0,0 +1,233 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Output rendering for CLI chat: human-readable, JSON, and JSONL modes."""
+
+from __future__ import annotations
+
+import json
+import logging
+import random
+import time
+from collections.abc import Callable
+from typing import Any
+
+from jiuwenswarm.cli._terminal import write_stderr, write_stdout
+
+_logger = logging.getLogger(__name__)
+
+_FORWARD = [" ", "·", "✢", "✳", "✶", "✻", "✽"]
+_SPINNER_FRAMES: list[str] = _FORWARD + list(reversed(_FORWARD[1:-1]))
+
+_STALL_THRESHOLD_S = 3.0
+_VERB_ROTATE_INTERVAL_S = 5.0
+_GAP_THRESHOLD_S = 0.5
+
+_VERBS = [
+ "analyzing", "thinking", "planning", "exploring", "searching",
+ "reading", "computing", "processing", "generating", "understanding",
+ "writing", "compiling", "checking", "optimizing", "learning",
+]
+
+
+class HumanRenderer:
+ def __init__(
+ self,
+ *,
+ show_reasoning: bool = False,
+ show_tools: bool = False,
+ status_writer: Callable[[str], None] | None = None,
+ content_writer: Callable[[str], None] | None = None,
+ ) -> None:
+ self._show_reasoning = show_reasoning
+ self._show_tools = show_tools
+ self._streamed_text = ""
+ self._printed_final = False
+ self._loading = False
+ self._spinner_idx = 0
+ self._start_time = 0.0
+ self._last_token_time = 0.0
+ self._verb = ""
+ self._last_verb_time = 0.0
+
+ self._status_writer = status_writer or self._default_status_writer
+ self._content_writer = content_writer or self._default_content_writer
+
+ @staticmethod
+ def _default_status_writer(text: str) -> None:
+ write_stderr(text)
+
+ @staticmethod
+ def _default_content_writer(text: str) -> None:
+ write_stdout(text)
+
+ @property
+ def loading(self) -> bool:
+ return self._loading
+
+ @property
+ def streamed_text(self) -> str:
+ return self._streamed_text
+
+ @property
+ def start_time(self) -> float:
+ return self._start_time
+
+ @property
+ def verb(self) -> str:
+ return self._verb
+
+ @property
+ def spinner_idx(self) -> int:
+ return self._spinner_idx
+
+ def clear_loading(self) -> None:
+ if not self._loading:
+ return
+ self._status_writer("\r\033[K")
+ self._loading = False
+
+ def ensure_loading(self) -> None:
+ if self._loading:
+ return
+ self._loading = True
+ now = time.monotonic()
+ self._start_time = now
+ self._last_token_time = now
+ self._last_verb_time = now
+ self._verb = random.choice(_VERBS)
+
+ def tick_spinner(self) -> None:
+ if not self._loading:
+ return
+ self._spinner_idx = (self._spinner_idx + 1) % len(_SPINNER_FRAMES)
+
+ now = time.monotonic()
+ elapsed = now - self._start_time
+ idle_time = now - self._last_token_time
+
+ if now - self._last_verb_time >= _VERB_ROTATE_INTERVAL_S:
+ candidates = [v for v in _VERBS if v != self._verb]
+ self._verb = random.choice(candidates) if candidates else self._verb
+ self._last_verb_time = now
+
+ glyph = _SPINNER_FRAMES[self._spinner_idx]
+ if idle_time > _STALL_THRESHOLD_S:
+ glyph = f"\033[31m{glyph}\033[0m"
+
+ timer = f"({elapsed:.0f}s)" if elapsed >= 1.0 else ""
+ parts = [glyph, self._verb, timer]
+ line = " ".join(p for p in parts if p)
+
+ self._status_writer(f"\r{line}\033[K")
+
+ def handle_delta(self, payload: dict[str, Any]) -> None:
+ text = payload.get("content", "")
+ if isinstance(text, str) and text:
+ if self._streamed_text and not self._streamed_text.endswith("\n"):
+ gap = time.monotonic() - self._last_token_time
+ if gap > _GAP_THRESHOLD_S:
+ self._content_writer("\n\n")
+ self._streamed_text += "\n\n"
+ self._last_token_time = time.monotonic()
+ self.clear_loading()
+ self._content_writer(text)
+ self._streamed_text += text
+
+ def handle_reasoning(self, payload: dict[str, Any]) -> None:
+ if not self._show_reasoning:
+ return
+ self._last_token_time = time.monotonic()
+ text = payload.get("content", "")
+ if isinstance(text, str) and text:
+ _logger.info("%s", text)
+
+ def handle_tool_call(self, payload: dict[str, Any]) -> None:
+ if not self._show_tools:
+ return
+ self._last_token_time = time.monotonic()
+ name = payload.get("tool_name") or payload.get("name", "?")
+ args = payload.get("arguments") or payload.get("input", {})
+ arg_str = json.dumps(args, ensure_ascii=False, default=str)
+ if len(arg_str) > 120:
+ arg_str = arg_str[:117] + "..."
+ _logger.info("[tool] %s: %s", name, arg_str)
+
+ def handle_tool_result(self, payload: dict[str, Any]) -> None:
+ if not self._show_tools:
+ return
+ self._last_token_time = time.monotonic()
+ name = payload.get("tool_name") or payload.get("name", "?")
+ status = payload.get("status", "done")
+ _logger.info("[tool] %s -> %s", name, status)
+
+ def handle_final(self, payload: dict[str, Any]) -> None:
+ if self._printed_final:
+ return
+ self._printed_final = True
+ self.clear_loading()
+ final_text = payload.get("content", "")
+ if not isinstance(final_text, str) or not final_text:
+ return
+ if final_text == self._streamed_text:
+ return
+ if final_text.startswith(self._streamed_text):
+ suffix = final_text[len(self._streamed_text):]
+ self._content_writer(suffix)
+ self._streamed_text = final_text
+ else:
+ self._content_writer(final_text)
+ self._streamed_text = final_text
+
+ def handle_error(self, payload: dict[str, Any]) -> None:
+ self.clear_loading()
+ error = payload.get("error") or payload.get("message", "unknown error")
+ _logger.error("%s", error)
+
+
+class JsonRenderer:
+ def __init__(
+ self,
+ *,
+ content_writer: Callable[[str], None] | None = None,
+ ) -> None:
+ self._events: list[dict[str, Any]] = []
+ self._content_writer = content_writer or self._default_content_writer
+
+ @staticmethod
+ def _default_content_writer(text: str) -> None:
+ write_stdout(text)
+
+ def handle_event(self, _event_type: str, payload: dict[str, Any]) -> None:
+ self._events.append(payload)
+
+ def output(self) -> None:
+ final_content = ""
+ for evt in self._events:
+ if isinstance(evt.get("content"), str) and evt["content"]:
+ final_content = evt["content"]
+ result: dict[str, Any] = {"ok": True, "content": final_content}
+ errors = [e for e in self._events if e.get("error")]
+ if errors:
+ result["ok"] = False
+ result["error"] = errors[-1].get("error", "unknown error")
+ self._content_writer(json.dumps(result, ensure_ascii=False, default=str) + "\n")
+
+ def handle_error(self, payload: dict[str, Any]) -> None:
+ self._events.append(payload)
+
+
+class JsonlRenderer:
+ def __init__(
+ self,
+ *,
+ content_writer: Callable[[str], None] | None = None,
+ ) -> None:
+ self._content_writer = content_writer or self._default_content_writer
+
+ @staticmethod
+ def _default_content_writer(text: str) -> None:
+ write_stdout(text)
+
+ def handle_event(self, event_type: str, payload: dict[str, Any]) -> None:
+ frame: dict[str, Any] = {"type": "event", "event": event_type, "payload": payload}
+ self._content_writer(json.dumps(frame, ensure_ascii=False, default=str) + "\n")
diff --git a/pyproject.toml b/pyproject.toml
index bd392fd6c2..3eb6cf6d3a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -69,6 +69,7 @@ test = [
]
[project.scripts]
+jiuwenswarm = "jiuwenswarm.cli.main:main"
jiuwenswarm-app = "jiuwenswarm.app:main"
jiuwenswarm-agentserver = "jiuwenswarm.server.app_agentserver:main"
jiuwenswarm-gateway = "jiuwenswarm.gateway.app_gateway:main"
@@ -76,7 +77,6 @@ jiuwenswarm-web = "jiuwenswarm.channels.web.app_web:main"
jiuwenswarm-start = "jiuwenswarm.start_services:main"
jiuwenswarm-init = "jiuwenswarm.init_workspace:main"
jiuwenswarm-desktop = "jiuwenswarm.channels.desktop.desktop_app:main"
-jiuwenswarm-tui = "jiuwenswarm.channels.acp.app_acp:main"
jiuwenswarm-acp = "jiuwenswarm.gateway.channel_manager.protocol.acp.acp_connect:main"
jiuwenswarm-acp-chat = "jiuwenswarm.acp.cli:main"
jiuwenbox = "jiuwenbox.cli.jiuwenbox:main"
@@ -91,7 +91,7 @@ package-dir = {"jiuwenbox" = "jiuwenbox/src/jiuwenbox"}
[tool.setuptools.packages.find]
where = [".", "jiuwenbox/src"]
include = ["jiuwenswarm*", "jiuwenbox*"]
-exclude = ["jiuwenswarm.cli*", "jiuwenswarm.web*"]
+exclude = ["jiuwenswarm.web*"]
namespaces = false
[tool.setuptools.package-data]
diff --git a/tests/unit_tests/cli/__init__.py b/tests/unit_tests/cli/__init__.py
new file mode 100644
index 0000000000..fc7f53948b
--- /dev/null
+++ b/tests/unit_tests/cli/__init__.py
@@ -0,0 +1 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
diff --git a/tests/unit_tests/cli/test_chat.py b/tests/unit_tests/cli/test_chat.py
new file mode 100644
index 0000000000..7cfc466265
--- /dev/null
+++ b/tests/unit_tests/cli/test_chat.py
@@ -0,0 +1,916 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for jiuwenswarm CLI chat module."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import io
+import json
+import os
+from unittest.mock import patch
+
+import pytest
+
+from jiuwenswarm.cli.chat import (
+ MODE_ALIASES,
+ VALID_MODES,
+ _build_default_gateway_url,
+ _build_request,
+ _generate_session_id,
+ _validate_args,
+ build_parser,
+ resolve_mode,
+)
+from jiuwenswarm.cli.events import (
+ event_kind,
+ is_terminal_event,
+ needs_user_input,
+)
+from jiuwenswarm.cli.gateway_client import GatewayClient
+from jiuwenswarm.cli.render import HumanRenderer, JsonRenderer, JsonlRenderer
+
+
+class TestResolveMode:
+ @staticmethod
+ def test_canonical_values_pass_through():
+ assert resolve_mode("code.normal") == "code.normal"
+ assert resolve_mode("agent.plan") == "agent.plan"
+ assert resolve_mode("agent.fast") == "agent.fast"
+ assert resolve_mode("code.plan") == "code.plan"
+ assert resolve_mode("code.team") == "code.team"
+ assert resolve_mode("team") == "team"
+
+ @staticmethod
+ def test_alias_resolution():
+ assert resolve_mode("agent") == "agent.plan"
+ assert resolve_mode("fast") == "agent.fast"
+ assert resolve_mode("code") == "code.normal"
+ assert resolve_mode("normal") == "code.normal"
+ assert resolve_mode("team.normal") == "team"
+
+ @staticmethod
+ def test_case_insensitive():
+ assert resolve_mode("AGENT") == "agent.plan"
+ assert resolve_mode("Code.Normal") == "code.normal"
+ assert resolve_mode(" fast ") == "agent.fast"
+
+ @staticmethod
+ def test_invalid_mode_raises():
+ with pytest.raises(ValueError, match="invalid mode"):
+ resolve_mode("garbage")
+
+ @staticmethod
+ def test_empty_string_raises():
+ with pytest.raises(ValueError, match="invalid mode"):
+ resolve_mode("")
+
+ @staticmethod
+ def test_alias_set_is_complete():
+ for alias, canonical in MODE_ALIASES.items():
+ assert canonical in VALID_MODES
+
+
+class TestGatewayUrl:
+ @staticmethod
+ def test_default_with_env_port(monkeypatch):
+ monkeypatch.setenv("GATEWAY_PORT", "20000")
+ monkeypatch.setenv("GATEWAY_HOST", "127.0.0.1")
+ assert _build_default_gateway_url() == "ws://127.0.0.1:20000/tui"
+
+ @staticmethod
+ def test_default_without_env(monkeypatch):
+ monkeypatch.delenv("GATEWAY_PORT", raising=False)
+ monkeypatch.delenv("GATEWAY_HOST", raising=False)
+ assert _build_default_gateway_url() == "ws://127.0.0.1:19001/tui"
+
+ @staticmethod
+ def test_custom_path():
+ url = _build_default_gateway_url(path="/tui")
+ assert url.endswith("/tui")
+
+
+class TestSessionId:
+ @staticmethod
+ def test_generated_id_format():
+ sid = _generate_session_id()
+ assert sid.startswith("cli-")
+ parts = sid[4:].split("-")
+ assert len(parts) == 3
+ assert len(parts[0]) == 8
+ assert len(parts[1]) == 6
+ assert len(parts[2]) == 8
+
+ @staticmethod
+ def test_generated_ids_are_unique():
+ ids = {_generate_session_id() for _ in range(20)}
+ assert len(ids) == 20
+
+
+class TestBuildRequest:
+ @staticmethod
+ def test_minimal_request(monkeypatch):
+ monkeypatch.setattr(os, "getcwd", lambda: "/tmp/test_cwd")
+ args = argparse.Namespace(
+ mode="code.normal",
+ session=None,
+ cwd=None,
+ project_dir=None,
+ trusted_dir=None,
+ )
+ req = _build_request(args, "hello world")
+
+ assert req["type"] == "req"
+ assert req["method"] == "chat.send"
+ assert req["is_stream"] is True
+ assert req["params"]["content"] == "hello world"
+ assert req["params"]["query"] == "hello world"
+ assert req["params"]["mode"] == "code.normal"
+ assert req["params"]["cwd"].endswith("test_cwd")
+ assert req["params"]["project_dir"].endswith("test_cwd")
+ assert req["params"]["session_id"].startswith("cli-")
+
+ @staticmethod
+ def test_with_session(monkeypatch):
+ monkeypatch.setattr(os, "getcwd", lambda: "/home/test")
+ args = argparse.Namespace(
+ mode="code.normal",
+ session="my-session",
+ cwd=None,
+ project_dir=None,
+ trusted_dir=None,
+ )
+ req = _build_request(args, "test")
+ assert req["params"]["session_id"] == "my-session"
+
+ @staticmethod
+ def test_with_cwd_override(monkeypatch):
+ monkeypatch.setattr(os, "getcwd", lambda: "/cwd")
+ args = argparse.Namespace(
+ mode="code.normal",
+ session=None,
+ cwd="/custom/cwd",
+ project_dir=None,
+ trusted_dir=None,
+ )
+ req = _build_request(args, "test")
+ assert req["params"]["cwd"] == "/custom/cwd"
+
+ @staticmethod
+ def test_with_project_dir(monkeypatch):
+ monkeypatch.setattr(os, "getcwd", lambda: "/cwd")
+ args = argparse.Namespace(
+ mode="code.normal",
+ session=None,
+ cwd=None,
+ project_dir="/custom/project",
+ trusted_dir=None,
+ )
+ req = _build_request(args, "test")
+ assert req["params"]["project_dir"] == "/custom/project"
+
+ @staticmethod
+ def test_with_trusted_dirs(monkeypatch):
+ monkeypatch.setattr(os, "getcwd", lambda: "/cwd")
+ args = argparse.Namespace(
+ mode="code.normal",
+ session=None,
+ cwd=None,
+ project_dir=None,
+ trusted_dir=["/dir1", "/dir2"],
+ )
+ req = _build_request(args, "test")
+ assert sorted(str(d) for d in req["params"]["trusted_dirs"]) == sorted(
+ ["/dir1", "/dir2"]
+ )
+
+ @staticmethod
+ def test_mode_included(monkeypatch):
+ monkeypatch.setattr(os, "getcwd", lambda: "/cwd")
+ args = argparse.Namespace(
+ mode="agent.fast",
+ session=None,
+ cwd=None,
+ project_dir=None,
+ trusted_dir=None,
+ )
+ req = _build_request(args, "test")
+ assert req["params"]["mode"] == "agent.fast"
+
+ @staticmethod
+ def test_request_id_is_different_each_call(monkeypatch):
+ monkeypatch.setattr(os, "getcwd", lambda: "/cwd")
+ args = argparse.Namespace(
+ mode="code.normal",
+ session=None,
+ cwd=None,
+ project_dir=None,
+ trusted_dir=None,
+ )
+ ids = {_build_request(args, "test")["id"] for _ in range(5)}
+ assert len(ids) == 5
+
+
+class TestValidateArgs:
+ @staticmethod
+ def test_valid():
+ args = argparse.Namespace(mode="code.normal", json=False, jsonl=False,
+ show_reasoning=False, show_tools=False, timeout=None)
+ assert _validate_args(args) is None
+ assert args.mode == "code.normal"
+
+ @staticmethod
+ def test_invalid_mode():
+ args = argparse.Namespace(mode="garbage", json=False, jsonl=False,
+ show_reasoning=False, show_tools=False, timeout=None)
+ assert _validate_args(args) == 2
+
+ @staticmethod
+ def test_json_and_jsonl_conflict():
+ args = argparse.Namespace(mode="code.normal", json=True, jsonl=True,
+ show_reasoning=False, show_tools=False, timeout=None)
+ assert _validate_args(args) == 2
+
+ @staticmethod
+ def test_negative_timeout():
+ args = argparse.Namespace(mode="code.normal", json=False, jsonl=False,
+ show_reasoning=False, show_tools=False, timeout=-1.0)
+ assert _validate_args(args) == 2
+
+ @staticmethod
+ def test_zero_timeout():
+ args = argparse.Namespace(mode="code.normal", json=False, jsonl=False,
+ show_reasoning=False, show_tools=False, timeout=0)
+ assert _validate_args(args) == 2
+
+ @staticmethod
+ def test_mode_resolved():
+ args = argparse.Namespace(mode="fast", json=False, jsonl=False,
+ show_reasoning=False, show_tools=False, timeout=None)
+ assert _validate_args(args) is None
+ assert args.mode == "agent.fast"
+
+
+class TestParser:
+ @staticmethod
+ def test_root_parser_has_chat():
+ p = build_parser()
+ assert p.prog == "jiuwenswarm chat"
+
+ @staticmethod
+ def test_default_mode():
+ p = build_parser()
+ ns = p.parse_args(["hello"])
+ assert ns.mode == "code.normal"
+
+ @staticmethod
+ def test_prompt_collects_remaining():
+ p = build_parser()
+ ns = p.parse_args(["hello", "world", "test"])
+ assert ns.prompt == ["hello", "world", "test"]
+
+ @staticmethod
+ def test_no_prompt():
+ p = build_parser()
+ ns = p.parse_args([])
+ assert ns.prompt == []
+
+ @staticmethod
+ def test_all_options_parsed():
+ p = build_parser()
+ ns = p.parse_args(
+ [
+ "--mode", "agent.fast",
+ "--session", "s1",
+ "--cwd", "/tmp",
+ "--project-dir", "/proj",
+ "--trusted-dir", "/d1",
+ "--trusted-dir", "/d2",
+ "--gateway-url", "ws://h:1/tui",
+ "--name", "inst",
+ "--dotenv", "/path/.env",
+ "--json",
+ "--show-reasoning",
+ "--show-tools",
+ "--timeout", "60",
+ "prompt",
+ ]
+ )
+ assert ns.mode == "agent.fast"
+ assert ns.session == "s1"
+ assert ns.cwd == "/tmp"
+ assert ns.project_dir == "/proj"
+ assert ns.trusted_dir == ["/d1", "/d2"]
+ assert ns.gateway_url == "ws://h:1/tui"
+ assert ns.name == "inst"
+ assert ns.dotenv == "/path/.env"
+ assert ns.json is True
+ assert ns.show_reasoning is True
+ assert ns.show_tools is True
+ assert ns.timeout == 60
+
+
+class TestEvents:
+ @staticmethod
+ def test_event_kind_delta():
+ assert event_kind("chat.delta") == "delta"
+
+ @staticmethod
+ def test_event_kind_reasoning():
+ assert event_kind("chat.reasoning") == "reasoning"
+
+ @staticmethod
+ def test_event_kind_tool_call():
+ assert event_kind("chat.tool_call") == "tool_call"
+
+ @staticmethod
+ def test_event_kind_tool_result():
+ assert event_kind("chat.tool_result") == "tool_result"
+
+ @staticmethod
+ def test_event_kind_final():
+ assert event_kind("chat.final") == "final"
+
+ @staticmethod
+ def test_event_kind_error():
+ assert event_kind("chat.error") == "error"
+
+ @staticmethod
+ def test_event_kind_interactive():
+ assert event_kind("chat.ask_user_question") == "interactive"
+ assert event_kind("plan.approval_required") == "interactive"
+
+ @staticmethod
+ def test_event_kind_processing_status():
+ assert event_kind("chat.processing_status") == "processing_status"
+
+ @staticmethod
+ def test_event_kind_other():
+ assert event_kind("chat.unknown") == "chat"
+ assert event_kind("some.other") == "other"
+
+ @staticmethod
+ def test_is_terminal_chat_final():
+ assert is_terminal_event("chat.final", {}) is True
+
+ @staticmethod
+ def test_is_terminal_chat_final_keepalive():
+ assert is_terminal_event("chat.final", {"event_type": "keepalive"}) is False
+
+ @staticmethod
+ def test_is_terminal_chat_error():
+ assert is_terminal_event("chat.error", {}) is True
+
+ @staticmethod
+ def test_is_terminal_processing_done():
+ assert is_terminal_event("chat.processing_status", {"is_processing": False}) is True
+
+ @staticmethod
+ def test_is_terminal_processing_still_active():
+ assert is_terminal_event("chat.processing_status", {"is_processing": True}) is False
+
+ @staticmethod
+ def test_needs_user_input_ask():
+ assert needs_user_input("chat.ask_user_question") is True
+
+ @staticmethod
+ def test_needs_user_input_plan():
+ assert needs_user_input("plan.approval_required") is True
+
+ @staticmethod
+ def test_needs_user_input_other():
+ assert needs_user_input("chat.delta") is False
+
+
+class TestHumanRenderer:
+ @staticmethod
+ def _make_renderer(*, show_reasoning=False, show_tools=False):
+ content_io = io.StringIO()
+ status_io = io.StringIO()
+ renderer = HumanRenderer(
+ show_reasoning=show_reasoning,
+ show_tools=show_tools,
+ content_writer=lambda text: content_io.write(text),
+ status_writer=lambda text: status_io.write(text),
+ )
+ return renderer, content_io, status_io
+
+ @staticmethod
+ def test_delta_writes_to_stdout():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "hello"})
+ assert cout.getvalue() == "hello"
+
+ @staticmethod
+ def test_delta_accumulates_text():
+ r, _, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "hello"})
+ r.handle_delta({"content": " world"})
+ assert r.streamed_text == "hello world"
+
+ @staticmethod
+ def test_delta_clears_loading():
+ r, _, _ = TestHumanRenderer._make_renderer()
+ r.ensure_loading()
+ assert r.loading is True
+ r.handle_delta({"content": "hi"})
+ assert r.loading is False
+
+ @staticmethod
+ def test_final_deduplicates_delta():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "hello world"})
+ cout.truncate(0)
+ cout.seek(0)
+
+ r.handle_final({"content": "hello world"})
+ assert cout.getvalue() == ""
+
+ @staticmethod
+ def test_final_appends_suffix():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "hello"})
+ cout.truncate(0)
+ cout.seek(0)
+
+ r.handle_final({"content": "hello world"})
+ assert cout.getvalue() == " world"
+
+ @staticmethod
+ def test_final_full_replacement():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "partial"})
+ cout.truncate(0)
+ cout.seek(0)
+
+ r.handle_final({"content": "completely different"})
+ assert cout.getvalue() == "completely different"
+
+ @staticmethod
+ def test_final_only_called_once():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_final({"content": "first"})
+ cout.truncate(0)
+ cout.seek(0)
+ r.handle_final({"content": "second"})
+ assert cout.getvalue() == ""
+
+ @staticmethod
+ def test_final_skip_keepalive():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_final({"content": ""})
+ assert cout.getvalue() == ""
+
+ @staticmethod
+ def _capture_logging(logger_name, capture_builder):
+ import logging
+ stream = io.StringIO()
+ handler = logging.StreamHandler(stream)
+ handler.setLevel(logging.INFO)
+ logger = logging.getLogger(logger_name)
+ logger.addHandler(handler)
+ logger.setLevel(logging.INFO)
+ logger.propagate = False
+ try:
+ capture_builder(stream)
+ finally:
+ logger.removeHandler(handler)
+ handler.close()
+ logger.propagate = True
+
+ @staticmethod
+ def test_error_writes_to_stderr():
+ def _run(stream):
+ r = HumanRenderer()
+ r.handle_error({"error": "bad thing"})
+ assert "bad thing" in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_reasoning_hidden_by_default():
+ def _run(stream):
+ r = HumanRenderer()
+ r.handle_reasoning({"content": "thinking..."})
+ assert "thinking" not in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_reasoning_shown_when_enabled():
+ def _run(stream):
+ r = HumanRenderer(show_reasoning=True)
+ r.handle_reasoning({"content": "thinking..."})
+ assert "thinking..." in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_tool_call_hidden_by_default():
+ def _run(stream):
+ r = HumanRenderer()
+ r.handle_tool_call({"tool_name": "bash", "arguments": "{}"})
+ assert "bash" not in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_tool_call_shown_when_enabled():
+ def _run(stream):
+ r = HumanRenderer(show_tools=True)
+ r.handle_tool_call({"tool_name": "bash", "arguments": '{"cmd":"ls"}'})
+ assert "bash" in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_tool_result_hidden_by_default():
+ def _run(stream):
+ r = HumanRenderer()
+ r.handle_tool_result({"tool_name": "bash", "status": "done"})
+ assert "bash" not in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_tool_result_shown_when_enabled():
+ def _run(stream):
+ r = HumanRenderer(show_tools=True)
+ r.handle_tool_result({"tool_name": "bash", "status": "done"})
+ assert "bash" in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_ensure_loading_picks_random_verb():
+ r = HumanRenderer()
+ r.ensure_loading()
+ assert r.verb
+ assert r.start_time > 0
+
+
+class TestJsonRenderer:
+ @staticmethod
+ def _make_renderer():
+ content_io = io.StringIO()
+ renderer = JsonRenderer(
+ content_writer=lambda text: content_io.write(text),
+ )
+ return renderer, content_io
+
+ @staticmethod
+ def test_output_ok():
+ r, cout = TestJsonRenderer._make_renderer()
+ r.handle_event("chat.final", {"content": "result"})
+ r.output()
+ data = json.loads(cout.getvalue())
+ assert data["ok"] is True
+ assert data["content"] == "result"
+
+ @staticmethod
+ def test_output_error():
+ r, cout = TestJsonRenderer._make_renderer()
+ r.handle_error({"error": "fail"})
+ r.output()
+ data = json.loads(cout.getvalue())
+ assert data["ok"] is False
+ assert data["error"] == "fail"
+
+ @staticmethod
+ def test_output_uses_last_content():
+ r, cout = TestJsonRenderer._make_renderer()
+ r.handle_event("chat.final", {"content": "first"})
+ r.handle_event("chat.final", {"content": "last"})
+ r.output()
+ data = json.loads(cout.getvalue())
+ assert data["content"] == "last"
+
+
+class TestJsonlRenderer:
+ @staticmethod
+ def test_handle_event_emits_frame():
+ content_io = io.StringIO()
+ r = JsonlRenderer(content_writer=lambda text: content_io.write(text))
+ r.handle_event("chat.delta", {"content": "hi"})
+ frame = json.loads(content_io.getvalue())
+ assert frame["type"] == "event"
+ assert frame["event"] == "chat.delta"
+ assert frame["payload"]["content"] == "hi"
+
+
+class TestGatewayClient:
+ @pytest.mark.asyncio
+ @staticmethod
+ async def test_connect_waits_for_ack():
+ async def _mock_connect(url, **kwargs):
+ class FakeWs:
+ async def recv(self):
+ return json.dumps({
+ "type": "event",
+ "event": "connection.ack",
+ "payload": {"protocol_version": "1.0", "transport": "tui"},
+ })
+
+ async def close(self):
+ pass
+
+ return FakeWs()
+
+ with patch("jiuwenswarm.cli.gateway_client._connect_ws", _mock_connect):
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ await client.connect()
+
+ @pytest.mark.asyncio
+ @staticmethod
+ async def test_connect_rejects_non_ack():
+ async def _mock_connect(url, **kwargs):
+ class FakeWs:
+ async def recv(self):
+ return json.dumps({"type": "req", "id": "x"})
+
+ async def close(self):
+ pass
+
+ return FakeWs()
+
+ with patch("jiuwenswarm.cli.gateway_client._connect_ws", _mock_connect):
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ with pytest.raises(ConnectionError):
+ await client.connect()
+
+ @pytest.mark.asyncio
+ @staticmethod
+ async def test_connect_rejects_invalid_json():
+ async def _mock_connect(url, **kwargs):
+ class FakeWs:
+ async def recv(self):
+ return "not json"
+
+ async def close(self):
+ pass
+
+ return FakeWs()
+
+ with patch("jiuwenswarm.cli.gateway_client._connect_ws", _mock_connect):
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ with pytest.raises(ConnectionError):
+ await client.connect()
+
+
+class TestInteractiveLoop:
+ @staticmethod
+ async def _make_connected_client(messages: list[dict]):
+ class FakeWs:
+ def __init__(self):
+ self._idx = 0
+
+ async def recv(self):
+ if self._idx < len(messages):
+ data = json.dumps(messages[self._idx])
+ self._idx += 1
+ return data
+ await asyncio.sleep(10)
+ return json.dumps({})
+
+ async def send(self, _data):
+ pass
+
+ async def close(self):
+ pass
+
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ client.set_mock_ws(FakeWs())
+ return client
+
+ @pytest.mark.asyncio
+ async def test_stream_delta_until_final(self):
+ messages = [
+ {"type": "event", "event": "chat.delta", "payload": {"content": "Hello"}},
+ {"type": "event", "event": "chat.delta", "payload": {"content": " world"}},
+ {"type": "event", "event": "chat.final", "payload": {"content": "Hello world"}},
+ ]
+
+ from jiuwenswarm.cli.chat import _run_interactive_loop
+
+ client = await self._make_connected_client(messages)
+ renderer = HumanRenderer()
+ request = {
+ "type": "req", "id": "r1", "method": "chat.send",
+ "is_stream": True,
+ "params": {"session_id": "s1", "content": "hi", "query": "hi",
+ "mode": "code.normal", "cwd": "/tmp", "project_dir": "/tmp",
+ "trusted_dirs": ["/tmp"]},
+ }
+ code = await _run_interactive_loop(client, renderer, request)
+ assert code == 0
+ assert renderer.streamed_text == "Hello world"
+
+ @pytest.mark.asyncio
+ async def test_chat_error_returns_1(self):
+ messages = [
+ {"type": "event", "event": "chat.error", "payload": {"error": "something broke"}},
+ ]
+
+ from jiuwenswarm.cli.chat import _run_interactive_loop
+
+ client = await self._make_connected_client(messages)
+ renderer = HumanRenderer()
+ request = {
+ "type": "req", "id": "r1", "method": "chat.send",
+ "is_stream": True,
+ "params": {"session_id": "s1", "content": "hi", "query": "hi",
+ "mode": "code.normal", "cwd": "/tmp", "project_dir": "/tmp",
+ "trusted_dirs": ["/tmp"]},
+ }
+ code = await _run_interactive_loop(client, renderer, request)
+ assert code == 1
+
+ @pytest.mark.asyncio
+ async def test_keepalive_final_does_not_terminate(self):
+ messages = [
+ {"type": "event", "event": "chat.processing_status", "payload": {"is_processing": True}},
+ {"type": "event", "event": "chat.final", "payload": {"event_type": "keepalive"}},
+ {"type": "event", "event": "chat.delta", "payload": {"content": "ok"}},
+ {"type": "event", "event": "chat.final", "payload": {"content": "ok"}},
+ ]
+
+ from jiuwenswarm.cli.chat import _run_interactive_loop
+
+ client = await self._make_connected_client(messages)
+ renderer = HumanRenderer()
+ request = {
+ "type": "req", "id": "r1", "method": "chat.send",
+ "is_stream": True,
+ "params": {"session_id": "s1", "content": "hi", "query": "hi",
+ "mode": "code.normal", "cwd": "/tmp", "project_dir": "/tmp",
+ "trusted_dirs": ["/tmp"]},
+ }
+ code = await _run_interactive_loop(client, renderer, request)
+ assert code == 0
+
+ @pytest.mark.asyncio
+ @staticmethod
+ async def test_connection_closed_gracefully():
+ class FakeWs:
+ def __init__(self):
+ self._called = 0
+
+ async def recv(self):
+ self._called += 1
+ if self._called == 1:
+ return json.dumps({
+ "type": "event",
+ "event": "connection.ack",
+ "payload": {"protocol_version": "1.0", "transport": "cli"},
+ })
+ raise ConnectionError("closed")
+
+ async def send(self, _data):
+ pass
+
+ async def close(self):
+ pass
+
+ from jiuwenswarm.cli.chat import _run_interactive_loop
+
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ client.set_mock_ws(FakeWs())
+ renderer = HumanRenderer()
+ request = {
+ "type": "req", "id": "r1", "method": "chat.send",
+ "is_stream": True,
+ "params": {"session_id": "s1", "content": "hi", "query": "hi",
+ "mode": "code.normal", "cwd": "/tmp", "project_dir": "/tmp",
+ "trusted_dirs": ["/tmp"]},
+ }
+ code = await _run_interactive_loop(client, renderer, request)
+ assert code == 0
+
+ @pytest.mark.asyncio
+ async def test_processing_status_restarts_spinner(self):
+ messages = [
+ {"type": "event", "event": "chat.processing_status", "payload": {"is_processing": True}},
+ {"type": "event", "event": "chat.delta", "payload": {"content": "step1"}},
+ {"type": "event", "event": "chat.processing_status", "payload": {"is_processing": True}},
+ {"type": "event", "event": "chat.delta", "payload": {"content": "step2"}},
+ {"type": "event", "event": "chat.final", "payload": {"content": "step1step2"}},
+ ]
+
+ from jiuwenswarm.cli.chat import _run_interactive_loop
+
+ client = await self._make_connected_client(messages)
+ renderer = HumanRenderer()
+ request = {
+ "type": "req", "id": "r1", "method": "chat.send",
+ "is_stream": True,
+ "params": {"session_id": "s1", "content": "hi", "query": "hi",
+ "mode": "code.normal", "cwd": "/tmp", "project_dir": "/tmp",
+ "trusted_dirs": ["/tmp"]},
+ }
+ code = await _run_interactive_loop(client, renderer, request)
+ assert code == 0
+ assert renderer.streamed_text == "step1step2"
+
+ @pytest.mark.asyncio
+ @staticmethod
+ async def test_delta_gap_inserts_line_break():
+ from jiuwenswarm.cli.chat import _run_interactive_loop
+
+ messages = [
+ {"type": "event", "event": "chat.delta", "payload": {"content": "part1"}},
+ {"type": "event", "event": "chat.delta", "payload": {"content": "part2"}},
+ {"type": "event", "event": "chat.final", "payload": {"content": "part1\n\npart2"}},
+ ]
+
+ fake_time = [0.0]
+
+ class FakeWs:
+ def __init__(self):
+ self._idx = 0
+
+ async def recv(self):
+ if self._idx == 0:
+ fake_time[0] = 0.0
+ elif self._idx == 1:
+ fake_time[0] = 1.0
+ if self._idx < len(messages):
+ data = json.dumps(messages[self._idx])
+ self._idx += 1
+ return data
+ await asyncio.sleep(10)
+ return json.dumps({})
+
+ async def send(self, _data):
+ pass
+
+ async def close(self):
+ pass
+
+ def mock_monotonic():
+ return fake_time[0]
+
+ with patch("jiuwenswarm.cli.render.time.monotonic", mock_monotonic):
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ client.set_mock_ws(FakeWs())
+ renderer = HumanRenderer()
+ request = {
+ "type": "req", "id": "r1", "method": "chat.send",
+ "is_stream": True,
+ "params": {"session_id": "s1", "content": "hi", "query": "hi",
+ "mode": "code.normal", "cwd": "/tmp", "project_dir": "/tmp",
+ "trusted_dirs": ["/tmp"]},
+ }
+ code = await _run_interactive_loop(client, renderer, request)
+ assert code == 0
+ assert renderer.streamed_text == "part1\n\npart2"
+
+
+class TestSpinner:
+ @staticmethod
+ def test_spinner_frames_cycle():
+ from jiuwenswarm.cli.render import _SPINNER_FRAMES as frames
+
+ r = HumanRenderer()
+ r.ensure_loading()
+ first = r.spinner_idx
+ r.tick_spinner()
+ assert r.spinner_idx == (first + 1) % len(frames)
+
+ @staticmethod
+ def test_spinner_clears_on_delta():
+ r = HumanRenderer()
+ r.ensure_loading()
+ assert r.loading is True
+ r.handle_delta({"content": "x"})
+ assert r.loading is False
+
+ @staticmethod
+ def test_spinner_idle_noop():
+ r = HumanRenderer()
+ r.tick_spinner()
+ assert r.spinner_idx == 0
+
+ @staticmethod
+ def test_spinner_verb_rotates():
+ from jiuwenswarm.cli.render import _VERBS
+
+ fake_time = 1000.0
+
+ def mock_monotonic():
+ return fake_time
+
+ with patch("jiuwenswarm.cli.render.time.monotonic", mock_monotonic):
+ r = HumanRenderer()
+ r.ensure_loading()
+ initial_verb = r.verb
+
+ fake_time += 5.5
+
+ with patch("jiuwenswarm.cli.render.time.monotonic", mock_monotonic):
+ r.tick_spinner()
+
+ assert r.verb != initial_verb
+
+ @staticmethod
+ def test_spinner_restarts_on_processing_status():
+ r = HumanRenderer()
+ r.ensure_loading()
+ assert r.loading is True
+ r.handle_delta({"content": "x"})
+ assert r.loading is False
+ r.ensure_loading()
+ assert r.loading is True
diff --git a/tests/unit_tests/cli/test_events.py b/tests/unit_tests/cli/test_events.py
new file mode 100644
index 0000000000..e339aaeeec
--- /dev/null
+++ b/tests/unit_tests/cli/test_events.py
@@ -0,0 +1,83 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for jiuwenswarm.cli.events."""
+
+from __future__ import annotations
+
+from jiuwenswarm.cli.events import (
+ event_kind,
+ is_terminal_event,
+ needs_user_input,
+)
+
+
+class TestEvents:
+ @staticmethod
+ def test_event_kind_delta():
+ assert event_kind("chat.delta") == "delta"
+
+ @staticmethod
+ def test_event_kind_reasoning():
+ assert event_kind("chat.reasoning") == "reasoning"
+
+ @staticmethod
+ def test_event_kind_tool_call():
+ assert event_kind("chat.tool_call") == "tool_call"
+
+ @staticmethod
+ def test_event_kind_tool_result():
+ assert event_kind("chat.tool_result") == "tool_result"
+
+ @staticmethod
+ def test_event_kind_final():
+ assert event_kind("chat.final") == "final"
+
+ @staticmethod
+ def test_event_kind_error():
+ assert event_kind("chat.error") == "error"
+
+ @staticmethod
+ def test_event_kind_interactive():
+ assert event_kind("chat.ask_user_question") == "interactive"
+ assert event_kind("plan.approval_required") == "interactive"
+
+ @staticmethod
+ def test_event_kind_processing_status():
+ assert event_kind("chat.processing_status") == "processing_status"
+
+ @staticmethod
+ def test_event_kind_other():
+ assert event_kind("chat.unknown") == "chat"
+ assert event_kind("some.other") == "other"
+
+ @staticmethod
+ def test_is_terminal_chat_final():
+ assert is_terminal_event("chat.final", {}) is True
+
+ @staticmethod
+ def test_is_terminal_chat_final_keepalive():
+ assert is_terminal_event("chat.final", {"event_type": "keepalive"}) is False
+
+ @staticmethod
+ def test_is_terminal_chat_error():
+ assert is_terminal_event("chat.error", {}) is True
+
+ @staticmethod
+ def test_is_terminal_processing_done():
+ assert is_terminal_event("chat.processing_status", {"is_processing": False}) is True
+
+ @staticmethod
+ def test_is_terminal_processing_still_active():
+ assert is_terminal_event("chat.processing_status", {"is_processing": True}) is False
+
+ @staticmethod
+ def test_needs_user_input_ask():
+ assert needs_user_input("chat.ask_user_question") is True
+
+ @staticmethod
+ def test_needs_user_input_plan():
+ assert needs_user_input("plan.approval_required") is True
+
+ @staticmethod
+ def test_needs_user_input_other():
+ assert needs_user_input("chat.delta") is False
diff --git a/tests/unit_tests/cli/test_gateway_client.py b/tests/unit_tests/cli/test_gateway_client.py
new file mode 100644
index 0000000000..c1ebe46035
--- /dev/null
+++ b/tests/unit_tests/cli/test_gateway_client.py
@@ -0,0 +1,71 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for jiuwenswarm.cli.gateway_client."""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import patch
+
+import pytest
+
+from jiuwenswarm.cli.gateway_client import GatewayClient
+
+
+class TestGatewayClient:
+ @pytest.mark.asyncio
+ @staticmethod
+ async def test_connect_waits_for_ack():
+ async def _mock_connect(url, **kwargs):
+ class FakeWs:
+ async def recv(self):
+ return json.dumps({
+ "type": "event",
+ "event": "connection.ack",
+ "payload": {"protocol_version": "1.0", "transport": "tui"},
+ })
+
+ async def close(self):
+ pass
+
+ return FakeWs()
+
+ with patch("jiuwenswarm.cli.gateway_client._connect_ws", _mock_connect):
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ await client.connect()
+
+ @pytest.mark.asyncio
+ @staticmethod
+ async def test_connect_rejects_non_ack():
+ async def _mock_connect(url, **kwargs):
+ class FakeWs:
+ async def recv(self):
+ return json.dumps({"type": "req", "id": "x"})
+
+ async def close(self):
+ pass
+
+ return FakeWs()
+
+ with patch("jiuwenswarm.cli.gateway_client._connect_ws", _mock_connect):
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ with pytest.raises(ConnectionError):
+ await client.connect()
+
+ @pytest.mark.asyncio
+ @staticmethod
+ async def test_connect_rejects_invalid_json():
+ async def _mock_connect(url, **kwargs):
+ class FakeWs:
+ async def recv(self):
+ return "not json"
+
+ async def close(self):
+ pass
+
+ return FakeWs()
+
+ with patch("jiuwenswarm.cli.gateway_client._connect_ws", _mock_connect):
+ client = GatewayClient("ws://127.0.0.1:19001/tui")
+ with pytest.raises(ConnectionError):
+ await client.connect()
diff --git a/tests/unit_tests/cli/test_render.py b/tests/unit_tests/cli/test_render.py
new file mode 100644
index 0000000000..f5e10fc90c
--- /dev/null
+++ b/tests/unit_tests/cli/test_render.py
@@ -0,0 +1,277 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for jiuwenswarm.cli.render."""
+
+from __future__ import annotations
+
+import io
+import json
+
+from jiuwenswarm.cli.render import HumanRenderer, JsonRenderer, JsonlRenderer
+
+
+class TestHumanRenderer:
+ @staticmethod
+ def _make_renderer(*, show_reasoning=False, show_tools=False):
+ content_io = io.StringIO()
+ status_io = io.StringIO()
+ renderer = HumanRenderer(
+ show_reasoning=show_reasoning,
+ show_tools=show_tools,
+ content_writer=lambda text: content_io.write(text),
+ status_writer=lambda text: status_io.write(text),
+ )
+ return renderer, content_io, status_io
+
+ @staticmethod
+ def test_delta_writes_to_stdout():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "hello"})
+ assert cout.getvalue() == "hello"
+
+ @staticmethod
+ def test_delta_accumulates_text():
+ r, _, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "hello"})
+ r.handle_delta({"content": " world"})
+ assert r.streamed_text == "hello world"
+
+ @staticmethod
+ def test_delta_clears_loading():
+ r, _, _ = TestHumanRenderer._make_renderer()
+ r.ensure_loading()
+ assert r.loading is True
+ r.handle_delta({"content": "hi"})
+ assert r.loading is False
+
+ @staticmethod
+ def test_final_deduplicates_delta():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "hello world"})
+ cout.truncate(0)
+ cout.seek(0)
+
+ r.handle_final({"content": "hello world"})
+ assert cout.getvalue() == ""
+
+ @staticmethod
+ def test_final_appends_suffix():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "hello"})
+ cout.truncate(0)
+ cout.seek(0)
+
+ r.handle_final({"content": "hello world"})
+ assert cout.getvalue() == " world"
+
+ @staticmethod
+ def test_final_full_replacement():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_delta({"content": "partial"})
+ cout.truncate(0)
+ cout.seek(0)
+
+ r.handle_final({"content": "completely different"})
+ assert cout.getvalue() == "completely different"
+
+ @staticmethod
+ def test_final_only_called_once():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_final({"content": "first"})
+ cout.truncate(0)
+ cout.seek(0)
+ r.handle_final({"content": "second"})
+ assert cout.getvalue() == ""
+
+ @staticmethod
+ def test_final_skip_keepalive():
+ r, cout, _ = TestHumanRenderer._make_renderer()
+ r.handle_final({"content": ""})
+ assert cout.getvalue() == ""
+
+ @staticmethod
+ def _capture_logging(logger_name, capture_builder):
+ import logging
+ stream = io.StringIO()
+ handler = logging.StreamHandler(stream)
+ handler.setLevel(logging.INFO)
+ logger = logging.getLogger(logger_name)
+ logger.addHandler(handler)
+ logger.setLevel(logging.INFO)
+ logger.propagate = False
+ try:
+ capture_builder(stream)
+ finally:
+ logger.removeHandler(handler)
+ handler.close()
+ logger.propagate = True
+
+ @staticmethod
+ def test_error_writes_to_stderr():
+ def _run(stream):
+ r = HumanRenderer()
+ r.handle_error({"error": "bad thing"})
+ assert "bad thing" in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_reasoning_hidden_by_default():
+ def _run(stream):
+ r = HumanRenderer()
+ r.handle_reasoning({"content": "thinking..."})
+ assert "thinking" not in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_reasoning_shown_when_enabled():
+ def _run(stream):
+ r = HumanRenderer(show_reasoning=True)
+ r.handle_reasoning({"content": "thinking..."})
+ assert "thinking..." in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_tool_call_hidden_by_default():
+ def _run(stream):
+ r = HumanRenderer()
+ r.handle_tool_call({"tool_name": "bash", "arguments": "{}"})
+ assert "bash" not in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_tool_call_shown_when_enabled():
+ def _run(stream):
+ r = HumanRenderer(show_tools=True)
+ r.handle_tool_call({"tool_name": "bash", "arguments": '{"cmd":"ls"}'})
+ assert "bash" in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_tool_result_hidden_by_default():
+ def _run(stream):
+ r = HumanRenderer()
+ r.handle_tool_result({"tool_name": "bash", "status": "done"})
+ assert "bash" not in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_tool_result_shown_when_enabled():
+ def _run(stream):
+ r = HumanRenderer(show_tools=True)
+ r.handle_tool_result({"tool_name": "bash", "status": "done"})
+ assert "bash" in stream.getvalue()
+ TestHumanRenderer._capture_logging("jiuwenswarm.cli.render", _run)
+
+ @staticmethod
+ def test_ensure_loading_picks_random_verb():
+ r = HumanRenderer()
+ r.ensure_loading()
+ assert r.verb
+ assert r.start_time > 0
+
+
+class TestJsonRenderer:
+ @staticmethod
+ def _make_renderer():
+ content_io = io.StringIO()
+ renderer = JsonRenderer(
+ content_writer=lambda text: content_io.write(text),
+ )
+ return renderer, content_io
+
+ @staticmethod
+ def test_output_ok():
+ r, cout = TestJsonRenderer._make_renderer()
+ r.handle_event("chat.final", {"content": "result"})
+ r.output()
+ data = json.loads(cout.getvalue())
+ assert data["ok"] is True
+ assert data["content"] == "result"
+
+ @staticmethod
+ def test_output_error():
+ r, cout = TestJsonRenderer._make_renderer()
+ r.handle_error({"error": "fail"})
+ r.output()
+ data = json.loads(cout.getvalue())
+ assert data["ok"] is False
+ assert data["error"] == "fail"
+
+ @staticmethod
+ def test_output_uses_last_content():
+ r, cout = TestJsonRenderer._make_renderer()
+ r.handle_event("chat.final", {"content": "first"})
+ r.handle_event("chat.final", {"content": "last"})
+ r.output()
+ data = json.loads(cout.getvalue())
+ assert data["content"] == "last"
+
+
+class TestJsonlRenderer:
+ @staticmethod
+ def test_handle_event_emits_frame():
+ content_io = io.StringIO()
+ r = JsonlRenderer(content_writer=lambda text: content_io.write(text))
+ r.handle_event("chat.delta", {"content": "hi"})
+ frame = json.loads(content_io.getvalue())
+ assert frame["type"] == "event"
+ assert frame["event"] == "chat.delta"
+ assert frame["payload"]["content"] == "hi"
+
+
+class TestSpinner:
+ @staticmethod
+ def test_spinner_frames_cycle():
+ from jiuwenswarm.cli.render import _SPINNER_FRAMES as frames
+
+ r = HumanRenderer()
+ r.ensure_loading()
+ first = r.spinner_idx
+ r.tick_spinner()
+ assert r.spinner_idx == (first + 1) % len(frames)
+
+ @staticmethod
+ def test_spinner_clears_on_delta():
+ r = HumanRenderer()
+ r.ensure_loading()
+ assert r.loading is True
+ r.handle_delta({"content": "x"})
+ assert r.loading is False
+
+ @staticmethod
+ def test_spinner_idle_noop():
+ r = HumanRenderer()
+ r.tick_spinner()
+ assert r.spinner_idx == 0
+
+ @staticmethod
+ def test_spinner_verb_rotates():
+ from jiuwenswarm.cli.render import _VERBS
+ from unittest.mock import patch
+
+ fake_time = 1000.0
+
+ def mock_monotonic():
+ return fake_time
+
+ with patch("jiuwenswarm.cli.render.time.monotonic", mock_monotonic):
+ r = HumanRenderer()
+ r.ensure_loading()
+ initial_verb = r.verb
+
+ fake_time += 5.5
+
+ with patch("jiuwenswarm.cli.render.time.monotonic", mock_monotonic):
+ r.tick_spinner()
+
+ assert r.verb != initial_verb
+
+ @staticmethod
+ def test_spinner_restarts_on_processing_status():
+ r = HumanRenderer()
+ r.ensure_loading()
+ assert r.loading is True
+ r.handle_delta({"content": "x"})
+ assert r.loading is False
+ r.ensure_loading()
+ assert r.loading is True