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:/statusline支持agent自动写脚本并生效
openJiuwen-bot23a5c6770f22
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/statusline.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/statusline.tsindex 867ac9e5bf..27cfe02c97 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/statusline.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/statusline.ts@@ -30,7 +30,6 @@ function stripOuterQuotes(s: string): string {return trimmed;}-/** Unescape JSON-style backslash sequences so users can type `\"` to mean `"`, aligning with Claude Code's JSON config behavior. */function unescapeCommand(s: string): string {return s.replace(/\\(["\\])/g, "$1");}@@ -82,12 +81,20 @@ function showHelp(ctx: CommandContext): void {" JSON is piped via stdin. On Windows, you can also use the file at $JIUWENSWARM_SL_FILE.","","Subcommands:",+ " /statusline — show current configuration",+ " /statusline get — show current configuration"," /statusline set <command> — set the shell command to run"," /statusline padding <n> — set left & right padding (0 or positive)"," /statusline clear — remove statusline configuration"," /statusline help — show this guide"," /statusline json — show the real JSON data your command receives right now","",+ "Agent-generated mode :",+ " /statusline <prompt> — describe what you want the statusline to show,",+ " and the agent will automatically generate the",+ " appropriate shell command and configure it for you.",+ " Example: /statusline show my shell PS1 configuration",+ "","How to write a command:"," Single field: jq -r '.field'"," Multiple fields: input=$(cat); echo \"$(echo \"$input\" | jq -r .field1) | $(echo \"$input\" | jq -r .field2)\"",@@ -128,12 +135,43 @@ function showActualJsonData(ctx: CommandContext): void {);}+/**+ * Agent-generated mode: send a prompt to the agent to automatically write a statusline script.+ *+ *+ * - User types: /statusline <description of what they want>+ * - TUI sends it as a chat message with skills_to_use=["script-creator"] metadata+ * - SkillUseRail loads script-creator SKILL.md+ * - Agent writes the script and configures the statusline+ */+function agentGenerate(ctx: CommandContext, prompt: string): void {+ if (!prompt.trim()) {+ // No prompt given — show current config+ showCurrentConfig(ctx);+ return;+ }++ // Send the prompt as a chat message. The backend build_user_prompt will+ // detect "/statusline" prefix and inject skills_to_use=["script-creator"].+ const fullPrompt = `/statusline ${prompt.trim()}`;+ const requestId = ctx.sendMessage(fullPrompt);+ if (!requestId) {+ ctx.addItem(+ makeItem(ctx.sessionId, "error", "offline: waiting for reconnect before sending statusline request"),+ );+ }+}++// Known subcommands that are handled locally (not sent to agent)+const KNOWN_SUBCOMMANDS = ["set", "padding", "clear", "help", "json", "get"];+export function createStatusLineCommand(): SlashCommand {return {name: "statusline",+ altNames: ["sl"],description: "Configure custom status line footer",- usage: "/statusline <set|padding|clear|help|json>",- example: "/statusline set 'echo $mode | $model'",+ usage: "/statusline <set|padding|clear|help|json> | /statusline <prompt>",+ example: "/statusline set 'echo $mode | $model' OR /statusline show my PS1 config",kind: CommandKind.BUILT_IN,takesArgs: true,subCommands: [@@ -182,22 +220,36 @@ export function createStatusLineCommand(): SlashCommand {isSafeConcurrent: true,action: (ctx) => showActualJsonData(ctx),},+ {+ name: "get",+ description: "Show current statusline configuration",+ usage: "/statusline get",+ kind: CommandKind.BUILT_IN,+ takesArgs: false,+ isSafeConcurrent: true,+ action: (ctx) => showCurrentConfig(ctx),+ },],action: (ctx, args) => {- const sub = args.trim().split(/\s+/)[0];- if (!sub) {- showHelp(ctx);+ const trimmedArgs = args.trim();+ if (!trimmedArgs) {+ // No args — show current config (per docs: "/statusline" shows current config)+ showCurrentConfig(ctx);return;}- const matched = createStatusLineCommand().subCommands?.find((s) => s.name === sub);++ const firstWord = trimmedArgs.split(/\s+/)[0];++ // Check if first word is a known subcommand+ const matched = createStatusLineCommand().subCommands?.find((s) => s.name === firstWord);if (matched) {- const rest = args.trim().slice(sub.length).trim();+ const rest = trimmedArgs.slice(firstWord.length).trim();matched.action(ctx, rest);return;}- ctx.addItem(- makeItem(ctx.sessionId, "error", `Unknown sub-command: ${sub}\nUsage: /statusline <set|padding|clear|help|json>`, "m"),- );++ // NOT a known subcommand — treat as prompt for agent-generated mode+ agentGenerate(ctx, trimmedArgs);},};}\ No newline at end of filediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 4fb872832b..1d20745acc 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -173,13 +173,150 @@ _SKILL_COMMAND_REGEX = re.compile(r"^/skills use\s+(?P<skill_names>[^,]+)\s*,\s*(?P<query>.*)$")+# /statusline prompt-type 模式:+# 用户输入 "/statusline <描述>" → 直接注入 statusline-setup 指令到 prompt+# 排除已知子命令(set, padding, clear, help, json)——这些由 TUI 前端本地处理,+# 但如果消息经过 Gateway 传到 AgentServer,后端也需要区分。+_STATUSLINE_KNOWN_SUBCOMMANDS = {"set", "padding", "clear", "help", "json", "get"}+_STATUSLINE_PROMPT_REGEX = re.compile(+ r"^/statusline\s+(?P<description>.+)$"+)++# 不调用 /skills,直接把指令文本嵌入 prompt+_STATUSLINE_SETUP_PROMPT = """\+You are a status line setup agent. Your job is to configure the user's TUI status line \+by generating a shell command and writing it to the config file so the bottom bar \+updates immediately.++This is NOT about writing Python scripts or creating files — it's about writing a \+**shell command** that runs every 2 seconds and whose stdout becomes the status bar text.++## How the Status Line Works++1. The TUI runs the configured shell command every 2 seconds+2. Each time, it pipes a JSON object with session info as stdin to the command+3. The command's stdout is displayed at the bottom of the TUI screen+4. Config is stored in ~/.jiuwenswarm-tui/config.json under the "statusLine" field++The shell command can do anything a normal shell command can — read JSON fields, \+run git, check files, call system utilities, etc. The JSON input is just one \+convenient data source, not a constraint.++## Three Command Styles++**Style A: Pure JSON fields** — for session info (model, tokens, mode, etc.)+```+input=$(cat); field1=$(echo "$input" | jq -r '.field1 // "default"'); \+echo "label:$field1"+```++**Style B: Pure shell utilities** — for system info (git branch, disk, \+time, etc.) — no `input=$(cat)` needed+```+branch=$(git branch --show-current 2>/dev/null || echo "?"); \+time=$(date +%H:%M:%S); echo "$branch | $time"+```++**Style C: Mixed** — JSON fields + shell utilities (most common)+```+input=$(cat); model=$(echo "$input" | jq -r '.model // "?"'); \+branch=$(git branch --show-current 2>/dev/null || echo "?"); \+echo "$model | git:$branch"+```++## JSON Input Field Reference++The command receives this JSON via stdin every 2 seconds:++| Field | Description |+|-------|-------------|+| session_id | Current session ID |+| session_name | Session title (set via /rename) |+| cwd | Current working directory |+| mode | Current mode (agent.plan / agent.fast / code.normal / code.team / team) |+| model | Current model name |+| provider | Model provider |+| version | jiuwenswarm version |+| connection | Connection state (idle / connecting / connected / reconnecting / auth_failed) |+| is_processing | Is agent currently processing |+| last_error | Most recent error message or null |+| evolution_status | Evolution state (idle / running) |+| active_subtask_count | Number of active subtasks |+| todo_count | Number of todo items |+| trusted_dirs | Trusted directory paths (array) |+| usage.total_input_tokens | Session total input tokens |+| usage.total_output_tokens | Session total output tokens |+| usage.total_tokens | Session total tokens |+| context_window.context_window_size | Max context window tokens |+| context_window.used_percentage | Context used percentage (0-100) |+| context_window.remaining_percentage | Context remaining percentage (0-100) |++Common non-JSON shell approaches: git branch --show-current, \+df -h, date, hostname -s, whoami, etc.++## How to Apply the Config++DO NOT use `python -c "..."` one-liners — they break on Windows due \+to quoting and escaping issues. Instead, write a Python script file \+and then execute it. This is the ONLY reliable way on Windows.++Step 1: Write a Python script file (e.g. /tmp/update_statusline.py) \+that merges the new statusLine into the config:+```python+import json, os+d = os.path.expanduser('~/.jiuwenswarm-tui')+os.makedirs(d, exist_ok=True)+p = os.path.join(d, 'config.json')+if not os.path.exists(p):+ with open(p, 'w') as f:+ f.write('{}\\n')+with open(p) as f:+ c = json.load(f)+c['statusLine'] = {+ 'type': 'command',+ 'command': 'YOUR_COMMAND_HERE',+ 'padding': 0+}+with open(p, 'w') as f:+ json.dump(c, f, indent=2)+ f.write('\\n')+print('StatusLine configured')+```++Step 2: Execute the script:+```bash+python /tmp/update_statusline.py+```++IMPORTANT: The TUI polls config.json every 2 seconds, so the status \+bar updates automatically within 2 seconds after you write the config. \+No restart needed.++Guidelines:+- Only write to ~/.jiuwenswarm-tui/config.json — never overwrite \+ system files+- Always merge with existing config — preserve trustedDirs, theme, etc.+- Never hardcode secrets or API keys in the command+- The statusLine command runs in bash (sh -c) context, NOT in \+ PowerShell — so `$(cat)`, `$var`, `jq`, `echo` etc. are all \+ standard bash/sh syntax+- Commands should handle failures gracefully: use 2>/dev/null, \+ || echo "fallback"+- On Windows, $(cat) is automatically patched to read from a temp \+ file by the TUI+- DO NOT use `python -c` one-liners for config updates — they \+ break on Windows. Always write a .py script file and execute it.+- DO NOT read config.json with `cat` — use Python os.path.expanduser \+ instead, as `~` may not resolve correctly in some shell environments+"""+def _handle_skills_use_slash_command(query: str) -> Tuple[list, str]:"""Handle the /skills use slash command"""stripped = query.strip()if not stripped.startswith("/skills use"):return [], query-+skill_list = []matches = _SKILL_COMMAND_REGEX.match(stripped)if matches:@@ -191,6 +328,41 @@ def _handle_skills_use_slash_command(query: str) -> Tuple[list, str]:return [], query+def _handle_statusline_prompt_command(query: str) -> Tuple[str, str]:+ """处理 /statusline <prompt>++ 不调用 /skills 命令,不依赖 SkillUseRail,+ 直接把 statusline-setup 指令文本嵌入 user prompt。++ _handle_statusline_prompt_command() → 返回 (statusline_prompt, description)+ build_user_prompt() 把 statusline_prompt 嵌入到 user prompt 后面++ Args:+ query: 用户原始输入(含 "/statusline" 前缀)++ Returns:+ (statusline_prompt, description) — 注入的 prompt 文本和提取的描述+ 如果不是 /statusline prompt 模式,返回 ("", query)+ """+ stripped = query.strip()+ if not stripped.startswith("/statusline"):+ return "", query++ match = _STATUSLINE_PROMPT_REGEX.match(stripped)+ if match:+ description = match.group("description").strip()+ # 排除已知子命令——它们由 TUI 前端本地处理,不应被当作 prompt+ first_word = description.split()[0] if description else ""+ if first_word in _STATUSLINE_KNOWN_SUBCOMMANDS:+ return "", query+ if description:+ # 把用户的描述转化为让 Agent 自动配置状态栏的 prompt+ return _STATUSLINE_SETUP_PROMPT, description++ # /statusline 无参数 → 不是 prompt 模式(TUI 应已拦截处理 help)+ return "", query++def build_user_prompt(content: str | dict, files: dict, channel: str, language: str, *,trusted_dirs: list[str] | None = None, metadata: dict[str, Any] | None = None) -> str:"""Build user prompt for the agent."""@@ -210,9 +382,16 @@ def build_user_prompt(content: str | dict, files: dict, channel: str, language:skills_to_use, new_content = _handle_skills_use_slash_command(content)if new_content:content = new_content+ # /statusline <prompt> prompt-type 命令(仿 Claude Code,不调用 /skills)+ statusline_prompt, statusline_content = _handle_statusline_prompt_command(content)+ if statusline_prompt:+ content = statusline_contentelse:skills_to_use = []+ # /skills use 命令的 skills_to_use 仍然保留(供 SkillUseRail 正常流程使用)+ # /statusline 不走 SkillUseRail,直接注入 prompt 文本(见下方拼接)+if language == "zh":prompt = "你收到一条消息:\n"if channel == "cron":@@ -263,7 +442,20 @@ def build_user_prompt(content: str | dict, files: dict, channel: str, language:user_message_context["skills_to_use"] = skills_to_useif trusted_dirs:user_message_context["trusted_dirs"] = json.dumps(trusted_dirs, ensure_ascii=False)- return interaction_prefix + prompt + json.dumps(user_message_context, ensure_ascii=False)++ # 仿 Claude Code statusline-setup: 把指令文本直接嵌入 prompt+ base_prompt = interaction_prefix + prompt + json.dumps(user_message_context, ensure_ascii=False)+ if statusline_prompt:+ if language == "zh":+ return base_prompt + "\n\n你必须按照以下指令配置状态栏:\n" + statusline_prompt+ else:+ return (+ base_prompt+ + "\n\nYou must follow these instructions "+ + "to configure the status line:\n"+ + statusline_prompt+ )+ return base_prompt@@ -473,6 +665,15 @@ class JiuWenSwarm:trusted_dirs=trusted_dirs,metadata=request.metadata,)+ # 调试日志:确认 /statusline prompt 注入是否生效+ if isinstance(query, str) and "/statusline" in query:+ logger.info(+ "[_build_inputs][STATUSLINE] 原始 query=%s, 最终 prompt 长度=%d, "+ "包含 statusline-setup 指令=%s",+ query[:200],+ len(final_query) if isinstance(final_query, str) else 0,+ "status line setup agent" in final_query if isinstance(final_query, str) else False,+ )inputs: dict[str, Any] = {"conversation_id": request.session_id,diff --git a/tests/unit_tests/agentserver/test_statusline_prompt.py b/tests/unit_tests/agentserver/test_statusline_prompt.pynew file mode 100644index 0000000000..224234dd5c--- /dev/null+++ b/tests/unit_tests/agentserver/test_statusline_prompt.py@@ -0,0 +1,470 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for /statusline prompt-type command handling.++Tests cover:+- _STATUSLINE_PROMPT_REGEX: regex matching+- _handle_statusline_prompt_command: regex matching, known+ subcommand exclusion, description extraction, prompt text content+- build_user_prompt: full pipeline (statusline-setup prompt+ injection, normal messages unaffected)+- _STATUSLINE_SETUP_PROMPT: hardcoded prompt content validation++This follows Claude Code's pattern: /statusline is a prompt-type+command that injects a hardcoded statusline-setup instruction text+directly into the user prompt — no /skills command or SkillUseRail+involved.+"""++from __future__ import annotations++import json++import pytest++from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _STATUSLINE_KNOWN_SUBCOMMANDS,+ _STATUSLINE_PROMPT_REGEX,+ _STATUSLINE_SETUP_PROMPT,+ _handle_statusline_prompt_command,+ build_user_prompt,+)+++def _extract_json_from_prompt(prompt: str) -> dict:+ """Extract the first JSON object from a build_user_prompt result.++ The prompt format is:+ prefix_text + JSON_string + [optional statusline-setup+ prompt suffix] The JSON ends at the closing brace before+ the suffix.+ """+ json_start = prompt.index("{")+ brace_depth = 0+ for i in range(json_start, len(prompt)):+ if prompt[i] == "{":+ brace_depth += 1+ elif prompt[i] == "}":+ brace_depth -= 1+ if brace_depth == 0:+ json_str = prompt[json_start:i + 1]+ return json.loads(json_str)+ raise ValueError("No complete JSON object found in prompt")+++# ── _STATUSLINE_PROMPT_REGEX ────────────────────────────────────+++class TestStatuslinePromptRegex:+ """Tests for _STATUSLINE_PROMPT_REGEX."""++ @staticmethod+ def test_matches_statusline_with_description():+ m = _STATUSLINE_PROMPT_REGEX.match(+ "/statusline show model and tokens"+ )+ assert m is not None+ assert m.group("description") == "show model and tokens"++ @staticmethod+ def test_matches_statusline_with_chinese():+ m = _STATUSLINE_PROMPT_REGEX.match(+ "/statusline 展示模型名称和token数量"+ )+ assert m is not None+ assert m.group("description") == "展示模型名称和token数量"++ @staticmethod+ def test_no_match_bare_statusline():+ """'/statusline' with no trailing description should NOT match."""+ m = _STATUSLINE_PROMPT_REGEX.match("/statusline")+ assert m is None++ @staticmethod+ def test_no_match_other_slash_command():+ m = _STATUSLINE_PROMPT_REGEX.match(+ "/skills use script-creator, hello"+ )+ assert m is None++ @staticmethod+ def test_no_match_plain_text():+ m = _STATUSLINE_PROMPT_REGEX.match("just a normal message")+ assert m is None+++# ── _handle_statusline_prompt_command ──────────────────────────+++class TestHandleStatuslinePromptCommand:+ """Tests for _handle_statusline_prompt_command.++ This function returns (statusline_prompt_text, description)+ when matched, or ("", original_query) when not matched.+ """++ # --- Matching cases (should return non-empty prompt text) ---++ @staticmethod+ def test_chinese_prompt():+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline 展示模型名称和使用的token数量"+ )+ assert prompt_text == _STATUSLINE_SETUP_PROMPT+ assert content == "展示模型名称和使用的token数量"++ @staticmethod+ def test_english_prompt():+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline show my PS1 config"+ )+ assert prompt_text == _STATUSLINE_SETUP_PROMPT+ assert content == "show my PS1 config"++ @staticmethod+ def test_prompt_with_whitespace():+ prompt_text, content = _handle_statusline_prompt_command(+ " /statusline display git branch "+ )+ assert prompt_text == _STATUSLINE_SETUP_PROMPT+ assert content == "display git branch"++ @staticmethod+ def test_prompt_starting_with_non_subcommand_word():+ """First word is NOT a known subcommand → treat as prompt."""+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline hello world"+ )+ assert prompt_text == _STATUSLINE_SETUP_PROMPT+ assert content == "hello world"++ @staticmethod+ def test_returns_same_prompt_for_all_matches():+ """All matching inputs return the same hardcoded prompt."""+ _, c1 = _handle_statusline_prompt_command("/statusline show model")+ _, c2 = _handle_statusline_prompt_command("/statusline show git branch")+ _, c3 = _handle_statusline_prompt_command("/statusline 展示磁盘")+ # All three have different content, but same prompt_text+ assert c1 != c2 != c3++ # --- Exclusion cases (known subcommands should NOT be matched) ---++ @pytest.mark.parametrize(+ "subcmd", list(_STATUSLINE_KNOWN_SUBCOMMANDS)+ )+ @staticmethod+ def test_known_subcommands_excluded(subcmd: str):+ """Every known subcommand should NOT be treated as a prompt."""+ prompt_text, content = _handle_statusline_prompt_command(+ f"/statusline {subcmd} some_args"+ )+ assert prompt_text == ""+ assert content == f"/statusline {subcmd} some_args"++ @staticmethod+ def test_set_subcommand_with_echo_command():+ """'/statusline set echo $mode' is a subcommand, not a prompt."""+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline set 'echo $mode | $model'"+ )+ assert prompt_text == ""+ assert "/statusline set" in content++ @staticmethod+ def test_help_subcommand():+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline help"+ )+ assert prompt_text == ""++ @staticmethod+ def test_json_subcommand():+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline json"+ )+ assert prompt_text == ""++ @staticmethod+ def test_clear_subcommand():+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline clear"+ )+ assert prompt_text == ""++ @staticmethod+ def test_padding_subcommand():+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline padding 1"+ )+ assert prompt_text == ""++ @staticmethod+ def test_get_subcommand():+ """'/statusline get' is a known subcommand, not a prompt."""+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline get"+ )+ assert prompt_text == ""++ # --- Non-matching cases (should return empty prompt_text) ---++ @staticmethod+ def test_non_statusline_input():+ prompt_text, content = _handle_statusline_prompt_command(+ "hello world"+ )+ assert prompt_text == ""+ assert content == "hello world"++ @staticmethod+ def test_other_slash_command():+ prompt_text, content = _handle_statusline_prompt_command(+ "/skills use something"+ )+ assert prompt_text == ""++ @staticmethod+ def test_empty_string():+ prompt_text, content = _handle_statusline_prompt_command("")+ assert prompt_text == ""+ assert content == ""++ @staticmethod+ def test_bare_statusline_no_args():+ """'/statusline' without description → no prompt."""+ prompt_text, content = _handle_statusline_prompt_command(+ "/statusline"+ )+ assert prompt_text == ""+ assert content == "/statusline"+++# ── _STATUSLINE_SETUP_PROMPT (hardcoded prompt content) ─────────+++class TestStatuslineSetupPrompt:+ """Verify _STATUSLINE_SETUP_PROMPT contains all necessary instructions."""++ @staticmethod+ def test_contains_setup_agent_identity():+ assert "status line setup agent" in _STATUSLINE_SETUP_PROMPT++ @staticmethod+ def test_contains_json_field_table():+ assert "usage.total_tokens" in _STATUSLINE_SETUP_PROMPT+ assert "model" in _STATUSLINE_SETUP_PROMPT+ assert "mode" in _STATUSLINE_SETUP_PROMPT+ assert "context_window.used_percentage" in _STATUSLINE_SETUP_PROMPT++ @staticmethod+ def test_contains_config_json_instructions():+ assert "config.json" in _STATUSLINE_SETUP_PROMPT+ assert "jiuwenswarm-tui" in _STATUSLINE_SETUP_PROMPT+ assert "statusLine" in _STATUSLINE_SETUP_PROMPT++ @staticmethod+ def test_contains_three_command_styles():+ assert "Style A" in _STATUSLINE_SETUP_PROMPT+ assert "Style B" in _STATUSLINE_SETUP_PROMPT+ assert "Style C" in _STATUSLINE_SETUP_PROMPT++ @staticmethod+ def test_contains_shell_command_examples():+ assert "jq" in _STATUSLINE_SETUP_PROMPT+ assert "git" in _STATUSLINE_SETUP_PROMPT+ assert "input=$(cat)" in _STATUSLINE_SETUP_PROMPT++ @staticmethod+ def test_contains_safety_guidelines():+ assert "2>/dev/null" in _STATUSLINE_SETUP_PROMPT++ @staticmethod+ def test_contains_auto_update_note():+ assert "2 seconds" in _STATUSLINE_SETUP_PROMPT+++# ── build_user_prompt (full pipeline) ───────────────────────────+++class TestBuildUserPromptStatusline:+ """Tests for build_user_prompt with /statusline prompt-type injection."""++ @staticmethod+ def test_statusline_prompt_injects_setup_instructions_zh():+ """Chinese /statusline prompt should have instructions injected."""+ prompt = build_user_prompt(+ "/statusline 展示模型名称和token数量",+ files={},+ channel="tui",+ language="zh",+ )+ # statusline-setup instructions should be present+ assert "status line setup agent" in prompt+ assert "jq" in prompt+ assert "config.json" in prompt+ # The instruction suffix in Chinese+ assert "你必须按照以下指令配置状态栏" in prompt+ # The user's description should be in the prompt content+ prompt_data = _extract_json_from_prompt(prompt)+ assert "展示模型名称和token数量" in prompt_data.get(+ "content", ""+ )+ # The /statusline prefix should be stripped from content+ assert "/statusline" not in prompt_data.get("content", "")++ @staticmethod+ def test_statusline_prompt_injects_setup_instructions_en():+ """English /statusline prompt should have instructions injected."""+ prompt = build_user_prompt(+ "/statusline show model and tokens",+ files={},+ channel="tui",+ language="en",+ )+ assert "status line setup agent" in prompt+ assert "jq" in prompt+ assert (+ "You must follow these instructions "+ "to configure the status line" in prompt+ )+ prompt_data = _extract_json_from_prompt(prompt)+ assert "show model and tokens" in prompt_data.get(+ "content", ""+ )++ @staticmethod+ def test_normal_message_no_injection():+ """Normal messages (not /statusline) should NOT have any injection."""+ prompt = build_user_prompt(+ "你好,帮我写个脚本",+ files={},+ channel="tui",+ language="zh",+ )+ assert "status line setup agent" not in prompt+ assert "状态栏" not in prompt+ assert "你必须按照" not in prompt++ @staticmethod+ def test_skills_use_command_no_statusline_conflict():+ """'/skills use' should be handled by its own handler."""+ prompt = build_user_prompt(+ "/skills use script-creator, show tokens",+ files={},+ channel="tui",+ language="zh",+ )+ # Should NOT inject statusline-setup prompt+ assert "status line setup agent" not in prompt+ # Content should contain the query part+ assert "show tokens" in prompt++ @staticmethod+ def test_statusline_set_subcommand_not_injected():+ """'/statusline set' is a known subcommand → no injection."""+ prompt = build_user_prompt(+ "/statusline set 'echo $mode'",+ files={},+ channel="tui",+ language="zh",+ )+ assert "你必须按照以下指令配置状态栏" not in prompt+ assert "status line setup agent" not in prompt+ prompt_data = _extract_json_from_prompt(prompt)+ assert prompt_data.get("content") == "/statusline set 'echo $mode'"++ @staticmethod+ def test_statusline_preserves_other_prompt_features():+ """build_user_prompt should still include timestamp, channel, etc."""+ prompt = build_user_prompt(+ "/statusline show git branch",+ files={},+ channel="tui",+ language="en",+ )+ prompt_data = _extract_json_from_prompt(prompt)+ assert prompt_data.get("source") == "tui"+ assert prompt_data.get("timezone") == "Asia/Shanghai"+ assert prompt_data.get("type") == "user input"+ assert "timestamp" in prompt_data++ @staticmethod+ def test_statusline_with_files_and_trusted_dirs():+ """/statusline prompt with files and trusted_dirs should work."""+ prompt = build_user_prompt(+ "/statusline show model",+ files={"test.py": "content"},+ channel="tui",+ language="zh",+ trusted_dirs=["/home/user/project"],+ )+ assert "status line setup agent" in prompt+ prompt_data = _extract_json_from_prompt(prompt)+ assert prompt_data.get("trusted_dirs") is not None++ @staticmethod+ def test_cron_channel_prompt_injected():+ """/statusline should work even in cron channel."""+ prompt = build_user_prompt(+ "/statusline show something",+ files={},+ channel="cron",+ language="zh",+ )+ assert "status line setup agent" in prompt++ @staticmethod+ def test_no_skill_file_dependency():+ """Injection from hardcoded string, not SKILL.md — aligned with Claude Code."""+ prompt = build_user_prompt(+ "/statusline show model",+ files={},+ channel="tui",+ language="en",+ )+ # Should NOT reference skill files or skill-loading mechanisms+ assert "[Skill:" not in prompt+ assert "SkillUseRail" not in prompt+ assert "SKILL.md" not in prompt+ # Should use the hardcoded prompt text+ assert _STATUSLINE_SETUP_PROMPT in prompt+++# ── Known subcommands constant ──────────────────────────────────+++class TestStatuslineKnownSubcommands:+ """Verify the known subcommands set is correct."""++ @staticmethod+ def test_set_is_known():+ assert "set" in _STATUSLINE_KNOWN_SUBCOMMANDS++ @staticmethod+ def test_padding_is_known():+ assert "padding" in _STATUSLINE_KNOWN_SUBCOMMANDS++ @staticmethod+ def test_clear_is_known():+ assert "clear" in _STATUSLINE_KNOWN_SUBCOMMANDS++ @staticmethod+ def test_help_is_known():+ assert "help" in _STATUSLINE_KNOWN_SUBCOMMANDS++ @staticmethod+ def test_json_is_known():+ assert "json" in _STATUSLINE_KNOWN_SUBCOMMANDS++ @staticmethod+ def test_get_is_known():+ assert "get" in _STATUSLINE_KNOWN_SUBCOMMANDS++ @staticmethod+ def test_all_six_subcommands():+ assert len(_STATUSLINE_KNOWN_SUBCOMMANDS) == 6++ @staticmethod+ def test_unknown_word_not_in_set():+ assert "show" not in _STATUSLINE_KNOWN_SUBCOMMANDS+ assert "display" not in _STATUSLINE_KNOWN_SUBCOMMANDS