Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

test(codex): add regression tests for bug 3 config injection

JerrettDavis1c6ae456037f
diff --git a/tests/test_install/test_providers.py b/tests/test_install/test_providers.py
index 0a82df15c..ba1e4525f 100644
--- a/tests/test_install/test_providers.py
+++ b/tests/test_install/test_providers.py
@@ -234,51 +234,312 @@ def test_openclaw_revert_provider_scope_skips_without_binary(monkeypatch, tmp_pa
def fail_if_called(command: list[str]) -> None:
nonlocal called
- // ... 309 lines omitted
+ called = True
+
+ monkeypatch.setattr("headroom.providers.openclaw.install._invoke_openclaw", fail_if_called)
+
from headroom.providers.openclaw.install import (
- // ... 308 lines omitted
+ revert_provider_scope as revert_openclaw_provider_scope,
+ )
+
+ revert_openclaw_provider_scope(
+ ManagedMutation(target="openclaw", kind="openclaw-wrap", path=str(tmp_path / "cfg.json")),
+ _manifest(tmp_path),
+ )
+
+ assert called is False
+
+
def test_openclaw_revert_provider_scope_invokes_unwrap(monkeypatch, tmp_path: Path) -> None:
- // ... 307 lines omitted
+ recorded: list[list[str]] = []
+ monkeypatch.setattr("headroom.providers.openclaw.install.shutil_which", lambda name: "openclaw")
+ monkeypatch.setattr(
+ "headroom.providers.openclaw.install.resolve_headroom_command",
+ lambda: ["headroom"],
+ )
+ monkeypatch.setattr(
+ "headroom.providers.openclaw.install._invoke_openclaw",
+ lambda command: recorded.append(command),
+ )
+
from headroom.providers.openclaw.install import (
- // ... 306 lines omitted
+ revert_provider_scope as revert_openclaw_provider_scope,
+ )
+
+ revert_openclaw_provider_scope(
+ ManagedMutation(target="openclaw", kind="openclaw-wrap", path=str(tmp_path / "cfg.json")),
+ _manifest(tmp_path),
+ )
+
+ assert recorded == [["headroom", "unwrap", "openclaw"]]
+
+
def test_windows_env_scope_restores_previous_values(monkeypatch, tmp_path: Path) -> None:
- // ... 305 lines omitted
+ manifest = _manifest(tmp_path)
+ manifest.scope = "user"
+ manifest.targets = ["claude"]
+ manifest.base_env = {"HEADROOM_PORT": "8787"}
+ manifest.tool_envs = {"claude": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787"}}
+
+ calls: list[list[str]] = []
+ previous_values = {
+ "HEADROOM_PORT": "7777",
+ "ANTHROPIC_BASE_URL": "https://old",
}
- // ... 304 lines omitted
+
class Result:
def __init__(self, stdout: str = "") -> None:
- // ... 302 lines omitted
+ self.stdout = stdout
+
def fake_run(command: list[str], **kwargs):
- // ... 301 lines omitted
+ calls.append(command)
+ script = command[-1]
+ if "GetEnvironmentVariable" in script:
+ name = script.split("GetEnvironmentVariable('", 1)[1].split("'", 1)[0]
+ value = previous_values.get(name, "__HEADROOM_UNSET__")
+ return Result(stdout=value)
+ return Result()
+
+ monkeypatch.setattr("headroom.install.providers.subprocess.run", fake_run)
+
+ mutations = _apply_windows_env_scope(manifest)
+ _remove_windows_env_scope(mutations)
+
+ previous_by_name = {mutation.data["name"]: mutation.data["previous"] for mutation in mutations}
+ assert previous_by_name["HEADROOM_PORT"] == "7777"
+ assert previous_by_name["ANTHROPIC_BASE_URL"] == "https://old"
+ assert any(
+ "[Environment]::SetEnvironmentVariable('HEADROOM_PORT','7777','User')" in command[-1]
+ for command in calls
+ )
+ assert any(
+ "[Environment]::SetEnvironmentVariable('ANTHROPIC_BASE_URL','https://old','User')"
+ in command[-1]
+ for command in calls
+ )
+
+
def test_remove_windows_env_scope_requires_name_and_scope() -> None:
- // ... 300 lines omitted
+ try:
+ _remove_windows_env_scope([ManagedMutation(target="env", kind="windows-env", data={})])
+ except ValueError as exc:
+ assert "variable name" in str(exc)
+ else:
+ raise AssertionError("expected missing variable name to raise")
+
+ try:
+ _remove_windows_env_scope(
+ [ManagedMutation(target="env", kind="windows-env", data={"name": "X", "scope": 1})]
+ )
+ except ValueError as exc:
+ assert "valid scope" in str(exc)
+ else:
+ raise AssertionError("expected invalid scope to raise")
+
+
def test_apply_mutations_runs_openclaw_for_user_scope(monkeypatch, tmp_path: Path) -> None:
- // ... 299 lines omitted
+ manifest = _manifest(tmp_path)
+ manifest.scope = "user"
+ manifest.targets = ["openclaw"]
+ manifest.base_env = {"HEADROOM_PORT": "8787"}
+ manifest.tool_envs = {}
+
+ if os.name == "nt":
+ monkeypatch.setattr(
+ "headroom.install.providers._apply_windows_env_scope", lambda deployment: []
+ )
+ else:
+ monkeypatch.setattr(
+ "headroom.install.providers._apply_unix_env_scope", lambda deployment: []
+ )
+ monkeypatch.setattr(
+ "headroom.install.providers.apply_provider_scope_mutations",
+ lambda deployment: [ManagedMutation(target="openclaw", kind="openclaw-wrap")],
+ )
+
from headroom.install.providers import apply_mutations
- // ... 298 lines omitted
+
+ mutations = apply_mutations(manifest)
+
+ assert [mutation.kind for mutation in mutations] == ["openclaw-wrap"]
+
+
def test_claude_build_install_env_returns_proxy_base_url() -> None:
- // ... 297 lines omitted
+ # Arrange / Act
+ env = build_claude_install_env(port=5566, backend="ignored")
+
+ # Assert
+ assert env == {"ANTHROPIC_BASE_URL": "http://127.0.0.1:5566"}
+
+
def test_copilot_build_install_env_uses_provider_type_specific_proxy_urls() -> None:
- // ... 296 lines omitted
+ anthropic_env = build_copilot_install_env(port=8787, backend="anthropic")
+ openai_env = build_copilot_install_env(port=8787, backend="anyllm")
+
+ assert anthropic_env == {
+ "COPILOT_PROVIDER_TYPE": "anthropic",
+ "COPILOT_PROVIDER_BASE_URL": "http://127.0.0.1:8787",
}
- // ... 295 lines omitted
+ assert openai_env == {
+ "COPILOT_PROVIDER_TYPE": "openai",
+ "COPILOT_PROVIDER_BASE_URL": "http://127.0.0.1:8787/v1",
+ "COPILOT_PROVIDER_WIRE_API": "completions",
}
- // ... 294 lines omitted
+
+
def test_apply_claude_provider_scope_skips_non_provider_scope(monkeypatch, tmp_path: Path) -> None:
- // ... 293 lines omitted
+ # Arrange
+ settings_path = tmp_path / "settings.json"
+ monkeypatch.setattr(
+ "headroom.providers.claude.install.claude_settings_path", lambda: settings_path
+ )
+ manifest = _manifest(tmp_path)
+ manifest.scope = "user"
+
+ # Act
+ mutation = apply_claude_provider_scope(manifest)
+
+ # Assert
+ assert mutation is None
+ assert not settings_path.exists()
+
+
def test_revert_claude_provider_scope_removes_new_values_from_non_mapping_env(
- // ... 292 lines omitted
+ monkeypatch, tmp_path: Path
+) -> None:
+ # Arrange
+ settings_path = tmp_path / "settings.json"
+ settings_path.write_text(json.dumps({"env": ["not-a-map"]}))
+ monkeypatch.setattr(
+ "headroom.providers.claude.install.claude_settings_path", lambda: settings_path
+ )
+ manifest = _manifest(tmp_path)
+
+ # Act
+ mutation = apply_claude_provider_scope(manifest)
+ apply_payload = json.loads(settings_path.read_text())
+ revert_claude_provider_scope(mutation, manifest)
+ reverted_payload = json.loads(settings_path.read_text())
+
+ # Assert
+ assert mutation is not None
+ assert mutation.data["previous"] == {"ANTHROPIC_BASE_URL": None}
+ assert apply_payload["env"] == {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787"}
+ assert reverted_payload["env"] == {}
+
+
def test_apply_claude_provider_scope_creates_settings_when_missing(
- // ... 291 lines omitted
+ monkeypatch, tmp_path: Path
+) -> None:
+ # Arrange
+ settings_path = tmp_path / "nested" / "settings.json"
+ monkeypatch.setattr(
+ "headroom.providers.claude.install.claude_settings_path", lambda: settings_path
+ )
+ manifest = _manifest(tmp_path)
+
+ # Act
+ mutation = apply_claude_provider_scope(manifest)
+
+ # Assert
+ assert mutation is not None
+ assert json.loads(settings_path.read_text()) == {
+ "env": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787"}
}
- // ... 290 lines omitted
+
+
def test_revert_claude_provider_scope_ignores_missing_mutation_path(tmp_path: Path) -> None:
- // ... 289 lines omitted
+ # Arrange
+ manifest = _manifest(tmp_path)
+ mutation = ManagedMutation(target="claude", kind="json-env", data={"previous": {}})
+
+ # Act / Assert
+ revert_claude_provider_scope(mutation, manifest)
+
+
def test_revert_claude_provider_scope_ignores_missing_settings_file(tmp_path: Path) -> None:
- // ... 288 lines omitted
+ # Arrange
+ manifest = _manifest(tmp_path)
+ mutation = ManagedMutation(
+ target="claude",
+ kind="json-env",
+ path=str(tmp_path / "missing-settings.json"),
+ data={"previous": {}},
+ )
+
+ # Act / Assert
+ revert_claude_provider_scope(mutation, manifest)
+
+
+# ---------------------------------------------------------------------------
+# Bug 3 regression tests (#406): requires_openai_auth and openai_base_url
+# must never appear in the headroom provider block.
+# ---------------------------------------------------------------------------
+
+
def test_headroom_provider_block_never_sets_requires_openai_auth(
- // ... 287 lines omitted
+ monkeypatch, tmp_path: Path
+) -> None:
+ """apply_provider_scope must NOT emit requires_openai_auth in the headroom block.
+
+ Bug 3 (#406): requires_openai_auth = true on a custom [model_providers.headroom]
+ block forces codex to demand OpenAI OAuth login for headroom-routed traffic.
+ Headroom is a local proxy — it must not require OpenAI auth.
+ """
+ for port in (8787, 9999):
+ config_path = tmp_path / f"config_{port}.toml"
+ monkeypatch.setattr(
+ "headroom.providers.codex.install.codex_config_path", lambda: config_path
+ )
+ manifest = _manifest(tmp_path)
+ manifest.port = port
+
+ apply_codex_provider_scope(manifest)
+
+ content = config_path.read_text()
+ # The rendered TOML for the headroom provider block must not contain this
+ # field. If it does, codex will prompt for OpenAI OAuth on every startup.
+ assert "requires_openai_auth" not in content, (
+ f"requires_openai_auth must be absent from the headroom provider block "
+ f"(port={port}); got:\n{content}"
+ )
+ # Sanity: the block itself is present and points at the right port.
+ assert f'base_url = "http://127.0.0.1:{port}/v1"' in content
+ assert "[model_providers.headroom]" in content
+
+
def test_inject_codex_provider_config_does_not_write_openai_base_url(
- // ... 286 lines omitted
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """_inject_codex_provider_config must NOT write a top-level openai_base_url key.
+
+ Bug 3 (#406): injecting openai_base_url at the top level of config.toml
+ causes ChatGPT/subscription users to bypass headroom and ride the built-in
+ openai provider directly. The field must be absent after injection.
+ """
from headroom.cli import wrap as wrap_mod
-// ... 285 more lines (total: 544)
\ No newline at end of file
+
+ home = tmp_path
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+
+ wrap_mod._inject_codex_provider_config(8787)
+
+ config_file = home / ".codex" / "config.toml"
+ assert config_file.exists(), "inject must create ~/.codex/config.toml"
+ content = config_file.read_text()
+
+ # The top-level openai_base_url key must be absent. Its presence would
+ # bypass headroom for subscription/ChatGPT users.
+ assert "openai_base_url" not in content, (
+ "openai_base_url must not appear in config.toml after injection; "
+ f"got:\n{content}"
+ )
+ # Sanity: the provider block is actually there.
+ assert "[model_providers.headroom]" in content
+ assert 'base_url = "http://127.0.0.1:8787/v1"' in content
+ # requires_openai_auth must also be absent (bug 3 regression guard).
+ assert "requires_openai_auth" not in content, (
+ "requires_openai_auth must be absent from the injected provider block; "
+ f"got:\n{content}"
+ )