"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
fix: add minimax smoke coverage
yuhaob6c25564c8c4
diff --git a/minimax/agent-harness/FIX_NOTES.md b/minimax/agent-harness/FIX_NOTES.mdnew file mode 100644index 000000000..db2e18dc9--- /dev/null+++ b/minimax/agent-harness/FIX_NOTES.md@@ -0,0 +1,48 @@+# PR 189 MiniMax Harness Fix Notes++## Changes++- Added CLI subprocess smoke coverage in `test_full_e2e.py`.+- Added no-backend smoke tests for `--help`, `session status`, `models`, and `voices`.+- Added CLI-level missing `MINIMAX_API_KEY` validation.+- Added CLI-level invalid `MINIMAX_API_KEY` validation through a local HTTP fake.+- Added a local MiniMax-compatible fake server for API-mocked chat and TTS subprocess workflows.+- Fixed the `tts` command by renaming the Click callback parameter from `output` to `output_path`; the previous name shadowed the module-level `output()` helper and crashed the CLI TTS path.++## Commands Run++```bash+cd minimax/agent-harness+python3 -m py_compile \+ cli_anything/minimax/minimax_cli.py \+ cli_anything/minimax/core/session.py \+ cli_anything/minimax/utils/minimax_backend.py \+ cli_anything/minimax/tests/test_core.py \+ cli_anything/minimax/tests/test_full_e2e.py+python3 -m pytest cli_anything/minimax/tests/test_core.py cli_anything/minimax/tests/test_full_e2e.py -v+python3 -m pip install -e .+CLI_ANYTHING_FORCE_INSTALLED=1 python3 -m pytest \+ cli_anything/minimax/tests/test_full_e2e.py::TestCLISubprocessSmoke -v -s+```++## Results++- `py_compile`: passed.+- Full MiniMax unit/E2E suite: `25 passed in 2.82s`.+- Force-installed CLI smoke suite: `5 passed in 3.90s`, using `/root/miniconda3/bin/cli-anything-minimax`.++## Real Backend Validation++`MINIMAX_API_KEY` was unset in this environment, so real API validation was not executed. To validate against MiniMax:++```bash+cd minimax/agent-harness+python3 -m pip install -e .+export MINIMAX_API_KEY="sk-your-real-key"+cli-anything-minimax --json test+cli-anything-minimax --json chat --prompt "Say ok only" --max-tokens 10+cli-anything-minimax stream --prompt "Say ok only" --max-tokens 10+cli-anything-minimax --json tts --text "MiniMax validation" --output /tmp/minimax-validation.mp3+test -s /tmp/minimax-validation.mp3+python3 -m pytest cli_anything/minimax/tests/test_full_e2e.py -v -s+```diff --git a/minimax/agent-harness/cli_anything/minimax/README.md b/minimax/agent-harness/cli_anything/minimax/README.mdindex 8e7a035d1..f6092533d 100644--- a/minimax/agent-harness/cli_anything/minimax/README.md+++ b/minimax/agent-harness/cli_anything/minimax/README.md@@ -8,6 +8,14 @@ CLI harness for **MiniMax AI** — chat and text-to-speech via the MiniMax API.pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=minimax/agent-harness```+For local validation from this repository:++```bash+cd minimax/agent-harness+python3 -m pip install -e .+cli-anything-minimax --help+```+## Prerequisites- Python 3.10+@@ -93,3 +101,35 @@ cli-anything-minimax models --tts|----------|-------------|| `MINIMAX_API_KEY` | MiniMax API key (required) || `MINIMAX_BASE_URL` | Override API base URL (optional) |++## Validation++No-backend and mocked API validation:++```bash+cd minimax/agent-harness+python3 -m py_compile \+ cli_anything/minimax/minimax_cli.py \+ cli_anything/minimax/core/session.py \+ cli_anything/minimax/utils/minimax_backend.py \+ cli_anything/minimax/tests/test_core.py \+ cli_anything/minimax/tests/test_full_e2e.py+python3 -m pytest cli_anything/minimax/tests/test_core.py cli_anything/minimax/tests/test_full_e2e.py -v+python3 -m pip install -e .+CLI_ANYTHING_FORCE_INSTALLED=1 python3 -m pytest \+ cli_anything/minimax/tests/test_full_e2e.py::TestCLISubprocessSmoke -v -s+```++Real MiniMax backend validation:++```bash+cd minimax/agent-harness+python3 -m pip install -e .+export MINIMAX_API_KEY="sk-your-real-key"+cli-anything-minimax --json test+cli-anything-minimax --json chat --prompt "Say ok only" --max-tokens 10+cli-anything-minimax stream --prompt "Say ok only" --max-tokens 10+cli-anything-minimax --json tts --text "MiniMax validation" --output /tmp/minimax-validation.mp3+test -s /tmp/minimax-validation.mp3+python3 -m pytest cli_anything/minimax/tests/test_full_e2e.py -v -s+```diff --git a/minimax/agent-harness/cli_anything/minimax/minimax_cli.py b/minimax/agent-harness/cli_anything/minimax/minimax_cli.pyindex 2345fe965..beb269fd3 100644--- a/minimax/agent-harness/cli_anything/minimax/minimax_cli.py+++ b/minimax/agent-harness/cli_anything/minimax/minimax_cli.py@@ -249,6 +249,7 @@ def stream(ctx, prompt, model_opt=None, temperature=None, max_tokens=None):@click.option("--output","-o",+ "output_path",type=click.Path(),default="output.mp3",show_default=True,@@ -256,7 +257,7 @@ def stream(ctx, prompt, model_opt=None, temperature=None, max_tokens=None):)@click.pass_context@handle_error-def tts(ctx, text, model_opt, voice, output):+def tts(ctx, text, model_opt, voice, output_path):"""Synthesize text to speech using MiniMax TTS."""parent_key = ctx.obj.get("api_key") if ctx.obj else Noneapi_key = get_api_key(parent_key)@@ -266,16 +267,16 @@ def tts(ctx, text, model_opt, voice, output):text=text,model=model_opt,voice=voice,- output_path=output,+ output_path=output_path,)output_data = {- "output_file": output,+ "output_file": output_path,"size_bytes": len(audio_data),"model": model_opt,"voice": voice,}- output(output_data, f"✓ Audio saved to {output} ({len(audio_data)} bytes)")+ output(output_data, f"✓ Audio saved to {output_path} ({len(audio_data)} bytes)")@cli.group()diff --git a/minimax/agent-harness/cli_anything/minimax/tests/TEST.md b/minimax/agent-harness/cli_anything/minimax/tests/TEST.mdnew file mode 100644index 000000000..a06a8a5c5--- /dev/null+++ b/minimax/agent-harness/cli_anything/minimax/tests/TEST.md@@ -0,0 +1,76 @@+# MiniMax Harness Test Plan and Results++## Test Inventory++- `test_core.py`: 16 unit tests for API key resolution, config persistence, model/voice registries, mocked chat, streaming, TTS parsing, and full workflow helpers.+- `test_full_e2e.py`: 9 E2E tests covering installed-command smoke behavior, no-backend commands, missing/invalid API key failures, API-mocked CLI chat/TTS, and backend chat/stream/TTS paths.++## Unit Coverage++- `utils/minimax_backend.py`+ - API key priority: CLI argument, `MINIMAX_API_KEY`, config file, missing key.+ - Config read/write behavior with isolated config paths.+ - Chat request body, default temperature, MiniMax endpoint, and HTTP error wrapping.+ - Streaming SSE parsing and callback delivery.+ - TTS SSE parsing, hex audio decoding, endpoint selection, and API-level error handling.+ - `run_full_workflow` chat response and token metadata extraction.++## E2E and CLI Coverage++- Installed command resolution uses `_resolve_cli("cli-anything-minimax")`.+- `CLI_ANYTHING_FORCE_INSTALLED=1` requires the installed console script and fails if it is not on `PATH`.+- No-backend smoke tests verify `--help`, `session status`, `models`, and `voices` without `MINIMAX_API_KEY`.+- Missing-key CLI tests verify `chat` fails before making any network call and returns machine-readable JSON errors.+- Invalid-key CLI tests route through a local HTTP fake, return 401, and verify the CLI reports a MiniMax API error.+- API-mocked workflow tests run real CLI subprocesses against a local MiniMax-compatible fake server:+ - `chat` returns JSON content and usage.+ - `tts` writes MP3-like bytes to disk and reports output metadata.++## Real Backend Validation Steps++Run these from the repository root when a real MiniMax API key is available:++```bash+cd minimax/agent-harness+python3 -m pip install -e .+export MINIMAX_API_KEY="sk-your-real-key"+cli-anything-minimax --json test+cli-anything-minimax --json chat --prompt "Say ok only" --max-tokens 10+cli-anything-minimax stream --prompt "Say ok only" --max-tokens 10+cli-anything-minimax --json tts --text "MiniMax validation" --output /tmp/minimax-validation.mp3+test -s /tmp/minimax-validation.mp3+python3 -m pytest cli_anything/minimax/tests/test_full_e2e.py -v -s+```++Expected real-backend results:++- `test` returns JSON with `"status": "ok"`.+- `chat` returns non-empty assistant content.+- `stream` prints at least one streamed chunk.+- `tts` writes a non-empty `/tmp/minimax-validation.mp3`.+- `test_full_e2e.py` uses the real API for backend tests when `MINIMAX_API_KEY` is set.++## Local Validation Results++Environment note: `MINIMAX_API_KEY` was unset for this validation run, so real API calls used the mocked/no-backend test paths.++```text+$ python3 -m py_compile cli_anything/minimax/minimax_cli.py cli_anything/minimax/core/session.py cli_anything/minimax/utils/minimax_backend.py cli_anything/minimax/tests/test_core.py cli_anything/minimax/tests/test_full_e2e.py+# passed with exit code 0+```++```text+$ python3 -m pytest cli_anything/minimax/tests/test_core.py cli_anything/minimax/tests/test_full_e2e.py -v+25 passed in 2.82s+```++```text+$ CLI_ANYTHING_FORCE_INSTALLED=1 python3 -m pytest cli_anything/minimax/tests/test_full_e2e.py::TestCLISubprocessSmoke -v -s+[_resolve_cli] Using installed command: /root/miniconda3/bin/cli-anything-minimax+5 passed in 3.90s+```++## Coverage Gaps++- Real MiniMax backend validation still requires a live `MINIMAX_API_KEY`.+- The mocked TTS output verifies the CLI write path and MP3-like bytes, not perceptual audio quality.diff --git a/minimax/agent-harness/cli_anything/minimax/tests/test_full_e2e.py b/minimax/agent-harness/cli_anything/minimax/tests/test_full_e2e.pyindex 4ead4c685..383209df6 100644--- a/minimax/agent-harness/cli_anything/minimax/tests/test_full_e2e.py+++ b/minimax/agent-harness/cli_anything/minimax/tests/test_full_e2e.py@@ -2,6 +2,13 @@import osimport json+import shutil+import subprocess+import sys+import threading+from contextlib import contextmanager+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Pathfrom unittest.mock import patch, MagicMockfrom cli_anything.minimax.utils.minimax_backend import (@@ -11,6 +18,216 @@ from cli_anything.minimax.utils.minimax_backend import ()API_KEY = os.environ.get("MINIMAX_API_KEY")+HARNESS_ROOT = Path(__file__).resolve().parents[3]+++def _resolve_cli(name):+ """Resolve installed CLI command; fall back to python -m for local dev."""+ force = os.environ.get("CLI_ANYTHING_FORCE_INSTALLED", "").strip() == "1"+ path = shutil.which(name)+ if path:+ print(f"[_resolve_cli] Using installed command: {path}")+ return [path]+ if force:+ raise RuntimeError(f"{name} not found in PATH. Install with: pip install -e .")+ module = name.replace("cli-anything-", "cli_anything.")+ module = f"{module}.{name.split('-')[-1]}_cli"+ print(f"[_resolve_cli] Falling back to: {sys.executable} -m {module}")+ return [sys.executable, "-m", module]+++def _subprocess_env(tmp_path, extra=None):+ env = os.environ.copy()+ env.pop("MINIMAX_API_KEY", None)+ env["HOME"] = str(tmp_path)+ pythonpath_parts = [str(HARNESS_ROOT)]+ if env.get("PYTHONPATH"):+ pythonpath_parts.append(env["PYTHONPATH"])+ env["PYTHONPATH"] = os.pathsep.join(pythonpath_parts)+ if extra:+ env.update(extra)+ return env+++@contextmanager+def _fake_minimax_server(status_code=200):+ """Run a local MiniMax-compatible HTTP fake for CLI subprocess tests."""++ class Handler(BaseHTTPRequestHandler):+ requests_seen = []++ def do_POST(self):+ length = int(self.headers.get("Content-Length", "0"))+ body = self.rfile.read(length).decode("utf-8")+ payload = json.loads(body) if body else {}+ self.requests_seen.append(+ {+ "path": self.path,+ "authorization": self.headers.get("Authorization", ""),+ "payload": payload,+ }+ )++ if status_code != 200:+ response = b'{"error":"Invalid API key"}'+ self.send_response(status_code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(response)))+ self.end_headers()+ self.wfile.write(response)+ return++ if self.path.endswith("/chat/completions"):+ response = json.dumps(+ {+ "choices": [+ {"message": {"role": "assistant", "content": "mock chat ok"}}+ ],+ "usage": {+ "prompt_tokens": 3,+ "completion_tokens": 2,+ "total_tokens": 5,+ },+ }+ ).encode("utf-8")+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(response)))+ self.end_headers()+ self.wfile.write(response)+ return++ if self.path.endswith("/v1/t2a_v2"):+ hex_audio = bytes([0xFF, 0xFB, 0x11, 0x22]).hex()+ event = json.dumps(+ {+ "data": {"audio": hex_audio, "status": 2},+ "base_resp": {"status_code": 0, "status_msg": "success"},+ }+ )+ response = f"data:{event}\n\ndata:[DONE]\n\n".encode("utf-8")+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(response)))+ self.end_headers()+ self.wfile.write(response)+ return++ self.send_response(404)+ self.end_headers()++ def log_message(self, format, *args):+ return++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}", Handler.requests_seen+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++class TestCLISubprocessSmoke:+ CLI_BASE = _resolve_cli("cli-anything-minimax")++ def _run(self, args, tmp_path, extra_env=None, check=True):+ return subprocess.run(+ self.CLI_BASE + args,+ capture_output=True,+ text=True,+ check=check,+ env=_subprocess_env(tmp_path, extra_env),+ )++ def test_installed_command_help_smoke(self, tmp_path):+ result = self._run(["--help"], tmp_path)+ assert result.returncode == 0+ assert "MiniMax CLI" in result.stdout+ assert "chat" in result.stdout+ assert "tts" in result.stdout++ def test_no_backend_commands_work_without_api_key(self, tmp_path):+ session_status = self._run(["--json", "session", "status"], tmp_path)+ status = json.loads(session_status.stdout)+ assert status["message_count"] == 0+ assert status["history_count"] == 0++ models = self._run(["models"], tmp_path)+ assert "MiniMax-M2.7" in models.stdout++ voices = self._run(["voices"], tmp_path)+ assert "English_Graceful_Lady" in voices.stdout++ def test_missing_api_key_fails_before_network_call(self, tmp_path):+ result = self._run(+ ["--json", "chat", "--prompt", "hello"],+ tmp_path,+ check=False,+ )+ assert result.returncode == 1+ payload = json.loads(result.stdout)+ assert payload["type"] == "RuntimeError"+ assert "MiniMax API key not found" in payload["error"]+ assert "MINIMAX_API_KEY" in payload["error"]++ def test_invalid_minimax_api_key_reports_api_error(self, tmp_path):+ with _fake_minimax_server(status_code=401) as (base_url, requests_seen):+ result = self._run(+ ["--json", "chat", "--prompt", "hello"],+ tmp_path,+ extra_env={+ "MINIMAX_API_KEY": "invalid-key",+ "MINIMAX_BASE_URL": base_url,+ },+ check=False,+ )++ assert result.returncode == 1+ payload = json.loads(result.stdout)+ assert payload["type"] == "RuntimeError"+ assert "MiniMax API error" in payload["error"]+ assert requests_seen[0]["authorization"] == "Bearer invalid-key"++ def test_api_mocked_chat_and_tts_workflow(self, tmp_path):+ with _fake_minimax_server() as (base_url, requests_seen):+ chat = self._run(+ ["--json", "chat", "--prompt", "Say ok"],+ tmp_path,+ extra_env={+ "MINIMAX_API_KEY": "sk-test",+ "MINIMAX_BASE_URL": base_url,+ },+ )+ chat_payload = json.loads(chat.stdout)+ assert chat_payload["content"] == "mock chat ok"+ assert chat_payload["usage"]["total_tokens"] == 5++ audio_path = tmp_path / "mock.mp3"+ tts = self._run(+ [+ "--json",+ "tts",+ "--text",+ "Hello from the fake API",+ "--output",+ str(audio_path),+ ],+ tmp_path,+ extra_env={+ "MINIMAX_API_KEY": "sk-test",+ "MINIMAX_BASE_URL": base_url,+ },+ )+ tts_payload = json.loads(tts.stdout)++ assert tts_payload["output_file"] == str(audio_path)+ assert tts_payload["size_bytes"] == 4+ assert audio_path.read_bytes() == bytes([0xFF, 0xFB, 0x11, 0x22])+ assert any(req["path"].endswith("/chat/completions") for req in requests_seen)+ assert any(req["path"].endswith("/v1/t2a_v2") for req in requests_seen)# ── Chat ───────────────────────────────────────────────────────────────────────