Files
lemonade/test/server_cli2.py
anishp55andFlorian Reinle 5fec0a8217 when agent cli is not found print env vars and launch cmd (#1951)
* cli: show safe manual launch instructions when agent CLI is missing

Co-authored-by: anishp55 <[email protected]>

* fix: address remaining manual agent launch review findings

* fix: preserve Junie profile root in manual launch instructions

* fix: use absolute Junie profile path in manual launch

* fix: refactor and fix a bit

---------

Co-authored-by: Florian Reinle <[email protected]>
2026-11-19 06:59:08 +00:00

3440 lines
136 KiB
Python

"""
CLI client tests for Lemonade CLI (lemonade command).
Tests the lemonade CLI client commands (HTTP client for Lemonade Server):
- status
- list
- export
- backends
- cloud
- import (from JSON file)
- pull with labels and checkpoints
- load
- unload
- delete
Expects a running server (started by the installer or manually).
Usage:
python server_cli2.py
python server_cli2.py --cli-binary /path/to/lemonade
"""
import argparse
import glob
import json
import os
import platform
import re
import requests
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import unittest
import uuid
from utils.server_base import _auth_headers, set_server_config, wait_for_server
from utils.test_models import (
ENDPOINT_TEST_MODEL,
ENDPOINT_TEST_MODEL_CTX_SIZE,
MULTI_REPO_MODEL_A_CACHE_DIR,
MULTI_REPO_MODEL_A_MAIN,
MULTI_REPO_MODEL_A_NAME,
MULTI_REPO_MODEL_B_CACHE_DIR,
MULTI_REPO_MODEL_B_MAIN,
MULTI_REPO_MODEL_B_NAME,
MULTI_REPO_SHARED_CACHE_DIR,
MULTI_REPO_SHARED_CHECKPOINT,
PORT,
SHARED_REPO_MODEL_A_CHECKPOINT,
SHARED_REPO_MODEL_A_NAME,
SHARED_REPO_MODEL_B_CHECKPOINT,
SHARED_REPO_MODEL_B_NAME,
TIMEOUT_DEFAULT,
TIMEOUT_MODEL_OPERATION,
USER_MODEL_MAIN_CHECKPOINT,
USER_MODEL_TE_CHECKPOINT,
USER_MODEL_NAME,
get_default_cli_binary,
get_hf_cache_dir_candidates,
)
def _checkpoint_variant_path(checkpoint):
"""Return the repo-relative variant path for a HF checkpoint string."""
parts = checkpoint.split(":", 1)
if len(parts) != 2:
return ""
return os.path.join(*parts[1].split("/"))
def _find_cached_checkpoint(cache_root, repo_cache_dir, checkpoint):
"""Return the on-disk snapshot path for a checkpoint, if present."""
variant_path = _checkpoint_variant_path(checkpoint)
if not variant_path:
return None
pattern = os.path.join(cache_root, repo_cache_dir, "snapshots", "*", variant_path)
matches = glob.glob(pattern)
if matches:
return matches[0]
return None
def _resolve_hf_cache_root(repo_cache_dirs, checkpoint_specs=None):
"""Pick the HF cache root that actually contains the downloaded repo artifacts."""
diagnostics = []
matches = []
for hf_cache in get_hf_cache_dir_candidates():
missing = [
repo_dir
for repo_dir in repo_cache_dirs
if not os.path.isdir(os.path.join(hf_cache, repo_dir))
]
checkpoint_paths = []
if not missing and checkpoint_specs:
for repo_cache_dir, checkpoint in checkpoint_specs:
checkpoint_path = _find_cached_checkpoint(
hf_cache, repo_cache_dir, checkpoint
)
if checkpoint_path is None:
missing.append(f"{repo_cache_dir}:{checkpoint}")
else:
checkpoint_paths.append(checkpoint_path)
if not missing:
probe_paths = [
os.path.join(hf_cache, repo_cache_dir)
for repo_cache_dir in repo_cache_dirs
] + checkpoint_paths
newest_mtime = max(os.path.getmtime(path) for path in probe_paths)
matches.append((newest_mtime, hf_cache))
continue
diagnostics.append(f"{hf_cache} (missing: {', '.join(missing)})")
if matches:
matches.sort(reverse=True)
return matches[0][1]
raise AssertionError(
"Could not resolve HF cache root after pull. Checked: " + "; ".join(diagnostics)
)
# Global configuration
_config = {
"cli_binary": None,
"cli_api_key": None,
}
IS_WINDOWS = platform.system() == "Windows"
WINDOWS_LAUNCH_STUB_SKIP_REASON = "Windows launch-stub execution uses non-native script binaries; covered on Unix runners"
def get_cli_binary():
"""Get the lemonade CLI binary path."""
return _config["cli_binary"] or get_default_cli_binary()
def parse_cli_args():
"""Parse command line arguments for CLI client tests."""
parser = argparse.ArgumentParser(description="Test lemonade CLI client")
parser.add_argument(
"--cli-binary",
type=str,
default=get_default_cli_binary(),
help="Path to lemonade CLI binary (default: CMake build output)",
)
parser.add_argument(
"--api-key",
type=str,
default=None,
help="API key to pass to all CLI invocations (for servers requiring auth)",
)
args = parser.parse_args()
_config["cli_binary"] = args.cli_binary
_config["cli_api_key"] = args.api_key
return args
def run_cli_command(
args,
timeout=60,
check=False,
env=None,
input_text=None,
*,
inject_runner_key=True,
cwd=None,
):
"""
Run a CLI command and return the result.
If --api-key was provided to the test runner, it is automatically prepended
to every CLI invocation so commands work against a server requiring auth.
Args:
args: List of command arguments (without the binary)
timeout: Command timeout in seconds
check: If True, raise CalledProcessError on non-zero exit
env: Optional environment override for subprocess
input_text: Optional stdin text for interactive prompts
inject_runner_key: Whether to prepend the runner's API key (default: yes)
cwd: Optional working directory for subprocess
Returns:
subprocess.CompletedProcess result
"""
cli_args = list(args)
if inject_runner_key and _config["cli_api_key"]:
cli_args = ["--api-key", _config["cli_api_key"]] + cli_args
cli_binary = get_cli_binary()
if os.path.isabs(cli_binary):
resolved_cli_binary = cli_binary
elif os.path.sep in cli_binary or (os.path.altsep and os.path.altsep in cli_binary):
resolved_cli_binary = os.path.abspath(cli_binary)
else:
resolved_cli_binary = shutil.which(cli_binary) or cli_binary
cmd = [resolved_cli_binary] + cli_args
print(f"Running: {' '.join(cmd)}")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
input=input_text,
timeout=timeout,
encoding="utf-8",
errors="replace",
env=env,
cwd=cwd,
)
if result.stdout:
print(f"stdout: {result.stdout}")
if result.stderr:
print(f"stderr: {result.stderr}")
if check and result.returncode != 0:
raise subprocess.CalledProcessError(
result.returncode, cmd, result.stdout, result.stderr
)
return result
def _is_transient_cli_pull_failure(result):
"""Return True when a failed CLI pull looks like a transient server/HF issue."""
if result.returncode == 0:
return False
output = f"{result.stdout or ''}\n{result.stderr or ''}".lower()
transient_statuses = {408, 409, 429, 500, 502, 503, 504}
observed_statuses = {
int(match) for match in re.findall(r"(?:status\s*[:=]|http\s*)(\d{3})", output)
}
if observed_statuses.intersection(transient_statuses):
return True
return (
"too many requests" in output
or "rate limit" in output
or "temporarily unavailable" in output
or "connection reset" in output
or "connection aborted" in output
or "connection refused" in output
or "ssl connect error" in output
or "timed out" in output
or "timeout" in output
)
def run_cli_pull_command_with_retry(args, timeout=TIMEOUT_MODEL_OPERATION, attempts=3):
"""Run a CLI pull command with bounded retry for transient setup failures.
The command still has to succeed with exit code 0. This only retries failures
that look transient, such as HF rate limits or temporary server/network errors.
"""
last_result = None
for attempt in range(1, attempts + 1):
if attempt > 1:
time.sleep(min(30, 2 ** (attempt - 1)))
result = run_cli_command(args, timeout=timeout)
if result.returncode == 0:
return result
last_result = result
if _is_transient_cli_pull_failure(result) and attempt < attempts:
print(
f"Transient CLI pull failure, attempt {attempt}/{attempts}. "
"Retrying..."
)
continue
break
return last_result
class PersistentServerCLIClientTests(unittest.TestCase):
"""
CLI client tests that run with a persistent server.
Expects a running server (started by the installer or manually).
Tests run in order and may depend on previous test state.
"""
@classmethod
def setUpClass(cls):
"""Verify server is running."""
super().setUpClass()
print("\n=== Verifying server is reachable for CLI client tests ===")
try:
wait_for_server(timeout=30)
except TimeoutError:
raise RuntimeError(
"Server is not running on port %d. "
"Start the server before running tests." % PORT
)
print("Server is reachable")
def assertCommandSucceeds(self, args, timeout=60):
"""Assert that a CLI command succeeds (exit code 0)."""
result = run_cli_command(args, timeout=timeout)
self.assertEqual(
result.returncode,
0,
f"Command failed with exit code {result.returncode}: {result.stderr}",
)
return result
def assertCommandFails(self, args, timeout=60):
"""Assert that a CLI command fails (non-zero exit code)."""
result = run_cli_command(args, timeout=timeout)
self.assertNotEqual(
result.returncode,
0,
f"Command unexpectedly succeeded: {result.stdout}",
)
return result
def _write_fake_agent(self, directory, agent_name, capture_file, version=None):
"""Create a tiny fake agent binary that captures argv and selected env vars."""
exe_path = os.path.join(directory, agent_name)
script = f"""#!/usr/bin/env python3
import json
import os
import sys
if sys.argv[1:] == ["--version"]:
print({(version or "fake-agent-ok")!r})
sys.exit(0)
payload = {{
"argv": sys.argv[1:],
"env": {{
"ANTHROPIC_BASE_URL": os.environ.get("ANTHROPIC_BASE_URL", ""),
"ANTHROPIC_AUTH_TOKEN": os.environ.get("ANTHROPIC_AUTH_TOKEN", ""),
"LEMONADE_API_KEY": os.environ.get("LEMONADE_API_KEY", ""),
"OPENAI_BASE_URL": os.environ.get("OPENAI_BASE_URL", ""),
"OPENAI_API_KEY": os.environ.get("OPENAI_API_KEY", ""),
"ANTHROPIC_DEFAULT_SONNET_MODEL": os.environ.get("ANTHROPIC_DEFAULT_SONNET_MODEL", ""),
"CLAUDE_CODE_SUBAGENT_MODEL": os.environ.get("CLAUDE_CODE_SUBAGENT_MODEL", ""),
}},
}}
with open({capture_file!r}, "w", encoding="utf-8") as f:
json.dump(payload, f)
print("fake-agent-ok")
sys.exit(0)
"""
with open(exe_path, "w", encoding="utf-8") as f:
f.write(script)
os.chmod(exe_path, 0o755)
return exe_path
def _build_stubbed_agent_env(self, stub_dir):
"""Build isolated env so PATH resolves fake agents and avoids first-run side effects."""
env = os.environ.copy()
env.pop("OPENAI_BASE_URL", None)
# Outranks HOME, so a machine that sets it would have its real junie
# config rewritten instead of the stub directory.
env.pop("JUNIE_HOME", None)
# Same for pi: it would point launch at the real pi agent directory.
env.pop("PI_CODING_AGENT_DIR", None)
env["PATH"] = stub_dir + os.pathsep + env.get("PATH", "")
env["HOME"] = stub_dir
env["XDG_CONFIG_HOME"] = os.path.join(stub_dir, ".config")
env["XDG_CACHE_HOME"] = os.path.join(stub_dir, ".cache")
env["XDG_DATA_HOME"] = os.path.join(stub_dir, ".local", "share")
return env
def _build_noop_opener_env(self, stub_dir):
"""Build env with no-op URL opener binaries to avoid GUI popups in run tests on Unix."""
opener_script = "#!/usr/bin/env sh\nexit 0\n"
for name in ["xdg-open", "open"]:
opener_path = os.path.join(stub_dir, name)
with open(opener_path, "w", encoding="utf-8") as f:
f.write(opener_script)
os.chmod(opener_path, 0o755)
return self._build_stubbed_agent_env(stub_dir)
def _build_missing_agent_env(self, stub_dir):
"""Build env with isolated PATH, HOME, and Windows npm lookup roots."""
env = self._build_stubbed_agent_env(stub_dir)
env["PATH"] = stub_dir
if IS_WINDOWS:
env["APPDATA"] = stub_dir
env["USERPROFILE"] = stub_dir
return env
# =============================================================================
# Version Tests
# =============================================================================
def test_005_version(self):
"""Test --version flag."""
result = self.assertCommandSucceeds(["--version"])
self.assertTrue(
len(result.stdout) > 0 or len(result.stderr) > 0,
"Version command should produce output",
)
# =============================================================================
# Status Tests
# =============================================================================
def test_010_status(self):
"""Test status command."""
result = self.assertCommandSucceeds(["status"])
output = result.stdout + result.stderr
print(f"Status output: {output}")
def test_010a_status_json(self):
"""Test status --json emits parseable per-model detail."""
result = self.assertCommandSucceeds(["status", "--json"])
data = json.loads(result.stdout)
self.assertIn("port", data)
self.assertIsInstance(data["port"], int)
self.assertIn("version", data)
self.assertIn("models", data)
self.assertIsInstance(data["models"], list)
# Per-model detail only exists when something is loaded; the CLI suite
# does not guarantee that, so the contract is checked opportunistically.
for model in data["models"]:
for key in (
"model_name",
"checkpoint",
"type",
"device",
"recipe",
"recipe_options",
"status",
"pinned",
"pid",
"backend_url",
):
self.assertIn(key, model)
self.assertIsInstance(model["recipe_options"], dict)
self.assertIsInstance(model["pinned"], bool)
self.assertIsInstance(model["pid"], int)
def test_011_status_with_global_options(self):
"""Test status command with global options."""
result = run_cli_command(
["--host", "127.0.0.1", "--port", str(PORT), "status"],
timeout=TIMEOUT_DEFAULT,
)
print(f"Status with options exit code: {result.returncode}")
# =============================================================================
# List Tests
# =============================================================================
def _section_between(self, output, start_header, end_header=None):
lines = output.splitlines()
self.assertIn(start_header, lines)
start = lines.index(start_header) + 1
end = (
lines.index(end_header)
if end_header and end_header in lines
else len(lines)
)
return "\n".join(lines[start:end])
def _parse_model_table(self, section_text):
parsed_models = []
for line in section_text.splitlines():
line = line.strip()
if (
not line
or line.startswith("Model Name")
or line.startswith("---")
or "No local models" in line
or "No models available" in line
):
continue
parts = line.split()
if len(parts) >= 2:
name = parts[0]
downloaded = parts[1] == "Yes"
details = parts[2] if len(parts) > 2 else ""
parsed_models.append(
{"name": name, "downloaded": downloaded, "details": details}
)
return parsed_models
def test_020_list(self):
"""Test list command."""
result = self.assertCommandSucceeds(["list"])
output = result.stdout + result.stderr
print(f"List output: {output}")
output_lines = output.splitlines()
self.assertIn("Local", output_lines)
self.assertIn("Available for Download", output_lines)
self.assertLess(
output_lines.index("Local"),
output_lines.index("Available for Download"),
)
local_section = self._section_between(output, "Local", "Available for Download")
available_section = self._section_between(output, "Available for Download")
local_models = self._parse_model_table(local_section)
available_models = self._parse_model_table(available_section)
if not local_models:
self.assertIn("No local models downloaded.", local_section)
else:
for m in local_models:
self.assertTrue(
m["downloaded"],
f"Model {m['name']} in Local section should be downloaded (Yes)",
)
for m in available_models:
self.assertFalse(
m["downloaded"],
f"Model {m['name']} in Available for Download section should not be downloaded (No)",
)
def test_021_list_downloaded_flag(self):
"""Test list --downloaded flag."""
# Get all models from the full list to know what's available vs downloaded
all_result = self.assertCommandSucceeds(["list"])
all_output = all_result.stdout + all_result.stderr
available_section = self._section_between(all_output, "Available for Download")
available_models = self._parse_model_table(available_section)
result = self.assertCommandSucceeds(["list", "--downloaded"])
output = result.stdout + result.stderr
print(f"List --downloaded output: {output}")
output_lines = output.splitlines()
self.assertNotIn("Local", output_lines)
self.assertNotIn("Available for Download", output_lines)
# A fresh cache has no local models yet, so --downloaded may return
# the empty local-state message instead of a table.
if "No local models downloaded." in output:
downloaded_models = []
else:
self.assertIn("Model Name", output)
self.assertIn("Downloaded", output)
self.assertIn("Details", output)
downloaded_models = self._parse_model_table(output)
for m in downloaded_models:
self.assertTrue(
m["downloaded"],
f"Model {m['name']} in --downloaded list should be downloaded (Yes)",
)
non_downloaded_names = [
m["name"] for m in available_models if not m["downloaded"]
]
if non_downloaded_names:
downloaded_names = [m["name"] for m in downloaded_models]
for name in non_downloaded_names:
self.assertNotIn(
name,
downloaded_names,
f"Non-downloaded model {name} should not be in --downloaded list",
)
# =============================================================================
# Export Tests
# =============================================================================
def test_030_export_with_output_file(self):
"""Test export command with --output flag."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
temp_file = f.name
try:
result = run_cli_command(
["export", ENDPOINT_TEST_MODEL, "--output", temp_file],
timeout=TIMEOUT_DEFAULT,
)
print(f"Export to file exit code: {result.returncode}")
finally:
if os.path.exists(temp_file):
os.unlink(temp_file)
def test_031_export_to_stdout(self):
"""Test export command without --output (prints to stdout)."""
result = run_cli_command(
["export", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
)
print(f"Export to stdout exit code: {result.returncode}")
# =============================================================================
# Recipes Tests
# =============================================================================
def test_040_backends(self):
"""Test backends command."""
result = self.assertCommandSucceeds(["backends"])
output = result.stdout + result.stderr
self.assertTrue(
len(output) > 0,
f"Backends command should produce output: {output}",
)
print(f"Backends output: {output}")
@unittest.skipIf(
platform.system() == "Darwin", "llamacpp:cpu not supported on macOS"
)
def test_041_backends_install(self):
"""Test backends install."""
result = self.assertCommandSucceeds(["backends", "install", "llamacpp:cpu"])
print(f"Backends install exit code: {result.returncode}")
@unittest.skipIf(
platform.system() == "Darwin", "llamacpp:cpu not supported on macOS"
)
def test_042_backends_uninstall(self):
"""Test backends uninstall."""
result = self.assertCommandSucceeds(["backends", "uninstall", "llamacpp:cpu"])
print(f"Backends uninstall exit code: {result.returncode}")
def test_043_backends_info(self):
"""Test backends info prints the backend's author, publisher and license."""
result = self.assertCommandSucceeds(["backends", "info", "llamacpp:rocm"])
output = result.stdout
self.assertIn("llamacpp:rocm", output)
self.assertRegex(output, r"Author\s+ggml-org")
self.assertRegex(output, r"Publisher\s+lemonade-sdk")
self.assertRegex(output, r"License\s+MIT")
response = requests.get(
f"http://localhost:{PORT}/api/v1/system-info",
headers=_auth_headers(),
timeout=10,
)
self.assertEqual(response.status_code, 200)
rocm = response.json()["recipes"]["llamacpp"]["backends"]["rocm"]
for key in ("description", "author", "publisher", "license", "project_url"):
self.assertTrue(rocm.get(key), f"/system-info is missing {key}")
def test_044_backends_info_unknown_backend(self):
"""Test backends info rejects a backend the recipe does not have."""
self.assertCommandFails(["backends", "info", "llamacpp:no-such-backend"])
# =============================================================================
# Cloud Tests
# =============================================================================
def test_046_cloud_list_json(self):
"""Test `cloud list --json` emits the provider array from system-info."""
result = self.assertCommandSucceeds(["cloud", "list", "--json"])
providers = json.loads(result.stdout)
self.assertIsInstance(providers, list)
provider = "clijsonprobe"
base_url = "https://example.invalid/v1"
try:
self.assertCommandSucceeds(
["cloud", "install", provider, "--base-url", base_url]
)
result = self.assertCommandSucceeds(["cloud", "list", "--json"])
providers = json.loads(result.stdout)
self.assertIsInstance(providers, list)
entry = next((p for p in providers if p.get("name") == provider), None)
self.assertIsNotNone(entry, f"{provider} missing from {providers}")
for key in (
"name",
"base_url",
"env_var",
"env_var_set",
"runtime_key_set",
"models_discovered",
"allow_insecure_http",
):
self.assertIn(key, entry)
self.assertEqual(entry["base_url"], base_url)
self.assertEqual(entry["env_var"], "LEMONADE_CLIJSONPROBE_API_KEY")
self.assertFalse(entry["env_var_set"])
self.assertFalse(entry["runtime_key_set"])
self.assertEqual(entry["models_discovered"], 0)
self.assertFalse(entry["allow_insecure_http"])
human = self.assertCommandSucceeds(["cloud", "list"])
with self.assertRaises(json.JSONDecodeError):
json.loads(human.stdout)
self.assertIn(provider, human.stdout)
finally:
run_cli_command(["cloud", "uninstall", provider])
# =============================================================================
# Runtime Config Tests
# =============================================================================
def test_043_listen_all_via_runtime_config(self):
"""Test that setting host to 0.0.0.0 via /internal/set works."""
try:
# Set host to 0.0.0.0 (listen on all interfaces).
try:
set_server_config({"host": "0.0.0.0"})
print("[OK] Set host to 0.0.0.0 via /internal/set")
except Exception as e:
self.fail(f"Failed to set host to 0.0.0.0: {e}")
# Wait for server to finish rebinding. Use 127.0.0.1 explicitly
# because 0.0.0.0 only binds IPv4, and "localhost" may resolve to
# ::1 (IPv6) in some environments (e.g. Fedora containers).
for i in range(30):
try:
response = requests.get(
f"http://127.0.0.1:{PORT}/api/v1/health",
headers=_auth_headers(),
timeout=2,
)
if response.status_code == 200:
break
except requests.ConnectionError:
pass
time.sleep(1)
else:
self.fail(
"Server did not become reachable on 127.0.0.1 after rebind to 0.0.0.0"
)
# Verify the server still responds (status command should work).
result = self.assertCommandSucceeds(["status"])
output = result.stdout.lower() + result.stderr.lower()
self.assertTrue(
"running" in output or "online" in output or "active" in output,
f"Status should indicate server is running on 0.0.0.0: {result.stdout}",
)
# Verify via health endpoint too (use 127.0.0.1 for same IPv4 reason).
response = requests.get(
f"http://127.0.0.1:{PORT}/api/v1/health",
headers=_auth_headers(),
timeout=10,
)
self.assertEqual(response.status_code, 200)
finally:
# Best-effort restore: this test runs inside CI jobs that execute
# multiple modules against one long-lived server, so cleanup must not
# mask the primary assertion failure. reset_server_state also restores
# the host before subsequent CI suites.
try:
response = requests.post(
f"http://127.0.0.1:{PORT}/internal/set",
json={"host": "localhost"},
headers=_auth_headers(),
timeout=10,
)
if response.status_code < 400:
wait_for_server(port=PORT, timeout=30)
print("[OK] Restored host to localhost and server is reachable")
else:
print(
"Warning: Failed to restore host to localhost: "
f"{response.status_code}: {response.text}"
)
except Exception as e: # noqa: BLE001 - best-effort cleanup
print(f"Warning: Failed to restore host to localhost: {e}")
def test_044_config_set_flat_backend_key(self):
"""Flat backend keys (e.g. vllm_args) map to their nested form (issue #1824)."""
try:
# The flat underscore form is what the CLI flags and docs use; it
# must be accepted and stored under the nested "vllm.args" key.
self.assertCommandSucceeds(
["config", "set", "vllm_args=--max-num-seqs 128"]
)
result = self.assertCommandSucceeds(["config"])
output = result.stdout
self.assertIn(
"vllm.args",
output,
f"vllm.args should appear in config output: {output}",
)
self.assertIn(
"--max-num-seqs 128",
output,
f"flat vllm_args value should be stored under vllm.args: {output}",
)
finally:
# Restore the default (empty) value so later tests are unaffected.
run_cli_command(["config", "set", "vllm.args="])
def test_044_config_set_cli(self):
"""Verify that CLI config set parses nested dotted keys and modifies the server config."""
# 1. Set some values using the CLI config set
result = self.assertCommandSucceeds(
[
"config",
"set",
"telemetry.otlp.endpoint=http://127.0.0.1:4444/v1/traces",
"telemetry.otlp.protocol=http/json",
'telemetry.otlp.semantics=["openinference"]',
]
)
print(f"Config set output: {result.stdout}")
# 2. Read the config back to verify it parsed correctly and merged
response = requests.get(
f"http://localhost:{PORT}/internal/config",
headers=_auth_headers(),
timeout=10,
)
self.assertEqual(response.status_code, 200)
telemetry = response.json().get("telemetry", {})
self.assertEqual(
telemetry.get("otlp", {}).get("endpoint"), "http://127.0.0.1:4444/v1/traces"
)
self.assertEqual(telemetry.get("otlp", {}).get("protocol"), "http/json")
self.assertEqual(telemetry.get("otlp", {}).get("semantics"), ["openinference"])
def test_045_config_set_broadcast(self):
"""Verify that CLI config set can modify broadcast setting, and client CLI works with --discovery / --no-discovery."""
try:
# 1. Set broadcast to false using the CLI config set
result = self.assertCommandSucceeds(
[
"--port",
str(PORT),
"config",
"set",
"broadcast=false",
]
)
print(f"Config set broadcast=false output: {result.stdout}")
# Verify it is set to false on the server
response = requests.get(
f"http://localhost:{PORT}/internal/config",
headers=_auth_headers(),
timeout=10,
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json().get("broadcast"), False)
# 2. Set broadcast back to true
result = self.assertCommandSucceeds(
[
"--port",
str(PORT),
"config",
"set",
"broadcast=true",
]
)
response = requests.get(
f"http://localhost:{PORT}/internal/config",
headers=_auth_headers(),
timeout=10,
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json().get("broadcast"), True)
# 3. Test that the client works with --no-discovery and --discovery flags
self.assertCommandSucceeds(
[
"--port",
str(PORT),
"--no-discovery",
"status",
]
)
self.assertCommandSucceeds(
[
"--port",
str(PORT),
"--discovery",
"status",
]
)
finally:
# Restore default
run_cli_command(["--port", str(PORT), "config", "set", "broadcast=true"])
# =============================================================================
# Pull Tests
# =============================================================================
def test_050_pull_with_checkpoint(self):
"""Test pull command with --checkpoint option."""
result = run_cli_pull_command_with_retry(
[
"pull",
USER_MODEL_NAME,
"--checkpoint",
"main",
USER_MODEL_MAIN_CHECKPOINT,
"--recipe",
"llamacpp",
],
timeout=TIMEOUT_MODEL_OPERATION,
)
print(f"Pull with checkpoint exit code: {result.returncode}")
def test_051_pull_with_labels(self):
"""Test pull command with --label option."""
result = run_cli_pull_command_with_retry(
[
"pull",
USER_MODEL_NAME,
"--checkpoint",
"main",
USER_MODEL_MAIN_CHECKPOINT,
"--recipe",
"llamacpp",
"--label",
"reasoning",
"--label",
"coding",
],
timeout=TIMEOUT_MODEL_OPERATION,
)
print(f"Pull with labels exit code: {result.returncode}")
def test_052_pull_invalid_label(self):
"""Test pull command with invalid label should fail validation."""
result = self.assertCommandFails(
[
"pull",
USER_MODEL_NAME,
"--checkpoint",
"main",
USER_MODEL_MAIN_CHECKPOINT,
"--recipe",
"llamacpp",
"--label",
"invalid-label",
],
timeout=TIMEOUT_MODEL_OPERATION,
)
output = result.stdout + result.stderr
self.assertIn(
"run with --help",
output.lower(),
f"Should show validation error for invalid label: {output}",
)
def test_053_pull_with_multiple_checkpoints(self):
"""Test pull command with multiple checkpoints (e.g., main + mmproj)."""
result = run_cli_pull_command_with_retry(
[
"pull",
USER_MODEL_NAME,
"--checkpoint",
"main",
USER_MODEL_MAIN_CHECKPOINT,
"--checkpoint",
"text_encoder",
USER_MODEL_TE_CHECKPOINT,
"--recipe",
"sd-cpp",
],
timeout=TIMEOUT_MODEL_OPERATION,
)
print(f"Pull with multiple checkpoints exit code: {result.returncode}")
def test_054_pull_registered_name(self):
"""Test pull command with a registered model name (no flags)."""
result = run_cli_pull_command_with_retry(
["pull", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_MODEL_OPERATION,
)
self.assertEqual(
result.returncode,
0,
f"Command failed with exit code {result.returncode}: {result.stderr}",
)
output = result.stdout.lower() + result.stderr.lower()
self.assertFalse(
"error" in output and "failed" in output,
f"Pull should not report errors: {result.stdout}",
)
def test_055_pull_components_omni_collection(self):
"""Test pull command with --components flag registers an omni collection."""
collection_name = f"user.CliColl-{uuid.uuid4().hex[:8]}"
# Registered collections list under their canonical `user.` id (matching
# registration/fetch/chat); the bare name is a resolvable alias only.
bare_name = collection_name[5:]
try:
result = run_cli_pull_command_with_retry(
[
"pull",
collection_name,
"--recipe",
"collection.omni",
"--components",
ENDPOINT_TEST_MODEL,
],
timeout=TIMEOUT_MODEL_OPERATION,
)
self.assertEqual(
result.returncode,
0,
f"Command failed with exit code {result.returncode}: {result.stderr}",
)
output = result.stdout.lower() + result.stderr.lower()
self.assertFalse(
"error" in output and "failed" in output,
f"Pull should not report errors: {result.stdout}",
)
# Verify the collection landed in /models with components populated.
response = requests.get(
f"http://localhost:{PORT}/api/v1/models?show_all=true",
headers=_auth_headers(),
timeout=TIMEOUT_DEFAULT,
)
self.assertEqual(response.status_code, 200)
ids = [m["id"] for m in response.json()["data"]]
self.assertIn(
collection_name,
ids,
f"{collection_name} should appear in /models under its user. id",
)
self.assertNotIn(
bare_name,
ids,
"Collection must not also be listed under its bare name",
)
entry = next(
m for m in response.json()["data"] if m["id"] == collection_name
)
self.assertEqual(entry.get("recipe"), "collection.omni")
self.assertEqual(entry.get("components"), [ENDPOINT_TEST_MODEL])
# Both the bare and prefixed ids still resolve on GET /models/{id}.
for lookup in (collection_name, bare_name):
single = requests.get(
f"http://localhost:{PORT}/api/v1/models/{lookup}",
headers=_auth_headers(),
timeout=TIMEOUT_DEFAULT,
)
self.assertEqual(
single.status_code, 200, f"{lookup} should resolve: {single.text}"
)
self.assertEqual(single.json().get("id"), collection_name)
finally:
try:
requests.post(
f"http://localhost:{PORT}/api/v1/delete",
json={"model_name": collection_name},
headers=_auth_headers(),
timeout=TIMEOUT_DEFAULT,
)
except Exception:
pass
def test_056_pull_components_missing_for_omni_recipe(self):
"""`--recipe collection.omni` without --components is rejected by the CLI."""
result = self.assertCommandFails(
[
"pull",
f"user.MissingComps-{uuid.uuid4().hex[:8]}",
"--recipe",
"collection.omni",
],
timeout=TIMEOUT_DEFAULT,
)
output = (result.stdout + result.stderr).lower()
self.assertIn(
"--components",
output,
f"Error should point at the missing --components flag: {output}",
)
# =============================================================================
# Import Tests
# =============================================================================
def test_060_import_json_file(self):
"""Test import command with JSON configuration file."""
json_data = {
"model_name": USER_MODEL_NAME,
"checkpoint": USER_MODEL_MAIN_CHECKPOINT,
"recipe": "llamacpp",
"labels": ["reasoning"],
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json_file = f.name
json.dump(json_data, f)
try:
result = run_cli_command(
["import", json_file],
timeout=TIMEOUT_MODEL_OPERATION,
)
print(f"Import from JSON exit code: {result.returncode}")
finally:
if os.path.exists(json_file):
os.unlink(json_file)
def test_061_import_malformed_json(self):
"""Test import command with malformed JSON file should fail."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json_file = f.name
f.write('{"model_name": "test", "recipe": "llamacpp"')
try:
result = self.assertCommandFails(
["import", json_file],
timeout=TIMEOUT_DEFAULT,
)
output = result.stdout + result.stderr
self.assertIn(
"error",
output.lower(),
f"Should show JSON parse error: {output}",
)
finally:
if os.path.exists(json_file):
os.unlink(json_file)
def test_062_import_missing_model_name(self):
"""Test import command with JSON missing model_name should fail."""
json_data = {
"checkpoint": USER_MODEL_MAIN_CHECKPOINT,
"recipe": "llamacpp",
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json_file = f.name
json.dump(json_data, f)
try:
result = self.assertCommandFails(
["import", json_file],
timeout=TIMEOUT_DEFAULT,
)
output = result.stdout + result.stderr
self.assertIn(
"error",
output.lower(),
f"Should show error about missing model_name: {output}",
)
finally:
if os.path.exists(json_file):
os.unlink(json_file)
def test_063_import_missing_recipe(self):
"""Test import command with JSON missing recipe should fail."""
json_data = {
"model_name": USER_MODEL_NAME,
"checkpoint": USER_MODEL_MAIN_CHECKPOINT,
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json_file = f.name
json.dump(json_data, f)
try:
result = self.assertCommandFails(
["import", json_file],
timeout=TIMEOUT_DEFAULT,
)
output = result.stdout + result.stderr
self.assertIn(
"error",
output.lower(),
f"Should show error about missing recipe: {output}",
)
finally:
if os.path.exists(json_file):
os.unlink(json_file)
def test_064_import_missing_checkpoint(self):
"""Test import command with JSON missing checkpoint should fail."""
json_data = {
"model_name": USER_MODEL_NAME,
"recipe": "llamacpp",
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json_file = f.name
json.dump(json_data, f)
try:
result = self.assertCommandFails(
["import", json_file],
timeout=TIMEOUT_DEFAULT,
)
output = result.stdout + result.stderr
self.assertIn(
"error",
output.lower(),
f"Should show error about missing checkpoint: {output}",
)
finally:
if os.path.exists(json_file):
os.unlink(json_file)
def test_065_import_with_id_alias(self):
"""Test import command with JSON using 'id' as alias for model_name."""
json_data = {
"id": USER_MODEL_NAME,
"checkpoint": USER_MODEL_MAIN_CHECKPOINT,
"recipe": "llamacpp",
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json_file = f.name
json.dump(json_data, f)
try:
result = run_cli_command(
["import", json_file],
timeout=TIMEOUT_MODEL_OPERATION,
)
print(f"Import from JSON with id alias exit code: {result.returncode}")
finally:
if os.path.exists(json_file):
os.unlink(json_file)
def test_066_import_nonexistent_file(self):
"""Test import command with nonexistent file should fail."""
result = self.assertCommandFails(
["import", "nonexistent/path/to/file.json"],
timeout=TIMEOUT_DEFAULT,
)
output = result.stdout + result.stderr
self.assertIn(
"error",
output.lower(),
f"Should show error about nonexistent file: {output}",
)
def test_067_import_remote_noninteractive_requires_directory(self):
"""Remote import should fail in non-interactive mode without --directory."""
result = self.assertCommandFails(
["import", "--skip-prompt"],
timeout=TIMEOUT_DEFAULT,
)
output = result.stdout + result.stderr
self.assertIn(
"--directory",
output.lower(),
f"Should require --directory in non-interactive mode: {output}",
)
def test_068_import_remote_noninteractive_requires_recipe_file(self):
"""Remote import should fail in non-interactive mode without --recipe-file."""
result = self.assertCommandFails(
["import", "--skip-prompt", "--directory", "coding-agents"],
timeout=TIMEOUT_DEFAULT,
)
output = result.stdout + result.stderr
self.assertIn(
"--recipe-file",
output.lower(),
f"Should require --recipe-file in non-interactive mode: {output}",
)
# =============================================================================
# Load Tests
# =============================================================================
def test_070_load_with_ctx_size(self):
"""Test load command with --ctx-size option."""
result = run_cli_command(
["load", ENDPOINT_TEST_MODEL, "--ctx-size", "8192"],
timeout=TIMEOUT_DEFAULT,
)
print(f"Load with ctx-size exit code: {result.returncode}")
def test_071_load_with_save_options(self):
"""Test load command with --save-options flag."""
result = run_cli_command(
["load", ENDPOINT_TEST_MODEL, "--save-options"],
timeout=TIMEOUT_DEFAULT,
)
print(f"Load with save-options exit code: {result.returncode}")
# =============================================================================
# Run Tests
# =============================================================================
def test_100_run_with_model(self):
"""Test run command with explicit model."""
with tempfile.TemporaryDirectory(prefix="lemonade-open-stub-") as temp_dir:
env = self._build_noop_opener_env(temp_dir)
result = run_cli_command(
["run", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
def test_101_run_with_combined_options(self):
"""Test run command with --ctx-size and --save-options together."""
with tempfile.TemporaryDirectory(prefix="lemonade-open-stub-") as temp_dir:
env = self._build_noop_opener_env(temp_dir)
result = run_cli_command(
["run", ENDPOINT_TEST_MODEL, "--ctx-size", "2048", "--save-options"],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
def test_102_run_with_host_port(self):
"""Test run command using global --host/--port options."""
with tempfile.TemporaryDirectory(prefix="lemonade-open-stub-") as temp_dir:
env = self._build_noop_opener_env(temp_dir)
result = run_cli_command(
[
"--host",
"127.0.0.1",
"--port",
str(PORT),
"run",
ENDPOINT_TEST_MODEL,
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
# =============================================================================
# Launch Tests
# =============================================================================
# parser-only tests: run on all OSes
# process-execution tests: run on non-Windows only with shebang-based fake binaries
def test_110_launch_without_agent_prompts_selection(self):
"""Launch without an agent argument should present agent choices and continue."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "claude_capture_agent_prompt.json")
self._write_fake_agent(temp_dir, "claude", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"--model",
ENDPOINT_TEST_MODEL,
],
timeout=TIMEOUT_DEFAULT,
env=env,
input_text="1\n",
)
self.assertEqual(result.returncode, 0)
self.assertTrue(
os.path.exists(capture_path),
"Fake claude binary was not executed",
)
output = result.stdout + result.stderr
self.assertIn("Select an agent to launch", output)
self.assertIn("Selected agent: claude", output)
def test_111_launch_invalid_agent_rejected(self):
"""Launch should reject unsupported agent names."""
result = self.assertCommandFails(
["launch", "invalid-agent", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
)
output = result.stdout + result.stderr
self.assertIn("run with --help", output.lower())
def test_112_launch_claude_with_fake_binary_and_api_key(self):
"""Launch should execute fake claude binary and wire expected auth/model env vars."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "claude_capture.json")
self._write_fake_agent(temp_dir, "claude", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"claude",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
"test-api-key",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
self.assertTrue(
os.path.exists(capture_path),
"Fake claude binary was not executed",
)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
self.assertEqual(payload["env"]["ANTHROPIC_AUTH_TOKEN"], "test-api-key")
self.assertEqual(payload["env"]["LEMONADE_API_KEY"], "test-api-key")
self.assertEqual(
payload["env"]["ANTHROPIC_DEFAULT_SONNET_MODEL"],
ENDPOINT_TEST_MODEL,
)
self.assertEqual(
payload["env"]["CLAUDE_CODE_SUBAGENT_MODEL"],
ENDPOINT_TEST_MODEL,
)
output = result.stdout + result.stderr
self.assertIn(
"Model was provided explicitly; skipping recipe import prompts.",
output,
)
self.assertIn("Launching claude", output)
def test_113_launch_codex_with_fake_binary(self):
"""Launch should execute fake codex binary and pass expected argv/env."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "codex_capture.json")
self._write_fake_agent(temp_dir, "codex", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"codex",
"--model",
ENDPOINT_TEST_MODEL,
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
self.assertTrue(
os.path.exists(capture_path),
"Fake codex binary was not executed",
)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
argv = payload["argv"]
self.assertIn("-c", argv)
self.assertIn("-m", argv)
self.assertIn(ENDPOINT_TEST_MODEL, argv)
self.assertTrue(
any(arg.startswith("model_providers.lemonade=") for arg in argv),
"Expected injected Lemonade model provider config in codex args",
)
self.assertIn('model_provider="lemonade"', argv)
self.assertEqual(payload["env"]["OPENAI_BASE_URL"], "")
# OPENAI_API_KEY mirrors whatever lemonade was running with — the
# default "lemonade" when no key is set, or the LEMONADE_API_KEY
# env value when the test job sets one (e.g. Test API Key CI job).
self.assertEqual(
payload["env"]["OPENAI_API_KEY"],
os.environ.get("LEMONADE_API_KEY", "lemonade"),
)
def test_114_launch_claude_defaults_and_host_normalization(self):
"""Claude launch should default auth token and normalize wildcard host to localhost."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "claude_capture_defaults.json")
self._write_fake_agent(temp_dir, "claude", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"--host",
"0.0.0.0",
"launch",
"claude",
"--model",
ENDPOINT_TEST_MODEL,
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
self.assertTrue(
os.path.exists(capture_path),
"Fake claude binary was not executed",
)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
# Both env vars mirror the lemonade api key in use — default
# "lemonade" when no key is set, or LEMONADE_API_KEY when the
# test job sets one (e.g. Test API Key CI job).
expected_key = os.environ.get("LEMONADE_API_KEY", "lemonade")
self.assertEqual(payload["env"]["ANTHROPIC_AUTH_TOKEN"], expected_key)
self.assertEqual(payload["env"]["LEMONADE_API_KEY"], expected_key)
self.assertEqual(
payload["env"]["ANTHROPIC_BASE_URL"], f"http://localhost:{PORT}"
)
def test_115_launch_claude_windows_prefers_cmd_over_npm_shim(self):
"""On Windows, launch must run claude.cmd, not npm's extensionless shell script."""
if not IS_WINDOWS:
self.skipTest(
"Windows-only: npm shim vs .cmd resolution does not apply on Unix"
)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "claude_cmd_capture.txt")
# Recreate what 'npm install -g' leaves on PATH: a Unix shell
# script named just "claude" next to claude.cmd. Windows cannot
# run the shell script, so the launcher must pick the .cmd.
with open(os.path.join(temp_dir, "claude"), "w", encoding="utf-8") as f:
f.write('#!/bin/sh\nexec node "$(dirname "$0")/claude.js" "$@"\n')
with open(os.path.join(temp_dir, "claude.cmd"), "w", encoding="utf-8") as f:
f.write(f'@echo off\necho fake-agent-ok> "{capture_path}"\nexit /b 0\n')
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
["launch", "claude", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(
result.returncode,
0,
"launch failed; the extensionless npm shim was likely picked "
"instead of claude.cmd (Error 193)",
)
self.assertTrue(
os.path.exists(capture_path),
"claude.cmd was not executed",
)
def test_102c_launch_codex_provider_default(self):
"""Codex launch -p should select default provider without injecting provider config."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(
temp_dir, "codex_capture_user_config_default.json"
)
self._write_fake_agent(temp_dir, "codex", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"codex",
"--model",
ENDPOINT_TEST_MODEL,
"-p",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
argv = payload["argv"]
self.assertIn('model_provider="lemonade"', argv)
self.assertFalse(
any(arg.startswith("model_providers.lemonade=") for arg in argv)
)
def test_102d_launch_codex_provider_custom(self):
"""Codex launch --provider PROVIDER should target custom provider name."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(
temp_dir, "codex_capture_user_config_custom.json"
)
self._write_fake_agent(temp_dir, "codex", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"codex",
"--model",
ENDPOINT_TEST_MODEL,
"--provider",
"custom-provider",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
argv = payload["argv"]
self.assertIn('model_provider="custom-provider"', argv)
self.assertFalse(
any(arg.startswith("model_providers.custom-provider=") for arg in argv)
)
def test_102e_launch_codex_provider_without_config_check(self):
"""Codex --provider should not read/validate config.toml in launcher."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(
temp_dir, "codex_capture_provider_no_config_check.json"
)
self._write_fake_agent(temp_dir, "codex", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"codex",
"--model",
ENDPOINT_TEST_MODEL,
"--provider",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
argv = payload["argv"]
self.assertIn('model_provider="lemonade"', argv)
self.assertFalse(
any(arg.startswith("model_providers.lemonade=") for arg in argv)
)
def test_102f_launch_codex_provider_custom_without_config_check(self):
"""Codex --provider custom name should not be launcher-validated against config.toml."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(
temp_dir, "codex_capture_provider_custom_no_config_check.json"
)
self._write_fake_agent(temp_dir, "codex", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"codex",
"--model",
ENDPOINT_TEST_MODEL,
"--provider",
"missing-in-config",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
argv = payload["argv"]
self.assertIn('model_provider="missing-in-config"', argv)
self.assertFalse(
any(
arg.startswith("model_providers.missing-in-config=") for arg in argv
)
)
def test_102g_launch_claude_provider_rejected(self):
"""--provider should be rejected for non-codex agents."""
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
env = self._build_missing_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"claude",
"--model",
ENDPOINT_TEST_MODEL,
"--provider",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertNotEqual(result.returncode, 0)
output = result.stdout + result.stderr
self.assertIn(
"Error: --provider is only supported for 'lemonade launch codex'.",
output,
)
def test_102h_launch_agent_args_passthrough(self):
"""--agent-args should be tokenized and appended to agent argv."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "claude_capture_agent_args.json")
self._write_fake_agent(temp_dir, "claude", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"claude",
"--model",
ENDPOINT_TEST_MODEL,
"--agent-args",
"--approval-mode never --custom 'a b'",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
argv = payload["argv"]
self.assertIn("--approval-mode", argv)
self.assertIn("never", argv)
self.assertIn("--custom", argv)
self.assertIn("a b", argv)
def test_103_launch_explicit_model_with_repo_flags_is_deterministic(self):
"""Explicit model should skip import flow even when repo flags are present."""
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
env = self._build_missing_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"claude",
"--model",
ENDPOINT_TEST_MODEL,
"--directory",
"coding-agents",
"--recipe-file",
"dummy.json",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertNotEqual(result.returncode, 0)
output = result.stdout + result.stderr
self.assertIn(
"Model was provided explicitly; skipping recipe import prompts.",
output,
)
self.assertIn("Agent binary not found", output)
def test_116_launch_missing_binary_fails_fast(self):
"""Without a stub and no real claude installed, launch should fail at binary lookup."""
if shutil.which("claude") is not None:
self.skipTest(
"Real claude binary installed; missing-binary behavior not deterministic"
)
result = run_cli_command(
["launch", "claude", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
)
self.assertNotEqual(result.returncode, 0)
output = result.stdout + result.stderr
self.assertIn("Agent binary not found", output)
def test_116a_launch_missing_codex_command_quotes_arguments(self):
"""A missing Codex prints a command that preserves config and user argv."""
if not IS_WINDOWS and os.access("/usr/local/bin/codex", os.X_OK):
self.skipTest("Codex installed in a non-isolatable fixed fallback path")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
env = self._build_missing_agent_env(temp_dir)
env.pop("LEMONADE_ADMIN_API_KEY", None)
env.pop("LEMONADE_API_KEY", None)
result = run_cli_command(
[
"launch",
"codex",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
"shellTest-synthetic-key-a",
"--agent-args",
"--custom 'a b'",
],
timeout=TIMEOUT_DEFAULT,
env=env,
inject_runner_key=False,
cwd=temp_dir,
)
self.assertNotEqual(result.returncode, 0)
output = result.stdout + result.stderr
self.assertIn("Agent binary not found", output)
self.assertIn("Environment variables:", output)
self.assertNotIn("Loading model in background", output)
command = output.split("Command:\n", 1)[1].splitlines()[0].strip()
if IS_WINDOWS:
self.assertIn("Manual launch (PowerShell):", output)
self.assertTrue(command.startswith("& 'codex.cmd' "))
self.assertIn("'a b'", command)
self.assertIn("''Lemonade''", command)
self.assertIn("'-c'", command)
self.assertIn("'-m'", command)
self.assertIn("'--custom' 'a b'", command)
else:
self.assertIn("Manual launch (POSIX shell):", output)
argv = shlex.split(command)
self.assertEqual(argv[0], "codex")
self.assertIn("a b", argv)
self.assertIn('model_provider="lemonade"', argv)
self.assertIn(ENDPOINT_TEST_MODEL, argv)
pairs = list(zip(argv, argv[1:]))
self.assertIn(("-c", 'model_provider="lemonade"'), pairs)
self.assertIn(("-m", ENDPOINT_TEST_MODEL), pairs)
self.assertIn(("--custom", "a b"), pairs)
self.assertTrue(
any(a.startswith("model_providers.lemonade={ ") for a in argv)
)
def test_116b_launch_missing_agent_does_not_print_api_key(self):
"""Manual launch must redact a key in exports and custom agent arguments."""
if not IS_WINDOWS and os.access("/usr/local/bin/claude", os.X_OK):
self.skipTest("Claude installed in a non-isolatable fixed fallback path")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
env = self._build_missing_agent_env(temp_dir)
env.pop("LEMONADE_ADMIN_API_KEY", None)
env.pop("LEMONADE_API_KEY", None)
secret = "shellTest-synthetic-key-b"
result = run_cli_command(
[
"launch",
"claude",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
secret,
"--agent-args",
"--token=x" + secret + "y",
],
timeout=TIMEOUT_DEFAULT,
env=env,
inject_runner_key=False,
cwd=temp_dir,
)
self.assertNotEqual(result.returncode, 0)
output = result.stdout + result.stderr
self.assertIn("Agent binary not found", output)
self.assertNotIn(secret, output)
self.assertIn("Set LEMONADE_API_KEY securely", output)
command = output.split("Command:\n", 1)[1].splitlines()[0].strip()
if IS_WINDOWS:
self.assertIn(
"$env:ANTHROPIC_AUTH_TOKEN = $env:LEMONADE_API_KEY", output
)
self.assertIn("'--token=x' + $env:LEMONADE_API_KEY + 'y'", command)
else:
self.assertIn(
'export ANTHROPIC_AUTH_TOKEN="${LEMONADE_API_KEY}"', output
)
self.assertIn("export LEMONADE_API_KEY\n", output)
self.assertIn("'--token=x'\"${LEMONADE_API_KEY}\"'y'", command)
def test_116c_launch_missing_pi_does_not_bypass_config_sync(self):
"""A missing Pi must not print a key-bearing command before guarded sync."""
if not IS_WINDOWS and os.access("/usr/local/bin/pi", os.X_OK):
self.skipTest("Pi installed in a non-isolatable fixed fallback path")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
env = self._build_missing_agent_env(temp_dir)
env.pop("LEMONADE_ADMIN_API_KEY", None)
env.pop("LEMONADE_API_KEY", None)
secret = "shellTest-synthetic-key-c"
result = run_cli_command(
[
"launch",
"pi",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
secret,
],
timeout=TIMEOUT_DEFAULT,
env=env,
inject_runner_key=False,
cwd=temp_dir,
)
self.assertNotEqual(result.returncode, 0)
output = result.stdout + result.stderr
self.assertIn("Agent binary not found", output)
self.assertIn("rerun your original", output)
self.assertNotIn("Command:", output)
self.assertNotIn(secret, output)
def test_116e_launch_missing_opencode_sync_failure_has_no_manual_command(self):
"""A stale provider must not be used when config sync failed."""
if not IS_WINDOWS and os.access("/usr/local/bin/opencode", os.X_OK):
self.skipTest("OpenCode installed in a fixed fallback path")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
env = self._build_missing_agent_env(temp_dir)
env.pop("LEMONADE_ADMIN_API_KEY", None)
env.pop("LEMONADE_API_KEY", None)
config_path = os.path.join(temp_dir, ".config", "opencode", "opencode.json")
os.makedirs(os.path.dirname(config_path), exist_ok=True)
with open(config_path, "w", encoding="utf-8") as file:
file.write("{ invalid json")
result = run_cli_command(
[
"launch",
"opencode",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
"shellTest-synthetic-key-e",
],
timeout=TIMEOUT_DEFAULT,
env=env,
inject_runner_key=False,
cwd=temp_dir,
)
self.assertNotEqual(result.returncode, 0)
output = result.stdout + result.stderr
self.assertIn("Failed to sync opencode config", output)
self.assertIn("Agent binary not found", output)
self.assertIn("Agent provider config could not be updated", output)
self.assertNotIn("Command:", output)
def test_116f_launch_missing_claude_admin_key_precedence(self):
"""Manual recovery uses the same admin-key precedence as normal launch."""
if not IS_WINDOWS and os.access("/usr/local/bin/claude", os.X_OK):
self.skipTest("Claude installed in a non-isolatable fixed fallback path")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
env = self._build_missing_agent_env(temp_dir)
regular_key = "shellTest-regular-key-f"
admin_key = "shellTest-admin-key-f"
env["LEMONADE_API_KEY"] = regular_key
env["LEMONADE_ADMIN_API_KEY"] = admin_key
result = run_cli_command(
["launch", "claude", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
inject_runner_key=False,
cwd=temp_dir,
)
self.assertNotEqual(result.returncode, 0)
output = result.stdout + result.stderr
self.assertIn("Agent binary not found", output)
self.assertNotIn(admin_key, output)
self.assertNotIn(regular_key, output)
self.assertIn("Set LEMONADE_ADMIN_API_KEY", output)
if IS_WINDOWS:
self.assertIn(
"$env:ANTHROPIC_AUTH_TOKEN = $env:LEMONADE_ADMIN_API_KEY", output
)
self.assertIn(
"$env:LEMONADE_API_KEY = $env:LEMONADE_ADMIN_API_KEY", output
)
else:
self.assertIn(
'export ANTHROPIC_AUTH_TOKEN="${LEMONADE_ADMIN_API_KEY}"',
output,
)
self.assertIn(
'export LEMONADE_API_KEY="${LEMONADE_ADMIN_API_KEY}"',
output,
)
def test_117_launch_opencode_with_fake_binary(self):
"""Launch should execute fake opencode binary with -m Lemonade/MODEL."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "opencode_capture.json")
self._write_fake_agent(temp_dir, "opencode", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
["launch", "opencode", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
self.assertTrue(
os.path.exists(capture_path),
"Fake opencode binary was not executed",
)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
argv = payload["argv"]
self.assertIn("-m", argv)
model_idx = argv.index("-m") + 1
self.assertEqual(argv[model_idx], f"Lemonade/{ENDPOINT_TEST_MODEL}")
def test_118_launch_opencode_creates_config(self):
"""Launch opencode should create opencode.json with Lemonade provider."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "opencode_capture_cfg.json")
self._write_fake_agent(temp_dir, "opencode", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
["launch", "opencode", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
config_path = os.path.join(temp_dir, ".config", "opencode", "opencode.json")
self.assertTrue(
os.path.exists(config_path),
f"opencode.json not created at {config_path}",
)
with open(config_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
self.assertIn("provider", cfg)
self.assertIn("Lemonade", cfg["provider"])
lemonade = cfg["provider"]["Lemonade"]
self.assertEqual(lemonade["npm"], "@ai-sdk/openai-compatible")
self.assertIn("baseURL", lemonade["options"])
# Mirrors lemonade api key in use; LEMONADE_API_KEY env wins.
self.assertEqual(
lemonade["options"]["apiKey"],
os.environ.get("LEMONADE_API_KEY", "lemonade"),
)
self.assertIn(ENDPOINT_TEST_MODEL, lemonade["models"])
self.assertEqual(
lemonade["models"][ENDPOINT_TEST_MODEL]["limit"]["context"],
ENDPOINT_TEST_MODEL_CTX_SIZE,
)
self.assertEqual(
lemonade["models"][ENDPOINT_TEST_MODEL]["limit"]["output"],
int(ENDPOINT_TEST_MODEL_CTX_SIZE / 3),
)
def test_119_launch_opencode_refreshes_model_entries(self):
"""Launch opencode should refresh Lemonade models and remove stale entries."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "opencode_capture_merge.json")
self._write_fake_agent(temp_dir, "opencode", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
config_dir = os.path.join(temp_dir, ".config", "opencode")
os.makedirs(config_dir)
config_path = os.path.join(config_dir, "opencode.json")
existing = {
"$schema": "https://opencode.ai/config.json",
"provider": {
"anthropic": {
"models": {"claude-3.5-sonnet": {}},
},
"Lemonade": {
"npm": "@ai-sdk/openai-compatible",
"name": "Lemonade Server (local)",
"options": {"baseURL": "http://old:9999/v1"},
"models": {
"User-Custom-Model": {
"name": "My Model",
"contextWindow": 8192,
}
},
},
},
}
with open(config_path, "w", encoding="utf-8") as f:
json.dump(existing, f)
result = run_cli_command(
["launch", "opencode", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
with open(config_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
self.assertIn("anthropic", cfg["provider"])
self.assertIn("claude-3.5-sonnet", cfg["provider"]["anthropic"]["models"])
self.assertNotIn("User-Custom-Model", cfg["provider"]["Lemonade"]["models"])
self.assertIn(ENDPOINT_TEST_MODEL, cfg["provider"]["Lemonade"]["models"])
self.assertNotEqual(
cfg["provider"]["Lemonade"]["options"]["baseURL"],
"http://old:9999/v1",
)
def test_120_launch_opencode_with_api_key_sets_config(self):
"""When --api-key is provided, opencode.json should contain the same apiKey."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "opencode_capture_key.json")
self._write_fake_agent(temp_dir, "opencode", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"opencode",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
"real-secret-key",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
config_path = os.path.join(temp_dir, ".config", "opencode", "opencode.json")
with open(config_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
self.assertEqual(
cfg["provider"]["Lemonade"]["options"].get("apiKey"),
"real-secret-key",
)
def test_121_launch_opencode_backfills_schema_on_existing_config(self):
"""Launch opencode should add $schema when syncing an existing config missing it."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "opencode_capture_schema.json")
self._write_fake_agent(temp_dir, "opencode", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
config_dir = os.path.join(temp_dir, ".config", "opencode")
os.makedirs(config_dir)
config_path = os.path.join(config_dir, "opencode.json")
existing = {
"provider": {
"Lemonade": {
"npm": "@ai-sdk/openai-compatible",
"name": "Lemonade Server (local)",
"options": {"baseURL": "http://old:9999/v1"},
"models": {},
}
}
}
with open(config_path, "w", encoding="utf-8") as f:
json.dump(existing, f)
result = run_cli_command(
["launch", "opencode", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
with open(config_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
self.assertEqual(cfg.get("$schema"), "https://opencode.ai/config.json")
def test_122_launch_junie_with_fake_binary(self):
"""Launch should execute fake junie binary with --model custom:lemonade."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "junie_capture.json")
self._write_fake_agent(temp_dir, "junie", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
["launch", "junie", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
self.assertTrue(
os.path.exists(capture_path),
"Fake junie binary was not executed",
)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
argv = payload["argv"]
self.assertIn("--model", argv)
model_idx = argv.index("--model") + 1
self.assertEqual(argv[model_idx], "custom:lemonade")
def test_123_launch_junie_creates_model_profile(self):
"""Launch junie should create ~/.junie/models/lemonade.json for the local server."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "junie_capture_cfg.json")
self._write_fake_agent(temp_dir, "junie", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
["launch", "junie", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
profile_path = os.path.join(temp_dir, ".junie", "models", "lemonade.json")
self.assertTrue(
os.path.exists(profile_path),
f"lemonade.json not created at {profile_path}",
)
with open(profile_path, "r", encoding="utf-8") as f:
profile = json.load(f)
self.assertEqual(profile["id"], ENDPOINT_TEST_MODEL)
self.assertEqual(profile["apiType"], "OpenAICompletion")
self.assertEqual(profile["providerName"], "Lemonade")
# Junie appends nothing to baseUrl, so it must be the full endpoint.
self.assertTrue(profile["baseUrl"].endswith("/v1/chat/completions"))
self.assertGreater(profile["maxContextLength"], 0)
self.assertEqual(
profile.get("apiKey"),
os.environ.get("LEMONADE_API_KEY", "lemonade"),
)
def test_124_launch_junie_with_api_key_sets_profile(self):
"""When --api-key is provided, lemonade.json should contain the same apiKey."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "junie_capture_key.json")
self._write_fake_agent(temp_dir, "junie", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
[
"launch",
"junie",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
"real-secret-key",
],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
profile_path = os.path.join(temp_dir, ".junie", "models", "lemonade.json")
with open(profile_path, "r", encoding="utf-8") as f:
profile = json.load(f)
self.assertEqual(profile.get("apiKey"), "real-secret-key")
def test_125_launch_junie_honors_junie_home(self):
"""JUNIE_HOME should redirect the profile away from ~/.junie."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "junie_capture_home.json")
self._write_fake_agent(temp_dir, "junie", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
junie_home = os.path.join(temp_dir, "custom-junie-home")
env["JUNIE_HOME"] = junie_home
result = run_cli_command(
["launch", "junie", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
profile_path = os.path.join(junie_home, "models", "lemonade.json")
self.assertTrue(
os.path.exists(profile_path),
f"lemonade.json not created at {profile_path}",
)
self.assertFalse(
os.path.exists(os.path.join(temp_dir, ".junie")),
"JUNIE_HOME was set, so ~/.junie must not be created",
)
with open(profile_path, "r", encoding="utf-8") as f:
profile = json.load(f)
self.assertEqual(profile["id"], ENDPOINT_TEST_MODEL)
def test_126_launch_junie_leaves_other_profiles_alone(self):
"""Launch should replace lemonade.json only, keeping user-authored profiles."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "junie_capture_keep.json")
self._write_fake_agent(temp_dir, "junie", capture_path)
env = self._build_stubbed_agent_env(temp_dir)
models_dir = os.path.join(temp_dir, ".junie", "models")
os.makedirs(models_dir)
own_profile = {"id": "my-model", "baseUrl": "http://example.invalid"}
own_profile_path = os.path.join(models_dir, "my-model.json")
with open(own_profile_path, "w", encoding="utf-8") as f:
json.dump(own_profile, f)
with open(
os.path.join(models_dir, "lemonade.json"), "w", encoding="utf-8"
) as f:
json.dump({"id": "stale-model"}, f)
result = run_cli_command(
["launch", "junie", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(result.returncode, 0)
with open(own_profile_path, "r", encoding="utf-8") as f:
self.assertEqual(json.load(f), own_profile)
with open(
os.path.join(models_dir, "lemonade.json"), "r", encoding="utf-8"
) as f:
self.assertEqual(json.load(f)["id"], ENDPOINT_TEST_MODEL)
self.assertEqual(
sorted(os.listdir(models_dir)),
["lemonade.json", "my-model.json"],
)
def test_127_launch_junie_windows_uses_bat_shim(self):
"""On Windows, launch must run the junie.bat shim the installer writes."""
if not IS_WINDOWS:
self.skipTest("Windows-only: the .bat shim does not apply on Unix")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "junie_bat_capture.txt")
with open(os.path.join(temp_dir, "junie.bat"), "w", encoding="utf-8") as f:
f.write(f'@echo off\necho fake-agent-ok> "{capture_path}"\nexit /b 0\n')
env = self._build_stubbed_agent_env(temp_dir)
result = run_cli_command(
["launch", "junie", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=env,
)
self.assertEqual(
result.returncode,
0,
"launch failed; junie.bat was likely not considered during "
"binary lookup",
)
self.assertTrue(
os.path.exists(capture_path),
"junie.bat was not executed",
)
def _launch_pi(
self, temp_dir, extra_args=None, model=ENDPOINT_TEST_MODEL, version=None
):
"""Launch a fake pi from temp_dir and return its captured argv/env payload and stderr."""
capture_path = os.path.join(temp_dir, "pi_capture.json")
self._write_fake_agent(temp_dir, "pi", capture_path, version)
result = run_cli_command(
["launch", "pi", "--model", model] + (extra_args or []),
timeout=TIMEOUT_DEFAULT,
env=self._build_stubbed_agent_env(temp_dir),
)
self.assertEqual(result.returncode, 0, result.stderr)
with open(capture_path, "r", encoding="utf-8") as f:
payload = json.load(f)
payload["stdout"] = result.stdout
payload["stderr"] = result.stderr
return payload
def _pi_model_entry(self, temp_dir, model):
provider = self._read_pi_agent_json(temp_dir, "models.json")["providers"][
"Lemonade"
]
return next(m for m in provider["models"] if m["id"] == model)
def _register_unloadable_model(self, model_name, **labels):
# Registration is persisted before the download, so a checkpoint that
# does not exist leaves a registered model that never downloads or loads.
requests.post(
f"http://localhost:{PORT}/api/v1/pull",
json={
"model_name": f"user.{model_name}",
"checkpoint": "lemonade-sdk/pi-launch-label-probe-missing-GGUF:probe.gguf",
"recipe": "llamacpp",
"stream": False,
**labels,
},
headers=_auth_headers(),
timeout=TIMEOUT_MODEL_OPERATION,
)
def _save_ctx_size(self, ctx_size):
response = requests.post(
f"http://localhost:{PORT}/api/v1/models/{ENDPOINT_TEST_MODEL}/options",
json={"ctx_size": ctx_size},
headers=_auth_headers(),
timeout=TIMEOUT_DEFAULT,
)
self.assertEqual(response.status_code, 200, response.text)
def _saved_ctx_size(self):
return (
requests.get(
f"http://localhost:{PORT}/api/v1/models/{ENDPOINT_TEST_MODEL}/options",
headers=_auth_headers(),
timeout=TIMEOUT_DEFAULT,
)
.json()["saved"]
.get("ctx_size")
)
@staticmethod
def _read_pi_agent_json(temp_dir, name, default=None):
path = os.path.join(temp_dir, ".pi", "agent", name)
if default is not None and not os.path.exists(path):
return default
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def test_128_launch_pi_configures_and_starts_pi(self):
"""Launch pi should pass the model and flags to pi and write the model's window."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
payload = self._launch_pi(temp_dir, ["--codemode"])
argv = payload["argv"]
self.assertEqual(argv[argv.index("--provider") + 1], "Lemonade")
self.assertEqual(argv[argv.index("--model") + 1], ENDPOINT_TEST_MODEL)
self.assertEqual(argv[argv.index("--tools") + 1], "+codemode")
provider = self._read_pi_agent_json(temp_dir, "models.json")["providers"][
"Lemonade"
]
model = next(
m for m in provider["models"] if m["id"] == ENDPOINT_TEST_MODEL
)
self.assertEqual(model["contextWindow"], ENDPOINT_TEST_MODEL_CTX_SIZE)
settings = self._read_pi_agent_json(temp_dir, "settings.json")
self.assertEqual(settings["defaultProvider"], "Lemonade")
self.assertEqual(settings["defaultModel"], ENDPOINT_TEST_MODEL)
def test_129_launch_pi_keeps_api_key_off_disk(self):
"""With an API key, pi gets it from the environment, not from models.json."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
if os.environ.get("LEMONADE_ADMIN_API_KEY"):
self.skipTest("LEMONADE_ADMIN_API_KEY overrides --api-key")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
payload = self._launch_pi(temp_dir, ["--api-key", "real-secret-key"])
self.assertEqual(payload["env"]["LEMONADE_API_KEY"], "real-secret-key")
provider = self._read_pi_agent_json(temp_dir, "models.json")["providers"][
"Lemonade"
]
self.assertEqual(provider["apiKey"], "${LEMONADE_API_KEY}")
def test_130_launch_pi_mcp_flags(self):
"""--mcp adds the lemonade MCP server, later launches keep it, --no-mcp removes it."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
def mcp_servers(temp_dir):
return self._read_pi_agent_json(temp_dir, "mcp.json", {}).get(
"mcpServers", {}
)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
self._launch_pi(temp_dir)
self.assertNotIn("lemonade", mcp_servers(temp_dir))
self._launch_pi(temp_dir, ["--mcp"])
self.assertIn("lemonade", mcp_servers(temp_dir))
self._launch_pi(temp_dir)
self.assertIn("lemonade", mcp_servers(temp_dir))
self._launch_pi(temp_dir, ["--no-mcp"])
self.assertNotIn("lemonade", mcp_servers(temp_dir))
def test_131_launch_pi_uses_launch_ctx_size(self):
"""--ctx-size on launch is the window the model runs with, so pi gets it too."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
payload = self._launch_pi(temp_dir, ["--ctx-size", "4096"])
self.assertIn("Loading model in background", payload["stdout"])
model = self._pi_model_entry(temp_dir, ENDPOINT_TEST_MODEL)
self.assertEqual(model["contextWindow"], 4096)
self.assertEqual(model["maxTokens"], 4096)
def test_132_launch_pi_auto_ctx_size_waits_for_the_load(self):
"""An auto ctx_size is only known after the load, so pi gets the loaded window."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
model_url = f"http://localhost:{PORT}/api/v1/models/{ENDPOINT_TEST_MODEL}"
saved = self._saved_ctx_size()
self._save_ctx_size(-1)
try:
run_cli_command(["unload", ENDPOINT_TEST_MODEL], timeout=TIMEOUT_DEFAULT)
with tempfile.TemporaryDirectory(
prefix="lemonade-launch-stub-"
) as temp_dir:
payload = self._launch_pi(temp_dir)
# The model is already loaded, so no second load is sent.
self.assertNotIn("Loading model in background", payload["stdout"])
model = self._pi_model_entry(temp_dir, ENDPOINT_TEST_MODEL)
loaded_ctx = requests.get(
model_url, headers=_auth_headers(), timeout=TIMEOUT_DEFAULT
).json()["context_length"]
self.assertNotEqual(loaded_ctx, 40960)
self.assertEqual(model.get("contextWindow"), loaded_ctx)
self.assertEqual(model.get("maxTokens"), loaded_ctx)
finally:
self._save_ctx_size(saved)
def test_133_launch_pi_not_downloaded_model_keeps_labels(self):
"""A model that is not downloaded yet still gets its labels' image and tool settings."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
model_name = "PiLaunchLabelProbe-GGUF"
try:
self._register_unloadable_model(model_name, reasoning=True, vision=True)
info = requests.get(
f"http://localhost:{PORT}/api/v1/models/{model_name}",
headers=_auth_headers(),
timeout=TIMEOUT_DEFAULT,
).json()
self.assertFalse(info["downloaded"])
self.assertIn("vision", info["labels"])
self.assertIn("reasoning", info["labels"])
self.assertNotIn("tool-calling", info["labels"])
with tempfile.TemporaryDirectory(
prefix="lemonade-launch-stub-"
) as temp_dir:
# A known window skips the load for it, which would fail.
payload = self._launch_pi(
temp_dir, ["--ctx-size", "4096"], model=model_name
)
model = self._pi_model_entry(temp_dir, model_name)
self.assertEqual(model["input"], ["text", "image"])
self.assertNotIn("reasoning", model)
self.assertIn(
f"{model_name} is not labeled tool-calling", payload["stderr"]
)
finally:
run_cli_command(["delete", f"user.{model_name}"], timeout=TIMEOUT_DEFAULT)
def test_134_launch_pi_warns_on_unknown_model(self):
"""A model name the server does not know gets a warning instead of the tool-calling one."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
model_name = "PiLaunchUnknownProbe-GGUF"
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
payload = self._launch_pi(temp_dir, model=model_name)
self.assertIn(
f"{model_name} is not a model on the Lemonade server", payload["stderr"]
)
self.assertNotIn("is not labeled tool-calling", payload["stderr"])
def test_135_launch_pi_no_mcp_stops_when_removal_fails(self):
"""--no-mcp does not start pi when the lemonade MCP server cannot be removed."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
if os.geteuid() == 0:
self.skipTest("root ignores the read-only directory this test relies on")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
agent_dir = os.path.join(temp_dir, ".pi", "agent")
os.makedirs(agent_dir)
with open(os.path.join(agent_dir, "mcp.json"), "w", encoding="utf-8") as f:
json.dump({"mcpServers": {"lemonade": {"url": "http://x:1/mcp"}}}, f)
capture_path = os.path.join(temp_dir, "pi_capture.json")
self._write_fake_agent(temp_dir, "pi", capture_path)
os.chmod(agent_dir, 0o555)
try:
result = run_cli_command(
["launch", "pi", "--model", ENDPOINT_TEST_MODEL, "--no-mcp"],
timeout=TIMEOUT_DEFAULT,
env=self._build_stubbed_agent_env(temp_dir),
)
finally:
os.chmod(agent_dir, 0o755)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Failed to remove Lemonade MCP from pi", result.stderr)
self.assertFalse(os.path.exists(capture_path), "pi was started")
def test_136_launch_pi_with_key_stops_when_config_cannot_be_updated(self):
"""With an API key, pi is not started against config still pointing at another server."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
if os.geteuid() == 0:
self.skipTest("root ignores the read-only directory this test relies on")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
agent_dir = os.path.join(temp_dir, ".pi", "agent")
os.makedirs(agent_dir)
with open(os.path.join(agent_dir, "mcp.json"), "w", encoding="utf-8") as f:
json.dump(
{
"mcpServers": {
"lemonade": {
"url": "http://server-a.invalid:1/mcp",
"headers": {
"Authorization": "Bearer ${LEMONADE_API_KEY}"
},
}
}
},
f,
)
capture_path = os.path.join(temp_dir, "pi_capture.json")
self._write_fake_agent(temp_dir, "pi", capture_path)
os.chmod(agent_dir, 0o555)
try:
result = run_cli_command(
[
"launch",
"pi",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
"key-for-this-server",
],
timeout=TIMEOUT_DEFAULT,
env=self._build_stubbed_agent_env(temp_dir),
)
finally:
os.chmod(agent_dir, 0o755)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(os.path.exists(capture_path), "pi was started")
def test_137_launch_pi_with_key_stops_when_mcp_json_is_unreadable(self):
"""With an API key, pi is not started when launch cannot read pi's mcp.json."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
agent_dir = os.path.join(temp_dir, ".pi", "agent")
os.makedirs(agent_dir)
# Pi reads this file (Node replaces the invalid byte), so a stale
# entry in it would get this server's key.
with open(os.path.join(agent_dir, "mcp.json"), "wb") as f:
f.write(
b'{"mcpServers": {"lemonade": {"url": "http://server-a.invalid:1/mcp",'
b' "description": "caf\xe9",'
b' "headers": {"Authorization": "Bearer ${LEMONADE_API_KEY}"}}}}'
)
capture_path = os.path.join(temp_dir, "pi_capture.json")
self._write_fake_agent(temp_dir, "pi", capture_path)
result = run_cli_command(
[
"launch",
"pi",
"--model",
ENDPOINT_TEST_MODEL,
"--api-key",
"key-for-this-server",
],
timeout=TIMEOUT_DEFAULT,
env=self._build_stubbed_agent_env(temp_dir),
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("mcp.json", result.stderr)
self.assertFalse(os.path.exists(capture_path), "pi was started")
def test_138_launch_pi_missing_binary_does_not_load_the_model(self):
"""Launch checks that pi is installed before loading a model for its window."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
saved = self._saved_ctx_size()
self._save_ctx_size(-1)
try:
run_cli_command(["unload", ENDPOINT_TEST_MODEL], timeout=TIMEOUT_DEFAULT)
with tempfile.TemporaryDirectory(
prefix="lemonade-launch-stub-"
) as temp_dir:
result = run_cli_command(
["launch", "pi", "--model", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
env=self._build_missing_agent_env(temp_dir),
)
self.assertNotEqual(result.returncode, 0)
health = requests.get(
f"http://localhost:{PORT}/api/v1/health",
headers=_auth_headers(),
timeout=TIMEOUT_DEFAULT,
).json()
loaded = [m.get("model_name") for m in health.get("all_models_loaded", [])]
self.assertNotIn(ENDPOINT_TEST_MODEL, loaded)
finally:
self._save_ctx_size(saved)
def test_139_launch_pi_stops_when_the_model_fails_to_load(self):
"""Launch waits on the load for pi's window, so a failed load stops it."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
model_name = "PiLaunchLoadFailProbe-GGUF"
try:
self._register_unloadable_model(model_name)
with tempfile.TemporaryDirectory(
prefix="lemonade-launch-stub-"
) as temp_dir:
capture_path = os.path.join(temp_dir, "pi_capture.json")
self._write_fake_agent(temp_dir, "pi", capture_path)
result = run_cli_command(
["launch", "pi", "--model", model_name],
timeout=TIMEOUT_DEFAULT,
env=self._build_stubbed_agent_env(temp_dir),
)
self.assertNotEqual(result.returncode, 0)
self.assertIn(f"Failed to load {model_name}", result.stderr)
self.assertFalse(os.path.exists(capture_path), "pi was started")
finally:
run_cli_command(["delete", f"user.{model_name}"], timeout=TIMEOUT_DEFAULT)
def test_140_launch_pi_codemode_needs_pi_1_1(self):
"""--codemode on a pi older than 1.1 stops launch instead of breaking pi's tools."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
capture_path = os.path.join(temp_dir, "pi_capture.json")
self._write_fake_agent(temp_dir, "pi", capture_path, "1.0.4")
result = run_cli_command(
["launch", "pi", "--model", ENDPOINT_TEST_MODEL, "--codemode"],
timeout=TIMEOUT_DEFAULT,
env=self._build_stubbed_agent_env(temp_dir),
)
self.assertNotEqual(result.returncode, 0)
self.assertIn(
"--codemode needs pi 1.1 or newer (found 1.0.4)", result.stderr
)
self.assertFalse(os.path.exists(capture_path), "pi was started")
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
payload = self._launch_pi(temp_dir, ["--codemode"], version="1.1.0")
self.assertIn("+codemode", payload["argv"])
self.assertNotIn("needs pi", payload["stderr"])
def test_141_launch_pi_mcp_warns_on_pi_before_1_0(self):
"""--mcp on a pi older than 1.0 warns, since that pi ignores mcp.json."""
if IS_WINDOWS:
self.skipTest(WINDOWS_LAUNCH_STUB_SKIP_REASON)
with tempfile.TemporaryDirectory(prefix="lemonade-launch-stub-") as temp_dir:
payload = self._launch_pi(temp_dir, ["--mcp"], version="0.99.2")
self.assertIn(
"--mcp needs pi 1.0 or newer (found 0.99.2)", payload["stderr"]
)
# =============================================================================
# Unload Tests
# =============================================================================
def test_080_unload_with_model(self):
"""Test unload command with model name."""
result = run_cli_command(
["unload", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
)
print(f"Unload with model exit code: {result.returncode}")
def test_081_unload_without_model(self):
"""Test unload command without model name (unloads all)."""
result = run_cli_command(
["unload"],
timeout=TIMEOUT_DEFAULT,
)
print(f"Unload without model exit code: {result.returncode}")
# =============================================================================
# Delete Tests
# =============================================================================
def test_090_delete_model(self):
"""Test delete command with model name."""
result = run_cli_command(
["delete", ENDPOINT_TEST_MODEL],
timeout=TIMEOUT_DEFAULT,
)
print(f"Delete model exit code: {result.returncode}")
def test_090a_naming_spec_list_shows_canonical_shadowed_rows(self):
"""`list` prints API ids verbatim, so shadowed sources appear under their canonical IDs.
Verifies the copy-paste-safe contract: when a user.* shadows a built-in,
the list shows both `<bare>` (winner) and `builtin.<bare>` (shadowed),
and either string is directly usable in `lemonade load`/`delete`.
"""
bare = ENDPOINT_TEST_MODEL # known built-in
user_canonical = f"user.{bare}"
try:
pull_response = requests.post(
f"http://localhost:{PORT}/api/v1/pull",
json={
"model_name": user_canonical,
"checkpoint": USER_MODEL_MAIN_CHECKPOINT,
"recipe": "llamacpp",
"stream": False,
},
headers=_auth_headers(),
timeout=TIMEOUT_MODEL_OPERATION,
)
self.assertEqual(pull_response.status_code, 200)
result = self.assertCommandSucceeds(["list"], timeout=TIMEOUT_DEFAULT)
output = result.stdout + result.stderr
# Winner appears as bare id; shadowed built-in appears under its canonical id.
self.assertIn(bare, output)
self.assertIn(f"builtin.{bare}", output)
# The user.* canonical form must NOT appear in output — winners emit bare.
self.assertNotIn(user_canonical, output)
print(
f"[OK] list shows both {bare} (user winner) and builtin.{bare} (shadowed)"
)
finally:
run_cli_command(["delete", user_canonical], timeout=TIMEOUT_DEFAULT)
def test_091_delete_preserves_shared_repo(self):
"""Test that deleting one model preserves files used by another model sharing the same repo."""
# Import two user models that share the same HF repo (different GGUF quants)
for name, checkpoint in [
(SHARED_REPO_MODEL_A_NAME, SHARED_REPO_MODEL_A_CHECKPOINT),
(SHARED_REPO_MODEL_B_NAME, SHARED_REPO_MODEL_B_CHECKPOINT),
]:
json_file = os.path.join(tempfile.gettempdir(), f"lemonade_{name}.json")
with open(json_file, "w") as f:
f.write(
json.dumps(
{
"id": name,
"checkpoint": checkpoint,
"recipe": "llamacpp",
}
)
)
self.assertCommandSucceeds(
["import", json_file], timeout=TIMEOUT_MODEL_OPERATION
)
# Pull both models (downloads both quants into the same models-- directory)
for name in [SHARED_REPO_MODEL_A_NAME, SHARED_REPO_MODEL_B_NAME]:
result = run_cli_pull_command_with_retry(
["pull", name], timeout=TIMEOUT_MODEL_OPERATION
)
self.assertEqual(result.returncode, 0, result.stderr)
# Verify both show as downloaded
result = self.assertCommandSucceeds(["list", "--downloaded"])
output = result.stdout + result.stderr
self.assertIn(
"SharedRepo-TestA",
output,
"Model A should be listed as downloaded before delete",
)
self.assertIn(
"SharedRepo-TestB",
output,
"Model B should be listed as downloaded before delete",
)
# Delete model A — model B's files should be preserved
self.assertCommandSucceeds(
["delete", SHARED_REPO_MODEL_A_NAME], timeout=TIMEOUT_MODEL_OPERATION
)
# Verify model B is still listed as downloaded
result = self.assertCommandSucceeds(["list", "--downloaded"])
output = result.stdout + result.stderr
self.assertIn(
"SharedRepo-TestB",
output,
"Model B should still be downloaded after deleting model A",
)
self.assertNotIn(
"SharedRepo-TestA",
output,
"Model A should no longer be listed after delete",
)
# Clean up: delete model B
self.assertCommandSucceeds(
["delete", SHARED_REPO_MODEL_B_NAME], timeout=TIMEOUT_MODEL_OPERATION
)
@unittest.skipIf(
sys.platform == "darwin",
"macOS .pkg installs to /Library/Application Support/lemonade/hub, "
"which the HF cache resolver does not check",
)
def test_092_delete_preserves_cross_repo_dependency(self):
"""Test multi-repo dependency cleanup in the persistent CLI suite.
Scenario:
Model A: main from repo1, text_encoder from repo2 (shared)
Model B: main from repo3, text_encoder from repo2 (shared)
- Download A -> downloads repo1 + repo2
- Download B -> downloads repo3, repo2 already present
- Delete A -> removes A's main checkpoint file only; repo dirs may remain
if earlier persistent tests imported another model from the same repo
- Delete B -> deletes repo3 + repo2
Verifies both CLI output and on-disk HF cache state at each step.
"""
# Import both models with multi-checkpoint configs
for name, main_cp in [
(MULTI_REPO_MODEL_A_NAME, MULTI_REPO_MODEL_A_MAIN),
(MULTI_REPO_MODEL_B_NAME, MULTI_REPO_MODEL_B_MAIN),
]:
json_file = os.path.join(tempfile.gettempdir(), f"lemonade_{name}.json")
with open(json_file, "w") as f:
f.write(
json.dumps(
{
"id": name,
"checkpoints": {
"main": main_cp,
"text_encoder": MULTI_REPO_SHARED_CHECKPOINT,
},
"recipe": "llamacpp",
}
)
)
self.assertCommandSucceeds(
["import", json_file], timeout=TIMEOUT_MODEL_OPERATION
)
# Pull both models
for name in [MULTI_REPO_MODEL_A_NAME, MULTI_REPO_MODEL_B_NAME]:
result = run_cli_pull_command_with_retry(
["pull", name], timeout=TIMEOUT_MODEL_OPERATION
)
self.assertEqual(result.returncode, 0, result.stderr)
# Verify both show as downloaded
result = self.assertCommandSucceeds(["list", "--downloaded"])
output = result.stdout + result.stderr
self.assertIn(
"MultiRepo-TestA", output, "Model A should be listed as downloaded"
)
self.assertIn(
"MultiRepo-TestB", output, "Model B should be listed as downloaded"
)
hf_cache = _resolve_hf_cache_root(
[
MULTI_REPO_MODEL_A_CACHE_DIR,
MULTI_REPO_SHARED_CACHE_DIR,
MULTI_REPO_MODEL_B_CACHE_DIR,
],
[
(MULTI_REPO_MODEL_A_CACHE_DIR, MULTI_REPO_MODEL_A_MAIN),
(MULTI_REPO_SHARED_CACHE_DIR, MULTI_REPO_SHARED_CHECKPOINT),
(MULTI_REPO_MODEL_B_CACHE_DIR, MULTI_REPO_MODEL_B_MAIN),
],
)
repo1_path = os.path.join(hf_cache, MULTI_REPO_MODEL_A_CACHE_DIR)
repo2_path = os.path.join(hf_cache, MULTI_REPO_SHARED_CACHE_DIR)
repo3_path = os.path.join(hf_cache, MULTI_REPO_MODEL_B_CACHE_DIR)
model_a_main_path = _find_cached_checkpoint(
hf_cache, MULTI_REPO_MODEL_A_CACHE_DIR, MULTI_REPO_MODEL_A_MAIN
)
shared_checkpoint_path = _find_cached_checkpoint(
hf_cache, MULTI_REPO_SHARED_CACHE_DIR, MULTI_REPO_SHARED_CHECKPOINT
)
model_b_main_path = _find_cached_checkpoint(
hf_cache, MULTI_REPO_MODEL_B_CACHE_DIR, MULTI_REPO_MODEL_B_MAIN
)
# Verify all three repo dirs exist on disk after download
self.assertTrue(
os.path.isdir(repo1_path), f"repo1 dir should exist: {repo1_path}"
)
self.assertTrue(
os.path.isdir(repo2_path), f"shared repo dir should exist: {repo2_path}"
)
self.assertTrue(
os.path.isdir(repo3_path), f"repo3 dir should exist: {repo3_path}"
)
self.assertIsNotNone(
model_a_main_path,
f"Model A main checkpoint should exist in snapshots under {repo1_path}",
)
self.assertIsNotNone(
shared_checkpoint_path,
f"Shared checkpoint should exist in snapshots under {repo2_path}",
)
self.assertIsNotNone(
model_b_main_path,
f"Model B main checkpoint should exist in snapshots under {repo3_path}",
)
print("[OK] All three HF cache repo directories present after pull")
# Delete Model A -- Model B (and shared text_encoder repo2) should be preserved
self.assertCommandSucceeds(
["delete", MULTI_REPO_MODEL_A_NAME], timeout=TIMEOUT_MODEL_OPERATION
)
# Verify Model B is still downloaded via CLI
result = self.assertCommandSucceeds(["list", "--downloaded"])
output = result.stdout + result.stderr
self.assertIn("MultiRepo-TestB", output, "Model B should still be downloaded")
self.assertNotIn("MultiRepo-TestA", output, "Model A should be gone")
# Verify on-disk: Model A file deleted, repo2 (shared) preserved, repo3 preserved.
# repo1 directory may remain because this suite is persistent and other imported
# models can reference the same repo.
self.assertFalse(
os.path.exists(model_a_main_path),
f"Model A main checkpoint should be deleted after removing Model A: {model_a_main_path}",
)
self.assertTrue(
os.path.isdir(repo2_path),
f"shared repo should be preserved (still needed by Model B): {repo2_path}",
)
self.assertTrue(
os.path.exists(shared_checkpoint_path),
"Shared checkpoint should still exist after removing Model A",
)
self.assertTrue(
os.path.isdir(repo3_path),
f"repo3 should still exist (Model B main): {repo3_path}",
)
self.assertTrue(
os.path.exists(model_b_main_path),
"Model B main checkpoint should still exist after removing Model A",
)
print("[OK] After deleting A: A main file gone, shared repo2 + repo3 preserved")
# Delete Model B -- should clean up repo3 and shared repo2
self.assertCommandSucceeds(
["delete", MULTI_REPO_MODEL_B_NAME], timeout=TIMEOUT_MODEL_OPERATION
)
# Verify both gone from CLI
result = self.assertCommandSucceeds(["list", "--downloaded"])
output = result.stdout + result.stderr
self.assertNotIn("MultiRepo-TestA", output, "Model A should not be listed")
self.assertNotIn("MultiRepo-TestB", output, "Model B should not be listed")
# Verify on-disk: repo2 shared file and repo3 main file deleted, and both
# unique repo directories removed once the last dependent model is gone.
self.assertFalse(
os.path.exists(shared_checkpoint_path),
"Shared checkpoint should be deleted after removing the last dependent model",
)
self.assertFalse(
os.path.exists(model_b_main_path),
f"Model B main checkpoint should be deleted after removing Model B: {model_b_main_path}",
)
self.assertFalse(
os.path.isdir(repo2_path),
f"shared repo should be deleted after removing last dependent: {repo2_path}",
)
self.assertFalse(
os.path.isdir(repo3_path),
f"repo3 should be deleted after removing Model B: {repo3_path}",
)
print("[OK] After deleting B: all repo directories cleaned up")
def test_models_sync_command(self):
"""Test the 'update-models' CLI subcommand dry-run check and execution."""
# 1. Run update-models dry-run check (using --check)
result = self.assertCommandSucceeds(
["update-models", ENDPOINT_TEST_MODEL, "--check"]
)
self.assertIn("Checked", result.stdout)
self.assertIn("update(s) available", result.stdout)
# 3. Run update-models with --check --json option
result = self.assertCommandSucceeds(
["update-models", ENDPOINT_TEST_MODEL, "--check", "--json"]
)
self.assertIn("checked_count", result.stdout)
# 4. Run update-models on nonexistent model with --check --json, expecting exit code 1
result = run_cli_command(
["update-models", "nonexistent-model-test-xyz", "--check", "--json"],
timeout=TIMEOUT_DEFAULT,
)
self.assertEqual(
result.returncode,
1,
f"update-models nonexistent model with --json should fail, got returncode {result.returncode}",
)
self.assertIn("failed_models", result.stdout)
class CLIHelpDocsConsistencyTests(unittest.TestCase):
"""Lightweight checks that compare CLI help semantics with docs text."""
def test_899_run_load_recipe_options_are_grouped(self):
"""Run/load help should keep every recipe flag under the intended group."""
expected_groups = {
"General Options:": ["--ctx-size", "--merge-args"],
"Llama.cpp Backend Options:": [
"--llamacpp",
"--llamacpp-device",
"--llamacpp-args",
],
"Stable Diffusion Options:": ["--sdcpp", "--sdcpp-args"],
"vLLM Options:": ["--vllm", "--vllm-args"],
"Whisper.cpp Options:": ["--whispercpp", "--whispercpp-args"],
}
for command in ("run", "load"):
with self.subTest(command=command):
result = run_cli_command([command, "--help"], timeout=TIMEOUT_DEFAULT)
self.assertEqual(result.returncode, 0)
help_output = result.stdout + result.stderr
group_positions = {
group: help_output.find(group) for group in expected_groups
}
for group, position in group_positions.items():
self.assertNotEqual(position, -1, f"Missing help group: {group}")
ordered_groups = sorted(
group_positions.items(), key=lambda item: item[1]
)
for index, (group, start) in enumerate(ordered_groups):
end = (
ordered_groups[index + 1][1]
if index + 1 < len(ordered_groups)
else len(help_output)
)
section = help_output[start:end]
for flag in expected_groups[group]:
self.assertTrue(
any(
line.strip().startswith(flag)
and (
len(line.strip()) == len(flag)
or line.strip()[len(flag)] in " ,"
)
for line in section.splitlines()
),
f"{flag} missing from {group} in `{command} --help`",
)
def test_900_launch_docs_match_help_text(self):
"""The launch model-selection wording in docs should match actual CLI behavior/help."""
result = run_cli_command(["launch", "--help"], timeout=TIMEOUT_DEFAULT)
self.assertEqual(result.returncode, 0)
help_output = result.stdout + result.stderr
self.assertIn("Agents:", help_output)
self.assertIn("claude", help_output)
self.assertIn("codex", help_output)
self.assertIn("opencode", help_output)
self.assertNotIn("--model", help_output)
self.assertNotIn("--directory", help_output)
self.assertNotIn("--recipe-file", help_output)
self.assertNotIn("--agent-args", help_output)
self.assertNotIn("--provider", help_output)
self.assertNotIn("--ctx-size", help_output)
self.assertNotIn("LEMONADE_CTX_SIZE", help_output)
claude_result = run_cli_command(
["launch", "claude", "--help"], timeout=TIMEOUT_DEFAULT
)
self.assertEqual(claude_result.returncode, 0)
claude_help = claude_result.stdout + claude_result.stderr
self.assertNotIn("--provider", claude_help)
self.assertNotIn("--ctx-size", claude_help)
self.assertNotIn("LEMONADE_CTX_SIZE", claude_help)
self.assertNotIn("--llamacpp", claude_help)
opencode_result = run_cli_command(
["launch", "opencode", "--help"], timeout=TIMEOUT_DEFAULT
)
self.assertEqual(opencode_result.returncode, 0)
opencode_help = opencode_result.stdout + opencode_result.stderr
self.assertNotIn("--provider", opencode_help)
self.assertNotIn("--ctx-size", opencode_help)
self.assertNotIn("LEMONADE_CTX_SIZE", opencode_help)
codex_result = run_cli_command(
["launch", "codex", "--help"], timeout=TIMEOUT_DEFAULT
)
self.assertEqual(codex_result.returncode, 0)
codex_help = codex_result.stdout + codex_result.stderr
self.assertIn("Use model provider name for Codex", codex_help)
self.assertIn("--provider", codex_help)
self.assertNotIn("--ctx-size", codex_help)
self.assertNotIn("LEMONADE_CTX_SIZE", codex_help)
docs_path = os.path.join(
os.path.dirname(__file__), "..", "docs", "guide", "cli.md"
)
with open(docs_path, "r", encoding="utf-8") as f:
docs_text = f.read()
self.assertNotIn("`--use-recipe`", docs_text)
self.assertNotIn(
"Import a recipe from `lemonade-sdk/recipes` before launch",
docs_text,
)
self.assertIn(
"`--recipe-file` is only used for remote recipe import",
docs_text,
)
self.assertIn(
"For local recipe files, run `lemonade import <LOCAL_RECIPE_JSON>` first",
docs_text,
)
self.assertIn("--provider,-p [PROVIDER]", docs_text)
self.assertIn("--agent-args ARGS", docs_text)
launch_section = docs_text.split("## Options for launch", 1)[1].split(
"## Options for scan", 1
)[0]
self.assertNotIn("--ctx-size", launch_section)
self.assertNotIn("--llamacpp", launch_section)
class CLIUrlSchemeTests(unittest.TestCase):
"""Tests URL scheme parsing, HTTPS/TLS connections, and port overrides in the C++ CLI client."""
@classmethod
def setUpClass(cls):
import http.server
import threading
import socket
class MockHTTPHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass
def do_GET(self):
if self.path.startswith("/api/v1/models") or self.path.startswith(
"/api/v0/models"
):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"data":[]}')
else:
self.send_response(404)
self.end_headers()
# Find a free port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 0))
cls.mock_port = s.getsockname()[1]
s.close()
cls.server = http.server.HTTPServer(
("127.0.0.1", cls.mock_port), MockHTTPHandler
)
cls.thread = threading.Thread(target=cls.server.serve_forever)
cls.thread.daemon = True
cls.thread.start()
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.server.server_close()
cls.thread.join()
def test_http_scheme_port_default(self):
"""Should connect successfully and default port when http:// scheme is used."""
env = os.environ.copy()
env["LEMONADE_HOST"] = f"http://127.0.0.1:{self.mock_port}"
result = run_cli_command(["list"], env=env, timeout=10)
output = result.stdout + result.stderr
self.assertEqual(result.returncode, 0)
self.assertIn("No models available", output)
def test_https_scheme_connection_attempt(self):
"""Should attempt a secure TLS connection when https:// scheme is used."""
# Connecting https://127.0.0.1:mock_port will attempt a TLS handshake on our HTTP server.
# This will fail (since the server is HTTP), but it verifies that:
# 1. The hostname/port were parsed correctly to 127.0.0.1:mock_port.
# 2. It attempted a TLS handshake.
env = os.environ.copy()
env["LEMONADE_HOST"] = f"https://127.0.0.1:{self.mock_port}"
result = run_cli_command(["list"], env=env, timeout=10)
output = result.stdout + result.stderr
self.assertNotEqual(result.returncode, 0)
# Verify it either tried to establish connection/handshake or failed because HTTPS is compiled out
self.assertTrue(
"Could not connect to Lemonade server" in output
or "HTTPS support is not compiled" in output
or "'https' scheme is not supported" in output,
f"Expected connection error or HTTPS unsupported error, got: {output}",
)
class CLIConnectionErrorMessageTests(unittest.TestCase):
"""The CLI must tell a closed connection apart from a server that is not running."""
@staticmethod
def _free_port():
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def _run_status(self, port):
env = os.environ.copy()
env["LEMONADE_HOST"] = f"http://127.0.0.1:{port}"
result = run_cli_command(["status"], env=env, timeout=15)
self.assertNotEqual(result.returncode, 0)
return result.stdout + result.stderr
def test_connection_closed_by_server(self):
"""A server that accepts then drops the connection is reported as busy, not stopped."""
import socket
import threading
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))
listener.listen(5)
port = listener.getsockname()[1]
stop = threading.Event()
def drop_connections():
listener.settimeout(0.2)
while not stop.is_set():
try:
conn, _ = listener.accept()
except socket.timeout:
continue
except OSError:
return
conn.close()
thread = threading.Thread(target=drop_connections, daemon=True)
thread.start()
try:
output = self._run_status(port)
finally:
stop.set()
thread.join()
listener.close()
self.assertIn("closed the connection", output)
self.assertNotIn("Make sure the server is running", output)
def test_server_not_running(self):
"""Nothing listening keeps the original 'server is running' hint."""
output = self._run_status(self._free_port())
self.assertIn("Could not connect to Lemonade server", output)
self.assertIn("Make sure the server is running", output)
self.assertNotIn("closed the connection", output)
def run_cli_client_tests():
"""Run CLI client tests based on command line arguments."""
args = parse_cli_args()
print(f"\n{'=' * 70}")
print("CLI CLIENT TESTS")
print(f"CLI binary: {get_cli_binary()}")
print(f"{'=' * 70}\n")
# Create and run test suite
loader = unittest.TestLoader()
suite = unittest.TestSuite()
suite.addTests(loader.loadTestsFromTestCase(PersistentServerCLIClientTests))
suite.addTests(loader.loadTestsFromTestCase(CLIHelpDocsConsistencyTests))
suite.addTests(loader.loadTestsFromTestCase(CLIUrlSchemeTests))
suite.addTests(loader.loadTestsFromTestCase(CLIConnectionErrorMessageTests))
runner = unittest.TextTestRunner(verbosity=2, buffer=False, failfast=True)
result = runner.run(suite)
sys.exit(0 if (result and result.wasSuccessful()) else 1)
if __name__ == "__main__":
run_cli_client_tests()