opentui(phase3): launcher integration — HERMES_TUI_ENGINE dual-engine
hermes --tui launches the native OpenTUI engine (Bun) when HERMES_TUI_ENGINE=opentui (env) or display.tui_engine=opentui (config); Ink stays the default and the shipping path is untouched. - _resolve_tui_engine() (env > config > ink); refuses opentui on Windows/Termux (no Bun) -> falls back to ink with a notice. - _make_opentui_argv() -> [bun, src/entry.real.tsx] (no build step). - _bun_bin() with HERMES_BUN override. - Branch at top of _make_tui_argv BEFORE _ensure_tui_node (Bun-only host must not bootstrap Node). - Gate _launch_tui NODE_OPTIONS/--max-old-space-size on engine==ink (Bun is JSC; the V8 flag errors/ignores). Verified end-to-end via tmux: real hermes --tui -> Bun -> OpenTUI -> real Python gateway streamed a real reply. No-flag default still ink.
This commit is contained in:
@@ -41,16 +41,6 @@ def _suppress_concurrent_hermes_gate(request, monkeypatch):
|
||||
from hermes_cli import main as _cli_main
|
||||
except Exception:
|
||||
return
|
||||
# raising=False: under pytest's per-test spawn isolation, a concurrent
|
||||
# xdist worker importing a module that transitively touches hermes_cli.main
|
||||
# can briefly expose a partially-initialized module object here — one where
|
||||
# _detect_concurrent_hermes_instances isn't defined yet. A bare setattr
|
||||
# would raise AttributeError and error the (unrelated) test. The attribute
|
||||
# always exists once main.py finishes importing, so a no-op when it's
|
||||
# transiently absent is the correct, race-free default.
|
||||
monkeypatch.setattr(
|
||||
_cli_main,
|
||||
"_detect_concurrent_hermes_instances",
|
||||
lambda *_a, **_k: [],
|
||||
raising=False,
|
||||
_cli_main, "_detect_concurrent_hermes_instances", lambda *_a, **_k: []
|
||||
)
|
||||
|
||||
@@ -1,313 +0,0 @@
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
from hermes_cli import active_sessions
|
||||
|
||||
|
||||
def test_resolve_max_concurrent_sessions_values(caplog):
|
||||
assert active_sessions.resolve_max_concurrent_sessions({}) is None
|
||||
assert active_sessions.resolve_max_concurrent_sessions({"max_concurrent_sessions": None}) is None
|
||||
assert active_sessions.resolve_max_concurrent_sessions({"max_concurrent_sessions": 0}) is None
|
||||
assert active_sessions.resolve_max_concurrent_sessions({"max_concurrent_sessions": -1}) is None
|
||||
assert active_sessions.resolve_max_concurrent_sessions({"max_concurrent_sessions": "3"}) == 3
|
||||
assert (
|
||||
active_sessions.resolve_max_concurrent_sessions(
|
||||
{"gateway": {"max_concurrent_sessions": 4}}
|
||||
)
|
||||
== 4
|
||||
)
|
||||
assert (
|
||||
active_sessions.resolve_max_concurrent_sessions(
|
||||
{"max_concurrent_sessions": 2, "gateway": {"max_concurrent_sessions": 4}}
|
||||
)
|
||||
== 2
|
||||
)
|
||||
|
||||
caplog.set_level(logging.WARNING)
|
||||
assert active_sessions.resolve_max_concurrent_sessions({"max_concurrent_sessions": "many"}) is None
|
||||
assert any(
|
||||
"Ignoring invalid max_concurrent_sessions='many'" in record.message
|
||||
for record in caplog.records
|
||||
)
|
||||
|
||||
|
||||
def test_active_session_lease_blocks_until_release(tmp_path, monkeypatch):
|
||||
home = tmp_path / ".hermes"
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
cfg = {"max_concurrent_sessions": 1}
|
||||
|
||||
lease, message = active_sessions.try_acquire_active_session(
|
||||
session_id="session-1",
|
||||
surface="cli",
|
||||
config=cfg,
|
||||
)
|
||||
|
||||
assert message is None
|
||||
assert lease is not None
|
||||
|
||||
blocked_lease, blocked_message = active_sessions.try_acquire_active_session(
|
||||
session_id="session-2",
|
||||
surface="tui",
|
||||
config=cfg,
|
||||
)
|
||||
|
||||
assert blocked_lease is None
|
||||
assert blocked_message == (
|
||||
"Hermes is at the active session limit (1/1). "
|
||||
"Try again when another session finishes."
|
||||
)
|
||||
|
||||
lease.release()
|
||||
|
||||
next_lease, next_message = active_sessions.try_acquire_active_session(
|
||||
session_id="session-3",
|
||||
surface="gateway:telegram",
|
||||
config=cfg,
|
||||
)
|
||||
|
||||
assert next_message is None
|
||||
assert next_lease is not None
|
||||
next_lease.release()
|
||||
assert active_sessions.active_session_registry_snapshot() == []
|
||||
|
||||
|
||||
def test_active_session_registry_prunes_dead_pids(tmp_path, monkeypatch):
|
||||
home = tmp_path / ".hermes"
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
monkeypatch.setattr(
|
||||
"gateway.status._pid_exists",
|
||||
lambda pid: int(pid) != 99999999,
|
||||
)
|
||||
runtime = home / "runtime"
|
||||
runtime.mkdir(parents=True)
|
||||
active_sessions._write_entries(
|
||||
runtime / "active_sessions.json",
|
||||
[
|
||||
{
|
||||
"lease_id": "stale",
|
||||
"session_id": "stale-session",
|
||||
"surface": "cli",
|
||||
"pid": 99999999,
|
||||
"started_at": 1,
|
||||
"updated_at": 1,
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
lease, message = active_sessions.try_acquire_active_session(
|
||||
session_id="session-1",
|
||||
surface="cli",
|
||||
config={"max_concurrent_sessions": 1},
|
||||
)
|
||||
|
||||
assert message is None
|
||||
assert lease is not None
|
||||
assert [entry["session_id"] for entry in active_sessions.active_session_registry_snapshot()] == [
|
||||
"session-1"
|
||||
]
|
||||
lease.release()
|
||||
|
||||
|
||||
def test_pid_alive_uses_safe_pid_exists_without_signalling(monkeypatch):
|
||||
checked: list[int] = []
|
||||
|
||||
monkeypatch.setattr(
|
||||
active_sessions.os,
|
||||
"kill",
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("os.kill used")),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"gateway.status._pid_exists",
|
||||
lambda pid: checked.append(int(pid)) or True,
|
||||
)
|
||||
|
||||
assert active_sessions._pid_alive(12345) is True
|
||||
assert checked == [12345]
|
||||
|
||||
|
||||
def test_active_session_hard_exit_is_reclaimed(tmp_path, monkeypatch):
|
||||
home = tmp_path / ".hermes"
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
repo_root = Path(__file__).resolve().parents[2]
|
||||
env = os.environ.copy()
|
||||
env["HERMES_HOME"] = str(home)
|
||||
env["PYTHONPATH"] = str(repo_root)
|
||||
child = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
(
|
||||
"import os\n"
|
||||
"from hermes_cli.active_sessions import try_acquire_active_session\n"
|
||||
"lease, message = try_acquire_active_session("
|
||||
"session_id='crash-session', surface='cli', "
|
||||
"config={'max_concurrent_sessions': 1})\n"
|
||||
"assert message is None, message\n"
|
||||
"print(os.getpid(), flush=True)\n"
|
||||
"os._exit(0)\n"
|
||||
),
|
||||
],
|
||||
env=env,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
check=True,
|
||||
)
|
||||
child_pid = int(child.stdout.strip())
|
||||
|
||||
lease, message = active_sessions.try_acquire_active_session(
|
||||
session_id="next-session",
|
||||
surface="cli",
|
||||
config={"max_concurrent_sessions": 1},
|
||||
)
|
||||
|
||||
assert child_pid > 0
|
||||
assert message is None
|
||||
assert lease is not None
|
||||
assert [entry["session_id"] for entry in active_sessions.active_session_registry_snapshot()] == [
|
||||
"next-session"
|
||||
]
|
||||
lease.release()
|
||||
|
||||
|
||||
def test_concurrent_acquire_claims_only_one_last_slot(tmp_path, monkeypatch):
|
||||
home = tmp_path / ".hermes"
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
cfg = {"max_concurrent_sessions": 1}
|
||||
|
||||
def _claim(index: int):
|
||||
return active_sessions.try_acquire_active_session(
|
||||
session_id=f"session-{index}",
|
||||
surface="cli",
|
||||
config=cfg,
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(_claim, range(8)))
|
||||
|
||||
leases = [lease for lease, message in results if lease is not None and message is None]
|
||||
blocked = [message for lease, message in results if lease is None and message]
|
||||
|
||||
try:
|
||||
assert len(leases) == 1
|
||||
assert len(blocked) == 7
|
||||
assert active_sessions.active_session_registry_snapshot()[0]["session_id"].startswith("session-")
|
||||
finally:
|
||||
for lease in leases:
|
||||
lease.release()
|
||||
|
||||
|
||||
def test_cross_process_acquire_claims_only_one_last_slot(tmp_path, monkeypatch):
|
||||
home = tmp_path / ".hermes"
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
repo_root = Path(__file__).resolve().parents[2]
|
||||
ready_dir = tmp_path / "ready"
|
||||
ready_dir.mkdir()
|
||||
go_file = tmp_path / "go"
|
||||
env = os.environ.copy()
|
||||
env["HERMES_HOME"] = str(home)
|
||||
env["PYTHONPATH"] = str(repo_root)
|
||||
script = (
|
||||
"import os, time\n"
|
||||
"from pathlib import Path\n"
|
||||
"from hermes_cli.active_sessions import try_acquire_active_session\n"
|
||||
"idx = os.environ['WORKER_INDEX']\n"
|
||||
"ready_dir = Path(os.environ['READY_DIR'])\n"
|
||||
"go_file = Path(os.environ['GO_FILE'])\n"
|
||||
"(ready_dir / idx).write_text('ready', encoding='utf-8')\n"
|
||||
"deadline = time.time() + 10\n"
|
||||
"while not go_file.exists():\n"
|
||||
" if time.time() > deadline:\n"
|
||||
" raise RuntimeError('timed out waiting for go file')\n"
|
||||
" time.sleep(0.01)\n"
|
||||
"lease, message = try_acquire_active_session(\n"
|
||||
" session_id=f'process-{idx}',\n"
|
||||
" surface='cli',\n"
|
||||
" config={'max_concurrent_sessions': 1},\n"
|
||||
")\n"
|
||||
"if lease is None:\n"
|
||||
" print('BLOCK', flush=True)\n"
|
||||
"else:\n"
|
||||
" print('OK', flush=True)\n"
|
||||
" time.sleep(2.0)\n"
|
||||
" lease.release()\n"
|
||||
)
|
||||
workers: list[subprocess.Popen[str]] = []
|
||||
try:
|
||||
for index in range(6):
|
||||
worker_env = env.copy()
|
||||
worker_env["WORKER_INDEX"] = str(index)
|
||||
worker_env["READY_DIR"] = str(ready_dir)
|
||||
worker_env["GO_FILE"] = str(go_file)
|
||||
workers.append(
|
||||
subprocess.Popen(
|
||||
[sys.executable, "-c", script],
|
||||
env=worker_env,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
)
|
||||
|
||||
deadline = time.time() + 10
|
||||
while len(list(ready_dir.iterdir())) < len(workers):
|
||||
if time.time() > deadline:
|
||||
raise AssertionError("workers did not become ready")
|
||||
time.sleep(0.01)
|
||||
go_file.write_text("go", encoding="utf-8")
|
||||
|
||||
outputs = []
|
||||
for worker in workers:
|
||||
stdout, stderr = worker.communicate(timeout=10)
|
||||
assert worker.returncode == 0, stderr
|
||||
outputs.append(stdout.strip())
|
||||
finally:
|
||||
for worker in workers:
|
||||
if worker.poll() is None:
|
||||
worker.kill()
|
||||
worker.communicate()
|
||||
|
||||
assert outputs.count("OK") == 1
|
||||
assert outputs.count("BLOCK") == len(workers) - 1
|
||||
assert active_sessions.active_session_registry_snapshot() == []
|
||||
|
||||
|
||||
def test_pid_start_time_mismatch_prunes_reused_pid(tmp_path, monkeypatch):
|
||||
home = tmp_path / ".hermes"
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
monkeypatch.setattr("gateway.status._pid_exists", lambda _pid: True)
|
||||
monkeypatch.setattr(active_sessions, "_process_start_time", lambda _pid: 200.0)
|
||||
runtime = home / "runtime"
|
||||
runtime.mkdir(parents=True)
|
||||
active_sessions._write_entries(
|
||||
runtime / "active_sessions.json",
|
||||
[
|
||||
{
|
||||
"lease_id": "stale-reused-pid",
|
||||
"session_id": "stale-session",
|
||||
"surface": "cli",
|
||||
"pid": os.getpid(),
|
||||
"process_start_time": 100.0,
|
||||
"started_at": 1,
|
||||
"updated_at": 1,
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
lease, message = active_sessions.try_acquire_active_session(
|
||||
session_id="new-session",
|
||||
surface="cli",
|
||||
config={"max_concurrent_sessions": 1},
|
||||
)
|
||||
|
||||
assert message is None
|
||||
assert lease is not None
|
||||
assert [entry["session_id"] for entry in active_sessions.active_session_registry_snapshot()] == [
|
||||
"new-session"
|
||||
]
|
||||
lease.release()
|
||||
@@ -1,58 +0,0 @@
|
||||
"""Regression tests for the Anthropic model-picker dropping curated aliases.
|
||||
|
||||
Bug — newly-routed curated aliases vanished on a native Anthropic setup
|
||||
``provider_model_ids("anthropic")`` returned the live ``/v1/models`` dump
|
||||
verbatim whenever Anthropic credentials were configured. Anthropic's API
|
||||
lags behind freshly-routed aliases (e.g. ``claude-fable-5``, which is
|
||||
reachable on Anthropic before the models endpoint enumerates it), so the
|
||||
curated entry disappeared from the picker. The picker now merges the
|
||||
curated ``_PROVIDER_MODELS["anthropic"]`` list with the live catalog —
|
||||
curated entries first, live-only models appended, deduped — mirroring the
|
||||
OpenAI curated-merge philosophy.
|
||||
"""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from hermes_cli import models as M
|
||||
|
||||
|
||||
def test_anthropic_curated_alias_survives_when_live_omits_it():
|
||||
"""A curated alias missing from /v1/models still surfaces (first)."""
|
||||
curated = M._PROVIDER_MODELS["anthropic"]
|
||||
assert "claude-fable-5" in curated # sanity: the alias is curated
|
||||
|
||||
# Live catalog the API would actually return — no fable-5.
|
||||
live = ["claude-opus-4-8", "claude-sonnet-4-6", "claude-haiku-4-5-20251001"]
|
||||
with patch.object(M, "_fetch_anthropic_models", return_value=live):
|
||||
result = M.provider_model_ids("anthropic")
|
||||
|
||||
assert "claude-fable-5" in result
|
||||
# Curated order is preserved at the front.
|
||||
assert result[:len(curated)] == list(curated)
|
||||
|
||||
|
||||
def test_anthropic_merge_dedupes_overlap_and_appends_live_only():
|
||||
"""Models in both lists appear once; live-only models are appended."""
|
||||
live = [
|
||||
"claude-opus-4-8", # overlaps curated
|
||||
"claude-sonnet-4-6", # overlaps curated
|
||||
"claude-future-9-99", # live-only, not curated
|
||||
]
|
||||
with patch.object(M, "_fetch_anthropic_models", return_value=live):
|
||||
result = M.provider_model_ids("anthropic")
|
||||
|
||||
# No duplicates introduced by the merge.
|
||||
assert result.count("claude-opus-4-8") == 1
|
||||
# Live-only entry is preserved (discovery still works for unknown models).
|
||||
assert "claude-future-9-99" in result
|
||||
# Curated entries lead, live-only trails.
|
||||
assert result.index("claude-fable-5") < result.index("claude-future-9-99")
|
||||
|
||||
|
||||
def test_anthropic_falls_back_to_curated_when_live_unavailable():
|
||||
"""No creds / live failure -> curated list verbatim (alias still present)."""
|
||||
with patch.object(M, "_fetch_anthropic_models", return_value=None):
|
||||
result = M.provider_model_ids("anthropic")
|
||||
|
||||
assert result == list(M._PROVIDER_MODELS["anthropic"])
|
||||
assert "claude-fable-5" in result
|
||||
@@ -138,80 +138,3 @@ class TestApplyProfileOverrideHermesHomeGuard:
|
||||
_apply_profile_override()
|
||||
|
||||
assert os.environ.get("HERMES_HOME") is None
|
||||
|
||||
def test_subcommand_profile_flag_is_not_consumed(self, tmp_path, monkeypatch):
|
||||
"""Command argv flags named --profile must stay with that command.
|
||||
|
||||
Docker Desktop's MCP Toolkit uses `docker mcp gateway run --profile ...`.
|
||||
When that argv is passed through `hermes mcp add --args`, the early
|
||||
profile pre-parser must not interpret the Docker profile as a Hermes
|
||||
profile.
|
||||
"""
|
||||
hermes_root = tmp_path / ".hermes"
|
||||
hermes_root.mkdir(parents=True, exist_ok=True)
|
||||
argv = [
|
||||
"hermes",
|
||||
"mcp",
|
||||
"add",
|
||||
"docker-research",
|
||||
"--command",
|
||||
"docker",
|
||||
"--args",
|
||||
"mcp",
|
||||
"gateway",
|
||||
"run",
|
||||
"--profile",
|
||||
"research",
|
||||
]
|
||||
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
monkeypatch.delenv("HERMES_HOME", raising=False)
|
||||
monkeypatch.setattr(sys, "argv", list(argv))
|
||||
|
||||
from hermes_cli.main import _apply_profile_override
|
||||
_apply_profile_override()
|
||||
|
||||
assert os.environ.get("HERMES_HOME") is None
|
||||
assert sys.argv == argv
|
||||
|
||||
def test_profile_after_chat_subcommand_is_still_consumed(self, tmp_path, monkeypatch):
|
||||
"""Profile flags historically work after normal Hermes subcommands."""
|
||||
result = _run_apply_profile_override(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
hermes_home=None,
|
||||
active_profile="coder",
|
||||
argv=["hermes", "chat", "-p", "coder", "-q", "hello"],
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result.endswith("coder")
|
||||
assert sys.argv == ["hermes", "chat", "-q", "hello"]
|
||||
|
||||
def test_top_level_profile_after_value_flag_is_consumed(self, tmp_path, monkeypatch):
|
||||
"""Top-level --profile still works after other top-level value flags."""
|
||||
result = _run_apply_profile_override(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
hermes_home=None,
|
||||
active_profile="coder",
|
||||
argv=["hermes", "-m", "gpt-5", "--profile", "coder", "chat"],
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result.endswith("coder")
|
||||
assert sys.argv == ["hermes", "-m", "gpt-5", "chat"]
|
||||
|
||||
def test_top_level_profile_after_continue_flag_is_consumed(self, tmp_path, monkeypatch):
|
||||
"""--continue has an optional value, so a following --profile is a flag."""
|
||||
result = _run_apply_profile_override(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
hermes_home=None,
|
||||
active_profile="coder",
|
||||
argv=["hermes", "--continue", "--profile", "coder"],
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result.endswith("coder")
|
||||
assert sys.argv == ["hermes", "--continue"]
|
||||
|
||||
@@ -301,23 +301,19 @@ def test_save_codex_tokens_syncs_credential_pool(tmp_path, monkeypatch):
|
||||
|
||||
|
||||
def test_save_codex_tokens_syncs_manual_device_code_entries(tmp_path, monkeypatch):
|
||||
"""Re-auth must refresh ``manual:device_code`` entries that are true
|
||||
aliases of the singleton, while leaving INDEPENDENT entries alone.
|
||||
"""Re-auth must also refresh ``manual:device_code`` pool entries.
|
||||
|
||||
Original regression for #33538: a user who hit #33000 before the #33164
|
||||
fix landed would have run ``hermes auth add openai-codex`` as a
|
||||
workaround, leaving a pool entry with ``source="manual:device_code"``.
|
||||
On every subsequent re-auth via setup/model picker, the singleton-seeded
|
||||
``device_code`` entry got refreshed but the ``manual:device_code`` entry
|
||||
stayed stale, recreating the same 401 token_invalidated symptom that
|
||||
#33164 was supposed to fix.
|
||||
Regression for #33538: a user who hit #33000 before the #33164 fix landed
|
||||
would have run ``hermes auth add openai-codex`` as a workaround, leaving
|
||||
a pool entry with ``source="manual:device_code"``. On every subsequent
|
||||
re-auth via setup/model picker, the singleton-seeded ``device_code`` entry
|
||||
got refreshed but the ``manual:device_code`` entry stayed stale, recreating
|
||||
the same 401 token_invalidated symptom that #33164 was supposed to fix.
|
||||
|
||||
Narrowed for #39236: the original fix treated every ``manual:device_code``
|
||||
entry as a singleton-alias and refreshed them all, which silently
|
||||
clobbered independent accounts added via ``hermes auth add openai-codex``.
|
||||
The current behavior refreshes only entries whose access_token matches
|
||||
the *previous* singleton access_token (true legacy aliases), and leaves
|
||||
distinct-token entries alone (independent accounts).
|
||||
An interactive Codex device-code re-auth proves the user owns the ChatGPT
|
||||
account, so it is safe to refresh every device-code-backed entry in the
|
||||
pool — but NOT independent ``manual:api_key`` entries (separate accounts /
|
||||
explicit API keys).
|
||||
"""
|
||||
hermes_home = tmp_path / "hermes"
|
||||
hermes_home.mkdir(parents=True, exist_ok=True)
|
||||
@@ -339,30 +335,16 @@ def test_save_codex_tokens_syncs_manual_device_code_entries(tmp_path, monkeypatc
|
||||
"access_token": "old-at",
|
||||
"refresh_token": "old-rt",
|
||||
},
|
||||
# Legacy alias from the #33000 workaround era — its tokens
|
||||
# match the singleton, so it is a true alias and SHOULD be
|
||||
# refreshed (preserves #33538 behavior).
|
||||
{
|
||||
"id": "legacy-alias",
|
||||
"id": "auth-add",
|
||||
"source": "manual:device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "old-at",
|
||||
"refresh_token": "old-rt",
|
||||
"access_token": "stale-manual-at",
|
||||
"refresh_token": "stale-manual-rt",
|
||||
"last_status": "exhausted",
|
||||
"last_error_code": 401,
|
||||
"last_error_reason": "token_invalidated",
|
||||
},
|
||||
# Independent account from `hermes auth add openai-codex` —
|
||||
# its tokens are distinct from the singleton. Must NOT be
|
||||
# overwritten by a re-auth that targeted a different account
|
||||
# (#39236).
|
||||
{
|
||||
"id": "independent",
|
||||
"source": "manual:device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "independent-at",
|
||||
"refresh_token": "independent-rt",
|
||||
},
|
||||
{
|
||||
"id": "api-key",
|
||||
"source": "manual:api_key",
|
||||
@@ -381,23 +363,18 @@ def test_save_codex_tokens_syncs_manual_device_code_entries(tmp_path, monkeypatc
|
||||
pool = auth["credential_pool"]["openai-codex"]
|
||||
|
||||
# Singleton-seeded device_code entry: refreshed and error markers cleared.
|
||||
seeded = next(e for e in pool if e["id"] == "seeded")
|
||||
seeded = next(e for e in pool if e["source"] == "device_code")
|
||||
assert seeded["access_token"] == "fresh-at"
|
||||
assert seeded["refresh_token"] == "fresh-rt"
|
||||
|
||||
# Legacy alias (tokens matched previous singleton): ALSO refreshed.
|
||||
legacy = next(e for e in pool if e["id"] == "legacy-alias")
|
||||
assert legacy["access_token"] == "fresh-at"
|
||||
assert legacy["refresh_token"] == "fresh-rt"
|
||||
assert legacy["last_refresh"] == "2026-05-28T00:00:00Z"
|
||||
assert legacy["last_status"] is None
|
||||
assert legacy["last_error_code"] is None
|
||||
assert legacy["last_error_reason"] is None
|
||||
|
||||
# Independent manual:device_code entry: NOT overwritten (#39236).
|
||||
independent = next(e for e in pool if e["id"] == "independent")
|
||||
assert independent["access_token"] == "independent-at"
|
||||
assert independent["refresh_token"] == "independent-rt"
|
||||
# manual:device_code entry: ALSO refreshed (the new behavior).
|
||||
manual_dc = next(e for e in pool if e["source"] == "manual:device_code")
|
||||
assert manual_dc["access_token"] == "fresh-at"
|
||||
assert manual_dc["refresh_token"] == "fresh-rt"
|
||||
assert manual_dc["last_refresh"] == "2026-05-28T00:00:00Z"
|
||||
assert manual_dc["last_status"] is None
|
||||
assert manual_dc["last_error_code"] is None
|
||||
assert manual_dc["last_error_reason"] is None
|
||||
|
||||
# manual:api_key entry: untouched — independent credential.
|
||||
api_key = next(e for e in pool if e["source"] == "manual:api_key")
|
||||
@@ -405,333 +382,6 @@ def test_save_codex_tokens_syncs_manual_device_code_entries(tmp_path, monkeypatc
|
||||
assert "refresh_token" not in api_key or api_key.get("refresh_token") is None
|
||||
|
||||
|
||||
def test_save_codex_tokens_does_not_overwrite_independent_manual_entries(tmp_path, monkeypatch):
|
||||
"""Re-auth must NOT overwrite ``manual:device_code`` entries that hold
|
||||
independent token material (different OpenAI/ChatGPT accounts).
|
||||
|
||||
Regression for #39236: ``hermes auth add openai-codex`` for accounts B and C
|
||||
routes through ``_save_codex_tokens`` because the singleton path is the
|
||||
only Codex OAuth save flow. The #33538 fix refreshed every
|
||||
``manual:device_code`` entry on every re-auth, which works fine for the
|
||||
one-account/legacy-workaround case but silently overwrote distinct
|
||||
independent accounts with the latest-authenticated tokens (labels
|
||||
preserved, token material clobbered, status/quota readings then lie).
|
||||
|
||||
The safe invariant: an entry is a singleton-alias only when its current
|
||||
access_token matches the *previous* singleton access_token. Manual
|
||||
entries whose tokens never matched the singleton are independent accounts
|
||||
and must be left alone.
|
||||
"""
|
||||
hermes_home = tmp_path / "hermes"
|
||||
hermes_home.mkdir(parents=True, exist_ok=True)
|
||||
(hermes_home / "auth.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"openai-codex": {
|
||||
# Old singleton tokens — represent "account A" which the user
|
||||
# logged in with via setup originally.
|
||||
"tokens": {"access_token": "acctA-at", "refresh_token": "acctA-rt"},
|
||||
"last_refresh": "2026-01-01T00:00:00Z",
|
||||
"auth_mode": "chatgpt",
|
||||
"label": "account-A",
|
||||
},
|
||||
},
|
||||
"credential_pool": {
|
||||
"openai-codex": [
|
||||
# The seeded singleton mirror of account A.
|
||||
{
|
||||
"id": "seeded",
|
||||
"label": "account-A",
|
||||
"source": "device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "acctA-at",
|
||||
"refresh_token": "acctA-rt",
|
||||
},
|
||||
# Two INDEPENDENT manual entries added later via
|
||||
# ``hermes auth add openai-codex`` (account B and account C).
|
||||
# Each has its OWN distinct token material, unrelated to the
|
||||
# singleton.
|
||||
{
|
||||
"id": "acctB",
|
||||
"label": "account-B",
|
||||
"source": "manual:device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "acctB-at",
|
||||
"refresh_token": "acctB-rt",
|
||||
},
|
||||
{
|
||||
"id": "acctC",
|
||||
"label": "account-C",
|
||||
"source": "manual:device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "acctC-at",
|
||||
"refresh_token": "acctC-rt",
|
||||
},
|
||||
],
|
||||
},
|
||||
}))
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
|
||||
# User re-authenticates account A — fresh device-code login produces new
|
||||
# tokens. The legitimate update is the seeded singleton mirror; the
|
||||
# independent acctB/acctC entries must be untouched.
|
||||
_save_codex_tokens(
|
||||
{"access_token": "acctA-new-at", "refresh_token": "acctA-new-rt"},
|
||||
last_refresh="2026-06-05T00:00:00Z",
|
||||
)
|
||||
|
||||
auth = json.loads((hermes_home / "auth.json").read_text())
|
||||
pool = auth["credential_pool"]["openai-codex"]
|
||||
|
||||
# Singleton-seeded entry: refreshed (legitimate sync).
|
||||
seeded = next(e for e in pool if e["source"] == "device_code")
|
||||
assert seeded["access_token"] == "acctA-new-at"
|
||||
assert seeded["refresh_token"] == "acctA-new-rt"
|
||||
assert seeded["last_refresh"] == "2026-06-05T00:00:00Z"
|
||||
|
||||
# acctB: INDEPENDENT entry — must NOT be overwritten.
|
||||
acctB = next(e for e in pool if e["id"] == "acctB")
|
||||
assert acctB["access_token"] == "acctB-at", (
|
||||
"acctB was clobbered by acctA re-auth (#39236 regression)"
|
||||
)
|
||||
assert acctB["refresh_token"] == "acctB-rt"
|
||||
|
||||
# acctC: INDEPENDENT entry — must NOT be overwritten.
|
||||
acctC = next(e for e in pool if e["id"] == "acctC")
|
||||
assert acctC["access_token"] == "acctC-at", (
|
||||
"acctC was clobbered by acctA re-auth (#39236 regression)"
|
||||
)
|
||||
assert acctC["refresh_token"] == "acctC-rt"
|
||||
|
||||
|
||||
def test_save_codex_tokens_still_refreshes_legacy_manual_alias(tmp_path, monkeypatch):
|
||||
"""The #33538 legacy use case must keep working.
|
||||
|
||||
A user who hit #33000 before the #33164 fix landed might have run
|
||||
``hermes auth add openai-codex`` as a workaround when there was no
|
||||
singleton entry — that created a ``manual:device_code`` pool entry that
|
||||
holds the SAME token material as the (later) singleton. This entry is a
|
||||
true alias of the singleton and SHOULD still be refreshed on subsequent
|
||||
re-auths, otherwise it goes stale and recreates the #33538 symptom.
|
||||
|
||||
The distinguishing signal: a legacy alias has access_token == previous
|
||||
singleton access_token; an independent account does not.
|
||||
"""
|
||||
hermes_home = tmp_path / "hermes"
|
||||
hermes_home.mkdir(parents=True, exist_ok=True)
|
||||
(hermes_home / "auth.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"openai-codex": {
|
||||
"tokens": {"access_token": "shared-at", "refresh_token": "shared-rt"},
|
||||
"last_refresh": "2026-01-01T00:00:00Z",
|
||||
"auth_mode": "chatgpt",
|
||||
},
|
||||
},
|
||||
"credential_pool": {
|
||||
"openai-codex": [
|
||||
{
|
||||
"id": "seeded",
|
||||
"source": "device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "shared-at",
|
||||
"refresh_token": "shared-rt",
|
||||
},
|
||||
{
|
||||
"id": "legacy",
|
||||
"label": "legacy-alias",
|
||||
"source": "manual:device_code",
|
||||
"auth_type": "oauth",
|
||||
# Token material matches the singleton — this is a true
|
||||
# alias from the #33000 workaround era.
|
||||
"access_token": "shared-at",
|
||||
"refresh_token": "shared-rt",
|
||||
"last_status": "exhausted",
|
||||
"last_error_code": 401,
|
||||
"last_error_reason": "token_invalidated",
|
||||
},
|
||||
],
|
||||
},
|
||||
}))
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
|
||||
_save_codex_tokens(
|
||||
{"access_token": "fresh-at", "refresh_token": "fresh-rt"},
|
||||
last_refresh="2026-06-05T00:00:00Z",
|
||||
)
|
||||
|
||||
auth = json.loads((hermes_home / "auth.json").read_text())
|
||||
pool = auth["credential_pool"]["openai-codex"]
|
||||
|
||||
# Singleton: refreshed.
|
||||
seeded = next(e for e in pool if e["source"] == "device_code")
|
||||
assert seeded["access_token"] == "fresh-at"
|
||||
|
||||
# Legacy alias: still refreshed (preserves #33538 fix).
|
||||
legacy = next(e for e in pool if e["id"] == "legacy")
|
||||
assert legacy["access_token"] == "fresh-at"
|
||||
assert legacy["refresh_token"] == "fresh-rt"
|
||||
assert legacy["last_refresh"] == "2026-06-05T00:00:00Z"
|
||||
# Error markers cleared on the refreshed entry.
|
||||
assert legacy["last_status"] is None
|
||||
assert legacy["last_error_code"] is None
|
||||
assert legacy["last_error_reason"] is None
|
||||
|
||||
|
||||
def test_save_codex_tokens_handles_missing_previous_singleton_tokens(tmp_path, monkeypatch):
|
||||
"""First-ever Codex save (no prior singleton tokens) must not crash.
|
||||
|
||||
Edge case: a user has only pool entries (e.g. via direct auth.json edit
|
||||
or a partial state from a corrupted upgrade), no `providers.openai-codex.tokens`
|
||||
block at all. The previous-singleton-tokens guard must handle missing
|
||||
state gracefully — fall back to "no previous tokens", which means no
|
||||
pool entry can be a true alias and only the singleton-seeded entry gets
|
||||
written.
|
||||
"""
|
||||
hermes_home = tmp_path / "hermes"
|
||||
hermes_home.mkdir(parents=True, exist_ok=True)
|
||||
(hermes_home / "auth.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"providers": {},
|
||||
"credential_pool": {
|
||||
"openai-codex": [
|
||||
{
|
||||
"id": "preexisting",
|
||||
"label": "pre-existing-manual",
|
||||
"source": "manual:device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "preexisting-at",
|
||||
"refresh_token": "preexisting-rt",
|
||||
},
|
||||
],
|
||||
},
|
||||
}))
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
|
||||
_save_codex_tokens(
|
||||
{"access_token": "first-at", "refresh_token": "first-rt"},
|
||||
last_refresh="2026-06-05T00:00:00Z",
|
||||
)
|
||||
|
||||
auth = json.loads((hermes_home / "auth.json").read_text())
|
||||
pool = auth["credential_pool"]["openai-codex"]
|
||||
# Pre-existing independent entry with no relationship to a (now-new)
|
||||
# singleton MUST be preserved.
|
||||
pre = next(e for e in pool if e["id"] == "preexisting")
|
||||
assert pre["access_token"] == "preexisting-at"
|
||||
assert pre["refresh_token"] == "preexisting-rt"
|
||||
|
||||
|
||||
def test_save_codex_tokens_alias_match_uses_access_token_only(tmp_path, monkeypatch):
|
||||
"""A manual entry counts as an alias if its access_token matches the
|
||||
previous singleton access_token, regardless of refresh_token presence.
|
||||
|
||||
Some legacy entries (older auth.json schemas, pre-refresh-token versions)
|
||||
have access_token but no refresh_token. These should still be treated as
|
||||
aliases when the access_token matches.
|
||||
"""
|
||||
hermes_home = tmp_path / "hermes"
|
||||
hermes_home.mkdir(parents=True, exist_ok=True)
|
||||
(hermes_home / "auth.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"openai-codex": {
|
||||
"tokens": {"access_token": "shared-at", "refresh_token": "shared-rt"},
|
||||
"auth_mode": "chatgpt",
|
||||
},
|
||||
},
|
||||
"credential_pool": {
|
||||
"openai-codex": [
|
||||
{
|
||||
"id": "alias-no-refresh",
|
||||
"source": "manual:device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "shared-at",
|
||||
# No refresh_token at all — legacy schema.
|
||||
},
|
||||
],
|
||||
},
|
||||
}))
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
|
||||
_save_codex_tokens(
|
||||
{"access_token": "new-at", "refresh_token": "new-rt"},
|
||||
last_refresh="2026-06-05T00:00:00Z",
|
||||
)
|
||||
|
||||
auth = json.loads((hermes_home / "auth.json").read_text())
|
||||
pool = auth["credential_pool"]["openai-codex"]
|
||||
alias = next(e for e in pool if e["id"] == "alias-no-refresh")
|
||||
# Treated as alias → refreshed with new tokens.
|
||||
assert alias["access_token"] == "new-at"
|
||||
assert alias["refresh_token"] == "new-rt"
|
||||
|
||||
|
||||
def test_save_codex_tokens_clears_error_markers_only_on_refreshed_entries(tmp_path, monkeypatch):
|
||||
"""Error markers must be cleared only on entries that were actually
|
||||
refreshed by this re-auth. Independent ``manual:device_code`` entries
|
||||
with their own stale-error markers must be left alone (their stale state
|
||||
is not the current re-auth's business).
|
||||
"""
|
||||
hermes_home = tmp_path / "hermes"
|
||||
hermes_home.mkdir(parents=True, exist_ok=True)
|
||||
(hermes_home / "auth.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"openai-codex": {
|
||||
"tokens": {"access_token": "acctA-at", "refresh_token": "acctA-rt"},
|
||||
"auth_mode": "chatgpt",
|
||||
},
|
||||
},
|
||||
"credential_pool": {
|
||||
"openai-codex": [
|
||||
{
|
||||
"id": "seeded",
|
||||
"source": "device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "acctA-at",
|
||||
"refresh_token": "acctA-rt",
|
||||
"last_status": "exhausted",
|
||||
"last_error_code": 401,
|
||||
},
|
||||
{
|
||||
"id": "acctB",
|
||||
"source": "manual:device_code",
|
||||
"auth_type": "oauth",
|
||||
"access_token": "acctB-at",
|
||||
"refresh_token": "acctB-rt",
|
||||
"last_status": "exhausted",
|
||||
"last_error_code": 429,
|
||||
"last_error_reason": "quota_exhausted",
|
||||
},
|
||||
],
|
||||
},
|
||||
}))
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
|
||||
_save_codex_tokens(
|
||||
{"access_token": "fresh-at", "refresh_token": "fresh-rt"},
|
||||
last_refresh="2026-06-05T00:00:00Z",
|
||||
)
|
||||
|
||||
auth = json.loads((hermes_home / "auth.json").read_text())
|
||||
pool = auth["credential_pool"]["openai-codex"]
|
||||
|
||||
# Singleton: refreshed AND error markers cleared.
|
||||
seeded = next(e for e in pool if e["id"] == "seeded")
|
||||
assert seeded["access_token"] == "fresh-at"
|
||||
assert seeded["last_status"] is None
|
||||
assert seeded["last_error_code"] is None
|
||||
|
||||
# Independent acctB: NOT refreshed AND error markers NOT cleared.
|
||||
# (Its 429 quota state belongs to acctB's own account, not acctA's re-auth.)
|
||||
acctB = next(e for e in pool if e["id"] == "acctB")
|
||||
assert acctB["access_token"] == "acctB-at" # not overwritten
|
||||
assert acctB["last_status"] == "exhausted" # not cleared
|
||||
assert acctB["last_error_code"] == 429
|
||||
assert acctB["last_error_reason"] == "quota_exhausted"
|
||||
|
||||
|
||||
def test_import_codex_cli_tokens(tmp_path, monkeypatch):
|
||||
codex_home = tmp_path / "codex-cli"
|
||||
codex_home.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -397,92 +397,15 @@ def test_auth_add_codex_oauth_persists_pool_entry(tmp_path, monkeypatch):
|
||||
|
||||
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
||||
entries = payload["credential_pool"]["openai-codex"]
|
||||
# The add path now creates a distinct, self-contained ``manual:device_code``
|
||||
# pool entry per account instead of routing through the singleton save path
|
||||
# (which collapsed multiple accounts into the latest login — #39236).
|
||||
entry = next(item for item in entries if item["source"] == "manual:device_code")
|
||||
entry = next(item for item in entries if item["source"] == "device_code")
|
||||
assert payload["active_provider"] == "openai-codex"
|
||||
# No singleton ``providers.openai-codex`` block is written by the add path.
|
||||
assert "openai-codex" not in payload.get("providers", {})
|
||||
assert payload["providers"]["openai-codex"]["tokens"]["access_token"] == token
|
||||
assert entry["label"] == "codex@example.com"
|
||||
assert entry["source"] == "manual:device_code"
|
||||
assert entry["access_token"] == token
|
||||
assert entry["source"] == "device_code"
|
||||
assert entry["refresh_token"] == "refresh-token"
|
||||
assert entry["base_url"] == "https://chatgpt.com/backend-api/codex"
|
||||
|
||||
|
||||
def test_auth_add_codex_oauth_keeps_distinct_pool_accounts(tmp_path, monkeypatch):
|
||||
"""Two ``hermes auth add openai-codex`` runs for different ChatGPT
|
||||
accounts must produce two independent pool entries with distinct tokens.
|
||||
|
||||
Regression for #39236: the add path used to route through the singleton
|
||||
``_save_codex_tokens`` save, so the second login overwrote the first
|
||||
account's singleton-mirrored ``device_code`` entry instead of adding a
|
||||
second independent one. ``hermes auth list`` showed two labels sharing
|
||||
one token pair, and rotation silently always used the latest account.
|
||||
"""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
||||
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
||||
first_token = _jwt_with_email("first-codex@example.com")
|
||||
second_token = _jwt_with_email("second-codex@example.com")
|
||||
logins = iter(
|
||||
[
|
||||
{
|
||||
"tokens": {
|
||||
"access_token": first_token,
|
||||
"refresh_token": "first-refresh-token",
|
||||
},
|
||||
"base_url": "https://chatgpt.com/backend-api/codex",
|
||||
"last_refresh": "2026-03-23T10:00:00Z",
|
||||
},
|
||||
{
|
||||
"tokens": {
|
||||
"access_token": second_token,
|
||||
"refresh_token": "second-refresh-token",
|
||||
},
|
||||
"base_url": "https://chatgpt.com/backend-api/codex",
|
||||
"last_refresh": "2026-03-23T10:05:00Z",
|
||||
},
|
||||
]
|
||||
)
|
||||
monkeypatch.setattr("hermes_cli.auth._codex_device_code_login", lambda: next(logins))
|
||||
|
||||
from hermes_cli.auth_commands import auth_add_command
|
||||
from agent.credential_pool import load_pool
|
||||
|
||||
class _Args:
|
||||
provider = "openai-codex"
|
||||
auth_type = "oauth"
|
||||
api_key = None
|
||||
label = None
|
||||
|
||||
auth_add_command(_Args())
|
||||
auth_add_command(_Args())
|
||||
|
||||
pool = load_pool("openai-codex")
|
||||
entries = pool.entries()
|
||||
|
||||
assert [entry.source for entry in entries] == [
|
||||
"manual:device_code",
|
||||
"manual:device_code",
|
||||
]
|
||||
assert [entry.label for entry in entries] == [
|
||||
"first-codex@example.com",
|
||||
"second-codex@example.com",
|
||||
]
|
||||
assert [entry.access_token for entry in entries] == [first_token, second_token]
|
||||
assert [entry.refresh_token for entry in entries] == [
|
||||
"first-refresh-token",
|
||||
"second-refresh-token",
|
||||
]
|
||||
|
||||
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
||||
# No singleton block — the add path is now pool-only.
|
||||
assert "openai-codex" not in payload.get("providers", {})
|
||||
# First add activated the provider; second add left it as-is.
|
||||
assert payload["active_provider"] == "openai-codex"
|
||||
|
||||
|
||||
def test_auth_add_xai_oauth_sets_active_provider(tmp_path, monkeypatch):
|
||||
"""hermes auth add xai-oauth must write providers singleton and set active_provider.
|
||||
|
||||
@@ -1390,9 +1313,9 @@ def test_auth_add_codex_clears_suppression_marker(tmp_path, monkeypatch):
|
||||
payload = json.loads((hermes_home / "auth.json").read_text())
|
||||
# Suppression marker must be cleared
|
||||
assert "openai-codex" not in payload.get("suppressed_sources", {})
|
||||
# New pool entry must be present (distinct manual:device_code entry — #39236)
|
||||
# New pool entry must be present
|
||||
entries = payload["credential_pool"]["openai-codex"]
|
||||
assert any(e["source"] == "manual:device_code" for e in entries)
|
||||
assert any(e["source"] == "device_code" for e in entries)
|
||||
assert payload["active_provider"] == "openai-codex"
|
||||
|
||||
|
||||
|
||||
@@ -465,7 +465,7 @@ def test_xai_loopback_login_manual_paste_missing_code_raises(monkeypatch):
|
||||
|
||||
|
||||
def test_xai_loopback_login_timeout_falls_back_to_manual_paste(monkeypatch):
|
||||
"""Loopback timeout should accept a bare Grok Build code paste."""
|
||||
"""Loopback timeout should offer the existing manual-paste path."""
|
||||
monkeypatch.setattr(
|
||||
auth_mod, "_xai_oauth_discovery",
|
||||
lambda *_a, **_k: {
|
||||
@@ -523,7 +523,7 @@ def test_xai_loopback_login_timeout_falls_back_to_manual_paste(monkeypatch):
|
||||
captured["prompt_calls"] += 1
|
||||
return {
|
||||
"code": "manual-auth-code",
|
||||
"state": None,
|
||||
"state": captured["state"],
|
||||
"error": None,
|
||||
"error_description": None,
|
||||
}
|
||||
@@ -558,48 +558,6 @@ def test_xai_loopback_login_timeout_falls_back_to_manual_paste(monkeypatch):
|
||||
assert creds["tokens"]["refresh_token"] == "rt-timeout"
|
||||
|
||||
|
||||
def test_xai_wait_for_callback_accepts_ready_stdin_code(monkeypatch):
|
||||
"""Users can paste the Grok Build code while Hermes is still waiting."""
|
||||
class _StubServer:
|
||||
shutdown_called = False
|
||||
close_called = False
|
||||
|
||||
def shutdown(self):
|
||||
self.shutdown_called = True
|
||||
|
||||
def server_close(self):
|
||||
self.close_called = True
|
||||
|
||||
class _StubThread:
|
||||
joined = False
|
||||
|
||||
def join(self, timeout=None):
|
||||
self.joined = True
|
||||
|
||||
server = _StubServer()
|
||||
thread = _StubThread()
|
||||
monkeypatch.setattr(
|
||||
auth_mod,
|
||||
"_read_ready_stdin_line",
|
||||
lambda: "ready-grok-build-code\n",
|
||||
)
|
||||
|
||||
out = auth_mod._xai_wait_for_callback(
|
||||
server,
|
||||
thread,
|
||||
{"code": None, "error": None},
|
||||
timeout_seconds=5,
|
||||
manual_paste_redirect_uri="http://127.0.0.1:56121/callback",
|
||||
)
|
||||
|
||||
assert out["code"] == "ready-grok-build-code"
|
||||
assert out["state"] is None
|
||||
assert out["_manual_paste"] is True
|
||||
assert server.shutdown_called is True
|
||||
assert server.close_called is True
|
||||
assert thread.joined is True
|
||||
|
||||
|
||||
def test_xai_loopback_login_timeout_noninteractive_reraises(monkeypatch):
|
||||
"""Non-interactive stdin must keep the original timeout error."""
|
||||
monkeypatch.setattr(
|
||||
|
||||
@@ -146,12 +146,6 @@ class TestShouldExclude:
|
||||
from hermes_cli.backup import _should_exclude
|
||||
assert not _should_exclude(Path("logs/agent.log"))
|
||||
|
||||
def test_includes_nested_hermes_agent_in_skills(self):
|
||||
"""skills/autonomous-ai-agents/hermes-agent/ must NOT be excluded —
|
||||
only the root-level hermes-agent/ repo is skipped."""
|
||||
from hermes_cli.backup import _should_exclude
|
||||
assert not _should_exclude(Path("skills/autonomous-ai-agents/hermes-agent/SKILL.md"))
|
||||
assert not _should_exclude(Path("skills/autonomous-ai-agents/hermes-agent/sub/item.txt"))
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backup tests
|
||||
@@ -192,66 +186,6 @@ class TestBackup:
|
||||
# Skins
|
||||
assert "skins/cyber.yaml" in names
|
||||
|
||||
def test_db_snapshots_staged_beside_output_zip(self, tmp_path, monkeypatch):
|
||||
"""SQLite staging temp files must be created on the output zip's
|
||||
filesystem (dir=out_path.parent), NOT the system /tmp default — a
|
||||
small tmpfs there silently drops large DBs from the backup (#35376)."""
|
||||
hermes_home = tmp_path / ".hermes"
|
||||
hermes_home.mkdir()
|
||||
_make_hermes_tree(hermes_home)
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
|
||||
out_dir = tmp_path / "external-drive"
|
||||
out_dir.mkdir()
|
||||
out_zip = out_dir / "backup.zip"
|
||||
args = Namespace(output=str(out_zip))
|
||||
|
||||
import hermes_cli.backup as backup_mod
|
||||
staged_dirs = []
|
||||
real_ntf = backup_mod.tempfile.NamedTemporaryFile
|
||||
|
||||
def _spy(*a, **kw):
|
||||
staged_dirs.append(kw.get("dir"))
|
||||
return real_ntf(*a, **kw)
|
||||
|
||||
monkeypatch.setattr(backup_mod.tempfile, "NamedTemporaryFile", _spy)
|
||||
backup_mod.run_backup(args)
|
||||
|
||||
# At least one .db was staged, and every staging call targeted the
|
||||
# output zip's directory rather than the system temp default.
|
||||
assert staged_dirs, "no SQLite snapshot was staged"
|
||||
assert all(d == str(out_dir) for d in staged_dirs), staged_dirs
|
||||
|
||||
def test_pre_update_db_snapshots_staged_beside_output_zip(self, tmp_path, monkeypatch):
|
||||
"""The pre-update/pre-migration zip path (_write_full_zip_backup) must
|
||||
also stage SQLite snapshots beside its output zip, not in /tmp."""
|
||||
hermes_home = tmp_path / ".hermes"
|
||||
hermes_home.mkdir()
|
||||
_make_hermes_tree(hermes_home)
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
|
||||
out_zip = hermes_home / "backups" / "pre-update-test.zip"
|
||||
out_zip.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
import hermes_cli.backup as backup_mod
|
||||
staged_dirs = []
|
||||
real_ntf = backup_mod.tempfile.NamedTemporaryFile
|
||||
|
||||
def _spy(*a, **kw):
|
||||
staged_dirs.append(kw.get("dir"))
|
||||
return real_ntf(*a, **kw)
|
||||
|
||||
monkeypatch.setattr(backup_mod.tempfile, "NamedTemporaryFile", _spy)
|
||||
result = backup_mod._write_full_zip_backup(out_zip, hermes_home)
|
||||
|
||||
assert result is not None
|
||||
assert staged_dirs, "no SQLite snapshot was staged"
|
||||
assert all(d == str(out_zip.parent) for d in staged_dirs), staged_dirs
|
||||
|
||||
def test_excludes_hermes_agent(self, tmp_path, monkeypatch):
|
||||
"""Backup does NOT include hermes-agent/ directory."""
|
||||
hermes_home = tmp_path / ".hermes"
|
||||
@@ -272,37 +206,6 @@ class TestBackup:
|
||||
agent_files = [n for n in names if "hermes-agent" in n]
|
||||
assert agent_files == [], f"hermes-agent files leaked into backup: {agent_files}"
|
||||
|
||||
def test_includes_nested_hermes_agent_in_skills(self, tmp_path, monkeypatch):
|
||||
"""Backup includes skills/.../hermes-agent/ but NOT root hermes-agent/."""
|
||||
hermes_home = tmp_path / ".hermes"
|
||||
hermes_home.mkdir()
|
||||
_make_hermes_tree(hermes_home)
|
||||
|
||||
# Add a nested hermes-agent directory inside skills (like the real layout)
|
||||
nested = hermes_home / "skills" / "autonomous-ai-agents" / "hermes-agent"
|
||||
nested.mkdir(parents=True)
|
||||
(nested / "SKILL.md").write_text("# Hermes Agent Skill\n")
|
||||
(nested / "sub").mkdir()
|
||||
(nested / "sub" / "item.txt").write_text("nested content\n")
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
|
||||
out_zip = tmp_path / "backup.zip"
|
||||
args = Namespace(output=str(out_zip))
|
||||
|
||||
from hermes_cli.backup import run_backup
|
||||
run_backup(args)
|
||||
|
||||
with zipfile.ZipFile(out_zip, "r") as zf:
|
||||
names = zf.namelist()
|
||||
# Root hermes-agent must be excluded
|
||||
root_agent = [n for n in names if n.startswith("hermes-agent/")]
|
||||
assert root_agent == [], f"root hermes-agent leaked: {root_agent}"
|
||||
# Nested skill hermes-agent must be included
|
||||
assert "skills/autonomous-ai-agents/hermes-agent/SKILL.md" in names
|
||||
assert "skills/autonomous-ai-agents/hermes-agent/sub/item.txt" in names
|
||||
|
||||
def test_excludes_pycache(self, tmp_path, monkeypatch):
|
||||
"""Backup does NOT include __pycache__ dirs."""
|
||||
hermes_home = tmp_path / ".hermes"
|
||||
|
||||
@@ -167,36 +167,3 @@ def test_build_welcome_banner_disabled_mcp_shows_disabled_not_failed():
|
||||
assert "broken" in output
|
||||
assert "failed" in output
|
||||
|
||||
|
||||
def test_build_welcome_banner_configured_mcp_is_not_failed():
|
||||
"""A configured MCP server with no connection attempt yet is not a failure."""
|
||||
with (
|
||||
patch.object(model_tools, "check_tool_availability", return_value=(["web"], [])),
|
||||
patch.object(banner, "get_available_skills", return_value={}),
|
||||
patch.object(banner, "get_update_result", return_value=None),
|
||||
patch.object(
|
||||
tools.mcp_tool,
|
||||
"get_mcp_status",
|
||||
return_value=[
|
||||
{
|
||||
"name": "docker-profile",
|
||||
"transport": "stdio",
|
||||
"tools": 0,
|
||||
"connected": False,
|
||||
"disabled": False,
|
||||
"status": "configured",
|
||||
},
|
||||
],
|
||||
),
|
||||
):
|
||||
console = Console(record=True, force_terminal=False, color_system=None, width=160)
|
||||
banner.build_welcome_banner(
|
||||
console=console, model="anthropic/test-model", cwd="/tmp/project",
|
||||
tools=[{"function": {"name": "read_file"}}],
|
||||
get_toolset_for_tool=lambda n: "file",
|
||||
)
|
||||
|
||||
output = console.export_text()
|
||||
assert "docker-profile" in output
|
||||
assert "configured" in output
|
||||
assert "failed" not in output
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
from cli import HermesCLI
|
||||
from hermes_cli.active_sessions import (
|
||||
active_session_registry_snapshot,
|
||||
try_acquire_active_session,
|
||||
)
|
||||
|
||||
|
||||
def test_cli_claim_active_session_respects_global_limit(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
|
||||
cfg = {"max_concurrent_sessions": 1}
|
||||
held, message = try_acquire_active_session(
|
||||
session_id="held-session",
|
||||
surface="tui",
|
||||
config=cfg,
|
||||
)
|
||||
assert message is None
|
||||
assert held is not None
|
||||
|
||||
cli = object.__new__(HermesCLI)
|
||||
cli.session_id = "new-cli-session"
|
||||
cli.config = cfg
|
||||
cli._active_session_lease = None
|
||||
printed: list[str] = []
|
||||
cli._console_print = lambda text: printed.append(text)
|
||||
|
||||
try:
|
||||
assert cli._claim_active_session("cli") is False
|
||||
assert printed == [
|
||||
"[bold red]Hermes is at the active session limit (1/1). "
|
||||
"Try again when another session finishes.[/]"
|
||||
]
|
||||
|
||||
held.release()
|
||||
|
||||
assert cli._claim_active_session("cli") is True
|
||||
assert [entry["session_id"] for entry in active_session_registry_snapshot()] == [
|
||||
"new-cli-session"
|
||||
]
|
||||
finally:
|
||||
held.release()
|
||||
cli._release_active_session()
|
||||
@@ -133,7 +133,7 @@ def test_model_command_uses_runtime_access_token_for_codex_list(monkeypatch):
|
||||
captured["access_token"] = access_token
|
||||
return ["gpt-5.2-codex", "gpt-5.2"]
|
||||
|
||||
def _fake_prompt_model_selection(model_ids, current_model="", **_kwargs):
|
||||
def _fake_prompt_model_selection(model_ids, current_model=""):
|
||||
captured["model_ids"] = list(model_ids)
|
||||
captured["current_model"] = current_model
|
||||
return None
|
||||
@@ -181,7 +181,7 @@ def test_model_command_prompts_to_reuse_or_reauthenticate_codex_session(monkeypa
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth._prompt_model_selection",
|
||||
lambda model_ids, current_model="", **_kwargs: None,
|
||||
lambda model_ids, current_model="": None,
|
||||
)
|
||||
|
||||
_model_flow_openai_codex({}, current_model="gpt-5.4")
|
||||
@@ -219,7 +219,7 @@ def test_model_command_uses_existing_codex_session_without_relogin(monkeypatch):
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth._prompt_model_selection",
|
||||
lambda model_ids, current_model="", **_kwargs: None,
|
||||
lambda model_ids, current_model="": None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth._login_openai_codex",
|
||||
|
||||
@@ -336,25 +336,19 @@ class TestSlackNativeSlashes:
|
||||
)
|
||||
|
||||
def test_includes_aliases_as_first_class_slashes(self):
|
||||
"""Aliases (/btw, /bg, …) must be registered as standalone
|
||||
"""Aliases (/btw, /bg, /reset) must be registered as standalone
|
||||
slashes — this is the whole point of native-slashes parity.
|
||||
|
||||
Asserts the contract (aliases are surfaced as first-class slashes),
|
||||
not a specific alias's survival of Slack's 50-slash clamp — which alias
|
||||
lands last shifts whenever a canonical command is added. Only the
|
||||
explicitly pinned ``_SLACK_PRIORITY_ALIASES`` are guaranteed slots;
|
||||
every other alias (e.g. ``reset``) may be clamped once the registry
|
||||
fills the cap — canonical commands win the contest, and clamped
|
||||
aliases stay reachable via ``/hermes <alias>``.
|
||||
"""
|
||||
slashes = slack_native_slashes()
|
||||
names = {n for n, _d, _h in slashes}
|
||||
# The pinned priority aliases are guaranteed to survive the clamp.
|
||||
Note: Slack's manifest hard-caps slash commands at 50
|
||||
(``_SLACK_MAX_SLASH_COMMANDS``). Canonical names win slots first,
|
||||
then aliases, so the lowest-priority aliases can be clamped off
|
||||
once the registry fills the cap (e.g. ``/q`` once ``/version``
|
||||
landed). The surviving aliases below still prove alias parity;
|
||||
anything dropped remains reachable via ``/hermes <command>``."""
|
||||
names = {n for n, _d, _h in slack_native_slashes()}
|
||||
assert "btw" in names
|
||||
assert "bg" in names
|
||||
# And at least one alias is surfaced as an alias entry (description
|
||||
# carries the "Alias for /…" marker), proving the alias pass ran.
|
||||
assert any(d.startswith("Alias for /") for _n, d, _h in slashes)
|
||||
assert "reset" in names
|
||||
|
||||
def test_telegram_parity(self):
|
||||
"""Every Telegram bot command must be registerable on Slack too.
|
||||
@@ -693,169 +687,6 @@ class TestSubcommandCompletion:
|
||||
completions = _completions(SlashCommandCompleter(), "/help ")
|
||||
assert completions == []
|
||||
|
||||
def test_tools_subcommand_completion(self):
|
||||
"""`/tools ` should suggest list, disable, enable."""
|
||||
completions = _completions(SlashCommandCompleter(), "/tools ")
|
||||
texts = {c.text for c in completions}
|
||||
assert texts == {"list", "disable", "enable"}
|
||||
|
||||
def test_tools_subcommand_prefix_filters(self):
|
||||
completions = _completions(SlashCommandCompleter(), "/tools en")
|
||||
texts = {c.text for c in completions}
|
||||
assert texts == {"enable"}
|
||||
|
||||
def test_tools_enable_completes_toolset_names(self, monkeypatch):
|
||||
"""`/tools enable ` should suggest currently-disabled toolsets."""
|
||||
from hermes_cli import commands as commands_mod
|
||||
|
||||
# `web` is enabled, `spotify` is disabled — enabling should only offer
|
||||
# the disabled ones.
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_platform_tools",
|
||||
lambda *_a, **_k: {"web", "file"},
|
||||
)
|
||||
monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_plugin_toolset_keys",
|
||||
lambda: set(),
|
||||
)
|
||||
|
||||
completions = _completions(SlashCommandCompleter(), "/tools enable ")
|
||||
texts = {c.text for c in completions}
|
||||
# Should include disabled toolsets, exclude already-enabled ones.
|
||||
assert "web" not in texts
|
||||
assert "file" not in texts
|
||||
assert "spotify" in texts
|
||||
|
||||
def test_tools_disable_completes_enabled_toolsets_only(self, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_platform_tools",
|
||||
lambda *_a, **_k: {"web", "file"},
|
||||
)
|
||||
monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_plugin_toolset_keys",
|
||||
lambda: set(),
|
||||
)
|
||||
|
||||
completions = _completions(SlashCommandCompleter(), "/tools disable ")
|
||||
texts = {c.text for c in completions}
|
||||
# Should include enabled toolsets, exclude disabled ones.
|
||||
assert texts == {"web", "file"}
|
||||
|
||||
def test_tools_enable_partial_filters(self, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_platform_tools",
|
||||
lambda *_a, **_k: set(),
|
||||
)
|
||||
monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_plugin_toolset_keys",
|
||||
lambda: set(),
|
||||
)
|
||||
|
||||
completions = _completions(SlashCommandCompleter(), "/tools enable sp")
|
||||
texts = {c.text for c in completions}
|
||||
assert texts == {"spotify"}
|
||||
|
||||
def test_tools_enable_skips_already_listed(self, monkeypatch):
|
||||
"""If the user already typed a name, don't suggest it again."""
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_platform_tools",
|
||||
lambda *_a, **_k: set(),
|
||||
)
|
||||
monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_plugin_toolset_keys",
|
||||
lambda: set(),
|
||||
)
|
||||
|
||||
completions = _completions(SlashCommandCompleter(), "/tools enable spotify ")
|
||||
texts = {c.text for c in completions}
|
||||
assert "spotify" not in texts
|
||||
|
||||
def test_tools_suggests_mcp_server_prefixes(self, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_platform_tools",
|
||||
lambda *_a, **_k: set(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.config.load_config",
|
||||
lambda: {"mcp_servers": {"github": {}, "linear": {}}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config._get_plugin_toolset_keys",
|
||||
lambda: set(),
|
||||
)
|
||||
|
||||
completions = _completions(SlashCommandCompleter(), "/tools enable git")
|
||||
texts = {c.text for c in completions}
|
||||
assert "github:" in texts
|
||||
|
||||
def _fake_gateway(self, monkeypatch, platforms):
|
||||
"""Patch load_gateway_config with a fake whose connected platforms are
|
||||
the keys of `platforms` (name -> home as None or a (chat_id, name) tuple).
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
enums = {name: SimpleNamespace(value=name) for name in platforms}
|
||||
homes = {
|
||||
name: (None if home is None else SimpleNamespace(chat_id=home[0], name=home[1]))
|
||||
for name, home in platforms.items()
|
||||
}
|
||||
fake = SimpleNamespace(
|
||||
get_connected_platforms=lambda: list(enums.values()),
|
||||
get_home_channel=lambda p: homes[p.value],
|
||||
)
|
||||
monkeypatch.setattr("gateway.config.load_gateway_config", lambda: fake)
|
||||
|
||||
def test_handoff_completes_connected_platforms(self, monkeypatch):
|
||||
"""`/handoff ` offers connected platforms, with or without a home channel."""
|
||||
self._fake_gateway(
|
||||
monkeypatch,
|
||||
{
|
||||
"telegram": ("123", "Me"),
|
||||
"discord": None, # no home channel yet -> still listed
|
||||
},
|
||||
)
|
||||
|
||||
texts = {c.text for c in _completions(SlashCommandCompleter(), "/handoff ")}
|
||||
assert texts == {"telegram", "discord"}
|
||||
|
||||
def test_handoff_filters_by_prefix(self, monkeypatch):
|
||||
self._fake_gateway(
|
||||
monkeypatch,
|
||||
{
|
||||
"telegram": ("1", "H"),
|
||||
"signal": ("2", "H"),
|
||||
},
|
||||
)
|
||||
|
||||
texts = {c.text for c in _completions(SlashCommandCompleter(), "/handoff te")}
|
||||
assert texts == {"telegram"}
|
||||
|
||||
def test_handoff_no_completion_after_platform_chosen(self, monkeypatch):
|
||||
self._fake_gateway(monkeypatch, {"telegram": ("1", "H")})
|
||||
assert _completions(SlashCommandCompleter(), "/handoff telegram ") == []
|
||||
|
||||
def test_handoff_completion_swallows_config_errors(self, monkeypatch):
|
||||
def _boom():
|
||||
raise RuntimeError("no gateway config")
|
||||
|
||||
monkeypatch.setattr("gateway.config.load_gateway_config", _boom)
|
||||
assert _completions(SlashCommandCompleter(), "/handoff ") == []
|
||||
|
||||
def test_personality_completes_configured_personalities(self):
|
||||
"""`/personality ` lists real personalities, not just `none`.
|
||||
|
||||
Regression: the completer read load_config().agent.personalities, a path
|
||||
that never exists, so it always came back empty. It must resolve from the
|
||||
CLI config the runtime actually applies (which ships built-ins).
|
||||
"""
|
||||
texts = {c.text for c in _completions(SlashCommandCompleter(), "/personality ")}
|
||||
assert "none" in texts
|
||||
assert len(texts) > 1
|
||||
|
||||
|
||||
# ── Ghost text (SlashCommandAutoSuggest) ────────────────────────────────
|
||||
|
||||
|
||||
@@ -292,25 +292,6 @@ class TestSaveEnvValueSecure:
|
||||
env_mode = (tmp_path / ".env").stat().st_mode & 0o777
|
||||
assert env_mode == 0o600
|
||||
|
||||
def test_save_env_value_preserves_existing_file_mode_on_posix(self, tmp_path):
|
||||
"""Regression for #31518: pre-existing .env mode (e.g. 0640 for a
|
||||
Docker bind-mount that the operator chose) survives subsequent
|
||||
writes. Previously _secure_file ran unconditionally after the
|
||||
mode-restore branch and re-tightened to 0600.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
return
|
||||
|
||||
env_path = tmp_path / ".env"
|
||||
env_path.write_text("EXISTING=value\n")
|
||||
os.chmod(env_path, 0o640)
|
||||
|
||||
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
|
||||
save_env_value("TENOR_API_KEY", "sk-test-secret")
|
||||
|
||||
env_mode = env_path.stat().st_mode & 0o777
|
||||
assert env_mode == 0o640, f"expected 0o640, got {oct(env_mode)}"
|
||||
|
||||
|
||||
class TestRemoveEnvValue:
|
||||
def test_removes_key_from_env_file(self, tmp_path):
|
||||
@@ -354,28 +335,6 @@ class TestRemoveEnvValue:
|
||||
remove_env_value("ORPHAN_KEY")
|
||||
assert "ORPHAN_KEY" not in os.environ
|
||||
|
||||
def test_remove_env_value_preserves_existing_file_mode_on_posix(self, tmp_path):
|
||||
"""Regression: pre-existing .env mode (e.g. 0640 for a Docker
|
||||
bind-mount the operator chose) survives a remove just as it does a
|
||||
save. Previously _secure_file ran unconditionally after the
|
||||
mode-restore branch and re-tightened to 0600 — the same bug fixed
|
||||
in save_env_value (#33699), in the sibling remove path.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
return
|
||||
|
||||
env_path = tmp_path / ".env"
|
||||
env_path.write_text("KEEP=value\nDROP=gone\n")
|
||||
os.chmod(env_path, 0o640)
|
||||
|
||||
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path), "DROP": "gone"}):
|
||||
removed = remove_env_value("DROP")
|
||||
|
||||
assert removed is True
|
||||
assert "DROP" not in env_path.read_text()
|
||||
env_mode = env_path.stat().st_mode & 0o777
|
||||
assert env_mode == 0o640, f"expected 0o640, got {oct(env_mode)}"
|
||||
|
||||
|
||||
class TestSaveConfigAtomicity:
|
||||
"""Verify save_config uses atomic writes (tempfile + os.replace)."""
|
||||
@@ -1097,50 +1056,3 @@ class TestEnvWriteDenylist:
|
||||
# But the write path still refuses to update it
|
||||
with pytest.raises(ValueError, match="denylist"):
|
||||
save_env_value("LD_PRELOAD", "/tmp/evil.so")
|
||||
|
||||
|
||||
class TestWriteApprovalMigration:
|
||||
"""Version 28→29 renames memory/skills write_mode → write_approval (bool).
|
||||
|
||||
Only an explicit ``approve`` carried gating intent and maps to ``True``;
|
||||
``on``/``off``/unset map to ``False`` (gate off). The old ``write_mode`` key
|
||||
is removed. Only a persisted key is rewritten — never invented.
|
||||
"""
|
||||
|
||||
def _write(self, tmp_path, body: str):
|
||||
(tmp_path / "config.yaml").write_text(body)
|
||||
|
||||
def test_approve_maps_to_true(self, tmp_path):
|
||||
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
|
||||
self._write(tmp_path,
|
||||
"_config_version: 28\nmemory:\n write_mode: approve\n"
|
||||
"skills:\n write_mode: approve\n")
|
||||
migrate_config(interactive=False, quiet=True)
|
||||
raw = yaml.safe_load((tmp_path / "config.yaml").read_text())
|
||||
assert raw["memory"]["write_approval"] is True
|
||||
assert raw["skills"]["write_approval"] is True
|
||||
assert "write_mode" not in raw["memory"]
|
||||
assert "write_mode" not in raw["skills"]
|
||||
|
||||
def test_on_and_off_map_to_false(self, tmp_path):
|
||||
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
|
||||
# YAML 1.1 parses bare on/off as bools — write_mode could be either
|
||||
# the string or the bool; both legacy "not gating" values → False.
|
||||
self._write(tmp_path,
|
||||
"_config_version: 28\nmemory:\n write_mode: 'on'\n"
|
||||
"skills:\n write_mode: 'off'\n")
|
||||
migrate_config(interactive=False, quiet=True)
|
||||
raw = yaml.safe_load((tmp_path / "config.yaml").read_text())
|
||||
assert raw["memory"]["write_approval"] is False
|
||||
assert raw["skills"]["write_approval"] is False
|
||||
|
||||
def test_unset_key_defaults_to_false(self, tmp_path):
|
||||
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
|
||||
self._write(tmp_path, "_config_version: 28\nmemory:\n memory_enabled: true\n")
|
||||
migrate_config(interactive=False, quiet=True)
|
||||
raw = yaml.safe_load((tmp_path / "config.yaml").read_text())
|
||||
# No write_mode was persisted, so the rename is a no-op; the missing-
|
||||
# field pass then seeds the default (False = gate off). Either way the
|
||||
# gate ends up off and there's no leftover write_mode key.
|
||||
assert raw["memory"].get("write_approval", False) is False
|
||||
assert "write_mode" not in raw.get("memory", {})
|
||||
|
||||
@@ -55,6 +55,7 @@ class TestCronCommandLifecycle:
|
||||
repeat=None,
|
||||
skill=None,
|
||||
skills=["maps", "blogwatcher"],
|
||||
profile="default",
|
||||
clear_skills=False,
|
||||
)
|
||||
)
|
||||
@@ -63,6 +64,7 @@ class TestCronCommandLifecycle:
|
||||
assert updated["name"] == "Edited Job"
|
||||
assert updated["prompt"] == "Revised prompt"
|
||||
assert updated["schedule_display"] == "every 120m"
|
||||
assert updated["profile"] == "default"
|
||||
|
||||
cron_command(
|
||||
Namespace(
|
||||
@@ -75,12 +77,14 @@ class TestCronCommandLifecycle:
|
||||
repeat=None,
|
||||
skill=None,
|
||||
skills=None,
|
||||
profile="",
|
||||
clear_skills=True,
|
||||
)
|
||||
)
|
||||
cleared = get_job(job["id"])
|
||||
assert cleared["skills"] == []
|
||||
assert cleared["skill"] is None
|
||||
assert cleared["profile"] is None
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert "Updated job" in out
|
||||
@@ -96,6 +100,7 @@ class TestCronCommandLifecycle:
|
||||
repeat=None,
|
||||
skill=None,
|
||||
skills=["blogwatcher", "maps"],
|
||||
profile="default",
|
||||
)
|
||||
)
|
||||
out = capsys.readouterr().out
|
||||
@@ -105,6 +110,7 @@ class TestCronCommandLifecycle:
|
||||
assert len(jobs) == 1
|
||||
assert jobs[0]["skills"] == ["blogwatcher", "maps"]
|
||||
assert jobs[0]["name"] == "Skill combo"
|
||||
assert jobs[0]["profile"] == "default"
|
||||
|
||||
def test_list_does_not_crash_when_repeat_is_null(self, tmp_cron_dir, capsys):
|
||||
"""A one-shot job can be persisted with ``"repeat": null``. `cron
|
||||
|
||||
@@ -201,91 +201,6 @@ class TestWebhookEndpoints:
|
||||
r = self.client.post("/api/webhooks", json={"name": "gh", "deliver": "log"})
|
||||
assert r.status_code == 400
|
||||
|
||||
def test_enable_platform_starts_gateway_restart(self, monkeypatch):
|
||||
import hermes_cli.web_server as ws
|
||||
from hermes_cli.config import load_config
|
||||
|
||||
ws._ACTION_PROCS.pop("gateway-restart", None)
|
||||
restart_calls = []
|
||||
|
||||
class FakeRestartProc:
|
||||
pid = 4242
|
||||
|
||||
def fake_spawn_action(subcommand, name):
|
||||
restart_calls.append((subcommand, name))
|
||||
return FakeRestartProc()
|
||||
|
||||
monkeypatch.setattr(ws, "_spawn_hermes_action", fake_spawn_action)
|
||||
|
||||
r = self.client.post("/api/webhooks/enable")
|
||||
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {
|
||||
"ok": True,
|
||||
"platform": "webhook",
|
||||
"enabled": True,
|
||||
"needs_restart": False,
|
||||
"restart_started": True,
|
||||
"restart_action": "gateway-restart",
|
||||
"restart_pid": 4242,
|
||||
}
|
||||
assert restart_calls == [(["gateway", "restart"], "gateway-restart")]
|
||||
assert load_config()["platforms"]["webhook"]["enabled"] is True
|
||||
assert self.client.get("/api/webhooks").json()["enabled"] is True
|
||||
|
||||
def test_enable_platform_reports_restart_failure_after_save(self, monkeypatch):
|
||||
import hermes_cli.web_server as ws
|
||||
from hermes_cli.config import load_config
|
||||
|
||||
ws._ACTION_PROCS.pop("gateway-restart", None)
|
||||
|
||||
def fail_spawn_action(subcommand, name):
|
||||
assert subcommand == ["gateway", "restart"]
|
||||
assert name == "gateway-restart"
|
||||
raise RuntimeError("supervisor unavailable")
|
||||
|
||||
monkeypatch.setattr(ws, "_spawn_hermes_action", fail_spawn_action)
|
||||
|
||||
r = self.client.post("/api/webhooks/enable")
|
||||
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["ok"] is True
|
||||
assert data["platform"] == "webhook"
|
||||
assert data["enabled"] is True
|
||||
assert data["needs_restart"] is True
|
||||
assert data["restart_started"] is False
|
||||
assert "supervisor unavailable" in data["restart_error"]
|
||||
assert load_config()["platforms"]["webhook"]["enabled"] is True
|
||||
|
||||
def test_enable_platform_reuses_inflight_gateway_restart(self, monkeypatch):
|
||||
import hermes_cli.web_server as ws
|
||||
from hermes_cli.config import load_config
|
||||
|
||||
ws._ACTION_PROCS.pop("gateway-restart", None)
|
||||
|
||||
class FakeRunningProc:
|
||||
pid = 5151
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setitem(ws._ACTION_PROCS, "gateway-restart", FakeRunningProc())
|
||||
|
||||
def fail_spawn_action(subcommand, name):
|
||||
raise AssertionError("must not spawn a second concurrent restart")
|
||||
|
||||
monkeypatch.setattr(ws, "_spawn_hermes_action", fail_spawn_action)
|
||||
|
||||
r = self.client.post("/api/webhooks/enable")
|
||||
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["needs_restart"] is False
|
||||
assert data["restart_started"] is True
|
||||
assert data["restart_pid"] == 5151
|
||||
assert load_config()["platforms"]["webhook"]["enabled"] is True
|
||||
|
||||
|
||||
class TestOpsEndpoints:
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -707,10 +622,6 @@ class TestAdminEndpointsAuthGate:
|
||||
resp = self.client.get(path)
|
||||
assert resp.status_code in (401, 403)
|
||||
|
||||
def test_webhooks_enable_post_gated(self):
|
||||
resp = self.client.post("/api/webhooks/enable")
|
||||
assert resp.status_code in (401, 403)
|
||||
|
||||
|
||||
class TestUpdateCheckEndpoint:
|
||||
"""``GET /api/hermes/update/check`` reports availability without applying.
|
||||
@@ -790,37 +701,6 @@ class TestUpdateCheckEndpoint:
|
||||
assert body["update_available"] is False
|
||||
assert body["message"]
|
||||
|
||||
def test_git_behind_includes_commits(self, monkeypatch):
|
||||
import hermes_cli.web_server as ws
|
||||
import hermes_cli.banner as banner
|
||||
|
||||
monkeypatch.setattr(ws, "detect_install_method", lambda *a, **k: "git")
|
||||
monkeypatch.setattr(banner, "check_for_updates", lambda: 3)
|
||||
monkeypatch.setattr(
|
||||
ws,
|
||||
"_recent_upstream_commits",
|
||||
lambda n=20: [
|
||||
{"sha": "abc1234", "summary": "feat: x", "author": "a", "at": 1},
|
||||
],
|
||||
)
|
||||
|
||||
body = self.client.get("/api/hermes/update/check").json()
|
||||
# The desktop overlay renders this as the "what's changed" list.
|
||||
assert isinstance(body["commits"], list)
|
||||
assert body["commits"][0]["sha"] == "abc1234"
|
||||
assert body["commits"][0]["summary"] == "feat: x"
|
||||
|
||||
def test_up_to_date_omits_commits(self, monkeypatch):
|
||||
import hermes_cli.web_server as ws
|
||||
import hermes_cli.banner as banner
|
||||
|
||||
monkeypatch.setattr(ws, "detect_install_method", lambda *a, **k: "git")
|
||||
monkeypatch.setattr(banner, "check_for_updates", lambda: 0)
|
||||
|
||||
body = self.client.get("/api/hermes/update/check").json()
|
||||
# No commits list when there's nothing to show (additive, non-breaking).
|
||||
assert body.get("commits", []) == []
|
||||
|
||||
|
||||
class TestDebugShareEndpoint:
|
||||
"""POST /api/ops/debug-share returns the paste URLs synchronously so the
|
||||
@@ -1042,3 +922,4 @@ class TestToolsConfigEndpoints:
|
||||
kwargs["json"] = payload
|
||||
r = fn(path, **kwargs)
|
||||
assert r.status_code == 401, f"{method} {path} not gated"
|
||||
|
||||
|
||||
@@ -191,111 +191,6 @@ def test_full_login_round_trip_unlocks_gated_api(gated_app):
|
||||
)
|
||||
|
||||
|
||||
def _complete_stub_login(client) -> None:
|
||||
"""Walk the stub OAuth round trip so ``client`` carries a valid session.
|
||||
|
||||
TestClient persists Set-Cookie across calls, so after this returns the
|
||||
client's cookie jar holds ``hermes_session_at`` / ``hermes_session_rt``
|
||||
and subsequent gated requests authenticate.
|
||||
"""
|
||||
r1 = client.get("/auth/login?provider=stub", follow_redirects=False)
|
||||
assert r1.status_code == 302
|
||||
state = r1.headers["location"].split("state=")[1]
|
||||
r2 = client.get(
|
||||
f"/auth/callback?code=stub_code&state={state}",
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert r2.status_code == 302
|
||||
|
||||
|
||||
def test_gated_require_token_endpoint_accepts_cookie_session(gated_app):
|
||||
"""Regression: ``_require_token`` endpoints must work under the OAuth gate.
|
||||
|
||||
In gated mode the legacy ``_SESSION_TOKEN`` is NOT injected into the SPA
|
||||
(it authenticates with the session cookie). Endpoints that call
|
||||
``_require_token`` directly — plugin install/enable/disable,
|
||||
``/api/dashboard/plugins/hub``, and others — used to re-check the absent
|
||||
token and 401 every cookie-authenticated request, making them permanently
|
||||
unreachable behind the gate (the dashboard surfaced a
|
||||
``401: {"detail":"Unauthorized"}`` popup on plugin install). The fix makes
|
||||
``_require_token`` defer to the gate, which has already verified the cookie
|
||||
and attached ``request.state.session`` before the handler runs.
|
||||
|
||||
We POST a deliberately invalid plugin identifier: a passing auth layer
|
||||
lets the request reach the handler, which rejects the identifier with a
|
||||
400. The assertion is simply "not 401" — proving auth succeeded without
|
||||
coupling to the validation message.
|
||||
"""
|
||||
_complete_stub_login(gated_app)
|
||||
r = gated_app.post(
|
||||
"/api/dashboard/agent-plugins/install",
|
||||
json={"identifier": "definitely not a valid identifier",
|
||||
"force": False, "enable": False},
|
||||
)
|
||||
assert r.status_code != 401, (
|
||||
"A _require_token endpoint 401'd a cookie-authenticated request under "
|
||||
f"the OAuth gate (the install-popup bug). Body: {r.text}"
|
||||
)
|
||||
# And specifically: it reached the handler's own validation.
|
||||
assert r.status_code == 400, (
|
||||
f"Expected the install handler's 400 (bad identifier), got "
|
||||
f"{r.status_code}: {r.text}"
|
||||
)
|
||||
|
||||
|
||||
def test_gated_require_token_endpoint_still_rejects_no_cookie(gated_app):
|
||||
"""The gate must still 401 a ``_require_token`` endpoint with no session.
|
||||
|
||||
The fix defers to the gate — it does not make these endpoints public. A
|
||||
request with no cookie is rejected by ``gated_auth_middleware`` before the
|
||||
handler runs, so the install endpoint stays protected.
|
||||
"""
|
||||
r = gated_app.post(
|
||||
"/api/dashboard/agent-plugins/install",
|
||||
json={"identifier": "owner/repo", "force": False, "enable": False},
|
||||
)
|
||||
assert r.status_code == 401, (
|
||||
f"Expected 401 for an unauthenticated install POST under the gate, "
|
||||
f"got {r.status_code}: {r.text}"
|
||||
)
|
||||
|
||||
|
||||
# A representative spread of the OTHER ``_require_token`` endpoints (there are
|
||||
# 14 in total). The install popup was just the reported symptom; the same bug
|
||||
# made API-key reveal, provider validation, the OAuth-provider connect flow,
|
||||
# and the rest of plugin management unreachable behind the gate. Each entry is
|
||||
# (method, path, json_body); we assert only that a logged-in request is NOT
|
||||
# 401'd — i.e. it cleared the auth layer and reached the handler. The
|
||||
# handler's own status (400/404/429/etc.) is route-specific and not asserted.
|
||||
_GATED_REQUIRE_TOKEN_ROUTES = [
|
||||
("get", "/api/dashboard/plugins/hub", None),
|
||||
("post", "/api/env/reveal", {"key": "NONEXISTENT_ENV_VAR_FOR_TEST"}),
|
||||
("post", "/api/providers/validate", {"key": "OPENAI_API_KEY", "value": ""}),
|
||||
("delete", "/api/providers/oauth/__not_a_real_provider__", None),
|
||||
("post", "/api/dashboard/agent-plugins/__nope__/enable", None),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method,path,body", _GATED_REQUIRE_TOKEN_ROUTES)
|
||||
def test_gated_require_token_routes_accept_cookie_session(
|
||||
gated_app, method, path, body
|
||||
):
|
||||
"""Every ``_require_token`` route must clear auth for a logged-in caller.
|
||||
|
||||
Same root cause and fix as
|
||||
``test_gated_require_token_endpoint_accepts_cookie_session`` — this just
|
||||
proves the fix covers the whole class, not only ``agent-plugins/install``.
|
||||
"""
|
||||
_complete_stub_login(gated_app)
|
||||
kwargs = {"json": body} if body is not None else {}
|
||||
r = gated_app.request(method.upper(), path, **kwargs)
|
||||
assert r.status_code != 401, (
|
||||
f"{method.upper()} {path} 401'd a cookie-authenticated request under "
|
||||
f"the OAuth gate — _require_token still rejecting a valid session. "
|
||||
f"Body: {r.text}"
|
||||
)
|
||||
|
||||
|
||||
def test_login_unknown_provider_returns_404(gated_app):
|
||||
r = gated_app.get("/auth/login?provider=nonexistent", follow_redirects=False)
|
||||
assert r.status_code == 404
|
||||
|
||||
@@ -387,90 +387,6 @@ class TestPublicUrlOverride:
|
||||
redirect_uri = self._redirect_uri(gated_app_direct)
|
||||
assert redirect_uri == "https://from-config.example/auth/callback"
|
||||
|
||||
def test_scheme_less_public_url_env_warns_operator(
|
||||
self, patch_config, monkeypatch, caplog
|
||||
):
|
||||
"""A non-empty env var that's missing its scheme (the #1 cause
|
||||
of "I set HERMES_DASHBOARD_PUBLIC_URL but the callback is still
|
||||
http://") must emit an operator-facing WARNING rather than being
|
||||
silently discarded. Regression for #42780."""
|
||||
import logging
|
||||
|
||||
from hermes_cli.dashboard_auth import prefix as prefix_mod
|
||||
|
||||
# Reset the per-value dedup cache so the warning fires in-test
|
||||
# regardless of test ordering.
|
||||
prefix_mod._warned_malformed_public_urls.clear()
|
||||
patch_config(None)
|
||||
monkeypatch.setenv("HERMES_DASHBOARD_PUBLIC_URL", "hermes.domain.com")
|
||||
|
||||
with caplog.at_level(logging.WARNING, logger=prefix_mod.__name__):
|
||||
result = prefix_mod.resolve_public_url()
|
||||
|
||||
assert result == "" # scheme-less value is still rejected
|
||||
warnings = [
|
||||
r.getMessage()
|
||||
for r in caplog.records
|
||||
if r.levelno == logging.WARNING
|
||||
]
|
||||
assert any(
|
||||
"HERMES_DASHBOARD_PUBLIC_URL" in m
|
||||
and "hermes.domain.com" in m
|
||||
and "scheme" in m
|
||||
for m in warnings
|
||||
), f"expected a scheme warning, got: {warnings!r}"
|
||||
|
||||
def test_scheme_less_public_url_warning_is_deduplicated(
|
||||
self, patch_config, monkeypatch, caplog
|
||||
):
|
||||
"""resolve_public_url runs per-request; the malformed-value
|
||||
warning must fire at most once per distinct value so a
|
||||
misconfigured deploy doesn't flood the logs."""
|
||||
import logging
|
||||
|
||||
from hermes_cli.dashboard_auth import prefix as prefix_mod
|
||||
|
||||
prefix_mod._warned_malformed_public_urls.clear()
|
||||
patch_config(None)
|
||||
monkeypatch.setenv("HERMES_DASHBOARD_PUBLIC_URL", "hermes.domain.com")
|
||||
|
||||
with caplog.at_level(logging.WARNING, logger=prefix_mod.__name__):
|
||||
for _ in range(5):
|
||||
prefix_mod.resolve_public_url()
|
||||
|
||||
scheme_warnings = [
|
||||
r
|
||||
for r in caplog.records
|
||||
if r.levelno == logging.WARNING
|
||||
and "hermes.domain.com" in r.getMessage()
|
||||
]
|
||||
assert len(scheme_warnings) == 1, (
|
||||
f"expected exactly one warning across 5 calls, "
|
||||
f"got {len(scheme_warnings)}"
|
||||
)
|
||||
|
||||
def test_valid_public_url_emits_no_warning(
|
||||
self, patch_config, monkeypatch, caplog
|
||||
):
|
||||
"""A correctly-formed value must not produce a spurious warning."""
|
||||
import logging
|
||||
|
||||
from hermes_cli.dashboard_auth import prefix as prefix_mod
|
||||
|
||||
prefix_mod._warned_malformed_public_urls.clear()
|
||||
patch_config(None)
|
||||
monkeypatch.setenv(
|
||||
"HERMES_DASHBOARD_PUBLIC_URL", "https://hermes.domain.com"
|
||||
)
|
||||
|
||||
with caplog.at_level(logging.WARNING, logger=prefix_mod.__name__):
|
||||
result = prefix_mod.resolve_public_url()
|
||||
|
||||
assert result == "https://hermes.domain.com"
|
||||
assert not [
|
||||
r for r in caplog.records if r.levelno == logging.WARNING
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cookies: Path attribute + __Host- / __Secure- prefix rules
|
||||
|
||||
@@ -27,7 +27,7 @@ import hermes_cli.dashboard_register as dr
|
||||
|
||||
|
||||
def _ns(**kw):
|
||||
defaults = dict(name=None, redirect_uri=None, portal_url=None)
|
||||
defaults = dict(name=None, redirect_uri=None)
|
||||
defaults.update(kw)
|
||||
return argparse.Namespace(**defaults)
|
||||
|
||||
@@ -76,7 +76,7 @@ def _fake_http_ok(payload: dict):
|
||||
|
||||
class TestHappyPath:
|
||||
def _run(self, *, args, account_token="tok_abc", portal="https://portal.nousresearch.com",
|
||||
response=None, captured=None, existing_client_id=None):
|
||||
response=None, captured=None):
|
||||
response = response or {
|
||||
"client_id": "agent:selfhost-1",
|
||||
"id": "selfhost-1",
|
||||
@@ -98,21 +98,12 @@ class TestHappyPath:
|
||||
def fake_save(key, value):
|
||||
saved[key] = value
|
||||
|
||||
# get_env_value is consulted twice: once for the stored client_id
|
||||
# (idempotency key) and once for HERMES_DASHBOARD_PORTAL_URL. Route by
|
||||
# key so a test can seed a prior client_id while keeping the portal
|
||||
# unset (the default-portal-not-persisted path).
|
||||
def fake_get_env(key):
|
||||
if key == "HERMES_DASHBOARD_OAUTH_CLIENT_ID":
|
||||
return existing_client_id
|
||||
return None
|
||||
|
||||
with patch(
|
||||
"hermes_cli.auth.resolve_nous_access_token", return_value=account_token
|
||||
), patch("hermes_cli.config.is_managed", return_value=False), patch.object(
|
||||
dr, "_resolve_portal_base_url", return_value=portal
|
||||
), patch(
|
||||
"hermes_cli.config.get_env_value", side_effect=fake_get_env
|
||||
"hermes_cli.config.get_env_value", return_value=None
|
||||
), patch(
|
||||
"hermes_cli.config.save_env_value", side_effect=fake_save
|
||||
), patch.object(
|
||||
@@ -166,394 +157,6 @@ class TestHappyPath:
|
||||
)
|
||||
|
||||
|
||||
class TestIdempotentRerun(TestHappyPath):
|
||||
"""Re-running with a stored client_id updates instead of creating.
|
||||
|
||||
Inherits ``_run`` from TestHappyPath; the only new lever is
|
||||
``existing_client_id`` (the HERMES_DASHBOARD_OAUTH_CLIENT_ID a prior run
|
||||
persisted), which the CLI re-sends so the portal updates that row.
|
||||
"""
|
||||
|
||||
def test_stored_client_id_is_sent_as_idempotency_key(self, capsys):
|
||||
captured: dict = {}
|
||||
# Portal echoes back the SAME id -> it updated in place.
|
||||
self._run(
|
||||
args=_ns(),
|
||||
existing_client_id="agent:selfhost-1",
|
||||
response={
|
||||
"client_id": "agent:selfhost-1",
|
||||
"id": "selfhost-1",
|
||||
"name": "dreamy_tesla",
|
||||
"kind": "SELF_HOSTED",
|
||||
"custom_redirect_uri": None,
|
||||
"created_at": "2026-06-04T12:00:00.000Z",
|
||||
},
|
||||
captured=captured,
|
||||
)
|
||||
assert captured["body"]["client_id"] == "agent:selfhost-1"
|
||||
|
||||
def test_rerun_without_name_omits_name_to_preserve_stored(self, capsys):
|
||||
# No --name on a re-run: don't churn the portal-stored name. The CLI
|
||||
# leaves `name` out of the body so the portal keeps what it has.
|
||||
captured: dict = {}
|
||||
self._run(
|
||||
args=_ns(),
|
||||
existing_client_id="agent:selfhost-1",
|
||||
captured=captured,
|
||||
)
|
||||
assert "name" not in captured["body"]
|
||||
assert captured["body"]["client_id"] == "agent:selfhost-1"
|
||||
|
||||
def test_rerun_with_explicit_name_still_sends_name(self, capsys):
|
||||
captured: dict = {}
|
||||
self._run(
|
||||
args=_ns(name="renamed_box"),
|
||||
existing_client_id="agent:selfhost-1",
|
||||
captured=captured,
|
||||
)
|
||||
assert captured["body"]["name"] == "renamed_box"
|
||||
assert captured["body"]["client_id"] == "agent:selfhost-1"
|
||||
|
||||
def test_rerun_prints_updated_when_same_id_returned(self, capsys):
|
||||
self._run(
|
||||
args=_ns(),
|
||||
existing_client_id="agent:selfhost-1",
|
||||
response={
|
||||
"client_id": "agent:selfhost-1",
|
||||
"id": "selfhost-1",
|
||||
"name": "dreamy_tesla",
|
||||
"kind": "SELF_HOSTED",
|
||||
"custom_redirect_uri": None,
|
||||
"created_at": "2026-06-04T12:00:00.000Z",
|
||||
},
|
||||
)
|
||||
out = capsys.readouterr().out
|
||||
assert "Updated dashboard" in out
|
||||
assert "Registered dashboard" not in out
|
||||
|
||||
def test_rerun_persists_returned_client_id(self, capsys):
|
||||
saved = self._run(
|
||||
args=_ns(),
|
||||
existing_client_id="agent:selfhost-1",
|
||||
)
|
||||
# Same id round-trips into .env -> idempotent, one record.
|
||||
assert saved["HERMES_DASHBOARD_OAUTH_CLIENT_ID"] == "agent:selfhost-1"
|
||||
|
||||
def test_stale_id_falls_through_to_create_prints_registered(self, capsys):
|
||||
# Stored id no longer resolves server-side -> portal created a fresh
|
||||
# row and returns a DIFFERENT id. The CLI treats that as a create and
|
||||
# persists the new id (re-run stays safe, never worse than first run).
|
||||
captured: dict = {}
|
||||
saved = self._run(
|
||||
args=_ns(name="seed_name"),
|
||||
existing_client_id="agent:selfhost-stale",
|
||||
response={
|
||||
"client_id": "agent:selfhost-new",
|
||||
"id": "selfhost-new",
|
||||
"name": "seed_name",
|
||||
"kind": "SELF_HOSTED",
|
||||
"custom_redirect_uri": None,
|
||||
"created_at": "2026-06-04T12:00:00.000Z",
|
||||
},
|
||||
captured=captured,
|
||||
)
|
||||
# The stale id is still SENT (portal decides create-vs-update).
|
||||
assert captured["body"]["client_id"] == "agent:selfhost-stale"
|
||||
# Returned id differs from what we sent -> message is "Registered".
|
||||
out = capsys.readouterr().out
|
||||
assert "Registered dashboard" in out
|
||||
assert "Updated dashboard" not in out
|
||||
assert saved["HERMES_DASHBOARD_OAUTH_CLIENT_ID"] == "agent:selfhost-new"
|
||||
|
||||
def test_blank_stored_client_id_treated_as_first_run(self, capsys):
|
||||
# A blank/whitespace stored value is not a usable key: treat as a
|
||||
# first registration (auto-generate a name, don't send client_id).
|
||||
captured: dict = {}
|
||||
self._run(
|
||||
args=_ns(),
|
||||
existing_client_id=" ",
|
||||
captured=captured,
|
||||
)
|
||||
assert "client_id" not in captured["body"]
|
||||
assert captured["body"].get("name") # auto-generated
|
||||
|
||||
|
||||
class TestCustomPortalPersistence:
|
||||
"""`--portal-url` / HERMES_DASHBOARD_PORTAL_URL is persisted to .env.
|
||||
|
||||
An *explicitly supplied* custom portal URL is an intentional choice the
|
||||
user wants to survive across sessions, so it's always written (updating an
|
||||
existing entry in place rather than appending a duplicate). When no custom
|
||||
URL is supplied, the older conservative behaviour is preserved: an inferred
|
||||
portal is only written when absent and non-default, and an existing entry
|
||||
is never altered unexpectedly.
|
||||
"""
|
||||
|
||||
def _run(self, *, args, portal, existing_portal):
|
||||
"""Drive cmd_dashboard_register, capturing save_env_value calls.
|
||||
|
||||
`existing_portal` is what get_env_value returns for
|
||||
HERMES_DASHBOARD_PORTAL_URL (None = not present in .env).
|
||||
"""
|
||||
response = {
|
||||
"client_id": "agent:selfhost-1",
|
||||
"id": "selfhost-1",
|
||||
"name": "dreamy_tesla",
|
||||
"kind": "SELF_HOSTED",
|
||||
"custom_redirect_uri": None,
|
||||
"created_at": "2026-06-04T12:00:00.000Z",
|
||||
}
|
||||
|
||||
saved: dict = {}
|
||||
|
||||
def fake_save(key, value):
|
||||
saved[key] = value
|
||||
|
||||
def fake_get_env_value(key, *a, **kw):
|
||||
if key == "HERMES_DASHBOARD_PORTAL_URL":
|
||||
return existing_portal
|
||||
return None
|
||||
|
||||
with patch(
|
||||
"hermes_cli.auth.resolve_nous_access_token", return_value="tok"
|
||||
), patch("hermes_cli.config.is_managed", return_value=False), patch.dict(
|
||||
dr.os.environ, {}, clear=False
|
||||
), patch.object(
|
||||
dr, "_resolve_portal_base_url", return_value=portal
|
||||
), patch(
|
||||
"hermes_cli.config.get_env_value", side_effect=fake_get_env_value
|
||||
), patch(
|
||||
"hermes_cli.config.save_env_value", side_effect=fake_save
|
||||
), patch.object(
|
||||
dr.urllib.request, "urlopen", return_value=_fake_http_ok(response)
|
||||
):
|
||||
# The ambient process env may carry HERMES_DASHBOARD_PORTAL_URL
|
||||
# (e.g. staging dev shells); drop it so `custom_portal_supplied`
|
||||
# is driven solely by the args.portal_url under test.
|
||||
dr.os.environ.pop("HERMES_DASHBOARD_PORTAL_URL", None)
|
||||
dr.cmd_dashboard_register(args)
|
||||
return saved
|
||||
|
||||
def test_explicit_custom_url_persisted_when_var_absent(self, capsys):
|
||||
saved = self._run(
|
||||
args=_ns(portal_url="https://preview.example.com"),
|
||||
portal="https://preview.example.com",
|
||||
existing_portal=None,
|
||||
)
|
||||
assert saved["HERMES_DASHBOARD_PORTAL_URL"] == "https://preview.example.com"
|
||||
|
||||
def test_explicit_custom_url_updates_existing_in_place(self, capsys):
|
||||
# An entry already exists with a different value; the explicit custom
|
||||
# URL overwrites it (save_env_value updates the matching key in place).
|
||||
saved = self._run(
|
||||
args=_ns(portal_url="https://new-preview.example.com"),
|
||||
portal="https://new-preview.example.com",
|
||||
existing_portal="https://old-preview.example.com",
|
||||
)
|
||||
assert (
|
||||
saved["HERMES_DASHBOARD_PORTAL_URL"] == "https://new-preview.example.com"
|
||||
)
|
||||
|
||||
def test_explicit_custom_url_persisted_even_when_equals_default(self, capsys):
|
||||
# User explicitly asked for the production portal — honour the explicit
|
||||
# request and persist it (the no-flag path would skip the default).
|
||||
saved = self._run(
|
||||
args=_ns(portal_url="https://portal.nousresearch.com"),
|
||||
portal="https://portal.nousresearch.com",
|
||||
existing_portal=None,
|
||||
)
|
||||
assert (
|
||||
saved["HERMES_DASHBOARD_PORTAL_URL"] == "https://portal.nousresearch.com"
|
||||
)
|
||||
|
||||
def test_explicit_custom_url_equal_to_existing_is_noop(self, capsys):
|
||||
# Already persisted with the same value → no redundant write.
|
||||
saved = self._run(
|
||||
args=_ns(portal_url="https://preview.example.com"),
|
||||
portal="https://preview.example.com",
|
||||
existing_portal="https://preview.example.com",
|
||||
)
|
||||
assert "HERMES_DASHBOARD_PORTAL_URL" not in saved
|
||||
|
||||
def test_no_flag_default_portal_not_written(self, capsys):
|
||||
# No custom URL supplied, resolves to default → not written.
|
||||
saved = self._run(
|
||||
args=_ns(),
|
||||
portal="https://portal.nousresearch.com",
|
||||
existing_portal=None,
|
||||
)
|
||||
assert "HERMES_DASHBOARD_PORTAL_URL" not in saved
|
||||
|
||||
def test_no_flag_does_not_overwrite_existing_entry(self, capsys):
|
||||
# No custom URL supplied and the var already exists → left untouched,
|
||||
# even if the inferred portal differs (acceptance criterion 4).
|
||||
saved = self._run(
|
||||
args=_ns(),
|
||||
portal="https://inferred-from-login.example.com",
|
||||
existing_portal="https://already-set.example.com",
|
||||
)
|
||||
assert "HERMES_DASHBOARD_PORTAL_URL" not in saved
|
||||
|
||||
|
||||
class TestPublicUrlPersistence:
|
||||
"""`--redirect-uri` derives & persists HERMES_DASHBOARD_PUBLIC_URL in .env.
|
||||
|
||||
--redirect-uri is the full public callback (e.g.
|
||||
https://hermes.example.com/auth/callback). At serve time the dashboard auth
|
||||
layer reconstructs that callback by appending "/auth/callback" to
|
||||
HERMES_DASHBOARD_PUBLIC_URL, so the value that's actually consumed is the
|
||||
ORIGIN (scheme://host). We derive the origin from the supplied redirect URI
|
||||
and persist THAT as HERMES_DASHBOARD_PUBLIC_URL — the var the runtime reads
|
||||
— so the public-URL override is genuinely wired, not just stored.
|
||||
|
||||
An explicitly supplied value is always written (updating an existing entry
|
||||
in place rather than appending a duplicate); a no-op when it already
|
||||
matches; and never written on a localhost-only install (no --redirect-uri).
|
||||
"""
|
||||
|
||||
def _run(self, *, args, existing_public=None):
|
||||
"""Drive cmd_dashboard_register, capturing save_env_value calls.
|
||||
|
||||
`existing_public` is what get_env_value returns for
|
||||
HERMES_DASHBOARD_PUBLIC_URL (None = not present in .env).
|
||||
"""
|
||||
response = {
|
||||
"client_id": "agent:selfhost-1",
|
||||
"id": "selfhost-1",
|
||||
"name": "dreamy_tesla",
|
||||
"kind": "SELF_HOSTED",
|
||||
"custom_redirect_uri": getattr(args, "redirect_uri", None),
|
||||
"created_at": "2026-06-04T12:00:00.000Z",
|
||||
}
|
||||
|
||||
saved: dict = {}
|
||||
|
||||
def fake_save(key, value):
|
||||
saved[key] = value
|
||||
|
||||
def fake_get_env_value(key, *a, **kw):
|
||||
if key == "HERMES_DASHBOARD_PUBLIC_URL":
|
||||
return existing_public
|
||||
return None
|
||||
|
||||
with patch(
|
||||
"hermes_cli.auth.resolve_nous_access_token", return_value="tok"
|
||||
), patch("hermes_cli.config.is_managed", return_value=False), patch.dict(
|
||||
dr.os.environ, {}, clear=False
|
||||
), patch.object(
|
||||
dr, "_resolve_portal_base_url", return_value="https://portal.nousresearch.com"
|
||||
), patch(
|
||||
"hermes_cli.config.get_env_value", side_effect=fake_get_env_value
|
||||
), patch(
|
||||
"hermes_cli.config.save_env_value", side_effect=fake_save
|
||||
), patch.object(
|
||||
dr.urllib.request, "urlopen", return_value=_fake_http_ok(response)
|
||||
):
|
||||
dr.os.environ.pop("HERMES_DASHBOARD_PORTAL_URL", None)
|
||||
dr.cmd_dashboard_register(args)
|
||||
return saved
|
||||
|
||||
def test_origin_derived_from_full_callback_path(self, capsys):
|
||||
# The key behaviour: a full callback URL is reduced to its ORIGIN so
|
||||
# the runtime's "public_url + /auth/callback" reconstruction matches.
|
||||
saved = self._run(
|
||||
args=_ns(redirect_uri="https://hermes.example.com/auth/callback"),
|
||||
existing_public=None,
|
||||
)
|
||||
assert saved["HERMES_DASHBOARD_PUBLIC_URL"] == "https://hermes.example.com"
|
||||
# The full callback path must NOT be persisted verbatim (would double
|
||||
# the path at serve time).
|
||||
assert "/auth/callback" not in saved["HERMES_DASHBOARD_PUBLIC_URL"]
|
||||
|
||||
def test_origin_preserves_port(self, capsys):
|
||||
saved = self._run(
|
||||
args=_ns(redirect_uri="https://hermes.example.com:8443/auth/callback"),
|
||||
existing_public=None,
|
||||
)
|
||||
assert saved["HERMES_DASHBOARD_PUBLIC_URL"] == "https://hermes.example.com:8443"
|
||||
|
||||
def test_public_url_updates_existing_in_place(self, capsys):
|
||||
# A stale public-url entry exists; the new derived origin overwrites it.
|
||||
saved = self._run(
|
||||
args=_ns(redirect_uri="https://new.example.com/auth/callback"),
|
||||
existing_public="https://old.example.com",
|
||||
)
|
||||
assert saved["HERMES_DASHBOARD_PUBLIC_URL"] == "https://new.example.com"
|
||||
|
||||
def test_public_url_equal_to_existing_is_noop(self, capsys):
|
||||
# Derived origin already matches what's stored → no redundant write.
|
||||
saved = self._run(
|
||||
args=_ns(redirect_uri="https://hermes.example.com/auth/callback"),
|
||||
existing_public="https://hermes.example.com",
|
||||
)
|
||||
assert "HERMES_DASHBOARD_PUBLIC_URL" not in saved
|
||||
|
||||
def test_no_redirect_flag_not_written(self, capsys):
|
||||
# Localhost-only install (no --redirect-uri) → var left untouched.
|
||||
saved = self._run(
|
||||
args=_ns(),
|
||||
existing_public=None,
|
||||
)
|
||||
assert "HERMES_DASHBOARD_PUBLIC_URL" not in saved
|
||||
|
||||
def test_no_redirect_flag_does_not_overwrite_existing(self, capsys):
|
||||
# No --redirect-uri supplied but a value already exists → never touch
|
||||
# it (an existing entry is only changed by an explicit new value).
|
||||
saved = self._run(
|
||||
args=_ns(),
|
||||
existing_public="https://already-set.example.com",
|
||||
)
|
||||
assert "HERMES_DASHBOARD_PUBLIC_URL" not in saved
|
||||
|
||||
def test_non_http_redirect_not_persisted(self, capsys):
|
||||
# A malformed / non-http(s) redirect yields no derivable origin → skip.
|
||||
saved = self._run(
|
||||
args=_ns(redirect_uri="not-a-url"),
|
||||
existing_public=None,
|
||||
)
|
||||
assert "HERMES_DASHBOARD_PUBLIC_URL" not in saved
|
||||
|
||||
def test_public_url_persisted_alongside_portal_url(self, capsys):
|
||||
# Both --portal-url and --redirect-uri supplied → portal_url AND the
|
||||
# derived public_url are both persisted (ADD semantics: the public-url
|
||||
# write does not displace portal-url persistence).
|
||||
response = {
|
||||
"client_id": "agent:selfhost-1",
|
||||
"id": "selfhost-1",
|
||||
"name": "dreamy_tesla",
|
||||
"kind": "SELF_HOSTED",
|
||||
"custom_redirect_uri": "https://hermes.example.com/auth/callback",
|
||||
"created_at": "2026-06-04T12:00:00.000Z",
|
||||
}
|
||||
saved: dict = {}
|
||||
|
||||
def fake_save(key, value):
|
||||
saved[key] = value
|
||||
|
||||
with patch(
|
||||
"hermes_cli.auth.resolve_nous_access_token", return_value="tok"
|
||||
), patch("hermes_cli.config.is_managed", return_value=False), patch.dict(
|
||||
dr.os.environ, {}, clear=False
|
||||
), patch.object(
|
||||
dr, "_resolve_portal_base_url", return_value="https://preview.example.com"
|
||||
), patch(
|
||||
"hermes_cli.config.get_env_value", return_value=None
|
||||
), patch(
|
||||
"hermes_cli.config.save_env_value", side_effect=fake_save
|
||||
), patch.object(
|
||||
dr.urllib.request, "urlopen", return_value=_fake_http_ok(response)
|
||||
):
|
||||
dr.os.environ.pop("HERMES_DASHBOARD_PORTAL_URL", None)
|
||||
dr.cmd_dashboard_register(
|
||||
_ns(
|
||||
portal_url="https://preview.example.com",
|
||||
redirect_uri="https://hermes.example.com/auth/callback",
|
||||
)
|
||||
)
|
||||
assert saved["HERMES_DASHBOARD_PORTAL_URL"] == "https://preview.example.com"
|
||||
assert saved["HERMES_DASHBOARD_PUBLIC_URL"] == "https://hermes.example.com"
|
||||
|
||||
|
||||
class TestPortalResolution:
|
||||
def test_override_arg_wins(self):
|
||||
assert (
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
"""Tests for the unified profile→machine dashboard launch routing.
|
||||
|
||||
`<profile> dashboard` routes to ONE machine-level dashboard instead of
|
||||
spawning a per-profile server: attach (open browser at ?profile=) when one
|
||||
is already listening, else re-exec as the machine dashboard with the
|
||||
launching profile preselected. `--isolated` opts out.
|
||||
"""
|
||||
import sys
|
||||
import types
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def main_mod():
|
||||
import hermes_cli.main as main_mod
|
||||
return main_mod
|
||||
|
||||
|
||||
def _args(**kw):
|
||||
defaults = dict(
|
||||
status=False, stop=False, host="127.0.0.1", port=9119,
|
||||
no_open=True, insecure=False, skip_build=False,
|
||||
isolated=False, open_profile="",
|
||||
)
|
||||
defaults.update(kw)
|
||||
return types.SimpleNamespace(**defaults)
|
||||
|
||||
|
||||
class TestUnifiedDashboardRouting:
|
||||
def test_profile_launch_attaches_to_running_dashboard(self, main_mod, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.profiles.get_active_profile_name", lambda: "worker_x"
|
||||
)
|
||||
monkeypatch.setattr(main_mod, "_dashboard_listening", lambda host, port: True)
|
||||
execs = []
|
||||
monkeypatch.setattr(main_mod.os, "execvpe", lambda *a, **k: execs.append(a))
|
||||
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
main_mod.cmd_dashboard(_args())
|
||||
assert exc.value.code == 0
|
||||
assert execs == [] # attached, never re-exec'd
|
||||
|
||||
def test_profile_launch_attach_opens_scoped_url(self, main_mod, monkeypatch):
|
||||
"""The attach path must open the browser at ?profile=<name> — that
|
||||
URL is the entire point of attaching (preselects the switcher)."""
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.profiles.get_active_profile_name", lambda: "worker_x"
|
||||
)
|
||||
monkeypatch.setattr(main_mod, "_dashboard_listening", lambda host, port: True)
|
||||
opened = []
|
||||
import webbrowser
|
||||
monkeypatch.setattr(webbrowser, "open", lambda url: opened.append(url))
|
||||
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
main_mod.cmd_dashboard(_args(no_open=False))
|
||||
assert exc.value.code == 0
|
||||
assert opened == ["http://127.0.0.1:9119/?profile=worker_x"]
|
||||
|
||||
def test_profile_launch_reexecs_machine_dashboard(self, main_mod, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.profiles.get_active_profile_name", lambda: "worker_x"
|
||||
)
|
||||
monkeypatch.setattr(main_mod, "_dashboard_listening", lambda host, port: False)
|
||||
execs = []
|
||||
|
||||
def fake_exec(exe, argv, env):
|
||||
execs.append((exe, argv, env))
|
||||
raise SystemExit(0) # execvpe never returns
|
||||
|
||||
monkeypatch.setattr(main_mod.os, "execvpe", fake_exec)
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
main_mod.cmd_dashboard(_args())
|
||||
|
||||
assert len(execs) == 1
|
||||
exe, argv, env = execs[0]
|
||||
assert exe == sys.executable
|
||||
# Pinned to the default profile + launching profile preselected.
|
||||
assert "-p" in argv and argv[argv.index("-p") + 1] == "default"
|
||||
assert "--open-profile" in argv
|
||||
assert argv[argv.index("--open-profile") + 1] == "worker_x"
|
||||
# Profile HERMES_HOME dropped so the child binds the machine root.
|
||||
assert "HERMES_HOME" not in env
|
||||
|
||||
def test_desktop_profile_backend_skips_machine_dashboard_reroute(self, main_mod, monkeypatch):
|
||||
"""A desktop-spawned named-profile backend (HERMES_DESKTOP=1) must NOT
|
||||
reroute into the machine dashboard. The reroute re-execs as the default
|
||||
profile and exits, so the desktop never sees a ready backend → boot
|
||||
loop. The guard keeps desktop pool backends per-profile."""
|
||||
monkeypatch.setenv("HERMES_DESKTOP", "1")
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.profiles.get_active_profile_name", lambda: "worker_x"
|
||||
)
|
||||
listening_calls = []
|
||||
monkeypatch.setattr(
|
||||
main_mod, "_dashboard_listening",
|
||||
lambda host, port: listening_calls.append(1) or False,
|
||||
)
|
||||
execs = []
|
||||
monkeypatch.setattr(main_mod.os, "execvpe", lambda *a, **k: execs.append(a))
|
||||
monkeypatch.setitem(sys.modules, "fastapi", None)
|
||||
|
||||
with pytest.raises((SystemExit, AttributeError, ImportError, TypeError)):
|
||||
main_mod.cmd_dashboard(_args())
|
||||
assert listening_calls == []
|
||||
assert execs == []
|
||||
|
||||
def test_isolated_flag_skips_routing(self, main_mod, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.profiles.get_active_profile_name", lambda: "worker_x"
|
||||
)
|
||||
listening_calls = []
|
||||
monkeypatch.setattr(
|
||||
main_mod, "_dashboard_listening",
|
||||
lambda host, port: listening_calls.append(1) or True,
|
||||
)
|
||||
# With --isolated the routing block is skipped entirely; the command
|
||||
# proceeds to dependency checks. Make the first post-routing step
|
||||
# bail so the test doesn't actually start a server.
|
||||
monkeypatch.setitem(sys.modules, "fastapi", None)
|
||||
|
||||
with pytest.raises((SystemExit, AttributeError, ImportError, TypeError)):
|
||||
main_mod.cmd_dashboard(_args(isolated=True))
|
||||
assert listening_calls == []
|
||||
|
||||
def test_default_profile_launch_skips_routing(self, main_mod, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.profiles.get_active_profile_name", lambda: "default"
|
||||
)
|
||||
listening_calls = []
|
||||
monkeypatch.setattr(
|
||||
main_mod, "_dashboard_listening",
|
||||
lambda host, port: listening_calls.append(1) or True,
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, "fastapi", None)
|
||||
|
||||
with pytest.raises((SystemExit, AttributeError, ImportError, TypeError)):
|
||||
main_mod.cmd_dashboard(_args())
|
||||
assert listening_calls == []
|
||||
|
||||
def test_reexec_child_does_not_reroute(self, main_mod, monkeypatch):
|
||||
"""The re-exec'd child carries --open-profile; the guard must treat
|
||||
that as 'already routed' and never re-exec again (no exec loop)."""
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.profiles.get_active_profile_name", lambda: "worker_x"
|
||||
)
|
||||
execs = []
|
||||
monkeypatch.setattr(main_mod.os, "execvpe", lambda *a, **k: execs.append(a))
|
||||
monkeypatch.setitem(sys.modules, "fastapi", None)
|
||||
|
||||
with pytest.raises((SystemExit, AttributeError, ImportError, TypeError)):
|
||||
main_mod.cmd_dashboard(_args(open_profile="worker_x"))
|
||||
assert execs == []
|
||||
|
||||
def test_dashboard_starts_mcp_discovery_for_ws_backend(self, main_mod, monkeypatch):
|
||||
"""The dashboard process serves the /api/ws gateway but never runs
|
||||
tui_gateway/entry.py, so it must kick off MCP discovery itself or
|
||||
desktop sessions never see a profile's MCP tools."""
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.profiles.get_active_profile_name", lambda: "default"
|
||||
)
|
||||
monkeypatch.delenv("HERMES_WEB_DIST", raising=False)
|
||||
monkeypatch.setattr(main_mod, "_sync_bundled_skills_quietly", lambda: None)
|
||||
monkeypatch.setattr(main_mod, "_build_web_ui", lambda *_a, **_k: True)
|
||||
monkeypatch.setitem(sys.modules, "fastapi", types.SimpleNamespace())
|
||||
monkeypatch.setitem(sys.modules, "uvicorn", types.SimpleNamespace())
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"hermes_logging",
|
||||
types.SimpleNamespace(setup_logging=lambda **_k: None),
|
||||
)
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"hermes_cli.plugins",
|
||||
types.SimpleNamespace(discover_plugins=lambda: None),
|
||||
)
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.mcp_startup.start_background_mcp_discovery",
|
||||
lambda **kwargs: calls.append(kwargs),
|
||||
)
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"hermes_cli.web_server",
|
||||
types.SimpleNamespace(start_server=lambda **_kwargs: None),
|
||||
)
|
||||
|
||||
main_mod.cmd_dashboard(_args())
|
||||
|
||||
assert calls == [
|
||||
{
|
||||
"logger": main_mod.logger,
|
||||
"thread_name": "dashboard-mcp-discovery",
|
||||
}
|
||||
]
|
||||
@@ -540,54 +540,6 @@ def test_run_doctor_accepts_hermes_provider_ids_that_catalog_aliases(
|
||||
)
|
||||
|
||||
|
||||
def test_run_doctor_accepts_vendor_slugs_for_named_custom_provider(monkeypatch, tmp_path):
|
||||
home = tmp_path / ".hermes"
|
||||
home.mkdir(parents=True, exist_ok=True)
|
||||
(home / "config.yaml").write_text(
|
||||
"model:\n"
|
||||
" provider: custom:hpc-ai\n"
|
||||
" default: deepseek/deepseek-v4-flash\n"
|
||||
"custom_providers:\n"
|
||||
" - name: hpc-ai\n"
|
||||
" base_url: https://hpc-ai.example/v1\n"
|
||||
" api_key: test-key\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(doctor_mod, "HERMES_HOME", home)
|
||||
monkeypatch.setattr(doctor_mod, "PROJECT_ROOT", tmp_path / "project")
|
||||
monkeypatch.setattr(doctor_mod, "_DHH", str(home))
|
||||
(tmp_path / "project").mkdir(exist_ok=True)
|
||||
|
||||
fake_model_tools = types.SimpleNamespace(
|
||||
check_tool_availability=lambda *a, **kw: ([], []),
|
||||
TOOLSET_REQUIREMENTS={},
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, "model_tools", fake_model_tools)
|
||||
|
||||
try:
|
||||
from hermes_cli import auth as _auth_mod
|
||||
monkeypatch.setattr(_auth_mod, "get_nous_auth_status", lambda: {})
|
||||
monkeypatch.setattr(_auth_mod, "get_codex_auth_status", lambda: {})
|
||||
monkeypatch.setattr(_auth_mod, "get_xai_oauth_auth_status", lambda: {})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf):
|
||||
doctor_mod.run_doctor(Namespace(fix=False))
|
||||
|
||||
out = buf.getvalue()
|
||||
assert "model.provider 'custom:hpc-ai' is not a recognised provider" not in out
|
||||
assert "model.provider 'custom:hpc-ai' is unknown" not in out
|
||||
assert (
|
||||
"model.default 'deepseek/deepseek-v4-flash' uses a vendor/model slug but provider is "
|
||||
"'custom:hpc-ai'"
|
||||
not in out
|
||||
)
|
||||
assert "Either set model.provider to 'openrouter', or drop the vendor prefix." not in out
|
||||
|
||||
|
||||
|
||||
|
||||
def test_run_doctor_accepts_kimi_coding_cn_provider(monkeypatch, tmp_path):
|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
"""Regression tests for hermes_cli._ensure_utf8().
|
||||
|
||||
Covers the crash class where the setup wizard (and other banner-printing
|
||||
commands) emit box-drawing characters and the ⚕ glyph, which raise
|
||||
UnicodeEncodeError when stdout/stderr are bound to a non-UTF-8 codec.
|
||||
|
||||
Historically the repair was gated on ``sys.platform == "win32"`` and only
|
||||
caught the Windows cp1252 case. Linux hosts with a latin-1 / C / POSIX locale
|
||||
(common on minimal Debian installs and Raspberry Pi) hit the identical crash
|
||||
in ``hermes setup`` because the repair returned early. See the Raspberry Pi
|
||||
report: latin-1 locale → UnicodeEncodeError before the wizard could start.
|
||||
"""
|
||||
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
|
||||
import hermes_cli
|
||||
|
||||
|
||||
# The exact glyphs the setup wizard / banners print (setup.py ~line 2962+).
|
||||
_BANNER = "┌─────┐\n│ ⚕ Hermes │\n└─────┘"
|
||||
|
||||
|
||||
class _FakeStream:
|
||||
"""Minimal text stream backed by an in-memory byte buffer with a codec.
|
||||
|
||||
Mirrors how CPython binds sys.stdout to the locale encoding: writes that
|
||||
can't be encoded raise UnicodeEncodeError, just like a real latin-1 TTY.
|
||||
"""
|
||||
|
||||
def __init__(self, encoding, *, supports_reconfigure=True):
|
||||
self.encoding = encoding
|
||||
self._supports_reconfigure = supports_reconfigure
|
||||
self.errors = "strict"
|
||||
self._buf = io.BytesIO()
|
||||
|
||||
def write(self, s):
|
||||
self._buf.write(s.encode(self.encoding, self.errors))
|
||||
return len(s)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
def reconfigure(self, *, encoding=None, errors=None):
|
||||
if not self._supports_reconfigure:
|
||||
raise AttributeError("reconfigure")
|
||||
if encoding is not None:
|
||||
self.encoding = encoding
|
||||
if errors is not None:
|
||||
self.errors = errors
|
||||
|
||||
def getvalue(self):
|
||||
return self._buf.getvalue()
|
||||
|
||||
|
||||
def _run_with_streams(monkeypatch, out, err):
|
||||
monkeypatch.setattr(sys, "stdout", out, raising=False)
|
||||
monkeypatch.setattr(sys, "stderr", err, raising=False)
|
||||
hermes_cli._ensure_utf8()
|
||||
|
||||
|
||||
def test_latin1_stdout_is_repaired_to_utf8(monkeypatch):
|
||||
"""A latin-1 stdout (the Raspberry Pi case) becomes UTF-8 capable."""
|
||||
out = _FakeStream("latin-1")
|
||||
err = _FakeStream("latin-1")
|
||||
|
||||
# Sanity: before the fix, the banner cannot be encoded.
|
||||
try:
|
||||
out.write(_BANNER)
|
||||
pre_fix_crashes = False
|
||||
except UnicodeEncodeError:
|
||||
pre_fix_crashes = True
|
||||
assert pre_fix_crashes, "fixture should reproduce the original crash"
|
||||
|
||||
out = _FakeStream("latin-1")
|
||||
err = _FakeStream("latin-1")
|
||||
_run_with_streams(monkeypatch, out, err)
|
||||
|
||||
assert sys.stdout.encoding.lower().replace("-", "") == "utf8"
|
||||
assert sys.stderr.encoding.lower().replace("-", "") == "utf8"
|
||||
# The banner now encodes without raising.
|
||||
sys.stdout.write(_BANNER)
|
||||
assert "⚕".encode("utf-8") in sys.stdout.getvalue()
|
||||
|
||||
|
||||
def test_ascii_posix_locale_is_repaired(monkeypatch):
|
||||
"""C/POSIX locale resolves to ascii stdout — also must be repaired."""
|
||||
out = _FakeStream("ascii")
|
||||
err = _FakeStream("ascii")
|
||||
_run_with_streams(monkeypatch, out, err)
|
||||
assert sys.stdout.encoding.lower().replace("-", "") == "utf8"
|
||||
sys.stdout.write(_BANNER) # no raise
|
||||
|
||||
|
||||
def test_utf8_stream_left_untouched(monkeypatch):
|
||||
"""Already-UTF-8 streams are a no-op: object identity preserved AND the
|
||||
process environment is left untouched (no PYTHONUTF8/PYTHONIOENCODING
|
||||
burned in on a healthy UTF-8 host)."""
|
||||
out = _FakeStream("utf-8")
|
||||
err = _FakeStream("utf-8")
|
||||
sentinel_out, sentinel_err = out, err
|
||||
monkeypatch.delenv("PYTHONUTF8", raising=False)
|
||||
monkeypatch.delenv("PYTHONIOENCODING", raising=False)
|
||||
_run_with_streams(monkeypatch, out, err)
|
||||
assert sys.stdout is sentinel_out
|
||||
assert sys.stderr is sentinel_err
|
||||
# Healthy UTF-8 host: no environment mutation (minimal footprint).
|
||||
assert "PYTHONUTF8" not in os.environ
|
||||
assert "PYTHONIOENCODING" not in os.environ
|
||||
|
||||
|
||||
def test_repair_sets_child_process_env(monkeypatch):
|
||||
"""When a real repair happens, child-process UTF-8 hints are set."""
|
||||
monkeypatch.delenv("PYTHONUTF8", raising=False)
|
||||
monkeypatch.delenv("PYTHONIOENCODING", raising=False)
|
||||
_run_with_streams(monkeypatch, _FakeStream("latin-1"), _FakeStream("latin-1"))
|
||||
assert os.environ.get("PYTHONUTF8") == "1"
|
||||
assert os.environ.get("PYTHONIOENCODING") == "utf-8"
|
||||
|
||||
|
||||
def test_repair_does_not_override_explicit_env(monkeypatch):
|
||||
"""A user's explicit PYTHONIOENCODING is respected (setdefault, not set)."""
|
||||
monkeypatch.setenv("PYTHONIOENCODING", "utf-16")
|
||||
monkeypatch.delenv("PYTHONUTF8", raising=False)
|
||||
_run_with_streams(monkeypatch, _FakeStream("latin-1"), _FakeStream("latin-1"))
|
||||
assert os.environ["PYTHONIOENCODING"] == "utf-16"
|
||||
|
||||
|
||||
def test_fallback_when_reconfigure_unavailable(monkeypatch, tmp_path):
|
||||
"""Streams without reconfigure() fall back to reopening the fd as UTF-8."""
|
||||
real_path = tmp_path / "out.txt"
|
||||
fh = open(real_path, "w", encoding="latin-1")
|
||||
|
||||
class _NoReconfigure:
|
||||
"""latin-1 stream exposing a real fileno() but no reconfigure()."""
|
||||
|
||||
encoding = "latin-1"
|
||||
|
||||
def fileno(self):
|
||||
return fh.fileno()
|
||||
|
||||
stream = _NoReconfigure()
|
||||
monkeypatch.setattr(sys, "stdout", stream, raising=False)
|
||||
monkeypatch.setattr(sys, "stderr", stream, raising=False)
|
||||
hermes_cli._ensure_utf8()
|
||||
|
||||
# Replaced with a new UTF-8 stream object (not reconfigured in place).
|
||||
assert sys.stdout is not stream
|
||||
assert sys.stdout.encoding.lower().replace("-", "") == "utf8"
|
||||
sys.stdout.write(_BANNER)
|
||||
sys.stdout.flush()
|
||||
fh.close()
|
||||
assert "⚕".encode("utf-8") in real_path.read_bytes()
|
||||
|
||||
|
||||
def test_broken_stream_does_not_raise(monkeypatch):
|
||||
"""A stream whose repair raises must be swallowed, never crash import."""
|
||||
|
||||
class _Hostile:
|
||||
encoding = "latin-1"
|
||||
|
||||
def reconfigure(self, *a, **k):
|
||||
raise OSError("nope")
|
||||
|
||||
def fileno(self):
|
||||
raise OSError("no fd")
|
||||
|
||||
monkeypatch.setattr(sys, "stdout", _Hostile(), raising=False)
|
||||
monkeypatch.setattr(sys, "stderr", _Hostile(), raising=False)
|
||||
# Must not propagate.
|
||||
hermes_cli._ensure_utf8()
|
||||
|
||||
|
||||
def test_none_streams_do_not_raise(monkeypatch):
|
||||
"""pythonw / detached streams (sys.stdout is None) must be tolerated."""
|
||||
monkeypatch.setattr(sys, "stdout", None, raising=False)
|
||||
monkeypatch.setattr(sys, "stderr", None, raising=False)
|
||||
hermes_cli._ensure_utf8()
|
||||
@@ -369,16 +369,6 @@ def test_systemd_install_checks_linger_status(monkeypatch, tmp_path, capsys):
|
||||
unit_path = tmp_path / "systemd" / "user" / "hermes-gateway.service"
|
||||
|
||||
monkeypatch.setattr(gateway, "get_systemd_unit_path", lambda system=False: unit_path)
|
||||
# Synthetic unit with a non-temp home: the real generator bakes the
|
||||
# hermetic test HERMES_HOME (a tmp dir), which the temp-home write
|
||||
# guard correctly refuses.
|
||||
monkeypatch.setattr(
|
||||
gateway,
|
||||
"generate_systemd_unit",
|
||||
lambda system=False, run_as_user=None: (
|
||||
'[Service]\nEnvironment="HERMES_HOME=/home/alice/.hermes"\n'
|
||||
),
|
||||
)
|
||||
|
||||
calls = []
|
||||
helper_calls = []
|
||||
@@ -406,15 +396,6 @@ def test_systemd_install_can_skip_enable_on_startup(monkeypatch, tmp_path, capsy
|
||||
unit_path = tmp_path / "systemd" / "user" / "hermes-gateway.service"
|
||||
|
||||
monkeypatch.setattr(gateway, "get_systemd_unit_path", lambda system=False: unit_path)
|
||||
# Non-temp home so the temp-home write guard (which trips on the
|
||||
# hermetic test HERMES_HOME) stays out of the way.
|
||||
monkeypatch.setattr(
|
||||
gateway,
|
||||
"generate_systemd_unit",
|
||||
lambda system=False, run_as_user=None: (
|
||||
'[Service]\nEnvironment="HERMES_HOME=/home/alice/.hermes"\n'
|
||||
),
|
||||
)
|
||||
|
||||
calls = []
|
||||
helper_calls = []
|
||||
|
||||
@@ -102,15 +102,6 @@ def test_systemd_install_calls_linger_helper(monkeypatch, tmp_path, capsys):
|
||||
unit_path = tmp_path / "systemd" / "user" / "hermes-gateway.service"
|
||||
|
||||
monkeypatch.setattr(gateway, "get_systemd_unit_path", lambda system=False: unit_path)
|
||||
# Non-temp home so the temp-home write guard (which trips on the
|
||||
# hermetic test HERMES_HOME) stays out of the way.
|
||||
monkeypatch.setattr(
|
||||
gateway,
|
||||
"generate_systemd_unit",
|
||||
lambda system=False, run_as_user=None: (
|
||||
'[Service]\nEnvironment="HERMES_HOME=/home/alice/.hermes"\n'
|
||||
),
|
||||
)
|
||||
|
||||
calls = []
|
||||
|
||||
|
||||
@@ -289,105 +289,6 @@ class TestSystemdServiceRefresh:
|
||||
"daemon-reload" in str(c) for c in ran
|
||||
), "daemon-reload must not run when write was refused"
|
||||
|
||||
def test_refresh_refuses_to_bake_any_tempdir_home_into_real_user_unit(
|
||||
self, tmp_path, monkeypatch
|
||||
):
|
||||
"""Structural guard: a manual E2E HERMES_HOME like
|
||||
``/tmp/hermes-e2e-41264`` carries none of the pytest markers but
|
||||
poisons the unit identically (seen live 2026-06-11 — an E2E probe ran
|
||||
``hermes gateway restart`` with a /tmp HERMES_HOME exported; the
|
||||
restart's unit refresh baked it into the production unit and the
|
||||
post-update restart produced a 7-hour zombie gateway). The refresh
|
||||
must refuse ANY temp-dir HERMES_HOME, not just pytest-shaped ones.
|
||||
"""
|
||||
unit_path = tmp_path / "hermes-gateway.service"
|
||||
unit_path.write_text("old unit\n", encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(
|
||||
gateway_cli, "get_systemd_unit_path", lambda system=False: unit_path
|
||||
)
|
||||
polluted_unit = (
|
||||
"[Service]\n"
|
||||
'Environment="HERMES_HOME=/tmp/hermes-e2e-41264"\n'
|
||||
"WorkingDirectory=/tmp/hermes-e2e-41264\n"
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
gateway_cli,
|
||||
"generate_systemd_unit",
|
||||
lambda system=False, run_as_user=None: polluted_unit,
|
||||
)
|
||||
|
||||
ran = []
|
||||
|
||||
def fake_run(cmd, check=True, **kwargs):
|
||||
ran.append(cmd)
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
|
||||
|
||||
result = gateway_cli.refresh_systemd_unit_if_needed(system=False)
|
||||
|
||||
assert result is False, "refresh should refuse to write a temp-home unit"
|
||||
assert (
|
||||
unit_path.read_text(encoding="utf-8") == "old unit\n"
|
||||
), "installed unit must be left untouched"
|
||||
assert not any(
|
||||
"daemon-reload" in str(c) for c in ran
|
||||
), "daemon-reload must not run when write was refused"
|
||||
|
||||
|
||||
class TestTempHomeServiceDefinitionGuard:
|
||||
"""_temp_home_in_service_definition() — structural temp-dir detection."""
|
||||
|
||||
def test_detects_tmp_home_in_systemd_unit(self):
|
||||
unit = '[Service]\nEnvironment="HERMES_HOME=/tmp/hermes-e2e-41264"\n'
|
||||
assert (
|
||||
gateway_cli._temp_home_in_service_definition(unit)
|
||||
== "/tmp/hermes-e2e-41264"
|
||||
)
|
||||
|
||||
def test_detects_var_tmp_home(self):
|
||||
unit = '[Service]\nEnvironment="HERMES_HOME=/var/tmp/hermes-x"\n'
|
||||
assert gateway_cli._temp_home_in_service_definition(unit) is not None
|
||||
|
||||
def test_detects_tempdir_env_home(self, monkeypatch, tmp_path):
|
||||
import tempfile as _tempfile
|
||||
|
||||
monkeypatch.setattr(_tempfile, "gettempdir", lambda: str(tmp_path))
|
||||
unit = f'[Service]\nEnvironment="HERMES_HOME={tmp_path}/hermes-home"\n'
|
||||
assert gateway_cli._temp_home_in_service_definition(unit) is not None
|
||||
|
||||
def test_detects_tmp_home_in_launchd_plist(self):
|
||||
plist = (
|
||||
"<dict>\n <key>HERMES_HOME</key>\n"
|
||||
" <string>/tmp/hermes-e2e-99999</string>\n</dict>\n"
|
||||
)
|
||||
assert (
|
||||
gateway_cli._temp_home_in_service_definition(plist)
|
||||
== "/tmp/hermes-e2e-99999"
|
||||
)
|
||||
|
||||
def test_accepts_real_home(self):
|
||||
unit = '[Service]\nEnvironment="HERMES_HOME=/home/alice/.hermes"\n'
|
||||
assert gateway_cli._temp_home_in_service_definition(unit) is None
|
||||
|
||||
def test_accepts_macos_real_home_plist(self):
|
||||
plist = (
|
||||
"<dict>\n <key>HERMES_HOME</key>\n"
|
||||
" <string>/Users/alice/.hermes</string>\n</dict>\n"
|
||||
)
|
||||
assert gateway_cli._temp_home_in_service_definition(plist) is None
|
||||
|
||||
def test_accepts_unit_without_hermes_home(self):
|
||||
unit = "[Service]\nExecStart=/usr/bin/python -m hermes_cli.main gateway run\n"
|
||||
assert gateway_cli._temp_home_in_service_definition(unit) is None
|
||||
|
||||
def test_tmp_prefixed_non_temp_path_is_accepted(self):
|
||||
# /tmpfs-data is NOT under /tmp — prefix matching must be
|
||||
# component-wise, not string startswith.
|
||||
unit = '[Service]\nEnvironment="HERMES_HOME=/tmpfs-data/.hermes"\n'
|
||||
assert gateway_cli._temp_home_in_service_definition(unit) is None
|
||||
|
||||
|
||||
class TestRequireServiceInstalled:
|
||||
def test_exits_with_install_hint_when_unit_missing(self, tmp_path, monkeypatch, capsys):
|
||||
@@ -580,17 +481,6 @@ class TestLaunchdServiceRecovery:
|
||||
plist_path.write_text("<plist>old content</plist>", encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: plist_path)
|
||||
# Patch the generator with synthetic content carrying a real-looking
|
||||
# home — the temp-home guard refuses to write plists whose
|
||||
# HERMES_HOME resolves under the (pytest tmp) test HERMES_HOME.
|
||||
monkeypatch.setattr(
|
||||
gateway_cli,
|
||||
"generate_launchd_plist",
|
||||
lambda: (
|
||||
"<plist>--replace\n<key>HERMES_HOME</key>"
|
||||
"<string>/Users/alice/.hermes</string></plist>"
|
||||
),
|
||||
)
|
||||
|
||||
calls = []
|
||||
|
||||
@@ -605,10 +495,7 @@ class TestLaunchdServiceRecovery:
|
||||
label = gateway_cli.get_launchd_label()
|
||||
domain = gateway_cli._launchd_domain()
|
||||
assert "--replace" in plist_path.read_text(encoding="utf-8")
|
||||
# The calls list includes launchctl print probes from _launchd_domain()
|
||||
# before the bootout/bootstrap calls. Filter to only bootout/bootstrap.
|
||||
service_calls = [c for c in calls if "bootout" in c or "bootstrap" in c]
|
||||
assert service_calls[:2] == [
|
||||
assert calls[:2] == [
|
||||
["launchctl", "bootout", f"{domain}/{label}"],
|
||||
["launchctl", "bootstrap", domain, str(plist_path)],
|
||||
]
|
||||
@@ -792,22 +679,10 @@ class TestLaunchdServiceRecovery:
|
||||
assert "stale" in output.lower()
|
||||
assert "not loaded" in output.lower()
|
||||
|
||||
def test_launchd_domain_uses_user_domain(self, monkeypatch):
|
||||
def test_launchd_domain_uses_user_domain(self):
|
||||
# The user/<uid> domain (not gui/<uid>) is the one reachable from
|
||||
# non-Aqua/background sessions on macOS 26+ (issue #23387).
|
||||
# When gui/<uid> fails to probe and user/<uid> succeeds,
|
||||
# _launchd_domain() must return user/<uid>.
|
||||
gateway_cli._resolved_launchd_domain = None
|
||||
monkeypatch.setattr(os, "getuid", lambda: 501)
|
||||
label = gateway_cli.get_launchd_label()
|
||||
|
||||
def fake_run(cmd, check=False, **kwargs):
|
||||
if "print" in cmd and "gui/" in " ".join(cmd):
|
||||
raise subprocess.CalledProcessError(1, cmd, stderr="Domain error")
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
|
||||
assert gateway_cli._launchd_domain() == "user/501"
|
||||
assert gateway_cli._launchd_domain() == f"user/{os.getuid()}"
|
||||
|
||||
def test_launchctl_domain_unsupported_recognizes_macos26_codes(self):
|
||||
# Codes that persist after a fresh bootstrap → launchd truly unavailable.
|
||||
@@ -886,17 +761,6 @@ class TestLaunchdServiceRecovery:
|
||||
"""macOS bootstrap error 5 should spawn a detached gateway, not crash."""
|
||||
plist_path = tmp_path / "ai.hermes.gateway.plist"
|
||||
monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: plist_path)
|
||||
# Synthetic plist with a non-temp home so the temp-home write guard
|
||||
# (which would trip on the pytest-tmp test HERMES_HOME) stays out of
|
||||
# the way — this test exercises the bootstrap-error fallback.
|
||||
monkeypatch.setattr(
|
||||
gateway_cli,
|
||||
"generate_launchd_plist",
|
||||
lambda: (
|
||||
"<plist><key>HERMES_HOME</key>"
|
||||
"<string>/Users/alice/.hermes</string></plist>"
|
||||
),
|
||||
)
|
||||
|
||||
def fake_run(cmd, check=False, **kwargs):
|
||||
if cmd[:2] == ["launchctl", "bootstrap"]:
|
||||
@@ -972,114 +836,6 @@ class TestLaunchdServiceRecovery:
|
||||
assert "nohup hermes gateway run" in out
|
||||
|
||||
|
||||
class TestLaunchdDomainDetection:
|
||||
"""Regression tests for _launchd_domain() probing (#40831).
|
||||
|
||||
The function must detect which launchd domain actually contains (or can
|
||||
manage) the service, rather than hardcoding ``user/<uid>`` or ``gui/<uid>``.
|
||||
"""
|
||||
|
||||
def _reset_domain_cache(self):
|
||||
"""Clear any cached domain result between tests."""
|
||||
gateway_cli._resolved_launchd_domain = None
|
||||
|
||||
def test_prefers_gui_domain_when_service_loaded_there(self, monkeypatch):
|
||||
"""In an Aqua session where the service is loaded under gui/<uid>,
|
||||
_launchd_domain() must return ``gui/<uid>`` — not ``user/<uid>``."""
|
||||
self._reset_domain_cache()
|
||||
monkeypatch.setattr(os, "getuid", lambda: 501)
|
||||
label = gateway_cli.get_launchd_label()
|
||||
|
||||
run_calls = []
|
||||
|
||||
def fake_run(cmd, check=False, **kwargs):
|
||||
run_calls.append(cmd)
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
|
||||
|
||||
domain = gateway_cli._launchd_domain()
|
||||
assert domain == f"gui/501"
|
||||
# Should have probed gui first
|
||||
assert run_calls[0] == ["launchctl", "print", f"gui/501/{label}"]
|
||||
|
||||
def test_falls_back_to_user_domain_when_gui_fails(self, monkeypatch):
|
||||
"""In a Background/SSH session where gui/<uid> fails but user/<uid>
|
||||
works, _launchd_domain() must return ``user/<uid>``."""
|
||||
self._reset_domain_cache()
|
||||
monkeypatch.setattr(os, "getuid", lambda: 501)
|
||||
label = gateway_cli.get_launchd_label()
|
||||
|
||||
run_calls = []
|
||||
|
||||
def fake_run(cmd, check=False, **kwargs):
|
||||
run_calls.append(cmd)
|
||||
if "print" in cmd and "gui/" in " ".join(cmd):
|
||||
raise subprocess.CalledProcessError(1, cmd, stderr="Domain error")
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
|
||||
|
||||
domain = gateway_cli._launchd_domain()
|
||||
assert domain == f"user/501"
|
||||
# Should have tried gui first, then user
|
||||
assert len(run_calls) >= 2
|
||||
|
||||
def test_uses_managername_heuristic_when_both_probe_fail(self, monkeypatch):
|
||||
"""When neither domain contains a loaded service, use
|
||||
``launchctl managername`` as a tiebreaker: Aqua -> gui, else -> user."""
|
||||
self._reset_domain_cache()
|
||||
monkeypatch.setattr(os, "getuid", lambda: 501)
|
||||
label = gateway_cli.get_launchd_label()
|
||||
|
||||
def fake_run(cmd, check=False, **kwargs):
|
||||
if "print" in cmd:
|
||||
raise subprocess.CalledProcessError(1, cmd, stderr="not found")
|
||||
if "managername" in cmd:
|
||||
return SimpleNamespace(returncode=0, stdout="Aqua\n", stderr="")
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
|
||||
|
||||
domain = gateway_cli._launchd_domain()
|
||||
assert domain == f"gui/501"
|
||||
|
||||
def test_managername_background_selects_user_domain(self, monkeypatch):
|
||||
"""When managername is Background (non-Aqua), use user/<uid>."""
|
||||
self._reset_domain_cache()
|
||||
monkeypatch.setattr(os, "getuid", lambda: 501)
|
||||
|
||||
def fake_run(cmd, check=False, **kwargs):
|
||||
if "print" in cmd:
|
||||
raise subprocess.CalledProcessError(1, cmd, stderr="not found")
|
||||
if "managername" in cmd:
|
||||
return SimpleNamespace(returncode=0, stdout="Background\n", stderr="")
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
|
||||
|
||||
domain = gateway_cli._launchd_domain()
|
||||
assert domain == f"user/501"
|
||||
|
||||
def test_caches_result_across_calls(self, monkeypatch):
|
||||
"""Domain detection should run once and cache the result."""
|
||||
self._reset_domain_cache()
|
||||
monkeypatch.setattr(os, "getuid", lambda: 501)
|
||||
|
||||
run_count = [0]
|
||||
|
||||
def fake_run(cmd, check=False, **kwargs):
|
||||
run_count[0] += 1
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
|
||||
|
||||
d1 = gateway_cli._launchd_domain()
|
||||
d2 = gateway_cli._launchd_domain()
|
||||
assert d1 == d2
|
||||
assert run_count[0] == 1 # Only probed once
|
||||
|
||||
|
||||
class TestGatewayServiceDetection:
|
||||
def test_supports_systemd_services_requires_systemctl_binary(self, monkeypatch):
|
||||
monkeypatch.setattr(gateway_cli, "is_linux", lambda: True)
|
||||
@@ -2016,12 +1772,7 @@ class TestProfileArg:
|
||||
monkeypatch.setattr(gateway_cli, "get_hermes_home", lambda: profile_dir)
|
||||
unit = gateway_cli.generate_systemd_unit(system=False)
|
||||
assert "--profile mybot" in unit
|
||||
assert "gateway run" in unit
|
||||
# Under a process supervisor (Restart=always), --replace makes each
|
||||
# restart kill its predecessor → self-kill loop. The systemd unit must
|
||||
# NOT use --replace; the supervisor owns the lifecycle. (--replace stays
|
||||
# on the manual launchd fallback path — see test_launchd_plist_includes_profile.)
|
||||
assert "--replace" not in unit
|
||||
assert "gateway run --replace" in unit
|
||||
|
||||
def test_launchd_plist_includes_profile(self, tmp_path, monkeypatch):
|
||||
"""generate_launchd_plist should include --profile in ProgramArguments for named profiles."""
|
||||
|
||||
@@ -70,7 +70,7 @@ def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):
|
||||
cli_main.cmd_gui(_ns())
|
||||
|
||||
assert exc.value.code == 0
|
||||
mock_install.assert_called_once_with("/usr/bin/npm", root, capture_output=False, env=None)
|
||||
mock_install.assert_called_once_with("/usr/bin/npm", root, capture_output=False)
|
||||
assert mock_run.call_args_list[0].args[0] == ["/usr/bin/npm", "run", "pack"]
|
||||
assert mock_run.call_args_list[0].kwargs["cwd"] == desktop_dir
|
||||
assert mock_run.call_args_list[1].args[0] == [str(packaged_exe)]
|
||||
@@ -498,42 +498,11 @@ def test_gui_retries_pack_once_after_purging_build_cache(tmp_path, monkeypatch):
|
||||
assert mock_run.call_args_list[2].args[0] == [str(packaged_exe)]
|
||||
|
||||
|
||||
def test_gui_falls_back_to_mirror_when_purge_finds_nothing(tmp_path, monkeypatch, capsys):
|
||||
"""Purge clears nothing (not a cache problem) → fall back to an Electron
|
||||
mirror once before failing, so a GitHub-blocked download self-heals."""
|
||||
def test_gui_does_not_retry_when_purge_finds_nothing(tmp_path, monkeypatch, capsys):
|
||||
"""If the purge clears nothing, there's no point retrying — fail fast."""
|
||||
root = _make_desktop_tree(tmp_path)
|
||||
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
|
||||
_make_packaged_executable(root, monkeypatch, platform="linux")
|
||||
monkeypatch.delenv("ELECTRON_MIRROR", raising=False)
|
||||
|
||||
install_ok = subprocess.CompletedProcess(["npm", "ci"], 0)
|
||||
pack_fail = subprocess.CompletedProcess(["npm", "run", "pack"], 1)
|
||||
|
||||
with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
|
||||
patch("hermes_cli.main._run_npm_install_deterministic", return_value=install_ok), \
|
||||
patch("hermes_cli.main._desktop_macos_relaunchable_fixup"), \
|
||||
patch("hermes_cli.main._purge_electron_build_cache", return_value=[]) as mock_purge, \
|
||||
patch("hermes_cli.main.subprocess.run", side_effect=[pack_fail, pack_fail]) as mock_run, \
|
||||
pytest.raises(SystemExit) as exc:
|
||||
cli_main.cmd_gui(_ns())
|
||||
|
||||
assert exc.value.code == 1
|
||||
mock_purge.assert_called_once()
|
||||
# pack(fail) → purge(nothing) → pack via mirror(fail) = 2 subprocess.run calls
|
||||
assert mock_run.call_count == 2
|
||||
# The retry runs the same build but with ELECTRON_MIRROR injected.
|
||||
assert "ELECTRON_MIRROR" not in (mock_run.call_args_list[0].kwargs.get("env") or {})
|
||||
assert mock_run.call_args_list[1].kwargs["env"]["ELECTRON_MIRROR"]
|
||||
assert "Desktop GUI build failed" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_gui_does_not_override_user_electron_mirror(tmp_path, monkeypatch, capsys):
|
||||
"""A user-pinned ELECTRON_MIRROR is respected: no extra mirror fallback
|
||||
attempt (and we never swap in our default mirror)."""
|
||||
root = _make_desktop_tree(tmp_path)
|
||||
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
|
||||
_make_packaged_executable(root, monkeypatch, platform="linux")
|
||||
monkeypatch.setenv("ELECTRON_MIRROR", "https://mirror.example/electron/")
|
||||
|
||||
install_ok = subprocess.CompletedProcess(["npm", "ci"], 0)
|
||||
pack_fail = subprocess.CompletedProcess(["npm", "run", "pack"], 1)
|
||||
@@ -549,80 +518,4 @@ def test_gui_does_not_override_user_electron_mirror(tmp_path, monkeypatch, capsy
|
||||
assert exc.value.code == 1
|
||||
mock_purge.assert_called_once()
|
||||
assert mock_run.call_count == 1
|
||||
assert mock_run.call_args_list[0].kwargs["env"]["ELECTRON_MIRROR"] == "https://mirror.example/electron/"
|
||||
assert "Desktop GUI build failed" in capsys.readouterr().out
|
||||
|
||||
|
||||
class _FakeProc:
|
||||
"""Minimal psutil.Process stand-in for the lock-breaker tests."""
|
||||
|
||||
def __init__(self, pid: int, exe: str | None):
|
||||
self.pid = pid
|
||||
self.info = {"pid": pid, "exe": exe}
|
||||
self.terminated = False
|
||||
self.killed = False
|
||||
|
||||
def terminate(self):
|
||||
self.terminated = True
|
||||
|
||||
def kill(self):
|
||||
self.killed = True
|
||||
|
||||
|
||||
def test_stop_desktop_build_lock_noop_off_windows(tmp_path, monkeypatch):
|
||||
"""POSIX can unlink a running binary, so the helper is a no-op there."""
|
||||
desktop_dir = tmp_path / "apps" / "desktop"
|
||||
exe = desktop_dir / "release" / "linux-unpacked" / "hermes"
|
||||
exe.parent.mkdir(parents=True)
|
||||
exe.write_text("", encoding="utf-8")
|
||||
monkeypatch.setattr(cli_main.sys, "platform", "linux")
|
||||
|
||||
proc = _FakeProc(4321, str(exe))
|
||||
with patch("psutil.process_iter", return_value=[proc]) as it:
|
||||
assert cli_main._stop_desktop_processes_locking_build(desktop_dir) == []
|
||||
it.assert_not_called()
|
||||
assert proc.terminated is False
|
||||
|
||||
|
||||
def test_stop_desktop_build_lock_terminates_only_release_procs(tmp_path, monkeypatch):
|
||||
desktop_dir = tmp_path / "apps" / "desktop"
|
||||
release = desktop_dir / "release" / "win-unpacked"
|
||||
release.mkdir(parents=True)
|
||||
locker_exe = release / "Hermes.exe"
|
||||
locker_exe.write_text("", encoding="utf-8")
|
||||
other_exe = tmp_path / "elsewhere" / "Hermes.exe"
|
||||
other_exe.parent.mkdir(parents=True)
|
||||
other_exe.write_text("", encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(cli_main.sys, "platform", "win32")
|
||||
monkeypatch.setattr(cli_main.os, "getpid", lambda: 999)
|
||||
|
||||
locker = _FakeProc(101, str(locker_exe))
|
||||
unrelated = _FakeProc(102, str(other_exe))
|
||||
selfish = _FakeProc(999, str(locker_exe)) # our own PID — never killed
|
||||
no_exe = _FakeProc(103, None)
|
||||
|
||||
captured = {}
|
||||
|
||||
def _wait(procs, timeout=None):
|
||||
captured["waited"] = list(procs)
|
||||
return procs, []
|
||||
|
||||
with patch("psutil.process_iter", return_value=[locker, unrelated, selfish, no_exe]), \
|
||||
patch("psutil.wait_procs", side_effect=_wait):
|
||||
stopped = cli_main._stop_desktop_processes_locking_build(desktop_dir)
|
||||
|
||||
assert stopped == [101]
|
||||
assert locker.terminated is True
|
||||
assert unrelated.terminated is False
|
||||
assert selfish.terminated is False
|
||||
assert captured["waited"] == [locker]
|
||||
|
||||
|
||||
def test_stop_desktop_build_lock_no_release_dir(tmp_path, monkeypatch):
|
||||
desktop_dir = tmp_path / "apps" / "desktop"
|
||||
desktop_dir.mkdir(parents=True)
|
||||
monkeypatch.setattr(cli_main.sys, "platform", "win32")
|
||||
with patch("psutil.process_iter") as it:
|
||||
assert cli_main._stop_desktop_processes_locking_build(desktop_dir) == []
|
||||
it.assert_not_called()
|
||||
|
||||
@@ -41,7 +41,6 @@ def _build_parser():
|
||||
mcp_add.add_argument("name")
|
||||
mcp_add.add_argument("--url")
|
||||
mcp_add.add_argument("--command", dest="mcp_command")
|
||||
mcp_add.add_argument("--args", nargs=argparse.REMAINDER, default=[])
|
||||
|
||||
return parser
|
||||
|
||||
@@ -86,26 +85,3 @@ class TestMcpAddCommandDest:
|
||||
assert args.command == "mcp"
|
||||
assert args.mcp_command is None
|
||||
assert args.url is None
|
||||
|
||||
def test_args_passthrough_keeps_nested_option_flags(self):
|
||||
"""`--args` must keep command flags like Docker MCP's --profile."""
|
||||
parser = _build_parser()
|
||||
args = parser.parse_args(
|
||||
[
|
||||
"mcp",
|
||||
"add",
|
||||
"docker-research",
|
||||
"--command",
|
||||
"docker",
|
||||
"--args",
|
||||
"mcp",
|
||||
"gateway",
|
||||
"run",
|
||||
"--profile",
|
||||
"research",
|
||||
]
|
||||
)
|
||||
|
||||
assert args.command == "mcp"
|
||||
assert args.mcp_command == "docker"
|
||||
assert args.args == ["mcp", "gateway", "run", "--profile", "research"]
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from agent.models_dev import ModelInfo
|
||||
from agent.usage_pricing import PricingEntry
|
||||
from hermes_cli.model_cost_guard import expensive_model_warning
|
||||
|
||||
|
||||
def test_no_warning_when_known_prices_are_at_threshold():
|
||||
info = ModelInfo(
|
||||
id="edge/model",
|
||||
name="edge/model",
|
||||
family="",
|
||||
provider_id="test",
|
||||
cost_input=20.0,
|
||||
cost_output=100.0,
|
||||
)
|
||||
|
||||
assert expensive_model_warning("edge/model", provider="test", model_info=info) is None
|
||||
|
||||
|
||||
def test_warns_when_models_dev_input_price_exceeds_threshold():
|
||||
info = ModelInfo(
|
||||
id="expensive/input",
|
||||
name="expensive/input",
|
||||
family="",
|
||||
provider_id="test",
|
||||
cost_input=20.01,
|
||||
cost_output=1.0,
|
||||
)
|
||||
|
||||
warning = expensive_model_warning(
|
||||
"expensive/input",
|
||||
provider="test",
|
||||
model_info=info,
|
||||
)
|
||||
|
||||
assert warning is not None
|
||||
assert warning.input_cost_per_million == Decimal("20.01")
|
||||
assert "EXPENSIVE MODEL WARNING" in warning.message
|
||||
assert "$20/M input" in warning.message
|
||||
|
||||
|
||||
def test_warns_when_pricing_entry_output_price_exceeds_threshold(monkeypatch):
|
||||
monkeypatch.setattr("agent.models_dev.get_model_info", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
"agent.usage_pricing.get_pricing_entry",
|
||||
lambda *_args, **_kwargs: PricingEntry(
|
||||
input_cost_per_million=Decimal("1.00"),
|
||||
output_cost_per_million=Decimal("100.01"),
|
||||
source="provider_models_api",
|
||||
),
|
||||
)
|
||||
|
||||
warning = expensive_model_warning("provider/expensive-output", provider="openrouter")
|
||||
|
||||
assert warning is not None
|
||||
assert warning.output_cost_per_million == Decimal("100.01")
|
||||
assert "$100.01/M" in warning.message
|
||||
|
||||
|
||||
def test_openai_gpt55_pro_adds_suggestion(monkeypatch):
|
||||
monkeypatch.setattr("agent.models_dev.get_model_info", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
"agent.usage_pricing.get_pricing_entry",
|
||||
lambda *_args, **_kwargs: PricingEntry(
|
||||
input_cost_per_million=Decimal("25"),
|
||||
output_cost_per_million=Decimal("125"),
|
||||
source="provider_models_api",
|
||||
),
|
||||
)
|
||||
|
||||
warning = expensive_model_warning("openai/gpt-5.5-pro", provider="openrouter")
|
||||
|
||||
assert warning is not None
|
||||
assert "did you mean to select openai/gpt-5.5?" in warning.message
|
||||
|
||||
|
||||
def test_openai_gpt55_pro_warns_for_nous_portal_pricing(monkeypatch):
|
||||
monkeypatch.setattr("agent.models_dev.get_model_info", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
"agent.usage_pricing.fetch_endpoint_model_metadata",
|
||||
lambda base_url, api_key="": {
|
||||
"openai/gpt-5.5-pro": {
|
||||
"pricing": {
|
||||
"prompt": "0.000025",
|
||||
"completion": "0.000125",
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
warning = expensive_model_warning("openai/gpt-5.5-pro", provider="nous")
|
||||
|
||||
assert warning is not None
|
||||
assert warning.input_cost_per_million == Decimal("25.000000")
|
||||
assert warning.output_cost_per_million == Decimal("125.000000")
|
||||
assert "did you mean to select openai/gpt-5.5?" in warning.message
|
||||
@@ -1,64 +0,0 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
from hermes_cli.model_switch import ModelSwitchResult
|
||||
|
||||
|
||||
def _bound(fn, instance):
|
||||
return fn.__get__(instance, type(instance))
|
||||
|
||||
|
||||
def test_prompt_toolkit_model_picker_defers_confirmation_off_key_handler(monkeypatch):
|
||||
import cli as cli_mod
|
||||
|
||||
result = ModelSwitchResult(
|
||||
success=True,
|
||||
new_model="openai/gpt-5.5-pro",
|
||||
target_provider="nous",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.model_switch.switch_model",
|
||||
lambda **_kwargs: result,
|
||||
)
|
||||
|
||||
captured = {}
|
||||
|
||||
class _Thread:
|
||||
def __init__(self, *, target, args, daemon):
|
||||
captured["target"] = target
|
||||
captured["args"] = args
|
||||
captured["daemon"] = daemon
|
||||
|
||||
def start(self):
|
||||
captured["started"] = True
|
||||
|
||||
monkeypatch.setattr(cli_mod.threading, "Thread", _Thread)
|
||||
|
||||
self_ = SimpleNamespace(
|
||||
_app=object(),
|
||||
_model_picker_state={
|
||||
"stage": "model",
|
||||
"provider_data": {"slug": "nous"},
|
||||
"model_list": ["openai/gpt-5.5-pro"],
|
||||
"selected": 0,
|
||||
"user_provs": None,
|
||||
"custom_provs": None,
|
||||
},
|
||||
provider="nous",
|
||||
model="openai/gpt-5.5",
|
||||
base_url="",
|
||||
api_key="",
|
||||
_restore_modal_input_snapshot=lambda: None,
|
||||
_invalidate=lambda **_kwargs: None,
|
||||
)
|
||||
self_._close_model_picker = _bound(cli_mod.HermesCLI._close_model_picker, self_)
|
||||
self_._confirm_and_apply_model_switch_result = (
|
||||
lambda *_args: captured.setdefault("ran_inline", True)
|
||||
)
|
||||
|
||||
_bound(cli_mod.HermesCLI._handle_model_picker_selection, self_)()
|
||||
|
||||
assert self_._model_picker_state is None
|
||||
assert captured["started"] is True
|
||||
assert captured["daemon"] is True
|
||||
assert captured["args"] == (result, False)
|
||||
assert "ran_inline" not in captured
|
||||
@@ -65,15 +65,6 @@ def test_resolve_provider_full_finds_named_custom_provider():
|
||||
assert resolved.source == "user-config"
|
||||
|
||||
|
||||
def test_is_aggregator_recognizes_named_custom_provider():
|
||||
assert providers_mod.is_aggregator("custom:hpc-ai") is True
|
||||
assert providers_mod.is_aggregator("custom:litellm") is True
|
||||
|
||||
|
||||
def test_is_aggregator_leaves_unknown_provider_non_aggregator():
|
||||
assert providers_mod.is_aggregator("not-a-provider") is False
|
||||
|
||||
|
||||
def test_switch_model_accepts_explicit_named_custom_provider(monkeypatch):
|
||||
"""Shared /model switch pipeline should accept --provider for custom_providers."""
|
||||
monkeypatch.setattr(
|
||||
|
||||
@@ -365,40 +365,6 @@ class TestPluginDiscovery:
|
||||
}
|
||||
assert len(non_bundled) == 1
|
||||
|
||||
def test_failed_discovery_is_not_cached(self, tmp_path, monkeypatch):
|
||||
"""A sweep that raises must not cache 'discovered' with no plugins.
|
||||
|
||||
Regression for the stranded-empty-registry class of failures: callers
|
||||
(e.g. tools.web_tools._ensure_web_plugins_loaded) swallow discovery
|
||||
exceptions as warnings, so if a failed sweep flipped ``_discovered``
|
||||
permanently, every later call would early-return against an empty
|
||||
registry ("No web provider configured") for the process lifetime.
|
||||
"""
|
||||
plugins_dir = tmp_path / "hermes_test" / "plugins"
|
||||
_make_plugin_dir(plugins_dir, "retry_plugin")
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes_test"))
|
||||
|
||||
mgr = PluginManager()
|
||||
|
||||
def _boom(self_inner):
|
||||
raise RuntimeError("sweep failed")
|
||||
|
||||
monkeypatch.setattr(PluginManager, "_discover_and_load_inner", _boom)
|
||||
with pytest.raises(RuntimeError, match="sweep failed"):
|
||||
mgr.discover_and_load()
|
||||
assert mgr._discovered is False, "failed sweep was cached as discovered"
|
||||
|
||||
# A later call (with discovery healthy again) must do the real scan.
|
||||
monkeypatch.undo()
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes_test"))
|
||||
mgr.discover_and_load()
|
||||
assert mgr._discovered is True
|
||||
non_bundled = {
|
||||
n: p for n, p in mgr._plugins.items()
|
||||
if p.manifest.source != "bundled"
|
||||
}
|
||||
assert len(non_bundled) == 1
|
||||
|
||||
def test_discover_skips_dir_without_manifest(self, tmp_path, monkeypatch):
|
||||
"""Directories without plugin.yaml are silently skipped."""
|
||||
plugins_dir = tmp_path / "hermes_test" / "plugins"
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -18,7 +16,6 @@ from hermes_cli.plugins_cmd import (
|
||||
_repo_name_from_url,
|
||||
_resolve_git_executable,
|
||||
_resolve_git_url,
|
||||
_resolve_subdir_within,
|
||||
_sanitize_plugin_name,
|
||||
)
|
||||
|
||||
@@ -100,127 +97,35 @@ class TestSanitizePluginName:
|
||||
|
||||
|
||||
class TestResolveGitUrl:
|
||||
"""Shorthand and full-URL resolution, with optional subdirectory."""
|
||||
"""Shorthand and full-URL resolution."""
|
||||
|
||||
def test_owner_repo_shorthand(self):
|
||||
url, subdir = _resolve_git_url("owner/repo")
|
||||
url = _resolve_git_url("owner/repo")
|
||||
assert url == "https://github.com/owner/repo.git"
|
||||
assert subdir is None
|
||||
|
||||
def test_https_url_passthrough(self):
|
||||
url, subdir = _resolve_git_url("https://github.com/x/y.git")
|
||||
url = _resolve_git_url("https://github.com/x/y.git")
|
||||
assert url == "https://github.com/x/y.git"
|
||||
assert subdir is None
|
||||
|
||||
def test_ssh_url_passthrough(self):
|
||||
url, subdir = _resolve_git_url("git@github.com:x/y.git")
|
||||
url = _resolve_git_url("git@github.com:x/y.git")
|
||||
assert url == "git@github.com:x/y.git"
|
||||
assert subdir is None
|
||||
|
||||
def test_http_url_passthrough(self):
|
||||
url, subdir = _resolve_git_url("http://example.com/repo.git")
|
||||
url = _resolve_git_url("http://example.com/repo.git")
|
||||
assert url == "http://example.com/repo.git"
|
||||
assert subdir is None
|
||||
|
||||
def test_file_url_passthrough(self):
|
||||
url, subdir = _resolve_git_url("file:///tmp/repo")
|
||||
url = _resolve_git_url("file:///tmp/repo")
|
||||
assert url == "file:///tmp/repo"
|
||||
assert subdir is None
|
||||
|
||||
def test_invalid_single_word_raises(self):
|
||||
with pytest.raises(ValueError, match="Invalid plugin identifier"):
|
||||
_resolve_git_url("justoneword")
|
||||
|
||||
def test_shorthand_with_subdir(self):
|
||||
url, subdir = _resolve_git_url("owner/repo/my-plugin")
|
||||
assert url == "https://github.com/owner/repo.git"
|
||||
assert subdir == "my-plugin"
|
||||
|
||||
def test_shorthand_with_nested_subdir(self):
|
||||
url, subdir = _resolve_git_url("owner/repo/path/to/plugin")
|
||||
assert url == "https://github.com/owner/repo.git"
|
||||
assert subdir == "path/to/plugin"
|
||||
|
||||
def test_shorthand_with_subdir_trailing_slash(self):
|
||||
url, subdir = _resolve_git_url("owner/repo/my-plugin/")
|
||||
assert url == "https://github.com/owner/repo.git"
|
||||
assert subdir == "my-plugin"
|
||||
|
||||
def test_https_url_with_subdir(self):
|
||||
url, subdir = _resolve_git_url("https://github.com/owner/repo.git/my-plugin")
|
||||
assert url == "https://github.com/owner/repo.git"
|
||||
assert subdir == "my-plugin"
|
||||
|
||||
def test_https_url_with_nested_subdir(self):
|
||||
url, subdir = _resolve_git_url(
|
||||
"https://github.com/owner/repo.git/path/to/plugin"
|
||||
)
|
||||
assert url == "https://github.com/owner/repo.git"
|
||||
assert subdir == "path/to/plugin"
|
||||
|
||||
def test_url_with_fragment_subdir(self):
|
||||
url, subdir = _resolve_git_url("https://github.com/owner/repo.git#my-plugin")
|
||||
assert url == "https://github.com/owner/repo.git"
|
||||
assert subdir == "my-plugin"
|
||||
|
||||
def test_file_url_with_fragment_subdir(self):
|
||||
url, subdir = _resolve_git_url("file:///tmp/repo#path/to/plugin")
|
||||
assert url == "file:///tmp/repo"
|
||||
assert subdir == "path/to/plugin"
|
||||
|
||||
def test_ssh_url_with_fragment_subdir(self):
|
||||
url, subdir = _resolve_git_url("git@github.com:owner/repo.git#sub")
|
||||
assert url == "git@github.com:owner/repo.git"
|
||||
assert subdir == "sub"
|
||||
|
||||
|
||||
# ── _resolve_subdir_within ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestResolveSubdirWithin:
|
||||
"""Subdirectory resolution stays within the clone and rejects traversal."""
|
||||
|
||||
def test_valid_subdir(self, tmp_path):
|
||||
(tmp_path / "my-plugin").mkdir()
|
||||
result = _resolve_subdir_within(tmp_path, "my-plugin")
|
||||
assert result == (tmp_path / "my-plugin").resolve()
|
||||
|
||||
def test_valid_nested_subdir(self, tmp_path):
|
||||
(tmp_path / "a" / "b" / "c").mkdir(parents=True)
|
||||
result = _resolve_subdir_within(tmp_path, "a/b/c")
|
||||
assert result == (tmp_path / "a" / "b" / "c").resolve()
|
||||
|
||||
def test_rejects_dot_dot_escape(self, tmp_path):
|
||||
clone = tmp_path / "clone"
|
||||
clone.mkdir()
|
||||
(tmp_path / "secret").mkdir()
|
||||
with pytest.raises(PluginOperationError, match="escapes the repository"):
|
||||
_resolve_subdir_within(clone, "../secret")
|
||||
|
||||
def test_rejects_absolute_path_escape(self, tmp_path):
|
||||
clone = tmp_path / "clone"
|
||||
clone.mkdir()
|
||||
# An absolute path resolves outside the clone root.
|
||||
with pytest.raises(PluginOperationError, match="escapes the repository"):
|
||||
_resolve_subdir_within(clone, "/etc")
|
||||
|
||||
def test_rejects_symlink_escape(self, tmp_path):
|
||||
clone = tmp_path / "clone"
|
||||
clone.mkdir()
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
(clone / "link").symlink_to(outside)
|
||||
with pytest.raises(PluginOperationError, match="escapes the repository"):
|
||||
_resolve_subdir_within(clone, "link")
|
||||
|
||||
def test_rejects_missing_subdir(self, tmp_path):
|
||||
with pytest.raises(PluginOperationError, match="does not exist"):
|
||||
_resolve_subdir_within(tmp_path, "nope")
|
||||
|
||||
def test_rejects_file_not_dir(self, tmp_path):
|
||||
(tmp_path / "afile").write_text("x")
|
||||
with pytest.raises(PluginOperationError, match="not a directory"):
|
||||
_resolve_subdir_within(tmp_path, "afile")
|
||||
def test_invalid_three_parts_raises(self):
|
||||
with pytest.raises(ValueError, match="Invalid plugin identifier"):
|
||||
_resolve_git_url("a/b/c")
|
||||
|
||||
|
||||
# ── _resolve_git_executable ─────────────────────────────────────────────────
|
||||
@@ -793,90 +698,3 @@ class TestNoAutoActivation:
|
||||
# The old code had: "Even with default config, check if a plugin registered one"
|
||||
# The fix removes this. Verify it's gone.
|
||||
assert "Even with default config, check if a plugin registered one" not in source
|
||||
|
||||
|
||||
# ── End-to-end subdirectory install ──────────────────────────────────────────
|
||||
|
||||
|
||||
class TestSubdirInstallE2E:
|
||||
"""Install a plugin that lives in a subdirectory of a real local git repo."""
|
||||
|
||||
@staticmethod
|
||||
def _make_repo_with_subdir_plugin(repo_root: Path) -> None:
|
||||
"""Create a git repo where the plugin lives in ``./my-plugin/`` and the
|
||||
repo root holds unrelated docs/tests."""
|
||||
import subprocess as sp
|
||||
|
||||
repo_root.mkdir(parents=True, exist_ok=True)
|
||||
# Root-level noise: docs + tests that should NOT be installed.
|
||||
(repo_root / "README.md").write_text("# Monorepo docs\n")
|
||||
(repo_root / "tests").mkdir()
|
||||
(repo_root / "tests" / "test_x.py").write_text("def test_x():\n pass\n")
|
||||
# The actual plugin in a subdirectory.
|
||||
plugin_dir = repo_root / "my-plugin"
|
||||
plugin_dir.mkdir()
|
||||
(plugin_dir / "plugin.yaml").write_text(
|
||||
"name: my-plugin\nmanifest_version: 1\ndescription: A subdir plugin\n"
|
||||
)
|
||||
(plugin_dir / "__init__.py").write_text("# plugin entry\n")
|
||||
|
||||
env = {
|
||||
**os.environ,
|
||||
"GIT_AUTHOR_NAME": "t",
|
||||
"GIT_AUTHOR_EMAIL": "t@t",
|
||||
"GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@t",
|
||||
}
|
||||
sp.run(["git", "init", "-q"], cwd=repo_root, check=True, env=env)
|
||||
sp.run(["git", "add", "-A"], cwd=repo_root, check=True, env=env)
|
||||
sp.run(
|
||||
["git", "commit", "-q", "-m", "init"],
|
||||
cwd=repo_root,
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
def test_installs_only_the_subdir_plugin(self, tmp_path, monkeypatch):
|
||||
if shutil.which("git") is None:
|
||||
pytest.skip("git not available")
|
||||
|
||||
from hermes_cli import plugins_cmd as pc
|
||||
|
||||
repo_root = tmp_path / "monorepo"
|
||||
self._make_repo_with_subdir_plugin(repo_root)
|
||||
|
||||
plugins_dir = tmp_path / "installed"
|
||||
plugins_dir.mkdir()
|
||||
monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)
|
||||
|
||||
identifier = f"file://{repo_root}#my-plugin"
|
||||
target, manifest, name = pc._install_plugin_core(identifier, force=False)
|
||||
|
||||
# Installed under the plugin's own name, not the repo name.
|
||||
assert name == "my-plugin"
|
||||
assert manifest.get("name") == "my-plugin"
|
||||
assert target == (plugins_dir / "my-plugin").resolve()
|
||||
|
||||
# The plugin's files are present...
|
||||
assert (target / "plugin.yaml").exists()
|
||||
assert (target / "__init__.py").exists()
|
||||
# ...and the repo-root noise is NOT.
|
||||
assert not (target / "README.md").exists()
|
||||
assert not (target / "tests").exists()
|
||||
|
||||
def test_missing_subdir_raises(self, tmp_path, monkeypatch):
|
||||
if shutil.which("git") is None:
|
||||
pytest.skip("git not available")
|
||||
|
||||
from hermes_cli import plugins_cmd as pc
|
||||
|
||||
repo_root = tmp_path / "monorepo"
|
||||
self._make_repo_with_subdir_plugin(repo_root)
|
||||
|
||||
plugins_dir = tmp_path / "installed"
|
||||
plugins_dir.mkdir()
|
||||
monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)
|
||||
|
||||
identifier = f"file://{repo_root}#does-not-exist"
|
||||
with pytest.raises(PluginOperationError, match="does not exist"):
|
||||
pc._install_plugin_core(identifier, force=False)
|
||||
|
||||
@@ -1,355 +0,0 @@
|
||||
"""Tests for the nested category plugin discovery fix (issue #41066).
|
||||
|
||||
Verifies that _discover_all_plugins() recurses into category directories
|
||||
(up to 2 levels deep) and that _plugin_status() checks both manifest name
|
||||
and path-derived key against the enabled/disabled sets.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_plugin_dir(parent: Path, name: str, manifest: dict) -> Path:
|
||||
"""Create a minimal plugin directory with a plugin.yaml."""
|
||||
d = parent / name
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
import yaml
|
||||
(d / "plugin.yaml").write_text(yaml.dump(manifest), encoding="utf-8")
|
||||
(d / "__init__.py").write_text("def register(ctx): pass\n", encoding="utf-8")
|
||||
return d
|
||||
|
||||
|
||||
def _make_category_plugin(
|
||||
parent: Path, category: str, name: str, manifest: dict
|
||||
) -> Path:
|
||||
"""Create a category-namespaced plugin: <parent>/<category>/<name>/plugin.yaml."""
|
||||
return _make_plugin_dir(parent / category, name, manifest)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _read_manifest_info
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestReadManifestInfo:
|
||||
def test_flat_plugin(self, tmp_path):
|
||||
from hermes_cli.plugins_cmd import _read_manifest_info
|
||||
|
||||
d = _make_plugin_dir(tmp_path, "my-plugin", {
|
||||
"name": "my-plugin", "version": "1.0.0", "description": "test"
|
||||
})
|
||||
result = _read_manifest_info(d, "")
|
||||
assert result is not None
|
||||
name, version, description, key = result
|
||||
assert name == "my-plugin"
|
||||
assert version == "1.0.0"
|
||||
assert description == "test"
|
||||
assert key == "my-plugin" # flat: key == name
|
||||
|
||||
def test_category_plugin(self, tmp_path):
|
||||
from hermes_cli.plugins_cmd import _read_manifest_info
|
||||
|
||||
d = _make_category_plugin(tmp_path, "web", "tavily", {
|
||||
"name": "web-tavily", "version": "2.0.0", "description": "search"
|
||||
})
|
||||
result = _read_manifest_info(d, "web")
|
||||
assert result is not None
|
||||
name, version, description, key = result
|
||||
assert name == "web-tavily" # manifest name
|
||||
assert key == "web/tavily" # path-derived key
|
||||
|
||||
def test_no_manifest(self, tmp_path):
|
||||
from hermes_cli.plugins_cmd import _read_manifest_info
|
||||
|
||||
d = tmp_path / "empty-dir"
|
||||
d.mkdir()
|
||||
assert _read_manifest_info(d, "") is None
|
||||
|
||||
def test_yml_extension(self, tmp_path):
|
||||
from hermes_cli.plugins_cmd import _read_manifest_info
|
||||
|
||||
d = tmp_path / "my-plugin"
|
||||
d.mkdir()
|
||||
import yaml
|
||||
(d / "plugin.yml").write_text(yaml.dump({"name": "my-plugin"}), encoding="utf-8")
|
||||
result = _read_manifest_info(d, "")
|
||||
assert result is not None
|
||||
assert result[0] == "my-plugin"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _discover_all_plugins — recursive discovery
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestDiscoverAllPlugins:
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_flat_plugins_still_discovered(self, mock_user_dir, mock_bundled_dir, tmp_path):
|
||||
from hermes_cli.plugins_cmd import _discover_all_plugins
|
||||
|
||||
_make_plugin_dir(tmp_path, "disk-cleanup", {
|
||||
"name": "disk-cleanup", "version": "1.0.0"
|
||||
})
|
||||
mock_user_dir.return_value = tmp_path
|
||||
mock_bundled_dir.return_value = tmp_path / "nonexistent"
|
||||
|
||||
entries = _discover_all_plugins()
|
||||
keys = [e[5] for e in entries]
|
||||
assert "disk-cleanup" in keys
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_category_plugins_discovered(self, mock_user_dir, mock_bundled_dir, tmp_path):
|
||||
from hermes_cli.plugins_cmd import _discover_all_plugins
|
||||
|
||||
_make_category_plugin(tmp_path, "web", "tavily", {
|
||||
"name": "web-tavily", "version": "1.0.0"
|
||||
})
|
||||
_make_category_plugin(tmp_path, "image_gen", "openai", {
|
||||
"name": "image-gen-openai", "version": "2.0.0"
|
||||
})
|
||||
mock_user_dir.return_value = tmp_path
|
||||
mock_bundled_dir.return_value = tmp_path / "nonexistent"
|
||||
|
||||
entries = _discover_all_plugins()
|
||||
keys = [e[5] for e in entries]
|
||||
assert "web/tavily" in keys
|
||||
assert "image_gen/openai" in keys
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_mixed_flat_and_category(self, mock_user_dir, mock_bundled_dir, tmp_path):
|
||||
from hermes_cli.plugins_cmd import _discover_all_plugins
|
||||
|
||||
_make_plugin_dir(tmp_path, "disk-cleanup", {
|
||||
"name": "disk-cleanup", "version": "1.0.0"
|
||||
})
|
||||
_make_category_plugin(tmp_path, "web", "tavily", {
|
||||
"name": "web-tavily", "version": "1.0.0"
|
||||
})
|
||||
_make_category_plugin(tmp_path, "web", "exa", {
|
||||
"name": "web-exa", "version": "1.0.0"
|
||||
})
|
||||
mock_user_dir.return_value = tmp_path
|
||||
mock_bundled_dir.return_value = tmp_path / "nonexistent"
|
||||
|
||||
entries = _discover_all_plugins()
|
||||
keys = [e[5] for e in entries]
|
||||
assert "disk-cleanup" in keys
|
||||
assert "web/tavily" in keys
|
||||
assert "web/exa" in keys
|
||||
assert len(entries) == 3
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_depth_cap_at_two(self, mock_user_dir, mock_bundled_dir, tmp_path):
|
||||
"""Plugins nested 3 levels deep should NOT be discovered."""
|
||||
from hermes_cli.plugins_cmd import _discover_all_plugins
|
||||
|
||||
# 2 levels: should be found
|
||||
_make_category_plugin(tmp_path, "web", "tavily", {
|
||||
"name": "web-tavily", "version": "1.0.0"
|
||||
})
|
||||
# 3 levels: should NOT be found
|
||||
deep = tmp_path / "a" / "b" / "c"
|
||||
deep.mkdir(parents=True)
|
||||
import yaml
|
||||
(deep / "plugin.yaml").write_text(
|
||||
yaml.dump({"name": "too-deep"}), encoding="utf-8"
|
||||
)
|
||||
mock_user_dir.return_value = tmp_path
|
||||
mock_bundled_dir.return_value = tmp_path / "nonexistent"
|
||||
|
||||
entries = _discover_all_plugins()
|
||||
keys = [e[5] for e in entries]
|
||||
assert "web/tavily" in keys
|
||||
assert "a/b/c" not in keys
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_tuple_has_six_elements(self, mock_user_dir, mock_bundled_dir, tmp_path):
|
||||
from hermes_cli.plugins_cmd import _discover_all_plugins
|
||||
|
||||
_make_category_plugin(tmp_path, "web", "tavily", {
|
||||
"name": "web-tavily", "version": "1.0.0", "description": "search"
|
||||
})
|
||||
mock_user_dir.return_value = tmp_path
|
||||
mock_bundled_dir.return_value = tmp_path / "nonexistent"
|
||||
|
||||
entries = _discover_all_plugins()
|
||||
assert len(entries) == 1
|
||||
entry = entries[0]
|
||||
assert len(entry) == 6
|
||||
name, version, description, source, dir_path, key = entry
|
||||
assert name == "web-tavily"
|
||||
assert key == "web/tavily"
|
||||
assert source == "user"
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_user_overrides_bundled_on_key_collision(self, mock_user_dir, mock_bundled_dir, tmp_path):
|
||||
"""User plugin with same key as bundled should win."""
|
||||
from hermes_cli.plugins_cmd import _discover_all_plugins
|
||||
|
||||
# Simulate a bundled plugin
|
||||
bundled_dir = tmp_path / "bundled"
|
||||
bundled_dir.mkdir()
|
||||
_make_plugin_dir(bundled_dir, "my-plugin", {
|
||||
"name": "my-plugin", "version": "1.0.0"
|
||||
})
|
||||
# User plugin with same key
|
||||
_make_plugin_dir(tmp_path, "my-plugin", {
|
||||
"name": "my-plugin", "version": "2.0.0"
|
||||
})
|
||||
mock_user_dir.return_value = tmp_path
|
||||
mock_bundled_dir.return_value = bundled_dir
|
||||
|
||||
entries = _discover_all_plugins()
|
||||
keys = [e[5] for e in entries]
|
||||
assert keys.count("my-plugin") == 1
|
||||
# User version should win
|
||||
entry = [e for e in entries if e[5] == "my-plugin"][0]
|
||||
assert entry[1] == "2.0.0"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _plugin_status — key-aware status
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestPluginStatus:
|
||||
def test_name_in_enabled(self):
|
||||
from hermes_cli.plugins_cmd import _plugin_status
|
||||
assert _plugin_status("my-plugin", {"my-plugin"}, set()) == "enabled"
|
||||
|
||||
def test_key_in_enabled(self):
|
||||
from hermes_cli.plugins_cmd import _plugin_status
|
||||
assert _plugin_status("web-tavily", {"web/tavily"}, set(), key="web/tavily") == "enabled"
|
||||
|
||||
def test_name_in_disabled(self):
|
||||
from hermes_cli.plugins_cmd import _plugin_status
|
||||
assert _plugin_status("my-plugin", set(), {"my-plugin"}) == "disabled"
|
||||
|
||||
def test_key_in_disabled(self):
|
||||
from hermes_cli.plugins_cmd import _plugin_status
|
||||
assert _plugin_status("web-tavily", set(), {"web/tavily"}, key="web/tavily") == "disabled"
|
||||
|
||||
def test_neither_name_nor_key(self):
|
||||
from hermes_cli.plugins_cmd import _plugin_status
|
||||
assert _plugin_status("unknown", {"other"}, set(), key="cat/unknown") == "not enabled"
|
||||
|
||||
def test_disabled_takes_precedence_over_enabled(self):
|
||||
from hermes_cli.plugins_cmd import _plugin_status
|
||||
assert _plugin_status("my-plugin", {"my-plugin"}, {"my-plugin"}) == "disabled"
|
||||
|
||||
def test_key_disabled_takes_precedence(self):
|
||||
from hermes_cli.plugins_cmd import _plugin_status
|
||||
assert _plugin_status("web-tavily", {"web/tavily"}, {"web/tavily"}, key="web/tavily") == "disabled"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration: _filter_plugin_entries with category plugins
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestFilterPluginEntries:
|
||||
def test_enabled_filter_uses_key(self):
|
||||
from hermes_cli.plugins_cmd import _filter_plugin_entries
|
||||
|
||||
entries = [
|
||||
("web-tavily", "1.0.0", "search", "user", Path("/tmp"), "web/tavily"),
|
||||
("disk-cleanup", "1.0.0", "cleanup", "bundled", Path("/tmp"), "disk-cleanup"),
|
||||
]
|
||||
args = MagicMock()
|
||||
args.no_bundled = False
|
||||
args.user = False
|
||||
args.enabled = True
|
||||
|
||||
result = _filter_plugin_entries(entries, args, {"web/tavily"}, set())
|
||||
assert len(result) == 1
|
||||
assert result[0][5] == "web/tavily"
|
||||
|
||||
def test_enabled_filter_by_name_still_works(self):
|
||||
from hermes_cli.plugins_cmd import _filter_plugin_entries
|
||||
|
||||
entries = [
|
||||
("disk-cleanup", "1.0.0", "cleanup", "bundled", Path("/tmp"), "disk-cleanup"),
|
||||
]
|
||||
args = MagicMock()
|
||||
args.no_bundled = False
|
||||
args.user = False
|
||||
args.enabled = True
|
||||
|
||||
result = _filter_plugin_entries(entries, args, {"disk-cleanup"}, set())
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration: cmd_list JSON output includes category plugins
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestCmdListJson:
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_json_output_includes_category_plugins(self, mock_user_dir, mock_bundled_dir, tmp_path, capsys):
|
||||
from hermes_cli.plugins_cmd import cmd_list
|
||||
|
||||
_make_category_plugin(tmp_path, "web", "tavily", {
|
||||
"name": "web-tavily", "version": "1.0.0", "description": "search"
|
||||
})
|
||||
_make_plugin_dir(tmp_path, "disk-cleanup", {
|
||||
"name": "disk-cleanup", "version": "2.0.0", "description": "cleanup"
|
||||
})
|
||||
mock_user_dir.return_value = tmp_path
|
||||
mock_bundled_dir.return_value = tmp_path / "nonexistent"
|
||||
|
||||
args = MagicMock()
|
||||
args.json = True
|
||||
args.plain = False
|
||||
args.no_bundled = False
|
||||
args.user = False
|
||||
args.enabled = False
|
||||
|
||||
cmd_list(args)
|
||||
captured = capsys.readouterr()
|
||||
payload = json.loads(captured.out)
|
||||
names = [p["name"] for p in payload]
|
||||
assert "web-tavily" in names
|
||||
assert "disk-cleanup" in names
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_json_status_uses_key(self, mock_user_dir, mock_bundled_dir, tmp_path, capsys):
|
||||
from hermes_cli.plugins_cmd import cmd_list
|
||||
|
||||
_make_category_plugin(tmp_path, "web", "tavily", {
|
||||
"name": "web-tavily", "version": "1.0.0"
|
||||
})
|
||||
mock_user_dir.return_value = tmp_path
|
||||
mock_bundled_dir.return_value = tmp_path / "nonexistent"
|
||||
|
||||
# Patch config to return web/tavily as enabled
|
||||
with patch("hermes_cli.plugins_cmd._get_enabled_set", return_value={"web/tavily"}):
|
||||
args = MagicMock()
|
||||
args.json = True
|
||||
args.plain = False
|
||||
args.no_bundled = False
|
||||
args.user = False
|
||||
args.enabled = False
|
||||
|
||||
cmd_list(args)
|
||||
captured = capsys.readouterr()
|
||||
payload = json.loads(captured.out)
|
||||
assert len(payload) == 1
|
||||
assert payload[0]["status"] == "enabled"
|
||||
@@ -1,193 +0,0 @@
|
||||
"""Tests for nested/alias-normalized enable & disable flows.
|
||||
|
||||
Companion to test_plugins_cmd_category_discovery.py. That file covers the
|
||||
*listing* side of nested category plugins (issue #41066). These tests cover
|
||||
the *mutation* side: `hermes plugins enable/disable` must resolve a bare name
|
||||
OR a full path-derived key (e.g. `observability/nemo_relay`) to the canonical
|
||||
registry key and write THAT — the same string PluginManager gates on — so a
|
||||
nested bundled plugin can actually be toggled.
|
||||
"""
|
||||
|
||||
import sys # noqa: F401
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _make_plugin_dir(parent: Path, name: str, manifest: dict) -> Path:
|
||||
d = parent / name
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
import yaml
|
||||
(d / "plugin.yaml").write_text(yaml.dump(manifest), encoding="utf-8")
|
||||
(d / "__init__.py").write_text("def register(ctx): pass\n", encoding="utf-8")
|
||||
return d
|
||||
|
||||
|
||||
def _make_category_plugin(parent: Path, category: str, name: str, manifest: dict) -> Path:
|
||||
return _make_plugin_dir(parent / category, name, manifest)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def nested_plugin_env(tmp_path):
|
||||
"""A user-plugins dir containing one nested and one flat plugin, with the
|
||||
bundled dir pointed at an empty path. Returns the tmp_path."""
|
||||
_make_category_plugin(tmp_path, "observability", "nemo_relay", {
|
||||
"name": "nemo_relay", "version": "1.0.0", "description": "relay obs"
|
||||
})
|
||||
_make_plugin_dir(tmp_path, "disk-cleanup", {
|
||||
"name": "disk-cleanup", "version": "1.0.0"
|
||||
})
|
||||
return tmp_path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _resolve_plugin_key
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestResolvePluginKey:
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_full_key_resolves_to_itself(self, mock_user, mock_bundled, nested_plugin_env):
|
||||
from hermes_cli.plugins_cmd import _resolve_plugin_key
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
assert _resolve_plugin_key("observability/nemo_relay") == "observability/nemo_relay"
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_bare_leaf_name_resolves_to_key(self, mock_user, mock_bundled, nested_plugin_env):
|
||||
from hermes_cli.plugins_cmd import _resolve_plugin_key
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
# "nemo_relay" (bare) must normalize to the path-derived key.
|
||||
assert _resolve_plugin_key("nemo_relay") == "observability/nemo_relay"
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_flat_plugin_resolves_to_name(self, mock_user, mock_bundled, nested_plugin_env):
|
||||
from hermes_cli.plugins_cmd import _resolve_plugin_key
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
assert _resolve_plugin_key("disk-cleanup") == "disk-cleanup"
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_unknown_returns_none(self, mock_user, mock_bundled, nested_plugin_env):
|
||||
from hermes_cli.plugins_cmd import _resolve_plugin_key
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
assert _resolve_plugin_key("does-not-exist") is None
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_ambiguous_leaf_name_returns_none(self, mock_user, mock_bundled, tmp_path):
|
||||
"""Same leaf name under two categories must NOT silently pick one."""
|
||||
from hermes_cli.plugins_cmd import _resolve_plugin_key
|
||||
_make_category_plugin(tmp_path, "image_gen", "openai", {"name": "image-gen-openai"})
|
||||
_make_category_plugin(tmp_path, "model-providers", "openai", {"name": "mp-openai"})
|
||||
mock_user.return_value = tmp_path
|
||||
mock_bundled.return_value = tmp_path / "nonexistent"
|
||||
# Bare "openai" is ambiguous -> None; the full key still resolves.
|
||||
assert _resolve_plugin_key("openai") is None
|
||||
assert _resolve_plugin_key("image_gen/openai") == "image_gen/openai"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# cmd_enable / cmd_disable — write the canonical key
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestEnableDisableNested:
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._save_disabled_set")
|
||||
@patch("hermes_cli.plugins_cmd._save_enabled_set")
|
||||
@patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())
|
||||
@patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())
|
||||
def test_enable_bare_name_writes_key(
|
||||
self, mock_en, mock_dis, mock_save_en, mock_save_dis,
|
||||
mock_user, mock_bundled, nested_plugin_env,
|
||||
):
|
||||
from hermes_cli.plugins_cmd import cmd_enable
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
|
||||
cmd_enable("nemo_relay") # bare name
|
||||
|
||||
saved = mock_save_en.call_args[0][0]
|
||||
# The canonical key — NOT the bare name — must be persisted, because
|
||||
# that is what PluginManager matches when deciding to load.
|
||||
assert "observability/nemo_relay" in saved
|
||||
assert "nemo_relay" not in saved or "observability/nemo_relay" in saved
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._save_disabled_set")
|
||||
@patch("hermes_cli.plugins_cmd._save_enabled_set")
|
||||
@patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())
|
||||
@patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())
|
||||
def test_enable_full_key_writes_key(
|
||||
self, mock_en, mock_dis, mock_save_en, mock_save_dis,
|
||||
mock_user, mock_bundled, nested_plugin_env,
|
||||
):
|
||||
from hermes_cli.plugins_cmd import cmd_enable
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
|
||||
cmd_enable("observability/nemo_relay")
|
||||
saved = mock_save_en.call_args[0][0]
|
||||
assert "observability/nemo_relay" in saved
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._save_disabled_set")
|
||||
@patch("hermes_cli.plugins_cmd._save_enabled_set")
|
||||
@patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())
|
||||
@patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())
|
||||
def test_disable_bare_name_writes_key_and_clears_alias(
|
||||
self, mock_en, mock_dis, mock_save_en, mock_save_dis,
|
||||
mock_user, mock_bundled, nested_plugin_env,
|
||||
):
|
||||
from hermes_cli.plugins_cmd import cmd_disable
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
# Simulate an existing config where the plugin was enabled under the
|
||||
# legacy bare name — disabling must clear that too, or the plugin would
|
||||
# keep loading (PluginManager accepts the bare name as well).
|
||||
mock_en.return_value = {"nemo_relay"}
|
||||
|
||||
cmd_disable("nemo_relay")
|
||||
saved_dis = mock_save_dis.call_args[0][0]
|
||||
saved_en = mock_save_en.call_args[0][0]
|
||||
assert "observability/nemo_relay" in saved_dis
|
||||
assert "nemo_relay" not in saved_en # stale bare alias dropped
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
def test_enable_unknown_plugin_exits(self, mock_user, mock_bundled, nested_plugin_env):
|
||||
from hermes_cli.plugins_cmd import cmd_enable
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
with pytest.raises(SystemExit):
|
||||
cmd_enable("does-not-exist")
|
||||
|
||||
@patch("hermes_cli.plugins.get_bundled_plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._plugins_dir")
|
||||
@patch("hermes_cli.plugins_cmd._save_disabled_set")
|
||||
@patch("hermes_cli.plugins_cmd._save_enabled_set")
|
||||
@patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())
|
||||
@patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())
|
||||
def test_enable_flat_plugin_unchanged(
|
||||
self, mock_en, mock_dis, mock_save_en, mock_save_dis,
|
||||
mock_user, mock_bundled, nested_plugin_env,
|
||||
):
|
||||
"""Flat plugins keep writing their bare name (key == name) — no regression."""
|
||||
from hermes_cli.plugins_cmd import cmd_enable
|
||||
mock_user.return_value = nested_plugin_env
|
||||
mock_bundled.return_value = nested_plugin_env / "nonexistent"
|
||||
|
||||
cmd_enable("disk-cleanup")
|
||||
saved = mock_save_en.call_args[0][0]
|
||||
assert "disk-cleanup" in saved
|
||||
@@ -18,9 +18,9 @@ def _args(**kwargs):
|
||||
|
||||
def test_filter_plugin_entries_enabled_only():
|
||||
entries = [
|
||||
("disk-cleanup", "2.0.0", "Bundled", "bundled", None, "disk-cleanup"),
|
||||
("web-search-plus", "2.2.0", "Search", "git", None, "web-search-plus"),
|
||||
("old-plugin", "1.0.0", "Old", "user", None, "old-plugin"),
|
||||
("disk-cleanup", "2.0.0", "Bundled", "bundled", None),
|
||||
("web-search-plus", "2.2.0", "Search", "git", None),
|
||||
("old-plugin", "1.0.0", "Old", "user", None),
|
||||
]
|
||||
|
||||
filtered = plugins_cmd._filter_plugin_entries(
|
||||
@@ -35,9 +35,9 @@ def test_filter_plugin_entries_enabled_only():
|
||||
|
||||
def test_filter_plugin_entries_no_bundled():
|
||||
entries = [
|
||||
("disk-cleanup", "2.0.0", "Bundled", "bundled", None, "disk-cleanup"),
|
||||
("drawthings-grpc", "0.3.0", "Draw Things", "user", None, "drawthings-grpc"),
|
||||
("web-search-plus", "2.2.0", "Search", "git", None, "web-search-plus"),
|
||||
("disk-cleanup", "2.0.0", "Bundled", "bundled", None),
|
||||
("drawthings-grpc", "0.3.0", "Draw Things", "user", None),
|
||||
("web-search-plus", "2.2.0", "Search", "git", None),
|
||||
]
|
||||
|
||||
filtered = plugins_cmd._filter_plugin_entries(
|
||||
@@ -52,8 +52,8 @@ def test_filter_plugin_entries_no_bundled():
|
||||
|
||||
def test_cmd_list_plain_compact_output(monkeypatch, capsys):
|
||||
entries = [
|
||||
("disk-cleanup", "2.0.0", "Bundled", "bundled", None, "disk-cleanup"),
|
||||
("web-search-plus", "2.2.0", "Search", "git", None, "web-search-plus"),
|
||||
("disk-cleanup", "2.0.0", "Bundled", "bundled", None),
|
||||
("web-search-plus", "2.2.0", "Search", "git", None),
|
||||
]
|
||||
monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", lambda: entries)
|
||||
monkeypatch.setattr(plugins_cmd, "_get_enabled_set", lambda: {"web-search-plus"})
|
||||
@@ -69,7 +69,7 @@ def test_cmd_list_plain_compact_output(monkeypatch, capsys):
|
||||
|
||||
|
||||
def test_cmd_list_json_output(monkeypatch, capsys):
|
||||
entries = [("web-search-plus", "2.2.0", "Search", "git", None, "web-search-plus")]
|
||||
entries = [("web-search-plus", "2.2.0", "Search", "git", None)]
|
||||
monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", lambda: entries)
|
||||
monkeypatch.setattr(plugins_cmd, "_get_enabled_set", lambda: {"web-search-plus"})
|
||||
monkeypatch.setattr(plugins_cmd, "_get_disabled_set", lambda: set())
|
||||
|
||||
@@ -442,18 +442,6 @@ class TestDeleteProfile:
|
||||
with pytest.raises(FileNotFoundError):
|
||||
delete_profile("nonexistent", yes=True)
|
||||
|
||||
def test_rmtree_failure_raises(self, profile_env):
|
||||
profile_dir = create_profile("coder", no_alias=True)
|
||||
set_active_profile("coder")
|
||||
|
||||
with patch("hermes_cli.profiles._cleanup_gateway_service"), \
|
||||
patch("hermes_cli.profiles.shutil.rmtree", side_effect=PermissionError("locked")):
|
||||
with pytest.raises(RuntimeError, match="Could not remove profile directory"):
|
||||
delete_profile("coder", yes=True)
|
||||
|
||||
assert profile_dir.is_dir()
|
||||
assert get_active_profile() == "default"
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# TestListProfiles
|
||||
|
||||
@@ -8,7 +8,6 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
@@ -212,75 +211,6 @@ class TestPtyBridgeClose:
|
||||
break
|
||||
assert reaped, f"pid {pid} still running after close()"
|
||||
|
||||
def test_close_signals_child_process_group(self, monkeypatch):
|
||||
sent: list[tuple[int, signal.Signals]] = []
|
||||
|
||||
class _FakeProc:
|
||||
pid = 12345
|
||||
fd = -1
|
||||
|
||||
def __init__(self):
|
||||
self.alive = True
|
||||
|
||||
def isalive(self):
|
||||
return self.alive
|
||||
|
||||
def kill(self, sig):
|
||||
raise AssertionError(f"single-process kill used: {sig}")
|
||||
|
||||
def close(self, force=False):
|
||||
self.closed = force
|
||||
|
||||
fake = _FakeProc()
|
||||
|
||||
def fake_killpg(pgid, sig):
|
||||
sent.append((pgid, sig))
|
||||
fake.alive = False
|
||||
|
||||
monkeypatch.setattr(os, "getpgid", lambda pid: 67890)
|
||||
monkeypatch.setattr(os, "killpg", fake_killpg)
|
||||
|
||||
bridge = PtyBridge.__new__(PtyBridge)
|
||||
bridge._proc = fake
|
||||
bridge._fd = -1
|
||||
bridge._closed = False
|
||||
|
||||
bridge.close()
|
||||
|
||||
assert sent == [(67890, signal.SIGHUP)]
|
||||
assert bridge._closed is True
|
||||
|
||||
def test_close_falls_back_to_single_process_signal_when_group_unknown(self, monkeypatch):
|
||||
sent: list[signal.Signals] = []
|
||||
|
||||
class _FakeProc:
|
||||
pid = 12345
|
||||
fd = -1
|
||||
|
||||
def __init__(self):
|
||||
self.alive = True
|
||||
|
||||
def isalive(self):
|
||||
return self.alive
|
||||
|
||||
def kill(self, sig):
|
||||
sent.append(sig)
|
||||
self.alive = False
|
||||
|
||||
def close(self, force=False):
|
||||
self.closed = force
|
||||
|
||||
monkeypatch.setattr(os, "getpgid", lambda pid: (_ for _ in ()).throw(OSError()))
|
||||
|
||||
bridge = PtyBridge.__new__(PtyBridge)
|
||||
bridge._proc = _FakeProc()
|
||||
bridge._fd = -1
|
||||
bridge._closed = False
|
||||
|
||||
bridge.close()
|
||||
|
||||
assert sent == [signal.SIGHUP]
|
||||
|
||||
|
||||
@skip_on_windows
|
||||
class TestPtyBridgeEnv:
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
"""Regression tests for issue #42130.
|
||||
|
||||
A credential added via `hermes auth add openrouter` lives in the credential
|
||||
pool, NOT as an OPENROUTER_API_KEY env var. Before the fix, resolve_provider()
|
||||
auto-detection only checked env vars, so such a credential was invisible:
|
||||
the provider failed to resolve (AuthError) or resolved without a key, and
|
||||
requests went out with no Authorization header — OpenRouter's
|
||||
"HTTP 401: Missing Authentication header".
|
||||
|
||||
These tests lock in that auto-detection consults the OpenRouter pool.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clean_inference_env(monkeypatch):
|
||||
"""Strip credential-shaped env vars so the pool is the only source."""
|
||||
for key in (
|
||||
"OPENROUTER_API_KEY",
|
||||
"OPENAI_API_KEY",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"ANTHROPIC_TOKEN",
|
||||
"CLAUDE_CODE_OAUTH_TOKEN",
|
||||
"NOUS_API_KEY",
|
||||
"HERMES_INFERENCE_PROVIDER",
|
||||
):
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
|
||||
|
||||
def _seed_openrouter_pool(token: str = "sk-or-FAKEKEY123") -> None:
|
||||
"""Mimic `hermes auth add openrouter <token>` — a manual pool entry."""
|
||||
from agent.credential_pool import (
|
||||
AUTH_TYPE_API_KEY,
|
||||
SOURCE_MANUAL,
|
||||
PooledCredential,
|
||||
load_pool,
|
||||
)
|
||||
|
||||
pool = load_pool("openrouter")
|
||||
pool.add_entry(
|
||||
PooledCredential(
|
||||
provider="openrouter",
|
||||
id=uuid.uuid4().hex[:6],
|
||||
label="api-key-1",
|
||||
auth_type=AUTH_TYPE_API_KEY,
|
||||
priority=0,
|
||||
source=SOURCE_MANUAL,
|
||||
access_token=token,
|
||||
base_url="https://openrouter.ai/api/v1",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_auto_detects_openrouter_from_pool(tmp_path, monkeypatch):
|
||||
"""With only a pool credential (no env var), auto-detection finds it."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
||||
(tmp_path / "hermes").mkdir(parents=True, exist_ok=True)
|
||||
_seed_openrouter_pool()
|
||||
|
||||
from hermes_cli.auth import resolve_provider
|
||||
|
||||
assert resolve_provider("auto") == "openrouter"
|
||||
|
||||
|
||||
def test_no_credentials_still_raises(tmp_path, monkeypatch):
|
||||
"""Empty pool + no env var must still fail to resolve — no false positive."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
||||
(tmp_path / "hermes").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from hermes_cli.auth import AuthError, resolve_provider
|
||||
|
||||
with pytest.raises(AuthError):
|
||||
resolve_provider("auto")
|
||||
@@ -712,76 +712,6 @@ def test_named_custom_provider_uses_saved_credentials(monkeypatch):
|
||||
assert resolved["source"] == "custom_provider:Local"
|
||||
|
||||
|
||||
def test_bare_custom_resolves_providers_dict_entry_named_custom(monkeypatch):
|
||||
"""A request for bare ``provider="custom"`` must resolve a literal
|
||||
``providers.custom`` entry (e.g. a cliproxy endpoint) instead of falling
|
||||
through to the global default. Regression for cron jobs stored with
|
||||
``provider: "custom"`` failing with ``auth_unavailable: providers=codex``.
|
||||
"""
|
||||
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
||||
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
|
||||
monkeypatch.setattr(
|
||||
rp,
|
||||
"load_config",
|
||||
lambda: {
|
||||
"providers": {
|
||||
"custom": {
|
||||
"api": "https://cliproxy.example.com/v1",
|
||||
"api_key": "cliproxy-key",
|
||||
"default_model": "gpt-5.4",
|
||||
"name": "CLIProxy",
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
# Reaching resolve_provider for bare custom with a matching entry means the
|
||||
# named-custom path was bypassed — that is the bug we are fixing.
|
||||
monkeypatch.setattr(
|
||||
rp,
|
||||
"resolve_provider",
|
||||
lambda *a, **k: (_ for _ in ()).throw(
|
||||
AssertionError(
|
||||
"resolve_provider must not be called; providers.custom should match"
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
resolved = rp.resolve_runtime_provider(requested="custom")
|
||||
|
||||
assert resolved["provider"] == "custom"
|
||||
assert resolved["base_url"] == "https://cliproxy.example.com/v1"
|
||||
assert resolved["api_key"] == "cliproxy-key"
|
||||
assert resolved["requested_provider"] == "custom"
|
||||
|
||||
|
||||
def test_bare_custom_without_named_entry_still_falls_through(monkeypatch):
|
||||
"""No literal providers.custom entry → bare custom keeps the legacy
|
||||
model.base_url trust-path behavior, unchanged by the fix."""
|
||||
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "openrouter")
|
||||
monkeypatch.setattr(
|
||||
rp,
|
||||
"_get_model_config",
|
||||
lambda: {
|
||||
"provider": "openrouter",
|
||||
"base_url": "http://127.0.0.1:8082/v1",
|
||||
"default": "my-local-model",
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rp,
|
||||
"load_config",
|
||||
lambda: {"providers": {"some-other-proxy": {"api": "https://x.example/v1"}}},
|
||||
)
|
||||
monkeypatch.delenv("CUSTOM_BASE_URL", raising=False)
|
||||
monkeypatch.delenv("OPENROUTER_BASE_URL", raising=False)
|
||||
monkeypatch.setenv("OPENROUTER_API_KEY", "or-key")
|
||||
|
||||
resolved = rp.resolve_runtime_provider(requested="custom")
|
||||
|
||||
assert resolved["provider"] == "custom"
|
||||
assert resolved["base_url"] == "http://127.0.0.1:8082/v1"
|
||||
|
||||
|
||||
def test_named_custom_provider_uses_providers_dict_when_list_missing(monkeypatch):
|
||||
"""After v11→v12 migration deletes custom_providers, resolution should
|
||||
still find entries in the providers dict via get_compatible_custom_providers."""
|
||||
|
||||
@@ -799,111 +799,3 @@ def test_s6_is_running_parses_svstat(
|
||||
return _sp.CompletedProcess(cmd, 0, "", "")
|
||||
monkeypatch.setattr("subprocess.run", _svstat_down)
|
||||
assert S6ServiceManager(scandir=s6_scandir).is_running("gateway-coder") is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# S6 stop writes a planned-stop marker (issue #42675)
|
||||
#
|
||||
# `hermes gateway stop` inside a container dispatches through
|
||||
# S6ServiceManager.stop() -> `s6-svc -d`, which SIGTERMs the gateway.
|
||||
# That SIGTERM is indistinguishable from the one s6/Docker sends on a
|
||||
# container restart unless we mark the intentional stop first. Without
|
||||
# the marker, the gateway's shutdown handler can't tell an operator
|
||||
# stop from a restart kill, and the gateway_state=stopped suppression
|
||||
# (run.py) would never engage for explicit stops.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_s6_supervised_pid_parses_svstat(monkeypatch, s6_scandir):
|
||||
"""_supervised_pid extracts the PID from `up (pid NNNN) ...`."""
|
||||
import subprocess as _sp
|
||||
|
||||
def _fake(cmd, **kw):
|
||||
return _sp.CompletedProcess(cmd, 0, "up (pid 4242) 17 seconds\n", "")
|
||||
|
||||
monkeypatch.setattr("subprocess.run", _fake)
|
||||
mgr = S6ServiceManager(scandir=s6_scandir)
|
||||
assert mgr._supervised_pid("gateway-coder") == 4242
|
||||
|
||||
|
||||
def test_s6_supervised_pid_none_when_down(monkeypatch, s6_scandir):
|
||||
"""A down service (`s6-svstat` rc!=0 or no pid) yields None."""
|
||||
import subprocess as _sp
|
||||
|
||||
def _fake(cmd, **kw):
|
||||
return _sp.CompletedProcess(cmd, 0, "down (exitcode 0) 3 seconds\n", "")
|
||||
|
||||
monkeypatch.setattr("subprocess.run", _fake)
|
||||
mgr = S6ServiceManager(scandir=s6_scandir)
|
||||
assert mgr._supervised_pid("gateway-coder") is None
|
||||
|
||||
|
||||
def test_s6_stop_writes_planned_stop_marker(monkeypatch, s6_scandir):
|
||||
"""stop() must mark the supervised PID before `s6-svc -d` so the
|
||||
gateway recognises the SIGTERM as an intentional stop (#42675)."""
|
||||
import subprocess as _sp
|
||||
|
||||
svc_dir = s6_scandir / "gateway-coder"
|
||||
svc_dir.mkdir() # so _run_svc doesn't raise GatewayNotRegisteredError
|
||||
|
||||
svc_calls: list[list[str]] = []
|
||||
|
||||
def _fake(cmd, **kw):
|
||||
seq = list(cmd) if isinstance(cmd, (list, tuple)) else [str(cmd)]
|
||||
if seq and seq[0].startswith("/command/"):
|
||||
seq[0] = seq[0][len("/command/"):]
|
||||
svc_calls.append(seq)
|
||||
if seq and seq[0] == "s6-svstat":
|
||||
return _sp.CompletedProcess(cmd, 0, "up (pid 9090) 5 seconds\n", "")
|
||||
return _sp.CompletedProcess(cmd, 0, "", "")
|
||||
|
||||
monkeypatch.setattr("subprocess.run", _fake)
|
||||
|
||||
marked: list[int] = []
|
||||
monkeypatch.setattr(
|
||||
"gateway.status.write_planned_stop_marker",
|
||||
lambda pid: marked.append(pid) or True,
|
||||
)
|
||||
|
||||
mgr = S6ServiceManager(scandir=s6_scandir)
|
||||
mgr.stop("gateway-coder")
|
||||
|
||||
assert marked == [9090], (
|
||||
f"stop() must write the planned-stop marker for the supervised PID; "
|
||||
f"marked={marked}"
|
||||
)
|
||||
# And it must still issue the down command.
|
||||
assert any(
|
||||
cmd[0] == "s6-svc" and "-d" in cmd for cmd in svc_calls
|
||||
), f"s6-svc -d not invoked; saw: {svc_calls}"
|
||||
|
||||
|
||||
def test_s6_stop_tolerates_marker_write_failure(monkeypatch, s6_scandir):
|
||||
"""A marker-write failure must not block the stop (best-effort)."""
|
||||
import subprocess as _sp
|
||||
|
||||
svc_dir = s6_scandir / "gateway-coder"
|
||||
svc_dir.mkdir()
|
||||
|
||||
svc_calls: list[list[str]] = []
|
||||
|
||||
def _fake(cmd, **kw):
|
||||
seq = list(cmd) if isinstance(cmd, (list, tuple)) else [str(cmd)]
|
||||
if seq and seq[0].startswith("/command/"):
|
||||
seq[0] = seq[0][len("/command/"):]
|
||||
svc_calls.append(seq)
|
||||
if seq and seq[0] == "s6-svstat":
|
||||
return _sp.CompletedProcess(cmd, 0, "up (pid 9090) 5 seconds\n", "")
|
||||
return _sp.CompletedProcess(cmd, 0, "", "")
|
||||
|
||||
monkeypatch.setattr("subprocess.run", _fake)
|
||||
|
||||
def _boom(pid):
|
||||
raise OSError("disk full")
|
||||
|
||||
monkeypatch.setattr("gateway.status.write_planned_stop_marker", _boom)
|
||||
|
||||
mgr = S6ServiceManager(scandir=s6_scandir)
|
||||
mgr.stop("gateway-coder") # must not raise
|
||||
|
||||
assert any(cmd[0] == "s6-svc" and "-d" in cmd for cmd in svc_calls)
|
||||
|
||||
@@ -9,13 +9,10 @@ from __future__ import annotations
|
||||
|
||||
def test_setup_ollama_cloud_passes_force_refresh(monkeypatch):
|
||||
"""The provider-setup model-fetch for ollama-cloud must pass ``force_refresh=True``."""
|
||||
# The ollama-cloud branch lives in ``_model_flow_api_key_provider``, which was
|
||||
# extracted from main.py into hermes_cli/model_setup_flows.py (god-file
|
||||
# decomposition Phase 2). Inspect the module the code now lives in.
|
||||
import hermes_cli.model_setup_flows as flows_mod
|
||||
import hermes_cli.main as main_mod
|
||||
import inspect
|
||||
|
||||
src = inspect.getsource(flows_mod)
|
||||
src = inspect.getsource(main_mod)
|
||||
|
||||
# Locate the ollama-cloud branch in the provider setup flow.
|
||||
marker = 'provider_id == "ollama-cloud"'
|
||||
|
||||
@@ -653,44 +653,6 @@ def test_browse_skills_dedup_uses_identifier_not_name(monkeypatch):
|
||||
)
|
||||
|
||||
|
||||
def test_do_browse_reports_live_per_source_progress():
|
||||
"""do_browse must pass an on_source_done callback so the status line ticks
|
||||
off each source as it resolves, instead of showing a frozen spinner while
|
||||
a slow source blocks. The page is still rendered once, after the full
|
||||
result set is merged and trust-sorted."""
|
||||
from hermes_cli.skills_hub import do_browse
|
||||
from tools.skills_hub import SkillMeta
|
||||
|
||||
meta = SkillMeta(
|
||||
name="demo", description="d", source="official",
|
||||
identifier="official/demo", trust_level="builtin",
|
||||
)
|
||||
|
||||
captured = {}
|
||||
|
||||
def fake_parallel(sources, query="", per_source_limits=None,
|
||||
source_filter="all", overall_timeout=30,
|
||||
on_source_done=None):
|
||||
# Simulate two sources completing — the callback must be wired through.
|
||||
assert on_source_done is not None, "do_browse must pass on_source_done"
|
||||
on_source_done("official", 1)
|
||||
on_source_done("clawhub", 0)
|
||||
captured["called"] = True
|
||||
return [meta], {"official": 1, "clawhub": 0}, []
|
||||
|
||||
sink = StringIO()
|
||||
console = Console(file=sink, force_terminal=False, color_system=None, width=120)
|
||||
|
||||
with patch("tools.skills_hub.create_source_router", return_value=[]), \
|
||||
patch("tools.skills_hub.GitHubAuth"), \
|
||||
patch("tools.skills_hub.parallel_search_sources", side_effect=fake_parallel):
|
||||
do_browse(page=1, page_size=20, console=console)
|
||||
|
||||
assert captured.get("called"), "parallel_search_sources was not invoked"
|
||||
# The rendered page still shows the (single) merged result.
|
||||
assert "demo" in sink.getvalue()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Regression: full identifier must be recoverable from `hermes skills search`
|
||||
# even when the slug is too long to fit the terminal width (issue #33674).
|
||||
|
||||
+4
-3
@@ -47,19 +47,20 @@ def test_cron_aliases():
|
||||
def test_cron_create_options():
|
||||
parser = _build()
|
||||
ns = parser.parse_args([
|
||||
"cron", "create", "0 9 * * *", "daily task prompt",
|
||||
"cron", "create", "0 9 * * *", "do the thing",
|
||||
"--name", "daily", "--deliver", "origin", "--repeat", "3",
|
||||
"--skill", "a", "--skill", "b", "--no-agent",
|
||||
"--workdir", "/tmp/x",
|
||||
"--workdir", "/tmp/x", "--profile", "work",
|
||||
])
|
||||
assert ns.schedule == "0 9 * * *"
|
||||
assert ns.prompt == "daily task prompt"
|
||||
assert ns.prompt == "do the thing"
|
||||
assert ns.name == "daily"
|
||||
assert ns.deliver == "origin"
|
||||
assert ns.repeat == 3
|
||||
assert ns.skills == ["a", "b"]
|
||||
assert ns.no_agent is True
|
||||
assert ns.workdir == "/tmp/x"
|
||||
assert ns.profile == "work"
|
||||
|
||||
|
||||
def test_cron_edit_no_agent_tristate():
|
||||
@@ -1,44 +0,0 @@
|
||||
from hermes_cli.web_server import _display_system_platform
|
||||
|
||||
|
||||
def test_windows_11_build_displays_as_windows_11():
|
||||
info = _display_system_platform(
|
||||
system="Windows",
|
||||
release="10",
|
||||
version="10.0.26200",
|
||||
platform_label="Windows-10-10.0.26200-SP0",
|
||||
)
|
||||
|
||||
assert info["os"] == "Windows"
|
||||
assert info["os_release"] == "11"
|
||||
assert info["os_version"] == "10.0.26200"
|
||||
assert info["platform"] == "Windows-11-10.0.26200-SP0"
|
||||
|
||||
|
||||
def test_windows_10_build_keeps_windows_10_label():
|
||||
info = _display_system_platform(
|
||||
system="Windows",
|
||||
release="10",
|
||||
version="10.0.19045",
|
||||
platform_label="Windows-10-10.0.19045-SP0",
|
||||
)
|
||||
|
||||
assert info["os"] == "Windows"
|
||||
assert info["os_release"] == "10"
|
||||
assert info["platform"] == "Windows-10-10.0.19045-SP0"
|
||||
|
||||
|
||||
def test_non_windows_platform_unchanged():
|
||||
info = _display_system_platform(
|
||||
system="Linux",
|
||||
release="6.8.0",
|
||||
version="#1 SMP",
|
||||
platform_label="Linux-6.8.0-x86_64-with-glibc2.39",
|
||||
)
|
||||
|
||||
assert info == {
|
||||
"os": "Linux",
|
||||
"os_release": "6.8.0",
|
||||
"os_version": "#1 SMP",
|
||||
"platform": "Linux-6.8.0-x86_64-with-glibc2.39",
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
cannot initialize (e.g. non-TTY, curses unavailable, terminal error)."""
|
||||
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
|
||||
from hermes_cli.config import load_config, save_config
|
||||
|
||||
@@ -25,46 +24,6 @@ def test_prompt_model_selection_falls_back_on_menu_runtime_error(monkeypatch):
|
||||
assert selected == "model-b"
|
||||
|
||||
|
||||
def test_prompt_model_selection_requires_expensive_confirmation(monkeypatch, capsys):
|
||||
from hermes_cli.auth import _prompt_model_selection
|
||||
|
||||
monkeypatch.setattr("hermes_cli.curses_ui.curses_radiolist", _raise_menu)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.model_cost_guard.expensive_model_warning",
|
||||
lambda *_args, **_kwargs: SimpleNamespace(message="EXPENSIVE MODEL WARNING"),
|
||||
)
|
||||
responses = iter(["1", "n"])
|
||||
monkeypatch.setattr("builtins.input", lambda _prompt="": next(responses))
|
||||
|
||||
selected = _prompt_model_selection(
|
||||
["openai/gpt-5.5-pro"],
|
||||
confirm_provider="nous",
|
||||
)
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert selected is None
|
||||
assert "EXPENSIVE MODEL WARNING" in out
|
||||
|
||||
|
||||
def test_prompt_model_selection_allows_confirmed_expensive_model(monkeypatch):
|
||||
from hermes_cli.auth import _prompt_model_selection
|
||||
|
||||
monkeypatch.setattr("hermes_cli.curses_ui.curses_radiolist", _raise_menu)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.model_cost_guard.expensive_model_warning",
|
||||
lambda *_args, **_kwargs: SimpleNamespace(message="EXPENSIVE MODEL WARNING"),
|
||||
)
|
||||
responses = iter(["1", "y"])
|
||||
monkeypatch.setattr("builtins.input", lambda _prompt="": next(responses))
|
||||
|
||||
selected = _prompt_model_selection(
|
||||
["openai/gpt-5.5-pro"],
|
||||
confirm_provider="nous",
|
||||
)
|
||||
|
||||
assert selected == "openai/gpt-5.5-pro"
|
||||
|
||||
|
||||
def test_prompt_reasoning_effort_falls_back_on_menu_runtime_error(monkeypatch):
|
||||
from hermes_cli.main import _prompt_reasoning_effort_selection
|
||||
|
||||
|
||||
@@ -975,19 +975,6 @@ def test_toolset_has_keys_treats_no_key_providers_as_configured():
|
||||
assert _toolset_has_keys("computer_use", config) is True
|
||||
|
||||
|
||||
def test_web_no_prompt_when_usable_keyless():
|
||||
"""Fresh install: web works via the free Parallel MCP, so enabling the web
|
||||
toolset should not force provider setup."""
|
||||
with patch("tools.web_tools.check_web_api_key", return_value=True):
|
||||
assert _toolset_needs_configuration_prompt("web", {}) is False
|
||||
|
||||
|
||||
def test_web_no_prompt_when_extract_backend_is_extract_capable():
|
||||
with patch("tools.web_tools.check_web_api_key", return_value=True):
|
||||
cfg = {"web": {"extract_backend": "parallel"}}
|
||||
assert _toolset_needs_configuration_prompt("web", cfg) is False
|
||||
|
||||
|
||||
def test_computer_use_needs_configuration_when_cua_driver_post_setup_pending():
|
||||
"""No-key providers can still need setup when their post_setup is unsatisfied.
|
||||
|
||||
|
||||
@@ -26,12 +26,6 @@ def _touch_tui_entry(root: Path) -> None:
|
||||
entry.write_text("console.log('tui')")
|
||||
|
||||
|
||||
def _assert_utf8_replace_capture(kwargs: dict) -> None:
|
||||
assert kwargs["text"] is True
|
||||
assert kwargs["encoding"] == "utf-8"
|
||||
assert kwargs["errors"] == "replace"
|
||||
|
||||
|
||||
def test_need_install_when_ink_missing(tmp_path: Path, main_mod) -> None:
|
||||
(tmp_path / "package-lock.json").write_text("{}")
|
||||
assert main_mod._tui_need_npm_install(tmp_path) is True
|
||||
@@ -234,8 +228,6 @@ def test_make_tui_argv_scopes_npm_install_on_termux_workspace(
|
||||
"--include-workspace-root=false",
|
||||
]
|
||||
assert calls[0][1]["cwd"] == str(tmp_path)
|
||||
_assert_utf8_replace_capture(calls[0][1])
|
||||
_assert_utf8_replace_capture(calls[1][1])
|
||||
|
||||
|
||||
def test_make_tui_argv_keeps_desktop_workspace_install_behaviour(
|
||||
@@ -271,8 +263,6 @@ def test_make_tui_argv_keeps_desktop_workspace_install_behaviour(
|
||||
"--progress=false",
|
||||
]
|
||||
assert calls[0][1]["cwd"] == str(tmp_path)
|
||||
_assert_utf8_replace_capture(calls[0][1])
|
||||
_assert_utf8_replace_capture(calls[1][1])
|
||||
|
||||
|
||||
def test_make_tui_argv_keeps_desktop_always_build_behaviour(
|
||||
@@ -296,35 +286,6 @@ def test_make_tui_argv_keeps_desktop_always_build_behaviour(
|
||||
|
||||
assert calls
|
||||
assert calls[0][0][0] == ["/bin/npm", "run", "build"]
|
||||
_assert_utf8_replace_capture(calls[0][1])
|
||||
|
||||
|
||||
def test_make_tui_argv_decodes_dev_prebuild_with_utf8_replace(
|
||||
tmp_path: Path, main_mod, monkeypatch
|
||||
) -> None:
|
||||
ink_dir = tmp_path / "packages" / "hermes-ink"
|
||||
ink_dir.mkdir(parents=True)
|
||||
tsx = tmp_path / "node_modules" / ".bin" / "tsx"
|
||||
tsx.parent.mkdir(parents=True)
|
||||
tsx.write_text("")
|
||||
|
||||
monkeypatch.setattr(main_mod, "_tui_need_npm_install", lambda _root: False)
|
||||
monkeypatch.setattr(main_mod.shutil, "which", lambda name: f"/bin/{name}")
|
||||
calls = []
|
||||
|
||||
def fake_run(*args, **kwargs):
|
||||
calls.append((args, kwargs))
|
||||
return types.SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(main_mod.subprocess, "run", fake_run)
|
||||
|
||||
argv, cwd = main_mod._make_tui_argv(tmp_path, tui_dev=True)
|
||||
|
||||
assert argv == [str(tsx), "src/entry.tsx"]
|
||||
assert cwd == tmp_path
|
||||
assert calls[0][0][0] == ["/bin/npm", "run", "build"]
|
||||
assert calls[0][1]["cwd"] == str(ink_dir)
|
||||
_assert_utf8_replace_capture(calls[0][1])
|
||||
|
||||
|
||||
# ── _workspace_root helper ──────────────────────────────────────────
|
||||
@@ -464,43 +425,3 @@ def test_tui_launch_install_uses_workspace_scope(
|
||||
install_cmd = npm_calls[0]
|
||||
assert "--workspace" in install_cmd
|
||||
assert "ui-tui" in install_cmd
|
||||
|
||||
def test_make_tui_argv_omits_workspace_when_tui_has_own_lockfile(
|
||||
tmp_path: Path, main_mod, monkeypatch
|
||||
) -> None:
|
||||
"""When ui-tui/ has its own package-lock.json, _workspace_root returns
|
||||
tui_dir itself. npm install --workspace ui-tui would fail in that case
|
||||
because npm cannot find a workspace named "ui-tui" inside ui-tui/.
|
||||
The fix omits --workspace and runs plain npm install from tui_dir.
|
||||
See #42973.
|
||||
"""
|
||||
tui_dir = tmp_path / "ui-tui"
|
||||
tui_dir.mkdir()
|
||||
(tui_dir / "package.json").write_text("{}")
|
||||
# Simulate curl-install layout: tui_dir has its own lockfile
|
||||
(tui_dir / "package-lock.json").write_text("{}")
|
||||
# Parent also has lockfile (but _workspace_root prefers tui_dir's own)
|
||||
(tmp_path / "package-lock.json").write_text("{}")
|
||||
|
||||
monkeypatch.delenv("TERMUX_VERSION", raising=False)
|
||||
monkeypatch.setenv("PREFIX", "/usr")
|
||||
monkeypatch.setattr(main_mod, "_tui_need_npm_install", lambda _root: True)
|
||||
monkeypatch.setattr(main_mod.shutil, "which", lambda name: f"/bin/{name}")
|
||||
calls = []
|
||||
|
||||
def fake_run(*args, **kwargs):
|
||||
calls.append((args, kwargs))
|
||||
return types.SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr(main_mod.subprocess, "run", fake_run)
|
||||
|
||||
main_mod._make_tui_argv(tui_dir, tui_dev=False)
|
||||
|
||||
install_cmd = calls[0][0][0]
|
||||
# Must NOT contain --workspace when npm_cwd == tui_dir
|
||||
assert "--workspace" not in install_cmd, (
|
||||
f"npm install should omit --workspace when tui_dir has its own lockfile, got: {install_cmd}"
|
||||
)
|
||||
assert install_cmd[:2] == ["/bin/npm", "install"]
|
||||
# cwd must be tui_dir (standalone), not parent
|
||||
assert calls[0][1]["cwd"] == str(tui_dir)
|
||||
|
||||
@@ -896,46 +896,6 @@ def test_launch_tui_exports_model_provider_and_toolsets(monkeypatch, main_mod):
|
||||
assert env["NODE_ENV"] == "production"
|
||||
|
||||
|
||||
def test_launch_tui_applies_terminal_backend_config(
|
||||
monkeypatch, main_mod, _isolate_hermes_home
|
||||
):
|
||||
captured = {}
|
||||
config_path = Path(os.environ["HERMES_HOME"]) / "config.yaml"
|
||||
config_path.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"terminal:",
|
||||
" backend: docker",
|
||||
" docker_image: example/hermes-tools:latest",
|
||||
" docker_extra_args:",
|
||||
" - --network=host",
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.delenv("TERMINAL_ENV", raising=False)
|
||||
monkeypatch.delenv("TERMINAL_DOCKER_IMAGE", raising=False)
|
||||
monkeypatch.delenv("TERMINAL_DOCKER_EXTRA_ARGS", raising=False)
|
||||
|
||||
monkeypatch.setattr(
|
||||
main_mod,
|
||||
"_make_tui_argv",
|
||||
lambda tui_dir, tui_dev: (["node", "dist/entry.js"], Path(".")),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
main_mod.subprocess,
|
||||
"call",
|
||||
lambda argv, cwd=None, env=None: captured.update({"env": env}) or 1,
|
||||
)
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
main_mod._launch_tui()
|
||||
|
||||
assert captured["env"]["TERMINAL_ENV"] == "docker"
|
||||
assert captured["env"]["TERMINAL_DOCKER_IMAGE"] == "example/hermes-tools:latest"
|
||||
assert captured["env"]["TERMINAL_DOCKER_EXTRA_ARGS"] == '["--network=host"]'
|
||||
|
||||
|
||||
def test_launch_tui_exit_code_42_relaunches_update(monkeypatch, main_mod):
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
@@ -350,7 +350,7 @@ def test_cmd_update_retries_optional_extras_individually_when_all_fails(monkeypa
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
recorded.append(cmd)
|
||||
if cmd == ["git", "fetch", "origin", "main"]:
|
||||
if cmd == ["git", "fetch", "origin"]:
|
||||
return SimpleNamespace(stdout="", stderr="", returncode=0)
|
||||
if cmd == ["git", "rev-parse", "--abbrev-ref", "HEAD"]:
|
||||
return SimpleNamespace(stdout="main\n", stderr="", returncode=0)
|
||||
@@ -399,7 +399,7 @@ def test_cmd_update_succeeds_with_extras(monkeypatch, tmp_path):
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
recorded.append(cmd)
|
||||
if cmd == ["git", "fetch", "origin", "main"]:
|
||||
if cmd == ["git", "fetch", "origin"]:
|
||||
return SimpleNamespace(stdout="", stderr="", returncode=0)
|
||||
if cmd == ["git", "rev-parse", "--abbrev-ref", "HEAD"]:
|
||||
return SimpleNamespace(stdout="main\n", stderr="", returncode=0)
|
||||
@@ -630,23 +630,6 @@ def test_cmd_update_no_checkout_when_already_on_main(monkeypatch, tmp_path):
|
||||
assert len(checkout_calls) == 0
|
||||
|
||||
|
||||
def test_cmd_update_fetch_is_scoped_to_target_branch(monkeypatch, tmp_path):
|
||||
"""The update fetch must name the target branch. A bare `git fetch origin`
|
||||
pulls every ref, and this repo has thousands of auto-generated branches, so
|
||||
an unscoped fetch can stall for minutes on a non-single-branch checkout."""
|
||||
_setup_update_mocks(monkeypatch, tmp_path)
|
||||
monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/uv" if name == "uv" else None)
|
||||
|
||||
side_effect, recorded = _make_update_side_effect()
|
||||
monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
|
||||
|
||||
hermes_main.cmd_update(SimpleNamespace())
|
||||
|
||||
fetch_calls = [c for c in recorded if "fetch" in c]
|
||||
assert fetch_calls == [["git", "fetch", "origin", "main"]]
|
||||
assert ["git", "fetch", "origin"] not in recorded
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fetch failure — friendly error messages
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -93,39 +93,7 @@ def test_check_for_updates_expired_cache(tmp_path, monkeypatch):
|
||||
result = check_for_updates()
|
||||
|
||||
assert result == 5
|
||||
assert mock_run.call_count == 3 # origin probe + git fetch + git rev-list
|
||||
|
||||
|
||||
def test_check_for_updates_official_ssh_origin_uses_https_probe(tmp_path):
|
||||
"""Passive update checks must not trigger SSH auth for official installs."""
|
||||
import hermes_cli.banner as banner
|
||||
|
||||
repo_dir = tmp_path / "hermes-agent"
|
||||
repo_dir.mkdir()
|
||||
(repo_dir / ".git").mkdir()
|
||||
|
||||
calls = []
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
calls.append(cmd)
|
||||
if cmd == ["git", "remote", "get-url", "origin"]:
|
||||
return MagicMock(returncode=0, stdout="git@github.com:NousResearch/hermes-agent.git\n")
|
||||
if cmd == ["git", "rev-parse", "HEAD"]:
|
||||
return MagicMock(returncode=0, stdout="local-sha\n")
|
||||
if cmd == [
|
||||
"git",
|
||||
"ls-remote",
|
||||
"https://github.com/NousResearch/hermes-agent.git",
|
||||
"refs/heads/main",
|
||||
]:
|
||||
return MagicMock(returncode=0, stdout="upstream-sha\trefs/heads/main\n")
|
||||
raise AssertionError(f"unexpected git command: {cmd!r}")
|
||||
|
||||
with patch("hermes_cli.banner.subprocess.run", side_effect=fake_run):
|
||||
result = banner._check_via_local_git(repo_dir)
|
||||
|
||||
assert result == banner.UPDATE_AVAILABLE_NO_COUNT
|
||||
assert ["git", "fetch", "origin", "--quiet"] not in calls
|
||||
assert mock_run.call_count == 2 # git fetch + git rev-list
|
||||
|
||||
|
||||
def test_check_for_updates_no_git_dir(tmp_path, monkeypatch):
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
"""Tests for interrupted-install self-heal (the ``.update-incomplete`` marker).
|
||||
|
||||
Covers the breadcrumb lifecycle and the launch-time recovery guard added so a
|
||||
``hermes update`` killed mid-install (Ctrl-C, terminal close, WSL OOM) gets
|
||||
finished automatically on the next launch instead of leaving a half-built venv.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import hermes_cli.main as m
|
||||
|
||||
|
||||
def test_marker_round_trip(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
marker = m._update_marker_path()
|
||||
assert marker == tmp_path / ".update-incomplete"
|
||||
assert not marker.exists()
|
||||
|
||||
m._write_update_incomplete_marker()
|
||||
assert marker.exists()
|
||||
body = marker.read_text()
|
||||
assert "started=" in body
|
||||
assert "pid=" in body
|
||||
|
||||
m._clear_update_incomplete_marker()
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
def test_clear_when_absent_is_noop(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
# Must not raise when the marker was never written.
|
||||
m._clear_update_incomplete_marker()
|
||||
assert not m._update_marker_path().exists()
|
||||
|
||||
|
||||
def test_recovery_noop_without_marker(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
called = {"install": False}
|
||||
monkeypatch.setattr(
|
||||
m,
|
||||
"_install_python_dependencies_with_optional_fallback",
|
||||
lambda *a, **k: called.__setitem__("install", True),
|
||||
)
|
||||
m._recover_from_interrupted_install()
|
||||
assert called["install"] is False, "recovery must not install when no marker"
|
||||
|
||||
|
||||
def test_recovery_clears_stray_marker_without_pyproject(tmp_path, monkeypatch):
|
||||
# No pyproject.toml (PyPI/Docker install) — a stray marker is not ours to
|
||||
# act on; recovery should just clear it without trying to install.
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
m._write_update_incomplete_marker()
|
||||
called = {"install": False}
|
||||
monkeypatch.setattr(
|
||||
m,
|
||||
"_install_python_dependencies_with_optional_fallback",
|
||||
lambda *a, **k: called.__setitem__("install", True),
|
||||
)
|
||||
m._recover_from_interrupted_install()
|
||||
assert called["install"] is False
|
||||
assert not m._update_marker_path().exists()
|
||||
|
||||
|
||||
def test_recovery_runs_install_and_clears_marker(tmp_path, monkeypatch):
|
||||
# Source-tree install (pyproject present) with marker set → recovery should
|
||||
# run the dep install and clear the marker on success.
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
(tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n")
|
||||
m._write_update_incomplete_marker()
|
||||
|
||||
seen = {"ensurepip": False, "install": False}
|
||||
|
||||
def fake_run(cmd, *a, **k):
|
||||
if "ensurepip" in cmd:
|
||||
seen["ensurepip"] = True
|
||||
|
||||
class R:
|
||||
returncode = 0
|
||||
|
||||
return R()
|
||||
|
||||
monkeypatch.setattr(m.subprocess, "run", fake_run)
|
||||
monkeypatch.setattr(m, "_is_termux_env", lambda *a, **k: False)
|
||||
monkeypatch.setattr("hermes_cli.managed_uv.ensure_uv", lambda: None)
|
||||
monkeypatch.setattr(
|
||||
m,
|
||||
"_install_python_dependencies_with_optional_fallback",
|
||||
lambda *a, **k: seen.__setitem__("install", True),
|
||||
)
|
||||
|
||||
m._recover_from_interrupted_install()
|
||||
|
||||
assert seen["ensurepip"] is True, "ensurepip must run unconditionally first"
|
||||
assert seen["install"] is True, "dep install must run"
|
||||
assert not m._update_marker_path().exists(), "marker cleared on success"
|
||||
|
||||
|
||||
def test_recovery_keeps_marker_on_failure(tmp_path, monkeypatch):
|
||||
# If the install itself blows up, the marker must survive so the next
|
||||
# launch retries — and recovery must not raise.
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
(tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n")
|
||||
m._write_update_incomplete_marker()
|
||||
|
||||
class R:
|
||||
returncode = 0
|
||||
|
||||
monkeypatch.setattr(m.subprocess, "run", lambda *a, **k: R())
|
||||
monkeypatch.setattr(m, "_is_termux_env", lambda *a, **k: False)
|
||||
monkeypatch.setattr("hermes_cli.managed_uv.ensure_uv", lambda: None)
|
||||
|
||||
def boom(*a, **k):
|
||||
raise RuntimeError("install died")
|
||||
|
||||
monkeypatch.setattr(
|
||||
m, "_install_python_dependencies_with_optional_fallback", boom
|
||||
)
|
||||
|
||||
# Must not raise.
|
||||
m._recover_from_interrupted_install()
|
||||
assert m._update_marker_path().exists(), "marker preserved for retry on failure"
|
||||
|
||||
|
||||
def _stub_install_env(monkeypatch, m, seen):
|
||||
"""Common stubs so recovery's install path is inert and observable."""
|
||||
|
||||
class R:
|
||||
returncode = 0
|
||||
|
||||
monkeypatch.setattr(m.subprocess, "run", lambda *a, **k: R())
|
||||
monkeypatch.setattr(m, "_is_termux_env", lambda *a, **k: False)
|
||||
monkeypatch.setattr("hermes_cli.managed_uv.ensure_uv", lambda: None)
|
||||
monkeypatch.setattr(
|
||||
m,
|
||||
"_install_python_dependencies_with_optional_fallback",
|
||||
lambda *a, **k: seen.__setitem__("install", True),
|
||||
)
|
||||
|
||||
|
||||
def test_recovery_skips_when_lock_held(tmp_path, monkeypatch):
|
||||
# Another process is mid-recovery (fresh lockfile) — this launch must skip
|
||||
# the install entirely and leave both marker and lock untouched.
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
(tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n")
|
||||
m._write_update_incomplete_marker()
|
||||
lock = tmp_path / ".update-incomplete.lock"
|
||||
lock.write_text("12345\n")
|
||||
|
||||
seen = {"install": False}
|
||||
_stub_install_env(monkeypatch, m, seen)
|
||||
|
||||
m._recover_from_interrupted_install()
|
||||
|
||||
assert seen["install"] is False, "must not install while another holds the lock"
|
||||
assert m._update_marker_path().exists(), "marker left for the lock holder"
|
||||
assert lock.exists(), "fresh lock must not be broken"
|
||||
|
||||
|
||||
def test_recovery_breaks_stale_lock(tmp_path, monkeypatch):
|
||||
# A lock older than an hour is from a crashed holder — it gets removed so
|
||||
# the NEXT launch can recover (this launch still skips).
|
||||
import os as _os
|
||||
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
(tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n")
|
||||
m._write_update_incomplete_marker()
|
||||
lock = tmp_path / ".update-incomplete.lock"
|
||||
lock.write_text("12345\n")
|
||||
stale = m._time.time() - 7200
|
||||
_os.utime(lock, (stale, stale))
|
||||
|
||||
seen = {"install": False}
|
||||
_stub_install_env(monkeypatch, m, seen)
|
||||
|
||||
m._recover_from_interrupted_install()
|
||||
|
||||
assert not lock.exists(), "stale lock must be broken"
|
||||
assert m._update_marker_path().exists()
|
||||
|
||||
# Next launch proceeds normally.
|
||||
m._recover_from_interrupted_install()
|
||||
assert seen["install"] is True
|
||||
assert not m._update_marker_path().exists()
|
||||
assert not lock.exists(), "lock released after recovery"
|
||||
|
||||
|
||||
def test_recovery_releases_lock_after_run(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
(tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n")
|
||||
m._write_update_incomplete_marker()
|
||||
|
||||
seen = {"install": False}
|
||||
_stub_install_env(monkeypatch, m, seen)
|
||||
|
||||
m._recover_from_interrupted_install()
|
||||
|
||||
assert seen["install"] is True
|
||||
assert not (tmp_path / ".update-incomplete.lock").exists()
|
||||
|
||||
|
||||
def test_recovery_output_goes_to_stderr(tmp_path, monkeypatch, capfd):
|
||||
# ACP speaks JSON-RPC on stdout — recovery output (including the streamed
|
||||
# install, which inherits fd 1) must land on stderr only.
|
||||
monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
|
||||
(tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n")
|
||||
m._write_update_incomplete_marker()
|
||||
|
||||
seen = {"install": False}
|
||||
_stub_install_env(monkeypatch, m, seen)
|
||||
|
||||
m._recover_from_interrupted_install()
|
||||
|
||||
out, err = capfd.readouterr()
|
||||
assert "interrupted mid-install" not in out
|
||||
assert "interrupted mid-install" in err
|
||||
assert "recovered" in err
|
||||
@@ -4,7 +4,6 @@ import os
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
@@ -1070,148 +1069,6 @@ class TestWebServerEndpoints:
|
||||
assert "GATEWAY_PROXY_URL" not in managed
|
||||
assert "GATEWAY_PROXY_URL" in _MESSAGING_KEYS_PAGE_KEYS
|
||||
|
||||
def test_model_set_requires_confirmation_for_expensive_model(self, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.model_cost_guard.expensive_model_warning",
|
||||
lambda *_args, **_kwargs: SimpleNamespace(message="EXPENSIVE MODEL WARNING"),
|
||||
)
|
||||
|
||||
resp = self.client.post(
|
||||
"/api/model/set",
|
||||
json={
|
||||
"scope": "main",
|
||||
"provider": "nous",
|
||||
"model": "openai/gpt-5.5-pro",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is False
|
||||
assert data["confirm_required"] is True
|
||||
assert data["confirm_message"] == "EXPENSIVE MODEL WARNING"
|
||||
|
||||
confirmed = self.client.post(
|
||||
"/api/model/set",
|
||||
json={
|
||||
"scope": "main",
|
||||
"provider": "nous",
|
||||
"model": "openai/gpt-5.5-pro",
|
||||
"confirm_expensive_model": True,
|
||||
},
|
||||
)
|
||||
|
||||
assert confirmed.status_code == 200
|
||||
assert confirmed.json()["ok"] is True
|
||||
|
||||
def test_model_set_normalizes_vendor_slug_for_native_provider(self, monkeypatch):
|
||||
"""'Use as → Main' with an OpenRouter slug + native provider must not
|
||||
persist the vendor-prefixed slug verbatim (it 400s against the native
|
||||
API and reads as "changing models does nothing")."""
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.model_cost_guard.expensive_model_warning",
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
resp = self.client.post(
|
||||
"/api/model/set",
|
||||
json={
|
||||
"scope": "main",
|
||||
"provider": "anthropic",
|
||||
"model": "anthropic/claude-opus-4.6",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is True
|
||||
assert data["provider"] == "anthropic"
|
||||
# Vendor prefix stripped + dots→hyphens for the native Anthropic API.
|
||||
assert data["model"] == "claude-opus-4-6"
|
||||
|
||||
from hermes_cli.config import load_config
|
||||
cfg = load_config()
|
||||
assert cfg["model"]["provider"] == "anthropic"
|
||||
assert cfg["model"]["default"] == "claude-opus-4-6"
|
||||
|
||||
def test_model_set_maps_unknown_vendor_to_aggregator(self, monkeypatch):
|
||||
"""A bare vendor name from analytics rows (no billing_provider) is not
|
||||
a Hermes provider — keep the user's aggregator instead of writing a
|
||||
provider that can never resolve credentials."""
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.model_cost_guard.expensive_model_warning",
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
from hermes_cli.config import load_config, save_config
|
||||
cfg = load_config()
|
||||
cfg["model"] = {"provider": "openrouter", "default": "openai/gpt-5.5"}
|
||||
save_config(cfg)
|
||||
|
||||
resp = self.client.post(
|
||||
"/api/model/set",
|
||||
json={
|
||||
"scope": "main",
|
||||
"provider": "moonshotai", # vendor prefix, not a provider
|
||||
"model": "moonshotai/kimi-k2.6",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is True
|
||||
assert data["provider"] == "openrouter"
|
||||
assert data["model"] == "moonshotai/kimi-k2.6"
|
||||
|
||||
def test_model_set_keeps_aggregator_slug_unchanged(self, monkeypatch):
|
||||
"""The happy path (picker → openrouter + vendor/model) is untouched."""
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.model_cost_guard.expensive_model_warning",
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
resp = self.client.post(
|
||||
"/api/model/set",
|
||||
json={
|
||||
"scope": "main",
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is True
|
||||
assert data["provider"] == "openrouter"
|
||||
assert data["model"] == "anthropic/claude-sonnet-4.6"
|
||||
|
||||
def test_ops_import_passes_force_flag(self, tmp_path, monkeypatch):
|
||||
"""force=True must append --force so the spawned non-interactive
|
||||
`hermes import` doesn't auto-abort at the overwrite prompt."""
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
archive = tmp_path / "backup.zip"
|
||||
import zipfile
|
||||
with zipfile.ZipFile(archive, "w") as zf:
|
||||
zf.writestr("config.yaml", "model: {}\n")
|
||||
|
||||
captured = {}
|
||||
|
||||
def fake_spawn(subcommand, name):
|
||||
captured["args"] = subcommand
|
||||
captured["name"] = name
|
||||
from types import SimpleNamespace as NS
|
||||
return NS(pid=12345)
|
||||
|
||||
monkeypatch.setattr(ws, "_spawn_hermes_action", fake_spawn)
|
||||
|
||||
resp = self.client.post(
|
||||
"/api/ops/import", json={"archive": str(archive), "force": True},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert captured["args"] == ["import", str(archive), "--force"]
|
||||
|
||||
resp = self.client.post(
|
||||
"/api/ops/import", json={"archive": str(archive)},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert captured["args"] == ["import", str(archive)]
|
||||
|
||||
|
||||
def test_reveal_env_var(self, tmp_path):
|
||||
"""POST /api/env/reveal should return the real unredacted value."""
|
||||
from hermes_cli.config import save_env_value
|
||||
@@ -1506,17 +1363,6 @@ class TestWebServerEndpoints:
|
||||
}
|
||||
|
||||
monkeypatch.setattr(ws, "_telegram_onboarding_request_sync", fake_request)
|
||||
ws._ACTION_PROCS.pop("gateway-restart", None)
|
||||
restart_calls = []
|
||||
|
||||
class FakeRestartProc:
|
||||
pid = 4242
|
||||
|
||||
def fake_spawn_action(subcommand, name):
|
||||
restart_calls.append((subcommand, name))
|
||||
return FakeRestartProc()
|
||||
|
||||
monkeypatch.setattr(ws, "_spawn_hermes_action", fake_spawn_action)
|
||||
|
||||
start = self.client.post("/api/messaging/telegram/onboarding/start", json={})
|
||||
assert start.status_code == 200
|
||||
@@ -1538,138 +1384,13 @@ class TestWebServerEndpoints:
|
||||
"ok": True,
|
||||
"platform": "telegram",
|
||||
"bot_username": "hermes_pair_ready_bot",
|
||||
"needs_restart": False,
|
||||
"restart_started": True,
|
||||
"restart_action": "gateway-restart",
|
||||
"restart_pid": 4242,
|
||||
"needs_restart": True,
|
||||
}
|
||||
assert restart_calls == [(["gateway", "restart"], "gateway-restart")]
|
||||
env = load_env()
|
||||
assert env["TELEGRAM_BOT_TOKEN"] == "123456:SECRET"
|
||||
assert env["TELEGRAM_ALLOWED_USERS"] == "123456789"
|
||||
assert load_config()["platforms"]["telegram"]["enabled"] is True
|
||||
|
||||
def test_telegram_onboarding_apply_reports_restart_failure_after_save(
|
||||
self, monkeypatch
|
||||
):
|
||||
import hermes_cli.web_server as ws
|
||||
from hermes_cli.config import load_config, load_env
|
||||
|
||||
with ws._telegram_onboarding_lock:
|
||||
ws._telegram_onboarding_pairings.clear()
|
||||
|
||||
def fake_request(method, path, *, body=None, bearer_token=None):
|
||||
if method == "POST":
|
||||
return {
|
||||
"pairing_id": "pair-restart-fails",
|
||||
"poll_token": "poll-secret",
|
||||
"suggested_username": "hermes_pair_restart_fails_bot",
|
||||
"deep_link": "https://t.me/newbot/HermesSetupBot/hermes_pair_restart_fails_bot",
|
||||
"qr_payload": "https://t.me/newbot/HermesSetupBot/hermes_pair_restart_fails_bot",
|
||||
"expires_at": "2027-05-18T00:00:00.000Z",
|
||||
}
|
||||
assert method == "GET"
|
||||
assert path == "/v1/telegram/pairings/pair-restart-fails"
|
||||
assert bearer_token == "poll-secret"
|
||||
return {
|
||||
"status": "ready",
|
||||
"bot_username": "hermes_pair_restart_fails_bot",
|
||||
"owner_user_id": 123456789,
|
||||
"token": "123456:SECRET",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(ws, "_telegram_onboarding_request_sync", fake_request)
|
||||
ws._ACTION_PROCS.pop("gateway-restart", None)
|
||||
|
||||
def fail_spawn_action(subcommand, name):
|
||||
assert subcommand == ["gateway", "restart"]
|
||||
assert name == "gateway-restart"
|
||||
raise RuntimeError("supervisor unavailable")
|
||||
|
||||
monkeypatch.setattr(ws, "_spawn_hermes_action", fail_spawn_action)
|
||||
|
||||
start = self.client.post("/api/messaging/telegram/onboarding/start", json={})
|
||||
assert start.status_code == 200
|
||||
ready = self.client.get("/api/messaging/telegram/onboarding/pair-restart-fails")
|
||||
assert ready.status_code == 200
|
||||
assert ready.json()["status"] == "ready"
|
||||
|
||||
applied = self.client.post(
|
||||
"/api/messaging/telegram/onboarding/pair-restart-fails/apply",
|
||||
json={"allowed_user_ids": ["123456789"]},
|
||||
)
|
||||
|
||||
assert applied.status_code == 200
|
||||
applied_data = applied.json()
|
||||
assert applied_data["ok"] is True
|
||||
assert applied_data["needs_restart"] is True
|
||||
assert applied_data["restart_started"] is False
|
||||
assert "supervisor unavailable" in applied_data["restart_error"]
|
||||
assert "token" not in applied_data
|
||||
env = load_env()
|
||||
assert env["TELEGRAM_BOT_TOKEN"] == "123456:SECRET"
|
||||
assert env["TELEGRAM_ALLOWED_USERS"] == "123456789"
|
||||
assert load_config()["platforms"]["telegram"]["enabled"] is True
|
||||
|
||||
def test_telegram_onboarding_apply_reuses_inflight_gateway_restart(
|
||||
self, monkeypatch
|
||||
):
|
||||
"""A live in-flight gateway restart is reused instead of spawning a
|
||||
second racing ``hermes gateway restart`` child (e.g. when a stale
|
||||
cached frontend also fires its own restart call)."""
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
with ws._telegram_onboarding_lock:
|
||||
ws._telegram_onboarding_pairings.clear()
|
||||
|
||||
def fake_request(method, path, *, body=None, bearer_token=None):
|
||||
if method == "POST":
|
||||
return {
|
||||
"pairing_id": "pair-reuse",
|
||||
"poll_token": "poll-secret",
|
||||
"suggested_username": "hermes_pair_reuse_bot",
|
||||
"deep_link": "https://t.me/newbot/HermesSetupBot/hermes_pair_reuse_bot",
|
||||
"qr_payload": "https://t.me/newbot/HermesSetupBot/hermes_pair_reuse_bot",
|
||||
"expires_at": "2027-05-18T00:00:00.000Z",
|
||||
}
|
||||
return {
|
||||
"status": "ready",
|
||||
"bot_username": "hermes_pair_reuse_bot",
|
||||
"owner_user_id": 123456789,
|
||||
"token": "123456:SECRET",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(ws, "_telegram_onboarding_request_sync", fake_request)
|
||||
|
||||
class FakeRunningProc:
|
||||
pid = 5151
|
||||
|
||||
def poll(self):
|
||||
return None # still running
|
||||
|
||||
monkeypatch.setitem(ws._ACTION_PROCS, "gateway-restart", FakeRunningProc())
|
||||
|
||||
def fail_spawn_action(subcommand, name):
|
||||
raise AssertionError("must not spawn a second concurrent restart")
|
||||
|
||||
monkeypatch.setattr(ws, "_spawn_hermes_action", fail_spawn_action)
|
||||
|
||||
start = self.client.post("/api/messaging/telegram/onboarding/start", json={})
|
||||
assert start.status_code == 200
|
||||
ready = self.client.get("/api/messaging/telegram/onboarding/pair-reuse")
|
||||
assert ready.status_code == 200
|
||||
|
||||
applied = self.client.post(
|
||||
"/api/messaging/telegram/onboarding/pair-reuse/apply",
|
||||
json={"allowed_user_ids": ["123456789"]},
|
||||
)
|
||||
|
||||
assert applied.status_code == 200
|
||||
applied_data = applied.json()
|
||||
assert applied_data["needs_restart"] is False
|
||||
assert applied_data["restart_started"] is True
|
||||
assert applied_data["restart_pid"] == 5151
|
||||
|
||||
def test_telegram_onboarding_apply_requires_ready_pairing(self, monkeypatch):
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
@@ -1880,28 +1601,6 @@ class TestWebServerEndpoints:
|
||||
out = _apply_main_model_assignment("not-a-dict", "custom", "m", "http://x/v1")
|
||||
assert out == {"provider": "custom", "default": "m", "base_url": "http://x/v1"}
|
||||
|
||||
# api_key follows the same lifecycle as base_url:
|
||||
# supplied → persisted.
|
||||
out = _apply_main_model_assignment(
|
||||
{}, "custom", "m", "http://x/v1", "sk-secret"
|
||||
)
|
||||
assert out["api_key"] == "sk-secret"
|
||||
|
||||
# same provider, no new key → existing key preserved (re-picking a model
|
||||
# on the same custom endpoint must not wipe the saved key).
|
||||
out = _apply_main_model_assignment(
|
||||
{"provider": "custom", "base_url": "http://x/v1", "api_key": "sk-keep"},
|
||||
"custom",
|
||||
"m2",
|
||||
)
|
||||
assert out["api_key"] == "sk-keep"
|
||||
|
||||
# switching providers without a new key → stale key cleared.
|
||||
out = _apply_main_model_assignment(
|
||||
{"provider": "custom", "api_key": "sk-old"}, "openrouter", "m"
|
||||
)
|
||||
assert out["api_key"] == ""
|
||||
|
||||
def test_parse_model_ids_handles_openai_and_bare_shapes(self):
|
||||
"""Model discovery must tolerate the common /v1/models shapes and
|
||||
never raise (so a slightly non-standard local endpoint still works)."""
|
||||
@@ -1958,45 +1657,6 @@ class TestWebServerEndpoints:
|
||||
assert model_cfg["default"] == "llama-3.1-8b"
|
||||
assert model_cfg["base_url"] == "http://127.0.0.1:8000/v1"
|
||||
|
||||
def test_set_model_main_custom_persists_api_key_and_registers_provider(self):
|
||||
"""A custom endpoint that requires auth must persist model.api_key (where
|
||||
the runtime reads it) AND register a named custom_providers entry so the
|
||||
endpoint reappears as a ready row in the picker — matching the
|
||||
``hermes model`` custom flow. Regression for the desktop loop where a
|
||||
keyed custom endpoint could never be configured from the GUI."""
|
||||
from hermes_cli.config import load_config
|
||||
|
||||
resp = self.client.post(
|
||||
"/api/model/set",
|
||||
json={
|
||||
"scope": "main",
|
||||
"provider": "custom",
|
||||
"model": "gpt-oss-120b",
|
||||
"base_url": "https://text.example.com/v1",
|
||||
"api_key": "sk-secret",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["ok"] is True
|
||||
|
||||
cfg = load_config()
|
||||
model_cfg = cfg.get("model")
|
||||
assert isinstance(model_cfg, dict)
|
||||
assert model_cfg["provider"] == "custom"
|
||||
assert model_cfg["base_url"] == "https://text.example.com/v1"
|
||||
assert model_cfg["api_key"] == "sk-secret"
|
||||
|
||||
# Registered in custom_providers (dedup by base_url) so the picker shows
|
||||
# a proper ready row instead of the "needs setup" dead-end.
|
||||
custom = cfg.get("custom_providers") or []
|
||||
assert any(
|
||||
isinstance(e, dict)
|
||||
and e.get("base_url") == "https://text.example.com/v1"
|
||||
and e.get("api_key") == "sk-secret"
|
||||
and e.get("model") == "gpt-oss-120b"
|
||||
for e in custom
|
||||
)
|
||||
|
||||
def test_set_model_main_non_custom_clears_stale_base_url(self):
|
||||
"""Switching to a hosted provider must clear a stale base_url so the
|
||||
resolver picks that provider's own default endpoint."""
|
||||
@@ -2421,42 +2081,6 @@ class TestNewEndpoints:
|
||||
resp = self.client.get("/api/cron/jobs/nonexistent-id")
|
||||
assert resp.status_code == 404
|
||||
|
||||
# --- Automation Blueprints ---
|
||||
|
||||
def test_cron_blueprints_list(self):
|
||||
resp = self.client.get("/api/cron/blueprints")
|
||||
assert resp.status_code == 200
|
||||
blueprints = resp.json()["blueprints"]
|
||||
assert len(blueprints) >= 1
|
||||
first = blueprints[0]
|
||||
assert "fields" in first
|
||||
assert first["command"].startswith("/blueprint")
|
||||
assert first["appUrl"].startswith("hermes://")
|
||||
|
||||
def test_blueprint_instantiate_creates_job(self):
|
||||
resp = self.client.post(
|
||||
"/api/cron/blueprints/instantiate",
|
||||
json={"blueprint": "morning-brief", "values": {"time": "07:30", "deliver": "local"}},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
job = resp.json()
|
||||
assert (job.get("schedule_display") or "").strip() == "30 7 * * *" or \
|
||||
(job.get("schedule", {}) or {}).get("expr") == "30 7 * * *"
|
||||
|
||||
def test_blueprint_instantiate_unknown_404(self):
|
||||
resp = self.client.post(
|
||||
"/api/cron/blueprints/instantiate",
|
||||
json={"blueprint": "does-not-exist", "values": {}},
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_blueprint_instantiate_bad_value_422(self):
|
||||
resp = self.client.post(
|
||||
"/api/cron/blueprints/instantiate",
|
||||
json={"blueprint": "morning-brief", "values": {"time": "99:99"}},
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
|
||||
# --- Profiles ---
|
||||
|
||||
def test_profiles_list_includes_default(self):
|
||||
@@ -2629,83 +2253,6 @@ class TestNewEndpoints:
|
||||
profiles = {p["name"]: p for p in self.client.get("/api/profiles").json()["profiles"]}
|
||||
assert profiles["fresh"]["skill_count"] == 1
|
||||
|
||||
def test_profiles_create_builder_fields_model_mcp_and_keep_skills(self, monkeypatch):
|
||||
"""Profile-builder create: model + MCP servers + keep-skills selection
|
||||
all land in the NEW profile's config, and hub installs are spawned
|
||||
scoped to that profile via ``-p <name>``."""
|
||||
from hermes_constants import (
|
||||
get_hermes_home,
|
||||
set_hermes_home_override,
|
||||
reset_hermes_home_override,
|
||||
)
|
||||
from hermes_cli.config import load_config
|
||||
from hermes_cli.skills_config import get_disabled_skills
|
||||
import hermes_cli.profiles as profiles_mod
|
||||
import hermes_cli.web_server as web_server
|
||||
|
||||
monkeypatch.setattr(profiles_mod, "create_wrapper_script", lambda name: None)
|
||||
|
||||
# Seed two known skills so keep-skills "replace" has something to act on.
|
||||
def fake_seed(profile_dir, quiet=False):
|
||||
for skill in ("keep-me", "drop-me"):
|
||||
d = profile_dir / "skills" / "custom" / skill
|
||||
d.mkdir(parents=True)
|
||||
(d / "SKILL.md").write_text(f"---\nname: {skill}\n---\n", encoding="utf-8")
|
||||
return {"copied": ["keep-me", "drop-me"]}
|
||||
|
||||
monkeypatch.setattr(profiles_mod, "seed_profile_skills", fake_seed)
|
||||
|
||||
# Capture hub-install spawns instead of launching real subprocesses.
|
||||
spawned = []
|
||||
|
||||
class _FakeProc:
|
||||
pid = 4321
|
||||
|
||||
def fake_spawn(subcommand, name):
|
||||
spawned.append((list(subcommand), name))
|
||||
return _FakeProc()
|
||||
|
||||
monkeypatch.setattr(web_server, "_spawn_hermes_action", fake_spawn)
|
||||
|
||||
resp = self.client.post(
|
||||
"/api/profiles",
|
||||
json={
|
||||
"name": "builder",
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
"mcp_servers": [
|
||||
{"name": "ctx7", "url": "https://mcp.context7.com/mcp"},
|
||||
{"name": "bogus"}, # no url/command -> must be skipped, no 500
|
||||
],
|
||||
"keep_skills": ["keep-me"],
|
||||
"hub_skills": ["someuser/some-skill"],
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["model_set"] is True
|
||||
assert data["mcp_written"] == 1 # bogus skipped
|
||||
assert data["skills_disabled"] == 1 # drop-me disabled, keep-me kept
|
||||
assert data["hub_installs"] == [{"identifier": "someuser/some-skill", "pid": 4321}]
|
||||
|
||||
# Hub install was scoped to the new profile.
|
||||
assert spawned == [(["-p", "builder", "skills", "install", "someuser/some-skill"], "skills-install")]
|
||||
|
||||
# Verify the writes landed in the NEW profile's config, not the root.
|
||||
prof_dir = get_hermes_home() / "profiles" / "builder"
|
||||
token = set_hermes_home_override(str(prof_dir))
|
||||
try:
|
||||
cfg = load_config()
|
||||
assert cfg["model"]["default"] == "anthropic/claude-sonnet-4.6"
|
||||
assert cfg["model"]["provider"] == "openrouter"
|
||||
assert sorted((cfg.get("mcp_servers") or {}).keys()) == ["ctx7"]
|
||||
disabled = get_disabled_skills(cfg)
|
||||
assert "drop-me" in disabled
|
||||
assert "keep-me" not in disabled
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
|
||||
def test_profile_open_terminal_uses_macos_terminal(self, monkeypatch):
|
||||
from hermes_constants import get_hermes_home
|
||||
import hermes_cli.web_server as web_server
|
||||
@@ -4599,39 +4146,6 @@ class TestPtyWebSocket:
|
||||
assert env["HERMES_TUI_INLINE"] == "1"
|
||||
assert env["HERMES_TUI_DISABLE_MOUSE"] == "1"
|
||||
|
||||
def test_resolve_chat_argv_applies_terminal_backend_config(
|
||||
self, monkeypatch, _isolate_hermes_home
|
||||
):
|
||||
import hermes_cli.main as main_mod
|
||||
|
||||
config_path = Path(os.environ["HERMES_HOME"]) / "config.yaml"
|
||||
config_path.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"terminal:",
|
||||
" backend: docker",
|
||||
" docker_image: example/hermes-tools:latest",
|
||||
" docker_extra_args:",
|
||||
" - --network=host",
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.delenv("TERMINAL_ENV", raising=False)
|
||||
monkeypatch.delenv("TERMINAL_DOCKER_IMAGE", raising=False)
|
||||
monkeypatch.delenv("TERMINAL_DOCKER_EXTRA_ARGS", raising=False)
|
||||
monkeypatch.setattr(
|
||||
main_mod,
|
||||
"_make_tui_argv",
|
||||
lambda project_root, tui_dev=False: (["node", "dist/entry.js"], "/tmp/ui-tui"),
|
||||
)
|
||||
|
||||
_argv, _cwd, env = self.ws_module._resolve_chat_argv()
|
||||
|
||||
assert env["TERMINAL_ENV"] == "docker"
|
||||
assert env["TERMINAL_DOCKER_IMAGE"] == "example/hermes-tools:latest"
|
||||
assert env["TERMINAL_DOCKER_EXTRA_ARGS"] == '["--network=host"]'
|
||||
|
||||
def test_rejects_when_embedded_chat_disabled(self, monkeypatch):
|
||||
monkeypatch.setattr(self.ws_module, "_DASHBOARD_EMBEDDED_CHAT_ENABLED", False)
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
@@ -4645,7 +4159,7 @@ class TestPtyWebSocket:
|
||||
monkeypatch.setattr(
|
||||
self.ws_module,
|
||||
"_resolve_chat_argv",
|
||||
lambda resume=None, sidecar_url=None, profile=None: (["/bin/cat"], None, None),
|
||||
lambda resume=None, sidecar_url=None: (["/bin/cat"], None, None),
|
||||
)
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
@@ -4658,7 +4172,7 @@ class TestPtyWebSocket:
|
||||
monkeypatch.setattr(
|
||||
self.ws_module,
|
||||
"_resolve_chat_argv",
|
||||
lambda resume=None, sidecar_url=None, profile=None: (["/bin/cat"], None, None),
|
||||
lambda resume=None, sidecar_url=None: (["/bin/cat"], None, None),
|
||||
)
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
@@ -4671,7 +4185,7 @@ class TestPtyWebSocket:
|
||||
monkeypatch.setattr(
|
||||
self.ws_module,
|
||||
"_resolve_chat_argv",
|
||||
lambda resume=None, sidecar_url=None, profile=None: (
|
||||
lambda resume=None, sidecar_url=None: (
|
||||
["/bin/sh", "-c", "printf hermes-ws-ok"],
|
||||
None,
|
||||
None,
|
||||
@@ -4701,7 +4215,7 @@ class TestPtyWebSocket:
|
||||
monkeypatch.setattr(
|
||||
self.ws_module,
|
||||
"_resolve_chat_argv",
|
||||
lambda resume=None, sidecar_url=None, profile=None: (["/bin/cat"], None, None),
|
||||
lambda resume=None, sidecar_url=None: (["/bin/cat"], None, None),
|
||||
)
|
||||
with self.client.websocket_connect(self._url()) as conn:
|
||||
conn.send_bytes(b"round-trip-payload\n")
|
||||
@@ -4734,7 +4248,7 @@ class TestPtyWebSocket:
|
||||
self.ws_module,
|
||||
"_resolve_chat_argv",
|
||||
# sleep gives the test time to push the resize before the child reads the ioctl.
|
||||
lambda resume=None, sidecar_url=None, profile=None: (
|
||||
lambda resume=None, sidecar_url=None: (
|
||||
[sys.executable, "-c", winsize_script],
|
||||
None,
|
||||
None,
|
||||
@@ -4770,7 +4284,7 @@ class TestPtyWebSocket:
|
||||
monkeypatch.setattr(
|
||||
self.ws_module,
|
||||
"_resolve_chat_argv",
|
||||
lambda resume=None, sidecar_url=None, profile=None: (["/bin/cat"], None, None),
|
||||
lambda resume=None, sidecar_url=None: (["/bin/cat"], None, None),
|
||||
)
|
||||
# Patch PtyBridge.spawn at the web_server module's binding.
|
||||
import hermes_cli.web_server as ws_mod
|
||||
@@ -4785,7 +4299,7 @@ class TestPtyWebSocket:
|
||||
def test_resume_parameter_is_forwarded_to_argv(self, monkeypatch):
|
||||
captured: dict = {}
|
||||
|
||||
def fake_resolve(resume=None, sidecar_url=None, profile=None):
|
||||
def fake_resolve(resume=None, sidecar_url=None):
|
||||
captured["resume"] = resume
|
||||
return (["/bin/sh", "-c", "printf resume-arg-ok"], None, None)
|
||||
|
||||
@@ -4805,7 +4319,7 @@ class TestPtyWebSocket:
|
||||
same channel — which is how tool events reach the dashboard sidebar."""
|
||||
captured: dict = {}
|
||||
|
||||
def fake_resolve(resume=None, sidecar_url=None, profile=None):
|
||||
def fake_resolve(resume=None, sidecar_url=None):
|
||||
captured["sidecar_url"] = sidecar_url
|
||||
return (["/bin/sh", "-c", "printf sidecar-ok"], None, None)
|
||||
|
||||
@@ -5079,83 +4593,6 @@ class TestValidateProviderCredential:
|
||||
data = self._post("OPENAI_API_KEY", " ").json()
|
||||
assert data["ok"] is False
|
||||
|
||||
def test_local_endpoint_forwards_api_key_as_bearer(self, monkeypatch):
|
||||
"""A custom endpoint that gates /v1/models behind auth must still
|
||||
enumerate models: the optional api_key is sent as a Bearer header so the
|
||||
probe doesn't come back empty (the desktop loop's root cause)."""
|
||||
captured = {}
|
||||
|
||||
class _Resp:
|
||||
status_code = 200
|
||||
is_success = True
|
||||
|
||||
def json(self):
|
||||
return {"data": [{"id": "gpt-oss-120b"}]}
|
||||
|
||||
class _Client:
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
def get(self, url, *a, headers=None, **k):
|
||||
captured["url"] = url
|
||||
captured["headers"] = headers
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr("httpx.Client", _Client)
|
||||
|
||||
resp = self.client.post(
|
||||
"/api/providers/validate",
|
||||
json={
|
||||
"key": "OPENAI_BASE_URL",
|
||||
"value": "https://text.example.com/v1",
|
||||
"api_key": "sk-secret",
|
||||
},
|
||||
)
|
||||
data = resp.json()
|
||||
assert data["ok"] is True and data["reachable"] is True
|
||||
assert data["models"] == ["gpt-oss-120b"]
|
||||
assert captured["url"] == "https://text.example.com/v1/models"
|
||||
assert captured["headers"] == {"Authorization": "Bearer sk-secret"}
|
||||
|
||||
def test_local_endpoint_without_key_sends_no_auth_header(self, monkeypatch):
|
||||
"""No key → no Authorization header (keyless local servers unaffected)."""
|
||||
captured = {}
|
||||
|
||||
class _Resp:
|
||||
status_code = 200
|
||||
is_success = True
|
||||
|
||||
def json(self):
|
||||
return {"data": []}
|
||||
|
||||
class _Client:
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
def get(self, url, *a, headers=None, **k):
|
||||
captured["headers"] = headers
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr("httpx.Client", _Client)
|
||||
|
||||
self.client.post(
|
||||
"/api/providers/validate",
|
||||
json={"key": "OPENAI_BASE_URL", "value": "http://127.0.0.1:8000/v1"},
|
||||
)
|
||||
assert captured["headers"] is None
|
||||
|
||||
|
||||
class TestDesktopCronTicker:
|
||||
"""The dashboard backend fires cron jobs itself only when desktop-spawned."""
|
||||
|
||||
@@ -1,246 +0,0 @@
|
||||
"""Tests for the dashboard-managed file browser API."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
from hermes_cli import web_server
|
||||
|
||||
|
||||
def _client_with_app_state():
|
||||
prev_auth_required = getattr(web_server.app.state, "auth_required", None)
|
||||
prev_bound_host = getattr(web_server.app.state, "bound_host", None)
|
||||
web_server.app.state.auth_required = False
|
||||
web_server.app.state.bound_host = None
|
||||
|
||||
client = TestClient(web_server.app)
|
||||
client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
|
||||
return client, prev_auth_required, prev_bound_host
|
||||
|
||||
|
||||
def _restore_app_state(prev_auth_required, prev_bound_host):
|
||||
if prev_auth_required is None:
|
||||
delattr(web_server.app.state, "auth_required")
|
||||
else:
|
||||
web_server.app.state.auth_required = prev_auth_required
|
||||
if prev_bound_host is None:
|
||||
if hasattr(web_server.app.state, "bound_host"):
|
||||
delattr(web_server.app.state, "bound_host")
|
||||
else:
|
||||
web_server.app.state.bound_host = prev_bound_host
|
||||
|
||||
|
||||
def _close_client(client):
|
||||
close = getattr(client, "close", None)
|
||||
if close is not None:
|
||||
close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def forced_files_client(monkeypatch, tmp_path):
|
||||
root = tmp_path / "data"
|
||||
monkeypatch.setenv("HERMES_DASHBOARD_FILES_ROOT", str(root))
|
||||
|
||||
client, prev_auth_required, prev_bound_host = _client_with_app_state()
|
||||
try:
|
||||
yield client, root
|
||||
finally:
|
||||
_close_client(client)
|
||||
_restore_app_state(prev_auth_required, prev_bound_host)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def local_files_client(monkeypatch, tmp_path):
|
||||
home = tmp_path / "home"
|
||||
home.mkdir()
|
||||
monkeypatch.delenv("HERMES_DASHBOARD_FILES_ROOT", raising=False)
|
||||
monkeypatch.delenv("HERMES_HOME", raising=False)
|
||||
monkeypatch.setenv("HOME", str(home))
|
||||
|
||||
client, prev_auth_required, prev_bound_host = _client_with_app_state()
|
||||
try:
|
||||
yield client, home
|
||||
finally:
|
||||
_close_client(client)
|
||||
_restore_app_state(prev_auth_required, prev_bound_host)
|
||||
|
||||
|
||||
def test_forced_root_file_upload_list_read_delete_roundtrip(forced_files_client):
|
||||
client, root = forced_files_client
|
||||
file_path = root / "out" / "hello.txt"
|
||||
|
||||
created = client.post(
|
||||
"/api/files/upload",
|
||||
json={
|
||||
"path": str(file_path),
|
||||
"data_url": "data:text/plain;base64,aGVsbG8=",
|
||||
},
|
||||
)
|
||||
assert created.status_code == 200
|
||||
assert created.json()["entry"]["path"] == str(file_path)
|
||||
assert created.json()["locked_root"] == str(root)
|
||||
assert created.json()["can_change_path"] is False
|
||||
assert file_path.read_text() == "hello"
|
||||
|
||||
listing = client.get("/api/files", params={"path": str(root / "out")})
|
||||
assert listing.status_code == 200
|
||||
assert listing.json()["path"] == str(root / "out")
|
||||
assert listing.json()["parent"] == str(root)
|
||||
assert listing.json()["entries"] == [
|
||||
{
|
||||
"name": "hello.txt",
|
||||
"path": str(file_path),
|
||||
"is_directory": False,
|
||||
"size": 5,
|
||||
"mtime": pytest.approx(file_path.stat().st_mtime),
|
||||
"mime_type": "text/plain",
|
||||
}
|
||||
]
|
||||
|
||||
read = client.get("/api/files/read", params={"path": str(file_path)})
|
||||
assert read.status_code == 200
|
||||
assert read.json()["data_url"] == "data:text/plain;base64,aGVsbG8="
|
||||
|
||||
deleted = client.request(
|
||||
"DELETE",
|
||||
"/api/files",
|
||||
json={"path": str(file_path)},
|
||||
)
|
||||
assert deleted.status_code == 200
|
||||
assert not file_path.exists()
|
||||
|
||||
|
||||
def test_directory_management_requires_recursive_delete_for_nonempty_dirs(forced_files_client):
|
||||
client, root = forced_files_client
|
||||
runs_path = root / "runs"
|
||||
checkpoints_path = runs_path / "checkpoints"
|
||||
|
||||
created = client.post("/api/files/mkdir", json={"path": str(checkpoints_path)})
|
||||
assert created.status_code == 200
|
||||
assert checkpoints_path.is_dir()
|
||||
|
||||
listing = client.get("/api/files", params={"path": str(runs_path)})
|
||||
assert listing.status_code == 200
|
||||
assert listing.json()["entries"][0]["path"] == str(checkpoints_path)
|
||||
assert listing.json()["entries"][0]["is_directory"] is True
|
||||
|
||||
non_recursive = client.request(
|
||||
"DELETE",
|
||||
"/api/files",
|
||||
json={"path": str(runs_path), "recursive": False},
|
||||
)
|
||||
assert non_recursive.status_code == 409
|
||||
|
||||
recursive = client.request(
|
||||
"DELETE",
|
||||
"/api/files",
|
||||
json={"path": str(runs_path), "recursive": True},
|
||||
)
|
||||
assert recursive.status_code == 200
|
||||
assert not runs_path.exists()
|
||||
|
||||
|
||||
def test_forced_root_paths_stay_under_root(forced_files_client, tmp_path):
|
||||
client, root = forced_files_client
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
(outside / "secret.txt").write_text("do not leak")
|
||||
|
||||
traversal = client.get("/api/files", params={"path": "../outside"})
|
||||
assert traversal.status_code == 400
|
||||
|
||||
outside_absolute = client.get("/api/files", params={"path": str(outside)})
|
||||
assert outside_absolute.status_code == 403
|
||||
|
||||
root_delete = client.request(
|
||||
"DELETE",
|
||||
"/api/files",
|
||||
json={"path": str(root), "recursive": True},
|
||||
)
|
||||
assert root_delete.status_code == 400
|
||||
|
||||
root.mkdir(exist_ok=True)
|
||||
link = root / "escape"
|
||||
try:
|
||||
link.symlink_to(outside, target_is_directory=True)
|
||||
except OSError:
|
||||
pytest.skip("filesystem does not allow directory symlinks")
|
||||
|
||||
escaped = client.get("/api/files", params={"path": str(link)})
|
||||
assert escaped.status_code == 403
|
||||
|
||||
|
||||
def test_local_mode_defaults_to_home_and_can_jump_to_absolute_path(local_files_client, tmp_path):
|
||||
client, home = local_files_client
|
||||
(home / "home.txt").write_text("home")
|
||||
|
||||
default_listing = client.get("/api/files")
|
||||
assert default_listing.status_code == 200
|
||||
assert default_listing.json()["path"] == str(home)
|
||||
assert default_listing.json()["locked_root"] is None
|
||||
assert default_listing.json()["can_change_path"] is True
|
||||
assert default_listing.json()["entries"][0]["path"] == str(home / "home.txt")
|
||||
|
||||
other = tmp_path / "other"
|
||||
other.mkdir()
|
||||
(other / "other.txt").write_text("other")
|
||||
|
||||
other_listing = client.get("/api/files", params={"path": str(other)})
|
||||
assert other_listing.status_code == 200
|
||||
assert other_listing.json()["path"] == str(other)
|
||||
assert other_listing.json()["parent"] == str(tmp_path)
|
||||
assert other_listing.json()["entries"][0]["path"] == str(other / "other.txt")
|
||||
|
||||
|
||||
def test_local_mode_upload_read_mkdir_delete_roundtrip(local_files_client):
|
||||
client, home = local_files_client
|
||||
folder = home / "workspace"
|
||||
file_path = folder / "note.txt"
|
||||
|
||||
created_folder = client.post("/api/files/mkdir", json={"path": str(folder)})
|
||||
assert created_folder.status_code == 200
|
||||
assert created_folder.json()["locked_root"] is None
|
||||
assert created_folder.json()["can_change_path"] is True
|
||||
assert folder.is_dir()
|
||||
|
||||
uploaded = client.post(
|
||||
"/api/files/upload",
|
||||
json={
|
||||
"path": str(file_path),
|
||||
"data_url": "data:text/plain;base64,bG9jYWw=",
|
||||
},
|
||||
)
|
||||
assert uploaded.status_code == 200
|
||||
assert file_path.read_text() == "local"
|
||||
|
||||
read = client.get("/api/files/read", params={"path": str(file_path)})
|
||||
assert read.status_code == 200
|
||||
assert read.json()["data_url"] == "data:text/plain;base64,bG9jYWw="
|
||||
|
||||
deleted = client.request(
|
||||
"DELETE",
|
||||
"/api/files",
|
||||
json={"path": str(folder), "recursive": True},
|
||||
)
|
||||
assert deleted.status_code == 200
|
||||
assert not folder.exists()
|
||||
|
||||
|
||||
def test_hosted_policy_locks_to_opt_data(monkeypatch):
|
||||
monkeypatch.delenv("HERMES_DASHBOARD_FILES_ROOT", raising=False)
|
||||
monkeypatch.setenv("HERMES_HOME", "/opt/data")
|
||||
client, prev_auth_required, prev_bound_host = _client_with_app_state()
|
||||
try:
|
||||
request = SimpleNamespace(
|
||||
app=web_server.app,
|
||||
client=SimpleNamespace(host="127.0.0.1"),
|
||||
url=SimpleNamespace(hostname="127.0.0.1"),
|
||||
)
|
||||
policy = web_server._managed_files_policy(request, create_root=False)
|
||||
finally:
|
||||
_restore_app_state(prev_auth_required, prev_bound_host)
|
||||
client.close()
|
||||
|
||||
assert str(policy.locked_root) == "/opt/data"
|
||||
assert policy.can_change_path is False
|
||||
@@ -1,188 +0,0 @@
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli import web_server
|
||||
|
||||
pytest.importorskip("starlette.testclient")
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
previous_auth_required = getattr(web_server.app.state, "auth_required", None)
|
||||
web_server.app.state.auth_required = False
|
||||
test_client = TestClient(web_server.app)
|
||||
test_client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
|
||||
try:
|
||||
yield test_client
|
||||
finally:
|
||||
if previous_auth_required is None:
|
||||
try:
|
||||
delattr(web_server.app.state, "auth_required")
|
||||
except AttributeError:
|
||||
pass
|
||||
else:
|
||||
web_server.app.state.auth_required = previous_auth_required
|
||||
|
||||
|
||||
def test_fs_list_sorts_and_hides_noise(client, tmp_path):
|
||||
root = tmp_path / "project"
|
||||
root.mkdir()
|
||||
(root / "b.txt").write_text("b")
|
||||
(root / "a_dir").mkdir()
|
||||
(root / "a.txt").write_text("a")
|
||||
(root / "node_modules").mkdir()
|
||||
(root / ".git").mkdir()
|
||||
|
||||
response = client.get("/api/fs/list", params={"path": str(root)})
|
||||
|
||||
assert response.status_code == 200
|
||||
entries = response.json()["entries"]
|
||||
assert [entry["name"] for entry in entries] == ["a_dir", "a.txt", "b.txt"]
|
||||
assert entries[0] == {"name": "a_dir", "path": str(root / "a_dir"), "isDirectory": True}
|
||||
assert all(entry["name"] not in {".git", "node_modules"} for entry in entries)
|
||||
|
||||
|
||||
def test_fs_list_accepts_relative_paths(client, tmp_path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
(tmp_path / "rel").mkdir()
|
||||
(tmp_path / "rel" / "file.txt").write_text("ok")
|
||||
|
||||
response = client.get("/api/fs/list", params={"path": "rel"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["entries"] == [
|
||||
{"name": "file.txt", "path": str(tmp_path / "rel" / "file.txt"), "isDirectory": False}
|
||||
]
|
||||
|
||||
|
||||
def test_fs_list_missing_path_returns_structured_error(client, tmp_path):
|
||||
response = client.get("/api/fs/list", params={"path": str(tmp_path / "missing")})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"entries": [], "error": "ENOENT"}
|
||||
|
||||
|
||||
def test_fs_read_text_matches_preview_shape_and_truncates(client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(web_server, "_FS_TEXT_SOURCE_MAX_BYTES", 32)
|
||||
monkeypatch.setattr(web_server, "_FS_TEXT_PREVIEW_MAX_BYTES", 5)
|
||||
target = tmp_path / "sample.py"
|
||||
target.write_text("print('hello')")
|
||||
|
||||
response = client.get("/api/fs/read-text", params={"path": str(target)})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"binary": False,
|
||||
"byteSize": 14,
|
||||
"language": "python",
|
||||
"mimeType": "text/x-python",
|
||||
"path": str(target),
|
||||
"text": "print",
|
||||
"truncated": True,
|
||||
}
|
||||
|
||||
|
||||
def test_fs_read_text_rejects_source_over_cap(client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(web_server, "_FS_TEXT_SOURCE_MAX_BYTES", 4)
|
||||
target = tmp_path / "large.txt"
|
||||
target.write_text("12345")
|
||||
|
||||
response = client.get("/api/fs/read-text", params={"path": str(target)})
|
||||
|
||||
assert response.status_code == 413
|
||||
|
||||
|
||||
def test_fs_read_text_flags_binary(client, tmp_path):
|
||||
target = tmp_path / "blob.bin"
|
||||
target.write_bytes(b"hello\x00world")
|
||||
|
||||
response = client.get("/api/fs/read-text", params={"path": str(target)})
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["binary"] is True
|
||||
assert body["text"].startswith("hello")
|
||||
|
||||
|
||||
def test_fs_read_data_url_returns_capped_data_url(client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(web_server, "_FS_DATA_URL_MAX_BYTES", 16)
|
||||
target = tmp_path / "image.png"
|
||||
target.write_bytes(b"pngbytes")
|
||||
|
||||
response = client.get("/api/fs/read-data-url", params={"path": str(target)})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"dataUrl": "data:image/png;base64," + base64.b64encode(b"pngbytes").decode("ascii")}
|
||||
|
||||
|
||||
def test_fs_read_data_url_rejects_over_cap(client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(web_server, "_FS_DATA_URL_MAX_BYTES", 3)
|
||||
target = tmp_path / "image.png"
|
||||
target.write_bytes(b"1234")
|
||||
|
||||
response = client.get("/api/fs/read-data-url", params={"path": str(target)})
|
||||
|
||||
assert response.status_code == 413
|
||||
|
||||
|
||||
def test_fs_git_root_for_nested_file(client, tmp_path):
|
||||
(tmp_path / ".git").mkdir()
|
||||
nested = tmp_path / "pkg" / "mod"
|
||||
nested.mkdir(parents=True)
|
||||
target = nested / "file.py"
|
||||
target.write_text("x")
|
||||
|
||||
response = client.get("/api/fs/git-root", params={"path": str(target)})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"root": str(tmp_path)}
|
||||
|
||||
|
||||
def test_fs_git_root_returns_null_outside_repo(client, tmp_path):
|
||||
response = client.get("/api/fs/git-root", params={"path": str(tmp_path)})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"root": None}
|
||||
|
||||
|
||||
def test_fs_default_cwd_prefers_existing_terminal_cwd(client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(web_server, "load_config", lambda: {"terminal": {"cwd": str(tmp_path)}})
|
||||
monkeypatch.setenv("TERMINAL_CWD", str(tmp_path / "env"))
|
||||
monkeypatch.setattr(web_server.Path, "cwd", lambda: tmp_path / "process")
|
||||
monkeypatch.setattr(web_server, "_fs_git_branch", lambda cwd: "main")
|
||||
|
||||
response = client.get("/api/fs/default-cwd")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"cwd": str(tmp_path), "branch": "main"}
|
||||
|
||||
|
||||
def test_fs_default_cwd_falls_back_when_terminal_cwd_is_invalid(client, tmp_path, monkeypatch):
|
||||
fallback = tmp_path / "backend"
|
||||
fallback.mkdir()
|
||||
monkeypatch.setattr(web_server, "load_config", lambda: {"terminal": {"cwd": "/client/missing"}})
|
||||
monkeypatch.setenv("TERMINAL_CWD", "/client/missing")
|
||||
monkeypatch.setattr(web_server.Path, "cwd", lambda: fallback)
|
||||
monkeypatch.setattr(web_server, "_fs_git_branch", lambda cwd: "")
|
||||
|
||||
response = client.get("/api/fs/default-cwd")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"cwd": str(fallback), "branch": ""}
|
||||
|
||||
|
||||
def test_fs_endpoints_require_auth(tmp_path):
|
||||
client = TestClient(web_server.app)
|
||||
target = tmp_path / "secret.txt"
|
||||
target.write_text("secret")
|
||||
|
||||
list_response = client.get("/api/fs/list", params={"path": str(tmp_path)})
|
||||
read_response = client.get("/api/fs/read-text", params={"path": str(target)})
|
||||
default_response = client.get("/api/fs/default-cwd")
|
||||
|
||||
assert list_response.status_code == 401
|
||||
assert read_response.status_code == 401
|
||||
assert default_response.status_code == 401
|
||||
@@ -1,395 +0,0 @@
|
||||
"""Regression tests for the machine-dashboard multi-profile unification.
|
||||
|
||||
The dashboard is ONE machine-level management surface: config, env, MCP,
|
||||
model, and chat-PTY endpoints accept an optional ``profile`` so the global
|
||||
profile switcher can target any profile's HERMES_HOME. These tests pin:
|
||||
reads/writes land in the REQUESTED profile, the dashboard's own profile
|
||||
stays untouched, and the chat PTY env is scoped via HERMES_HOME.
|
||||
"""
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_profiles(tmp_path, monkeypatch, _isolate_hermes_home):
|
||||
"""Isolated default home + one named profile, each with config + .env."""
|
||||
from hermes_constants import get_hermes_home
|
||||
from hermes_cli import profiles
|
||||
|
||||
default_home = get_hermes_home()
|
||||
profiles_root = default_home / "profiles"
|
||||
worker_home = profiles_root / "worker_beta"
|
||||
for home in (default_home, worker_home):
|
||||
home.mkdir(parents=True, exist_ok=True)
|
||||
(home / "config.yaml").write_text("{}\n", encoding="utf-8")
|
||||
(worker_home / ".env").write_text("", encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
|
||||
monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
|
||||
return {"default": default_home, "worker_beta": worker_home}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch, isolated_profiles):
|
||||
try:
|
||||
from starlette.testclient import TestClient
|
||||
except ImportError:
|
||||
pytest.skip("fastapi/starlette not installed")
|
||||
|
||||
import hermes_state
|
||||
from hermes_constants import get_hermes_home
|
||||
from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
|
||||
|
||||
monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db")
|
||||
c = TestClient(app)
|
||||
c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
|
||||
return c
|
||||
|
||||
|
||||
def _cfg(home):
|
||||
return yaml.safe_load((home / "config.yaml").read_text()) or {}
|
||||
|
||||
|
||||
class TestProfileScopedConfig:
|
||||
def test_config_put_lands_in_target_profile_only(self, client, isolated_profiles):
|
||||
resp = client.put(
|
||||
"/api/config",
|
||||
json={"config": {"timezone": "Mars/Olympus"}, "profile": "worker_beta"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert _cfg(isolated_profiles["worker_beta"]).get("timezone") == "Mars/Olympus"
|
||||
assert _cfg(isolated_profiles["default"]).get("timezone") != "Mars/Olympus"
|
||||
|
||||
def test_config_get_reads_target_profile(self, client, isolated_profiles):
|
||||
(isolated_profiles["worker_beta"] / "config.yaml").write_text(
|
||||
"timezone: Venus/Cloud\n", encoding="utf-8"
|
||||
)
|
||||
resp = client.get("/api/config", params={"profile": "worker_beta"})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json().get("timezone") == "Venus/Cloud"
|
||||
# Unscoped read sees the dashboard's own config.
|
||||
resp = client.get("/api/config")
|
||||
assert resp.json().get("timezone") != "Venus/Cloud"
|
||||
|
||||
def test_config_query_param_equivalent_to_body(self, client, isolated_profiles):
|
||||
"""The SPA's fetchJSON injects ?profile= — must scope like body.profile."""
|
||||
resp = client.put(
|
||||
"/api/config?profile=worker_beta",
|
||||
json={"config": {"timezone": "Pluto/Far"}},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert _cfg(isolated_profiles["worker_beta"]).get("timezone") == "Pluto/Far"
|
||||
assert _cfg(isolated_profiles["default"]).get("timezone") != "Pluto/Far"
|
||||
|
||||
def test_config_raw_round_trip_scoped(self, client, isolated_profiles):
|
||||
resp = client.put(
|
||||
"/api/config/raw",
|
||||
json={"yaml_text": "timezone: Io/Volcano\n", "profile": "worker_beta"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
resp = client.get("/api/config/raw", params={"profile": "worker_beta"})
|
||||
assert "Io/Volcano" in resp.json()["yaml"]
|
||||
resp = client.get("/api/config/raw")
|
||||
assert "Io/Volcano" not in resp.json()["yaml"]
|
||||
|
||||
def test_config_raw_path_reflects_requested_profile(self, client, isolated_profiles):
|
||||
"""The Config page header shows /api/config/raw's ``path`` — it must
|
||||
point at the SWITCHED profile's config.yaml, not the dashboard's own
|
||||
(the stale-path bug reported after the profile unification launch)."""
|
||||
resp = client.get("/api/config/raw", params={"profile": "worker_beta"})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["path"] == str(isolated_profiles["worker_beta"] / "config.yaml")
|
||||
resp = client.get("/api/config/raw")
|
||||
assert resp.json()["path"] == str(isolated_profiles["default"] / "config.yaml")
|
||||
|
||||
def test_unknown_profile_404(self, client, isolated_profiles):
|
||||
resp = client.get("/api/config", params={"profile": "ghost"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestProfileScopedEnv:
|
||||
def test_env_set_lands_in_target_profile_only(self, client, isolated_profiles):
|
||||
resp = client.put(
|
||||
"/api/env",
|
||||
json={"key": "FAL_KEY", "value": "test-fal-123", "profile": "worker_beta"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
worker_env = (isolated_profiles["worker_beta"] / ".env").read_text()
|
||||
assert "test-fal-123" in worker_env
|
||||
default_env_path = isolated_profiles["default"] / ".env"
|
||||
if default_env_path.exists():
|
||||
assert "test-fal-123" not in default_env_path.read_text()
|
||||
|
||||
def test_env_list_reads_target_profile(self, client, isolated_profiles):
|
||||
(isolated_profiles["worker_beta"] / ".env").write_text(
|
||||
"FAL_KEY=worker-only-value\n", encoding="utf-8"
|
||||
)
|
||||
resp = client.get("/api/env", params={"profile": "worker_beta"})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["FAL_KEY"]["is_set"] is True
|
||||
resp = client.get("/api/env")
|
||||
assert resp.json()["FAL_KEY"]["is_set"] is False
|
||||
|
||||
def test_env_delete_scoped(self, client, isolated_profiles):
|
||||
(isolated_profiles["worker_beta"] / ".env").write_text(
|
||||
"FAL_KEY=doomed\n", encoding="utf-8"
|
||||
)
|
||||
resp = client.request(
|
||||
"DELETE",
|
||||
"/api/env",
|
||||
json={"key": "FAL_KEY", "profile": "worker_beta"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert "doomed" not in (isolated_profiles["worker_beta"] / ".env").read_text()
|
||||
|
||||
|
||||
class TestProfileScopedMcp:
|
||||
def test_mcp_add_and_list_scoped(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/mcp/servers",
|
||||
json={"name": "scoped-srv", "url": "http://localhost:1234/sse",
|
||||
"profile": "worker_beta"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
worker_cfg = _cfg(isolated_profiles["worker_beta"])
|
||||
assert "scoped-srv" in worker_cfg.get("mcp_servers", {})
|
||||
assert "scoped-srv" not in _cfg(isolated_profiles["default"]).get("mcp_servers", {})
|
||||
|
||||
listing = client.get("/api/mcp/servers", params={"profile": "worker_beta"}).json()
|
||||
assert any(s["name"] == "scoped-srv" for s in listing["servers"])
|
||||
listing = client.get("/api/mcp/servers").json()
|
||||
assert not any(s["name"] == "scoped-srv" for s in listing["servers"])
|
||||
|
||||
def test_mcp_enabled_toggle_scoped(self, client, isolated_profiles):
|
||||
(isolated_profiles["worker_beta"] / "config.yaml").write_text(
|
||||
"mcp_servers:\n srv1:\n url: http://x/sse\n", encoding="utf-8"
|
||||
)
|
||||
resp = client.put(
|
||||
"/api/mcp/servers/srv1/enabled",
|
||||
json={"enabled": False, "profile": "worker_beta"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
worker_cfg = _cfg(isolated_profiles["worker_beta"])
|
||||
assert worker_cfg["mcp_servers"]["srv1"]["enabled"] is False
|
||||
|
||||
def test_mcp_probe_runs_inside_profile_scope(
|
||||
self, client, isolated_profiles, monkeypatch
|
||||
):
|
||||
"""The test-server probe must execute with the selected profile's
|
||||
scope active so env-placeholder expansion reads the profile's .env,
|
||||
matching the config the server was saved into."""
|
||||
import hermes_cli.mcp_config as mcp_config
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
(isolated_profiles["worker_beta"] / "config.yaml").write_text(
|
||||
"mcp_servers:\n probe-srv:\n url: http://x/sse\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
seen = {}
|
||||
|
||||
def fake_probe(name, config, connect_timeout=30):
|
||||
seen["home"] = str(get_hermes_home())
|
||||
return [("tool-a", "desc")]
|
||||
|
||||
monkeypatch.setattr(mcp_config, "_probe_single_server", fake_probe)
|
||||
resp = client.post(
|
||||
"/api/mcp/servers/probe-srv/test", params={"profile": "worker_beta"}
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["ok"] is True
|
||||
assert seen["home"] == str(isolated_profiles["worker_beta"])
|
||||
|
||||
def test_mcp_remove_scoped(self, client, isolated_profiles):
|
||||
(isolated_profiles["worker_beta"] / "config.yaml").write_text(
|
||||
"mcp_servers:\n srv2:\n url: http://x/sse\n", encoding="utf-8"
|
||||
)
|
||||
# Removing from the DASHBOARD's profile must 404 (srv2 lives in worker).
|
||||
resp = client.delete("/api/mcp/servers/srv2")
|
||||
assert resp.status_code == 404
|
||||
resp = client.delete("/api/mcp/servers/srv2", params={"profile": "worker_beta"})
|
||||
assert resp.status_code == 200
|
||||
assert "srv2" not in _cfg(isolated_profiles["worker_beta"]).get("mcp_servers", {})
|
||||
|
||||
|
||||
class TestProfileScopedModel:
|
||||
def test_model_set_main_scoped(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/model/set",
|
||||
json={
|
||||
"scope": "main",
|
||||
"provider": "openrouter",
|
||||
"model": "test/model-1",
|
||||
"confirm_expensive_model": True,
|
||||
"profile": "worker_beta",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
worker_cfg = _cfg(isolated_profiles["worker_beta"])
|
||||
model_cfg = worker_cfg.get("model", {})
|
||||
assert isinstance(model_cfg, dict)
|
||||
assert model_cfg.get("provider") == "openrouter"
|
||||
default_model = _cfg(isolated_profiles["default"]).get("model", {})
|
||||
if isinstance(default_model, dict):
|
||||
assert default_model.get("default") != "test/model-1"
|
||||
|
||||
def test_auxiliary_read_scoped_matches_write_target(
|
||||
self, client, isolated_profiles
|
||||
):
|
||||
"""Reads and writes must scope symmetrically: an aux pin written to
|
||||
the worker profile must show up ONLY in the worker-scoped read.
|
||||
(Regression: /api/model/auxiliary used to read unscoped while
|
||||
/api/model/set wrote scoped — the Models page displayed the
|
||||
dashboard profile's pins while editing the selected profile's.)"""
|
||||
(isolated_profiles["worker_beta"] / "config.yaml").write_text(
|
||||
"auxiliary:\n vision:\n provider: openrouter\n"
|
||||
" model: worker/vision-pin\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
resp = client.get("/api/model/auxiliary", params={"profile": "worker_beta"})
|
||||
assert resp.status_code == 200
|
||||
vision = next(t for t in resp.json()["tasks"] if t["task"] == "vision")
|
||||
assert vision["model"] == "worker/vision-pin"
|
||||
|
||||
# Unscoped read = the dashboard's own profile, which has no pin.
|
||||
resp = client.get("/api/model/auxiliary")
|
||||
assert resp.status_code == 200
|
||||
vision = next(t for t in resp.json()["tasks"] if t["task"] == "vision")
|
||||
assert vision["model"] != "worker/vision-pin"
|
||||
|
||||
def test_auxiliary_unknown_profile_404(self, client, isolated_profiles):
|
||||
resp = client.get("/api/model/auxiliary", params={"profile": "ghost"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_model_options_scoped_to_profile(self, client, isolated_profiles):
|
||||
"""The Models picker must read the SAME profile model/set writes —
|
||||
current model/provider in the payload come from the scoped config."""
|
||||
(isolated_profiles["worker_beta"] / "config.yaml").write_text(
|
||||
"model:\n provider: openrouter\n default: worker/current-pin\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
resp = client.get("/api/model/options", params={"profile": "worker_beta"})
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
# The payload carries the current selection somewhere stable; assert
|
||||
# the worker pin appears in the scoped response and not the unscoped.
|
||||
assert "worker/current-pin" in resp.text
|
||||
resp = client.get("/api/model/options")
|
||||
assert resp.status_code == 200
|
||||
assert "worker/current-pin" not in resp.text
|
||||
assert isinstance(body, dict)
|
||||
|
||||
def test_model_options_unknown_profile_404(self, client, isolated_profiles):
|
||||
resp = client.get("/api/model/options", params={"profile": "ghost"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_model_info_unknown_profile_404(self, client, isolated_profiles):
|
||||
"""Regression: the broad except used to convert the 404 into a 200
|
||||
with empty model info ("no model set" — silently wrong)."""
|
||||
resp = client.get("/api/model/info", params={"profile": "ghost"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_mcp_catalog_unknown_profile_404(self, client, isolated_profiles):
|
||||
resp = client.get("/api/mcp/catalog", params={"profile": "ghost"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestProfileScopedPostSetup:
|
||||
def test_post_setup_spawns_with_profile_flag(
|
||||
self, client, isolated_profiles, monkeypatch
|
||||
):
|
||||
"""Post-setup runs in a -p scoped subprocess so hooks that read
|
||||
config / write per-profile state see the same HERMES_HOME the rest
|
||||
of the drawer's writes targeted."""
|
||||
import hermes_cli.web_server as web_server
|
||||
|
||||
calls = []
|
||||
|
||||
class _FakeProc:
|
||||
pid = 777
|
||||
|
||||
monkeypatch.setattr(
|
||||
web_server,
|
||||
"_spawn_hermes_action",
|
||||
lambda subcommand, name: calls.append(list(subcommand)) or _FakeProc(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config.valid_post_setup_keys",
|
||||
lambda: {"agent_browser"},
|
||||
)
|
||||
resp = client.post(
|
||||
"/api/tools/toolsets/browser/post-setup",
|
||||
json={"key": "agent_browser", "profile": "worker_beta"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert calls == [
|
||||
["-p", "worker_beta", "tools", "post-setup", "agent_browser"]
|
||||
]
|
||||
|
||||
def test_post_setup_without_profile_keeps_legacy_argv(
|
||||
self, client, isolated_profiles, monkeypatch
|
||||
):
|
||||
import hermes_cli.web_server as web_server
|
||||
|
||||
calls = []
|
||||
|
||||
class _FakeProc:
|
||||
pid = 777
|
||||
|
||||
monkeypatch.setattr(
|
||||
web_server,
|
||||
"_spawn_hermes_action",
|
||||
lambda subcommand, name: calls.append(list(subcommand)) or _FakeProc(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.tools_config.valid_post_setup_keys",
|
||||
lambda: {"agent_browser"},
|
||||
)
|
||||
resp = client.post(
|
||||
"/api/tools/toolsets/browser/post-setup",
|
||||
json={"key": "agent_browser"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert calls == [["tools", "post-setup", "agent_browser"]]
|
||||
|
||||
|
||||
class TestProfileScopedChatPty:
|
||||
def test_chat_argv_scopes_hermes_home(self, isolated_profiles, monkeypatch):
|
||||
import hermes_cli.web_server as web_server
|
||||
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.main._make_tui_argv",
|
||||
lambda root, tui_dev=False: (["cat"], None),
|
||||
raising=False,
|
||||
)
|
||||
argv, cwd, env = web_server._resolve_chat_argv(profile="worker_beta")
|
||||
assert env is not None
|
||||
assert env["HERMES_HOME"] == str(isolated_profiles["worker_beta"])
|
||||
# Scoped chat must NOT attach to the dashboard's in-memory gateway.
|
||||
assert "HERMES_TUI_GATEWAY_URL" not in env
|
||||
|
||||
def test_chat_argv_unscoped_keeps_legacy_env(self, isolated_profiles, monkeypatch):
|
||||
import hermes_cli.web_server as web_server
|
||||
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.main._make_tui_argv",
|
||||
lambda root, tui_dev=False: (["cat"], None),
|
||||
raising=False,
|
||||
)
|
||||
argv, cwd, env = web_server._resolve_chat_argv()
|
||||
assert env is not None
|
||||
assert env.get("HERMES_HOME") != str(isolated_profiles["worker_beta"])
|
||||
|
||||
def test_chat_argv_unknown_profile_raises(self, isolated_profiles, monkeypatch):
|
||||
import hermes_cli.web_server as web_server
|
||||
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.main._make_tui_argv",
|
||||
lambda root, tui_dev=False: (["cat"], None),
|
||||
raising=False,
|
||||
)
|
||||
# Reuse the HTTPException class web_server itself raises — avoids a
|
||||
# direct fastapi import (unresolvable in the ty lint environment).
|
||||
with pytest.raises(web_server.HTTPException) as exc:
|
||||
web_server._resolve_chat_argv(profile="ghost")
|
||||
assert exc.value.status_code == 404
|
||||
@@ -1,83 +0,0 @@
|
||||
"""Test the platform-branched PTY bridge import in hermes_cli.web_server.
|
||||
|
||||
The /api/pty WebSocket handler in web_server.py picks its bridge at import
|
||||
time via ``sys.platform.startswith("win")`` — Windows gets the ConPTY
|
||||
backend, POSIX gets the fcntl/termios one. Both branches must:
|
||||
|
||||
1. Expose ``PtyBridge`` as the bridge class (or None) and
|
||||
``PtyUnavailableError`` as an exception class.
|
||||
2. Set ``_PTY_BRIDGE_AVAILABLE`` correctly.
|
||||
3. Never raise at import time when the platform-native dependency is
|
||||
missing — the dashboard's non-chat tabs must keep loading.
|
||||
|
||||
This test asserts the live state on whichever platform CI runs on, plus a
|
||||
source-text check confirming the branch shape is preserved so a future
|
||||
refactor can't accidentally collapse it back to a POSIX-only import.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli import web_server
|
||||
|
||||
|
||||
def test_web_server_exposes_pty_bridge_symbols():
|
||||
"""The two symbols /api/pty consumes must always exist."""
|
||||
assert hasattr(web_server, "PtyBridge")
|
||||
assert hasattr(web_server, "PtyUnavailableError")
|
||||
assert hasattr(web_server, "_PTY_BRIDGE_AVAILABLE")
|
||||
# PtyUnavailableError is always an exception class — either the real
|
||||
# one from the platform bridge, or the local fallback class.
|
||||
assert isinstance(web_server.PtyUnavailableError, type)
|
||||
assert issubclass(web_server.PtyUnavailableError, BaseException)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not sys.platform.startswith("win"), reason="Windows-only")
|
||||
def test_web_server_uses_win_pty_bridge_on_windows():
|
||||
"""On native Windows, web_server.PtyBridge must be the ConPTY backend."""
|
||||
from hermes_cli.win_pty_bridge import WinPtyBridge
|
||||
|
||||
assert web_server.PtyBridge is WinPtyBridge
|
||||
assert web_server._PTY_BRIDGE_AVAILABLE is True
|
||||
# And the error class must be the one from the same module so isinstance
|
||||
# checks in /api/pty's spawn fallback path actually work.
|
||||
from hermes_cli.win_pty_bridge import PtyUnavailableError as WinErr
|
||||
|
||||
assert web_server.PtyUnavailableError is WinErr
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform.startswith("win"), reason="POSIX-only")
|
||||
def test_web_server_uses_posix_pty_bridge_on_posix():
|
||||
"""On POSIX, the bridge must be the fcntl/termios PtyBridge."""
|
||||
from hermes_cli.pty_bridge import PtyBridge as PosixBridge
|
||||
from hermes_cli.pty_bridge import PtyUnavailableError as PosixErr
|
||||
|
||||
assert web_server.PtyBridge is PosixBridge
|
||||
assert web_server._PTY_BRIDGE_AVAILABLE is True
|
||||
assert web_server.PtyUnavailableError is PosixErr
|
||||
|
||||
|
||||
def test_pty_bridge_import_block_is_platform_branched():
|
||||
"""Source-level guard: a future refactor must not collapse the branch
|
||||
back to a single POSIX import. Reads web_server.py directly so this
|
||||
fails the same way on every OS — the runtime symbol checks above can
|
||||
pass even when the branch shape is wrong on the current platform."""
|
||||
src = pytest.importorskip("inspect").getsource(web_server)
|
||||
# The shape we expect (from PR #39913):
|
||||
#
|
||||
# if sys.platform.startswith("win"):
|
||||
# try:
|
||||
# from hermes_cli.win_pty_bridge import WinPtyBridge as PtyBridge, ...
|
||||
# except ImportError:
|
||||
# PtyBridge = None
|
||||
# ...
|
||||
# else:
|
||||
# try:
|
||||
# from hermes_cli.pty_bridge import PtyBridge, PtyUnavailableError
|
||||
# ...
|
||||
assert 'sys.platform.startswith("win")' in src or "sys.platform.startswith('win')" in src
|
||||
assert "from hermes_cli.win_pty_bridge import" in src
|
||||
assert "from hermes_cli.pty_bridge import" in src
|
||||
@@ -1,259 +0,0 @@
|
||||
"""Tests for the dashboard skill editor endpoints and cron skill attachment.
|
||||
|
||||
The Skills page can now create/edit custom skills (SKILL.md) and the Cron
|
||||
page can attach skills to jobs — closing the "SSH + nano is the only way"
|
||||
gap for headless/VPS users. These tests pin:
|
||||
|
||||
- GET /api/skills/content returns raw SKILL.md (and profile-scopes).
|
||||
- POST /api/skills creates a skill through the same validated write path
|
||||
as the agent's ``skill_manage`` tool (frontmatter validation enforced).
|
||||
- PUT /api/skills/content rewrites an existing SKILL.md (404 on unknown).
|
||||
- POST /api/cron/jobs accepts ``skills`` and persists it on the job;
|
||||
PUT /api/cron/jobs/{id} can update the list.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
|
||||
SKILL_MD = """---
|
||||
name: {name}
|
||||
description: a test skill
|
||||
---
|
||||
|
||||
# {name}
|
||||
|
||||
Do the thing.
|
||||
"""
|
||||
|
||||
|
||||
def _write_skill(skills_dir, name):
|
||||
d = skills_dir / name
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "SKILL.md").write_text(SKILL_MD.format(name=name), encoding="utf-8")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_profiles(tmp_path, monkeypatch, _isolate_hermes_home):
|
||||
"""Isolated default home + one named profile, each with its own skills."""
|
||||
from hermes_constants import get_hermes_home
|
||||
from hermes_cli import profiles
|
||||
|
||||
default_home = get_hermes_home()
|
||||
profiles_root = default_home / "profiles"
|
||||
worker_home = profiles_root / "worker_alpha"
|
||||
for home in (default_home, worker_home):
|
||||
(home / "skills").mkdir(parents=True, exist_ok=True)
|
||||
(home / "config.yaml").write_text("{}\n", encoding="utf-8")
|
||||
|
||||
_write_skill(default_home / "skills", "dashboard-skill")
|
||||
_write_skill(worker_home / "skills", "worker-skill")
|
||||
|
||||
monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
|
||||
monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
|
||||
return {"default": default_home, "worker_alpha": worker_home}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch, isolated_profiles):
|
||||
try:
|
||||
from starlette.testclient import TestClient
|
||||
except ImportError:
|
||||
pytest.skip("fastapi/starlette not installed")
|
||||
|
||||
import hermes_state
|
||||
from hermes_constants import get_hermes_home
|
||||
from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
|
||||
|
||||
monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db")
|
||||
c = TestClient(app)
|
||||
c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
|
||||
return c
|
||||
|
||||
|
||||
class TestSkillContent:
|
||||
def test_get_content_returns_raw_skill_md(self, client, isolated_profiles):
|
||||
resp = client.get("/api/skills/content", params={"name": "dashboard-skill"})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["name"] == "dashboard-skill"
|
||||
assert data["content"].startswith("---")
|
||||
assert "Do the thing." in data["content"]
|
||||
|
||||
def test_get_content_scopes_to_profile(self, client, isolated_profiles):
|
||||
resp = client.get(
|
||||
"/api/skills/content",
|
||||
params={"name": "worker-skill", "profile": "worker_alpha"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
# ...and the worker skill is invisible without the profile param.
|
||||
resp = client.get("/api/skills/content", params={"name": "worker-skill"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_get_content_unknown_skill_404(self, client, isolated_profiles):
|
||||
resp = client.get("/api/skills/content", params={"name": "nope"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestSkillCreate:
|
||||
def test_create_writes_skill_md(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/skills",
|
||||
json={"name": "my-new-skill", "content": SKILL_MD.format(name="my-new-skill")},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["success"] is True
|
||||
skill_md = isolated_profiles["default"] / "skills" / "my-new-skill" / "SKILL.md"
|
||||
assert skill_md.exists()
|
||||
assert "Do the thing." in skill_md.read_text(encoding="utf-8")
|
||||
|
||||
def test_create_with_category(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/skills",
|
||||
json={
|
||||
"name": "cat-skill",
|
||||
"category": "devops",
|
||||
"content": SKILL_MD.format(name="cat-skill"),
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert (
|
||||
isolated_profiles["default"] / "skills" / "devops" / "cat-skill" / "SKILL.md"
|
||||
).exists()
|
||||
|
||||
def test_create_scopes_to_profile(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/skills",
|
||||
json={
|
||||
"name": "worker-new",
|
||||
"content": SKILL_MD.format(name="worker-new"),
|
||||
"profile": "worker_alpha",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert (
|
||||
isolated_profiles["worker_alpha"] / "skills" / "worker-new" / "SKILL.md"
|
||||
).exists()
|
||||
# Dashboard's own skills dir stays clean.
|
||||
assert not (
|
||||
isolated_profiles["default"] / "skills" / "worker-new"
|
||||
).exists()
|
||||
|
||||
def test_create_rejects_missing_frontmatter(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/skills",
|
||||
json={"name": "bad-skill", "content": "no frontmatter here"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert "frontmatter" in resp.json()["detail"].lower()
|
||||
assert not (isolated_profiles["default"] / "skills" / "bad-skill").exists()
|
||||
|
||||
def test_create_rejects_duplicate_name(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/skills",
|
||||
json={
|
||||
"name": "dashboard-skill",
|
||||
"content": SKILL_MD.format(name="dashboard-skill"),
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert "already exists" in resp.json()["detail"]
|
||||
|
||||
def test_create_rejects_invalid_name(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/skills",
|
||||
json={"name": "../escape", "content": SKILL_MD.format(name="x")},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
class TestSkillUpdate:
|
||||
def test_update_rewrites_skill_md(self, client, isolated_profiles):
|
||||
new_content = SKILL_MD.format(name="dashboard-skill").replace(
|
||||
"Do the thing.", "Do the NEW thing."
|
||||
)
|
||||
resp = client.put(
|
||||
"/api/skills/content",
|
||||
json={"name": "dashboard-skill", "content": new_content},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
skill_md = (
|
||||
isolated_profiles["default"] / "skills" / "dashboard-skill" / "SKILL.md"
|
||||
)
|
||||
assert "Do the NEW thing." in skill_md.read_text(encoding="utf-8")
|
||||
|
||||
def test_update_unknown_skill_404(self, client, isolated_profiles):
|
||||
resp = client.put(
|
||||
"/api/skills/content",
|
||||
json={"name": "nope", "content": SKILL_MD.format(name="nope")},
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_update_invalid_frontmatter_400(self, client, isolated_profiles):
|
||||
resp = client.put(
|
||||
"/api/skills/content",
|
||||
json={"name": "dashboard-skill", "content": "broken"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
class TestEditorEndpointsAuth:
|
||||
@pytest.mark.parametrize(
|
||||
"method,path,kwargs",
|
||||
[
|
||||
("get", "/api/skills/content?name=dashboard-skill", {}),
|
||||
("post", "/api/skills", {"json": {"name": "x", "content": "y"}}),
|
||||
("put", "/api/skills/content", {"json": {"name": "x", "content": "y"}}),
|
||||
],
|
||||
)
|
||||
def test_endpoints_401_without_token(
|
||||
self, client, isolated_profiles, method, path, kwargs
|
||||
):
|
||||
from hermes_cli.web_server import _SESSION_HEADER_NAME
|
||||
|
||||
client.headers.pop(_SESSION_HEADER_NAME, None)
|
||||
resp = getattr(client, method)(path, **kwargs)
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
class TestCronJobSkills:
|
||||
def test_create_job_with_skills(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/cron/jobs",
|
||||
json={
|
||||
"prompt": "do work",
|
||||
"schedule": "every 1h",
|
||||
"name": "skilled-job",
|
||||
"skills": ["dashboard-skill"],
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
job = resp.json()
|
||||
assert job["skills"] == ["dashboard-skill"]
|
||||
|
||||
# Round-trip: the list endpoint carries the skills field too.
|
||||
listed = client.get("/api/cron/jobs", params={"profile": "default"}).json()
|
||||
match = [j for j in listed if j["id"] == job["id"]]
|
||||
assert match and match[0]["skills"] == ["dashboard-skill"]
|
||||
|
||||
def test_update_job_skills(self, client, isolated_profiles):
|
||||
job = client.post(
|
||||
"/api/cron/jobs",
|
||||
json={"prompt": "do work", "schedule": "every 1h"},
|
||||
).json()
|
||||
assert job.get("skills") in (None, [])
|
||||
|
||||
resp = client.put(
|
||||
f"/api/cron/jobs/{job['id']}",
|
||||
json={"updates": {"skills": ["dashboard-skill", "worker-skill"]}},
|
||||
params={"profile": "default"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["skills"] == ["dashboard-skill", "worker-skill"]
|
||||
|
||||
# Clearing works too.
|
||||
resp = client.put(
|
||||
f"/api/cron/jobs/{job['id']}",
|
||||
json={"updates": {"skills": []}},
|
||||
params={"profile": "default"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["skills"] == []
|
||||
@@ -1,210 +0,0 @@
|
||||
"""Regression tests for dashboard profile-scoped skills/toolsets management.
|
||||
|
||||
"Set as active" on the Profiles page only flips the sticky ``active_profile``
|
||||
file (future CLI/gateway runs) — it never retargets the running dashboard
|
||||
process. Before the ``profile`` parameter existed, toggling a skill after
|
||||
"activating" a profile silently wrote into the dashboard's own config.
|
||||
These tests pin the new behavior: reads and writes land in the REQUESTED
|
||||
profile's HERMES_HOME, and the dashboard's own profile stays untouched.
|
||||
"""
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
|
||||
def _write_skill(skills_dir, name, description="test skill"):
|
||||
d = skills_dir / name
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "SKILL.md").write_text(
|
||||
f"---\nname: {name}\ndescription: {description}\n---\n\n# {name}\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_profiles(tmp_path, monkeypatch, _isolate_hermes_home):
|
||||
"""Isolated default home + one named profile, each with its own skills."""
|
||||
from hermes_constants import get_hermes_home
|
||||
from hermes_cli import profiles
|
||||
|
||||
default_home = get_hermes_home()
|
||||
profiles_root = default_home / "profiles"
|
||||
worker_home = profiles_root / "worker_alpha"
|
||||
for home in (default_home, worker_home):
|
||||
(home / "skills").mkdir(parents=True, exist_ok=True)
|
||||
(home / "config.yaml").write_text("{}\n", encoding="utf-8")
|
||||
|
||||
_write_skill(default_home / "skills", "dashboard-skill")
|
||||
_write_skill(worker_home / "skills", "worker-skill")
|
||||
|
||||
monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
|
||||
monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
|
||||
return {"default": default_home, "worker_alpha": worker_home}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch, isolated_profiles):
|
||||
try:
|
||||
from starlette.testclient import TestClient
|
||||
except ImportError:
|
||||
pytest.skip("fastapi/starlette not installed")
|
||||
|
||||
import hermes_state
|
||||
from hermes_constants import get_hermes_home
|
||||
from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
|
||||
|
||||
monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db")
|
||||
c = TestClient(app)
|
||||
c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
|
||||
return c
|
||||
|
||||
|
||||
def _load_cfg(home):
|
||||
return yaml.safe_load((home / "config.yaml").read_text()) or {}
|
||||
|
||||
|
||||
class TestProfileScopedSkills:
|
||||
def test_skills_list_scopes_to_requested_profile(self, client, isolated_profiles):
|
||||
resp = client.get("/api/skills", params={"profile": "worker_alpha"})
|
||||
assert resp.status_code == 200
|
||||
names = {s["name"] for s in resp.json()}
|
||||
assert "worker-skill" in names
|
||||
assert "dashboard-skill" not in names
|
||||
|
||||
def test_skills_list_without_profile_uses_dashboard_home(
|
||||
self, client, isolated_profiles
|
||||
):
|
||||
resp = client.get("/api/skills")
|
||||
assert resp.status_code == 200
|
||||
names = {s["name"] for s in resp.json()}
|
||||
assert "dashboard-skill" in names
|
||||
assert "worker-skill" not in names
|
||||
|
||||
def test_toggle_writes_into_target_profile_only(self, client, isolated_profiles):
|
||||
resp = client.put(
|
||||
"/api/skills/toggle",
|
||||
json={"name": "worker-skill", "enabled": False, "profile": "worker_alpha"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == {"ok": True, "name": "worker-skill", "enabled": False}
|
||||
|
||||
worker_cfg = _load_cfg(isolated_profiles["worker_alpha"])
|
||||
assert "worker-skill" in worker_cfg.get("skills", {}).get("disabled", [])
|
||||
# The dashboard's own config must stay untouched — this was the bug.
|
||||
default_cfg = _load_cfg(isolated_profiles["default"])
|
||||
assert "worker-skill" not in default_cfg.get("skills", {}).get("disabled", [])
|
||||
|
||||
def test_toggle_reenable_round_trip(self, client, isolated_profiles):
|
||||
for enabled in (False, True):
|
||||
client.put(
|
||||
"/api/skills/toggle",
|
||||
json={
|
||||
"name": "worker-skill",
|
||||
"enabled": enabled,
|
||||
"profile": "worker_alpha",
|
||||
},
|
||||
)
|
||||
worker_cfg = _load_cfg(isolated_profiles["worker_alpha"])
|
||||
assert "worker-skill" not in worker_cfg.get("skills", {}).get("disabled", [])
|
||||
|
||||
def test_unknown_profile_returns_404(self, client, isolated_profiles):
|
||||
resp = client.get("/api/skills", params={"profile": "no_such_profile"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_invalid_profile_name_returns_400(self, client, isolated_profiles):
|
||||
resp = client.get("/api/skills", params={"profile": "Bad Name!"})
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_scope_restores_module_globals(self, client, isolated_profiles):
|
||||
"""The SKILLS_DIR swap is per-request; the module global must be
|
||||
restored even after a scoped call (cron-style locked swap)."""
|
||||
import tools.skills_tool as skills_tool
|
||||
|
||||
before = skills_tool.SKILLS_DIR
|
||||
client.get("/api/skills", params={"profile": "worker_alpha"})
|
||||
assert skills_tool.SKILLS_DIR == before
|
||||
|
||||
|
||||
class TestProfileScopedToolsets:
|
||||
def test_toolset_toggle_scopes_to_profile(self, client, isolated_profiles):
|
||||
resp = client.put(
|
||||
"/api/tools/toolsets/x_search",
|
||||
json={"enabled": True, "profile": "worker_alpha"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
worker_cfg = _load_cfg(isolated_profiles["worker_alpha"])
|
||||
assert "x_search" in worker_cfg.get("platform_toolsets", {}).get("cli", [])
|
||||
default_cfg = _load_cfg(isolated_profiles["default"])
|
||||
assert "x_search" not in default_cfg.get("platform_toolsets", {}).get("cli", [])
|
||||
|
||||
listing = client.get(
|
||||
"/api/tools/toolsets", params={"profile": "worker_alpha"}
|
||||
).json()
|
||||
assert {t["name"]: t for t in listing}["x_search"]["enabled"] is True
|
||||
# Unscoped listing reflects the dashboard's own (untouched) config.
|
||||
listing = client.get("/api/tools/toolsets").json()
|
||||
assert {t["name"]: t for t in listing}["x_search"]["enabled"] is False
|
||||
|
||||
def test_toolset_toggle_unknown_profile_404(self, client, isolated_profiles):
|
||||
resp = client.put(
|
||||
"/api/tools/toolsets/x_search",
|
||||
json={"enabled": True, "profile": "ghost"},
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestProfileScopedHubActions:
|
||||
def test_hub_install_spawns_with_profile_flag(
|
||||
self, client, isolated_profiles, monkeypatch
|
||||
):
|
||||
"""Hub installs must go through a fresh ``hermes -p <profile>``
|
||||
subprocess — the in-process scope can't reach skills_hub's
|
||||
import-time SKILLS_DIR binding."""
|
||||
import hermes_cli.web_server as web_server
|
||||
|
||||
calls = []
|
||||
|
||||
class _FakeProc:
|
||||
pid = 4242
|
||||
|
||||
def _fake_spawn(subcommand, name):
|
||||
calls.append((list(subcommand), name))
|
||||
return _FakeProc()
|
||||
|
||||
monkeypatch.setattr(web_server, "_spawn_hermes_action", _fake_spawn)
|
||||
resp = client.post(
|
||||
"/api/skills/hub/install",
|
||||
json={"identifier": "official/demo", "profile": "worker_alpha"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert calls == [
|
||||
(["-p", "worker_alpha", "skills", "install", "official/demo"], "skills-install")
|
||||
]
|
||||
|
||||
def test_hub_install_without_profile_keeps_legacy_argv(
|
||||
self, client, isolated_profiles, monkeypatch
|
||||
):
|
||||
import hermes_cli.web_server as web_server
|
||||
|
||||
calls = []
|
||||
|
||||
class _FakeProc:
|
||||
pid = 4242
|
||||
|
||||
monkeypatch.setattr(
|
||||
web_server,
|
||||
"_spawn_hermes_action",
|
||||
lambda subcommand, name: calls.append(list(subcommand)) or _FakeProc(),
|
||||
)
|
||||
resp = client.post(
|
||||
"/api/skills/hub/install", json={"identifier": "official/demo"}
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert calls == [["skills", "install", "official/demo"]]
|
||||
|
||||
def test_hub_install_unknown_profile_404(self, client, isolated_profiles):
|
||||
resp = client.post(
|
||||
"/api/skills/hub/install",
|
||||
json={"identifier": "official/demo", "profile": "ghost"},
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
@@ -140,29 +140,8 @@ class TestBuildWebUISkipsWhenFresh:
|
||||
assert kwargs["encoding"] == "utf-8"
|
||||
assert kwargs["errors"] == "replace"
|
||||
|
||||
def test_npm_install_sets_ci_to_suppress_postinstall_tty_output(self, tmp_path):
|
||||
web_dir, _ = _make_web_dir(tmp_path)
|
||||
(web_dir / "package-lock.json").write_text("{}", encoding="utf-8")
|
||||
|
||||
mock_cp = __import__("subprocess").CompletedProcess([], 0, stdout="", stderr="")
|
||||
with patch("hermes_cli.main.subprocess.run", return_value=mock_cp) as mock_run:
|
||||
_run_npm_install_deterministic(
|
||||
"/usr/bin/npm",
|
||||
web_dir,
|
||||
env={"PYTHON": "/nix/store/python"},
|
||||
)
|
||||
|
||||
_, kwargs = mock_run.call_args
|
||||
assert kwargs["env"]["CI"] == "1"
|
||||
assert kwargs["env"]["PYTHON"] == "/nix/store/python"
|
||||
|
||||
def test_npm_install_uses_workspace_web_scope(self, tmp_path):
|
||||
web_dir, _ = _make_web_dir(tmp_path)
|
||||
# Real workspace checkout: the single lockfile lives at the root, so
|
||||
# _workspace_root(web_dir) resolves to the parent and --workspace web
|
||||
# scopes the install. (Without a root lockfile, web_dir IS the root and
|
||||
# --workspace would be dropped — see test below and #42973.)
|
||||
(tmp_path / "package-lock.json").write_text("{}", encoding="utf-8")
|
||||
mock_cp = __import__("subprocess").CompletedProcess([], 0, stdout="", stderr="")
|
||||
build_ok = __import__("subprocess").CompletedProcess([], 0, stdout="", stderr="")
|
||||
with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
|
||||
@@ -174,36 +153,6 @@ class TestBuildWebUISkipsWhenFresh:
|
||||
assert "--workspace" in install_cmd
|
||||
assert install_cmd[install_cmd.index("--workspace") + 1] == "web"
|
||||
|
||||
def test_web_install_omits_workspace_when_web_has_own_lockfile(
|
||||
self, tmp_path, monkeypatch
|
||||
):
|
||||
"""web/ with its own lockfile => _workspace_root returns web_dir, so
|
||||
--workspace web would fail (npm can't find that workspace from inside
|
||||
web/). The flag must be dropped and the install run plainly from web_dir.
|
||||
Symmetric to the TUI fix in test_tui_npm_install.py. See #42973.
|
||||
|
||||
With web's own lockfile present at cwd, _run_npm_install_deterministic
|
||||
uses ``npm ci`` (not ``npm install``).
|
||||
"""
|
||||
web_dir, _ = _make_web_dir(tmp_path)
|
||||
(web_dir / "package-lock.json").write_text("{}", encoding="utf-8")
|
||||
(tmp_path / "package-lock.json").write_text("{}", encoding="utf-8")
|
||||
monkeypatch.delenv("TERMUX_VERSION", raising=False)
|
||||
monkeypatch.setenv("PREFIX", "/usr")
|
||||
|
||||
install_cp = __import__("subprocess").CompletedProcess([], 0, stdout="", stderr="")
|
||||
build_cp = __import__("subprocess").CompletedProcess([], 0, stdout="", stderr="")
|
||||
with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
|
||||
patch("hermes_cli.main.subprocess.run", return_value=install_cp) as mock_run, \
|
||||
patch("hermes_cli.main._run_with_idle_timeout", return_value=build_cp):
|
||||
result = _build_web_ui(web_dir)
|
||||
|
||||
assert result is True
|
||||
args, kwargs = mock_run.call_args
|
||||
assert "--workspace" not in args[0]
|
||||
assert args[0] == ["/usr/bin/npm", "ci", "--silent"]
|
||||
assert kwargs["cwd"] == web_dir
|
||||
|
||||
def test_web_build_uses_idle_timeout_helper(self, tmp_path):
|
||||
"""npm run build now goes through _run_with_idle_timeout (issue #33788).
|
||||
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
"""Unit tests for hermes_cli.win_pty_bridge — ConPTY spawning + byte forwarding.
|
||||
|
||||
Windows-only counterpart to tests/hermes_cli/test_pty_bridge.py. Drives
|
||||
``WinPtyBridge`` with minimal Windows processes (``cmd.exe``, ``python -c …``)
|
||||
to verify it behaves like a PTY you can read/write/resize/close, then a small
|
||||
set of platform-fallback assertions (``is_available``, ``PtyUnavailableError``)
|
||||
that run on every OS so the import surface stays exercised in CI.
|
||||
|
||||
The bridge is the ConPTY backend behind the dashboard ``/chat`` tab — see
|
||||
``hermes_cli/web_server.py`` ``/api/pty`` handler — so these tests are the
|
||||
unit-level half of the integration check that the dashboard chat pane is
|
||||
actually live on native Windows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
# WinPtyBridge can be imported on every platform — ``is_available`` just
|
||||
# returns False when pywinpty isn't usable. Importing the module itself
|
||||
# must never raise, otherwise the web_server import branch becomes a trap.
|
||||
from hermes_cli.win_pty_bridge import PtyUnavailableError, WinPtyBridge
|
||||
|
||||
windows_only = pytest.mark.skipif(
|
||||
not sys.platform.startswith("win"),
|
||||
reason="ConPTY bridge is Windows-only",
|
||||
)
|
||||
|
||||
|
||||
def _read_until(bridge: WinPtyBridge, needle: bytes, timeout: float = 10.0) -> bytes:
|
||||
"""Accumulate PTY output until we see ``needle`` or time out.
|
||||
|
||||
Mirrors the helper in test_pty_bridge.py so failures look familiar.
|
||||
"""
|
||||
deadline = time.monotonic() + timeout
|
||||
buf = bytearray()
|
||||
while time.monotonic() < deadline:
|
||||
chunk = bridge.read(timeout=0.2)
|
||||
if chunk is None:
|
||||
break
|
||||
buf.extend(chunk)
|
||||
if needle in buf:
|
||||
return bytes(buf)
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cross-platform fallback semantics
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestWinPtyBridgeUnavailable:
|
||||
"""Module-level surface that must stay importable on every OS so the
|
||||
web_server platform branch doesn't blow up at import time when pywinpty
|
||||
is missing or the host isn't Windows."""
|
||||
|
||||
def test_error_is_importable_and_carries_message(self):
|
||||
err = PtyUnavailableError("conpty missing")
|
||||
assert "conpty" in str(err)
|
||||
|
||||
def test_bridge_class_is_importable(self):
|
||||
# The platform-branched import in web_server.py relies on this:
|
||||
# from hermes_cli.win_pty_bridge import WinPtyBridge, PtyUnavailableError
|
||||
# Both symbols must always exist; ``is_available()`` is the gate.
|
||||
assert WinPtyBridge is not None
|
||||
assert callable(WinPtyBridge.is_available)
|
||||
|
||||
@pytest.mark.skipif(sys.platform.startswith("win"), reason="non-Windows only")
|
||||
def test_spawn_raises_unavailable_off_windows(self):
|
||||
with pytest.raises(PtyUnavailableError):
|
||||
WinPtyBridge.spawn(["true"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Windows-only end-to-end behaviour
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@windows_only
|
||||
class TestWinPtyBridgeSpawn:
|
||||
def test_is_available_on_windows(self):
|
||||
assert WinPtyBridge.is_available() is True
|
||||
|
||||
def test_spawn_returns_bridge_with_pid(self):
|
||||
bridge = WinPtyBridge.spawn(["cmd.exe", "/c", "exit 0"])
|
||||
try:
|
||||
assert bridge.pid > 0
|
||||
finally:
|
||||
bridge.close()
|
||||
|
||||
def test_spawn_raises_on_missing_argv0(self, tmp_path):
|
||||
# pywinpty wraps CreateProcessW failures; surface as OSError / RuntimeError.
|
||||
bogus = str(tmp_path / "definitely-not-a-real-binary.exe")
|
||||
with pytest.raises((FileNotFoundError, OSError, RuntimeError, PtyUnavailableError)):
|
||||
WinPtyBridge.spawn([bogus])
|
||||
|
||||
|
||||
@windows_only
|
||||
class TestWinPtyBridgeIO:
|
||||
def test_reads_child_stdout(self):
|
||||
bridge = WinPtyBridge.spawn(["cmd.exe", "/c", "echo hermes-ok"])
|
||||
try:
|
||||
output = _read_until(bridge, b"hermes-ok")
|
||||
assert b"hermes-ok" in output
|
||||
finally:
|
||||
bridge.close()
|
||||
|
||||
def test_write_sends_to_child_stdin(self):
|
||||
# python -c reads stdin, echoes a marker, exits. More reliable than
|
||||
# ``cat`` (not on Windows) and doesn't depend on a particular shell.
|
||||
script = (
|
||||
"import sys; "
|
||||
"line = sys.stdin.readline().strip(); "
|
||||
"sys.stdout.write('GOT:' + line + '\\n'); "
|
||||
"sys.stdout.flush()"
|
||||
)
|
||||
bridge = WinPtyBridge.spawn([sys.executable, "-c", script])
|
||||
try:
|
||||
bridge.write(b"hello-pty\r\n")
|
||||
output = _read_until(bridge, b"GOT:hello-pty")
|
||||
assert b"GOT:hello-pty" in output
|
||||
finally:
|
||||
bridge.close()
|
||||
|
||||
def test_write_after_close_is_silent(self):
|
||||
bridge = WinPtyBridge.spawn(["cmd.exe", "/c", "exit 0"])
|
||||
bridge.close()
|
||||
# Must not raise — the dashboard WebSocket reader sometimes writes
|
||||
# a final keystroke after the user has already closed the tab.
|
||||
bridge.write(b"ignored")
|
||||
|
||||
def test_read_returns_none_after_child_exits(self):
|
||||
bridge = WinPtyBridge.spawn(["cmd.exe", "/c", "echo done"])
|
||||
try:
|
||||
_read_until(bridge, b"done")
|
||||
# Give the child a beat to exit, then drain until EOF.
|
||||
deadline = time.monotonic() + 5.0
|
||||
while bridge.is_alive() and time.monotonic() < deadline:
|
||||
bridge.read(timeout=0.1)
|
||||
got_none = False
|
||||
for _ in range(20):
|
||||
if bridge.read(timeout=0.1) is None:
|
||||
got_none = True
|
||||
break
|
||||
assert got_none, "WinPtyBridge.read did not return None after child EOF"
|
||||
finally:
|
||||
bridge.close()
|
||||
|
||||
|
||||
@windows_only
|
||||
class TestWinPtyBridgeResize:
|
||||
def test_resize_does_not_raise_on_live_child(self):
|
||||
# ConPTY exposes no ioctl-equivalent for reading the child's current
|
||||
# winsize from Python land, so we can't verify the new dimensions
|
||||
# the way the POSIX test does (which reads TIOCGWINSZ). What we
|
||||
# CAN guarantee is what the dashboard depends on: ``resize`` never
|
||||
# raises, the bridge stays alive, and subsequent I/O still works.
|
||||
bridge = WinPtyBridge.spawn(
|
||||
[sys.executable, "-c", "import time; time.sleep(1.0)"],
|
||||
cols=80,
|
||||
rows=24,
|
||||
)
|
||||
try:
|
||||
bridge.resize(cols=123, rows=45)
|
||||
assert bridge.is_alive()
|
||||
finally:
|
||||
bridge.close()
|
||||
|
||||
def test_resize_clamps_garbage_dimensions(self):
|
||||
# Mirror the POSIX clamp test: a broken winsize probe must never
|
||||
# propagate to the ConPTY API. 131072 > unsigned short max — the
|
||||
# bridge has to coerce it down without raising.
|
||||
bridge = WinPtyBridge.spawn(
|
||||
[sys.executable, "-c", "import time; time.sleep(1.0)"],
|
||||
cols=80,
|
||||
rows=24,
|
||||
)
|
||||
try:
|
||||
bridge.resize(cols=131072, rows=1) # must not raise
|
||||
bridge.resize(cols=0, rows=-5) # nor this
|
||||
assert bridge.is_alive()
|
||||
finally:
|
||||
bridge.close()
|
||||
|
||||
def test_resize_after_close_is_silent(self):
|
||||
bridge = WinPtyBridge.spawn(["cmd.exe", "/c", "exit 0"])
|
||||
bridge.close()
|
||||
# Must not raise — closed bridges still receive late resize escapes
|
||||
# from xterm.js when the browser tab is closed mid-stream.
|
||||
bridge.resize(cols=100, rows=40)
|
||||
|
||||
|
||||
@windows_only
|
||||
class TestClampDimension:
|
||||
"""The clamp helper is the load-bearing piece — the dashboard sends
|
||||
untrusted winsize values straight from xterm.js, and pywinpty's
|
||||
setwinsize will happily raise on out-of-range u16 values."""
|
||||
|
||||
def test_clamps_above_max(self):
|
||||
from hermes_cli.win_pty_bridge import _MAX_COLS, _MAX_ROWS, _clamp
|
||||
|
||||
assert _clamp(131072, _MAX_COLS) == _MAX_COLS
|
||||
assert _clamp(131072, _MAX_ROWS) == _MAX_ROWS
|
||||
|
||||
def test_floors_at_one(self):
|
||||
from hermes_cli.win_pty_bridge import _MAX_COLS, _clamp
|
||||
|
||||
assert _clamp(0, _MAX_COLS) == 1
|
||||
assert _clamp(-5, _MAX_COLS) == 1
|
||||
|
||||
def test_passes_through_sane_values(self):
|
||||
from hermes_cli.win_pty_bridge import _MAX_COLS, _clamp
|
||||
|
||||
assert _clamp(80, _MAX_COLS) == 80
|
||||
assert _clamp(2000, _MAX_COLS) == 2000
|
||||
|
||||
def test_non_numeric_falls_back_to_min(self):
|
||||
from hermes_cli.win_pty_bridge import _MAX_COLS, _clamp
|
||||
|
||||
assert _clamp(None, _MAX_COLS) == 1 # type: ignore[arg-type]
|
||||
assert _clamp("not-a-number", _MAX_COLS) == 1 # type: ignore[arg-type]
|
||||
assert _clamp(float("nan"), _MAX_COLS) == 1 # type: ignore[arg-type]
|
||||
assert _clamp(float("inf"), _MAX_COLS) == 1 # type: ignore[arg-type]
|
||||
|
||||
|
||||
@windows_only
|
||||
class TestWinPtyBridgeClose:
|
||||
def test_close_is_idempotent(self):
|
||||
bridge = WinPtyBridge.spawn(
|
||||
[sys.executable, "-c", "import time; time.sleep(30)"]
|
||||
)
|
||||
bridge.close()
|
||||
bridge.close() # must not raise
|
||||
assert not bridge.is_alive()
|
||||
|
||||
def test_close_terminates_long_running_child(self):
|
||||
bridge = WinPtyBridge.spawn(
|
||||
[sys.executable, "-c", "import time; time.sleep(30)"]
|
||||
)
|
||||
pid = bridge.pid
|
||||
assert bridge.is_alive(), f"child pid {pid} not alive before close"
|
||||
bridge.close()
|
||||
# The bridge itself reports liveness via pywinpty.isalive(), which is
|
||||
# the same probe the dashboard PTY reader uses to decide when to stop
|
||||
# forwarding bytes — verifying that flips to False is the contract
|
||||
# that matters for /api/pty.
|
||||
deadline = time.monotonic() + 5.0
|
||||
while bridge.is_alive() and time.monotonic() < deadline:
|
||||
time.sleep(0.1)
|
||||
assert not bridge.is_alive(), (
|
||||
f"WinPtyBridge.is_alive() still True after close(); pid {pid}"
|
||||
)
|
||||
|
||||
|
||||
@windows_only
|
||||
class TestWinPtyBridgeEnv:
|
||||
def test_cwd_is_respected(self, tmp_path):
|
||||
bridge = WinPtyBridge.spawn(
|
||||
[sys.executable, "-c", "import os; print(os.getcwd())"],
|
||||
cwd=str(tmp_path),
|
||||
)
|
||||
try:
|
||||
# Path is case-insensitive on Windows; compare lowercased.
|
||||
needle_resolved = str(tmp_path.resolve()).lower().encode()
|
||||
deadline = time.monotonic() + 5.0
|
||||
buf = bytearray()
|
||||
while time.monotonic() < deadline:
|
||||
chunk = bridge.read(timeout=0.2)
|
||||
if chunk is None:
|
||||
break
|
||||
buf.extend(chunk)
|
||||
if needle_resolved in bytes(buf).lower():
|
||||
break
|
||||
assert needle_resolved in bytes(buf).lower(), (
|
||||
f"cwd {tmp_path!s} not echoed by child; got {bytes(buf)!r}"
|
||||
)
|
||||
finally:
|
||||
bridge.close()
|
||||
|
||||
def test_env_is_forwarded(self):
|
||||
bridge = WinPtyBridge.spawn(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
"import os; print('HERMES_PTY_TEST=' + os.environ.get('HERMES_PTY_TEST',''))",
|
||||
],
|
||||
env={**os.environ, "HERMES_PTY_TEST": "pty-env-works"},
|
||||
)
|
||||
try:
|
||||
output = _read_until(bridge, b"pty-env-works")
|
||||
assert b"pty-env-works" in output
|
||||
finally:
|
||||
bridge.close()
|
||||
|
||||
def test_spawn_defaults_term_when_not_set(self):
|
||||
# The bridge should set TERM=xterm-256color when the caller's env
|
||||
# doesn't already carry one — xterm.js expects ANSI/SGR sequences.
|
||||
env = {k: v for k, v in os.environ.items() if k.upper() != "TERM"}
|
||||
bridge = WinPtyBridge.spawn(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
"import os; print('TERM=' + os.environ.get('TERM',''))",
|
||||
],
|
||||
env=env,
|
||||
)
|
||||
try:
|
||||
output = _read_until(bridge, b"TERM=")
|
||||
assert b"TERM=xterm-256color" in output
|
||||
finally:
|
||||
bridge.close()
|
||||
@@ -1,78 +0,0 @@
|
||||
import argparse
|
||||
|
||||
|
||||
def test_xai_model_flow_reauth_uses_standard_radio_prompt(monkeypatch):
|
||||
from hermes_cli import main as main_mod
|
||||
|
||||
captured = {"login_calls": 0}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth.get_xai_oauth_auth_status",
|
||||
lambda: {"logged_in": True},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.setup._curses_prompt_choice",
|
||||
lambda title, choices, default, description=None: 1,
|
||||
)
|
||||
|
||||
def _fake_login(args, provider, force_new_login=False):
|
||||
captured["login_calls"] += 1
|
||||
captured["force_new_login"] = force_new_login
|
||||
captured["args"] = args
|
||||
|
||||
monkeypatch.setattr("hermes_cli.auth._login_xai_oauth", _fake_login)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth.resolve_xai_oauth_runtime_credentials",
|
||||
lambda *args, **kwargs: {"base_url": "https://api.x.ai/v1"},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth._prompt_model_selection",
|
||||
lambda model_ids, current_model="": None,
|
||||
)
|
||||
|
||||
main_mod._model_flow_xai_oauth(
|
||||
{},
|
||||
current_model="grok-build-0.1",
|
||||
args=argparse.Namespace(manual_paste=True, no_browser=True, timeout=3),
|
||||
)
|
||||
|
||||
assert captured["login_calls"] == 1
|
||||
assert captured["force_new_login"] is True
|
||||
assert captured["args"].manual_paste is True
|
||||
assert captured["args"].no_browser is True
|
||||
assert captured["args"].timeout == 3
|
||||
|
||||
|
||||
def test_xai_model_flow_cancel_skips_reauth(monkeypatch):
|
||||
from hermes_cli import main as main_mod
|
||||
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth.get_xai_oauth_auth_status",
|
||||
lambda: {"logged_in": True},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.setup._curses_prompt_choice",
|
||||
lambda title, choices, default, description=None: 2,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth._login_xai_oauth",
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("should not reauthenticate")),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth._prompt_model_selection",
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("should not pick a model")),
|
||||
)
|
||||
|
||||
main_mod._model_flow_xai_oauth({}, current_model="grok-build-0.1")
|
||||
|
||||
|
||||
def test_auth_credentials_choice_falls_back_to_numbered_prompt(monkeypatch):
|
||||
from hermes_cli import main as main_mod
|
||||
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.setup._curses_prompt_choice",
|
||||
lambda title, choices, default, description=None: -1,
|
||||
)
|
||||
monkeypatch.setattr("builtins.input", lambda prompt="": "2")
|
||||
|
||||
assert main_mod._prompt_auth_credentials_choice("Credentials:") == "reauth"
|
||||
Reference in New Issue
Block a user