headroom/tests/test_cli/test_wrap_bridge.py
Nestor G Pestelos Jr c8310819a4
fix(wrap): set xAI upstream for grok-build proxy (#2772)
## Description

`headroom wrap grok-build` injected the client hop into
`~/.grok/config.toml` but started the local proxy **without** setting
the OpenAI-compatible upstream to xAI. The proxy defaulted to
`api.openai.com`, so Grok session auth returned **401** on every chat
completion even though compression still ran.

`wrap grok` already passes `openai_api_url` → xAI. This PR aligns `wrap
grok-build` and the Grok-only persistent `install` path on the shared
`DEFAULT_API_URL` (`https://api.x.ai`).

Closes # (none — discovered in live Grok Build pilot)

## Type of Change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Pass `openai_api_url=_GROK_DEFAULT_API_URL` into
`_run_proxy_only_watcher` from `wrap grok-build`
- Use shared `DEFAULT_API_URL` from `wrap grok` (no hard-coded string
drift)
- Print proxy upstream in Grok Build setup lines
- Persistent install: when targets are Grok-only, set
`OPENAI_TARGET_API_URL` + `--openai-api-url` (skip when
Codex/Copilot/Aider/OpenCode share the proxy; explicit env still wins)
- Regression tests for wrap kwargs, setup lines, and install planner

## Testing

- [x] Unit tests pass (`pytest` targeted suite)
- [ ] Linting passes (`ruff check .`) — not run in this environment (no
native editable build)
- [ ] Type checking passes (`mypy headroom`) — not run
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ PYTHONPATH=$PWD python -m pytest \
    tests/test_cli/test_wrap_bridge.py::test_wrap_grok_build_passes_xai_openai_api_url \
    tests/test_cli/test_wrap_bridge.py::test_wrap_grok_build_uses_actual_proxy_port \
    tests/test_install/test_planner.py::test_build_manifest_grok_build_only_sets_xai_upstream \
    tests/test_install/test_planner.py::test_build_manifest_grok_with_codex_does_not_force_xai \
    tests/test_install/test_planner.py::test_build_manifest_extra_env_wins_over_grok_xai_default \
    tests/test_provider_grok_build.py::test_grok_build_setup_lines_include_proxy_url -q
......
6 passed in 0.33s
```

## Real Behavior Proof

- Environment: macOS (darwin), Headroom 0.33.0 via `uv tool install
"headroom-ai[proxy,mcp,code]==0.33.0"`, Grok Build CLI, models
`grok-build` and `grok-4.5`, proxy on `127.0.0.1:8787`, upstream must be
xAI
- Exact command / steps: (1) Before: stock `headroom wrap grok-build`
then `grok -m grok-build` one-shot prompt. (2) After: same wrap path
with this branch (`openai_api_url=DEFAULT_API_URL` into
`_run_proxy_only_watcher`) then `grok -m grok-build -p
'…HEADROOM_XAI_OK…'`. Also exercised `grok-4.5` via `[model."grok-4.5"]
base_url` → same proxy.
- Observed result: Before — proxy log outbound `api.openai.com` → HTTP
401; client failed while local compression still ran. After — setup line
prints Proxy upstream `https://api.x.ai`; proxy log `POST
https://api.x.ai/v1/chat/completions` (and `/v1/responses` for grok-4.5)
→ status=200; dashboard shows 0 failed requests and accumulating token
savings on live traffic.
- Not tested: full `uv run` editable/maturin native build on this host;
multi-tool install matrix beyond planner unit tests; Windows; ruff/mypy
full tree

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I commented my code, particularly in hard-to-understand areas
- [ ] I made corresponding changes to the documentation (CLI help text /
setup lines only)
- [x] My changes generate no new warnings
- [x] I added tests that prove my fix is effective or that my feature
works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — generated by release-please
from Conventional Commit PR title (a CI guard enforces this)

## Additional Notes

- Intentional non-goal: changing default model, savings %, or Grok Build
context-tool defaults
- Mixed-target install (e.g. `grok_build` + `codex`) does **not** force
xAI — operator must set upstream explicitly if they share one proxy
- Related live routing: manual `[model."grok-4.5"] base_url` through the
same proxy works once upstream is xAI (`/v1/responses`)

---------

Co-authored-by: Grok 4.5 <noreply@x.ai>
Co-authored-by: Nestor G Pestelos Jr <ngpestelos@me.com>
Co-authored-by: JD Davis <jd@jds-macbook-air.tail2a279.ts.net>
2026-08-16 15:04:59 -07:00

198 lines
6.6 KiB
Python

"""Tests for Docker-bridge wrap preparation flows."""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import patch
import pytest
from click.testing import CliRunner
from headroom.cli.main import main
@pytest.fixture(autouse=True)
def _no_retired_context_tool_env(monkeypatch) -> None:
"""Keep a developer's exported HEADROOM_CONTEXT_TOOL from failing every test.
The var is now rejected outright, so leaving it set in the ambient
environment would abort each wrap invocation below.
"""
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
def _set_test_home(monkeypatch, tmp_path: Path) -> None:
home = str(tmp_path)
monkeypatch.setenv("HOME", home)
monkeypatch.setenv("USERPROFILE", home)
def test_wrap_claude_prepare_only_skips_host_binary_lookup() -> None:
runner = CliRunner()
with patch("headroom.cli.wrap.shutil.which") as which_mock:
result = runner.invoke(main, ["wrap", "claude", "--prepare-only"])
assert result.exit_code == 0, result.output
which_mock.assert_not_called()
def test_wrap_codex_prepare_only_updates_config(monkeypatch, tmp_path: Path) -> None:
_set_test_home(monkeypatch, tmp_path)
runner = CliRunner()
with patch("headroom.cli.wrap.ensure_proxy_dependencies", return_value=None):
result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
assert result.exit_code == 0, result.output
config_file = tmp_path / ".codex" / "config.toml"
assert config_file.exists()
content = config_file.read_text(encoding="utf-8")
assert 'model_provider = "headroom"' in content
assert 'base_url = "http://127.0.0.1:8787/v1"' in content
def test_wrap_grok_build_uses_actual_proxy_port(monkeypatch, tmp_path: Path) -> None:
_set_test_home(monkeypatch, tmp_path)
runner = CliRunner()
def fake_watcher(**kwargs) -> None:
kwargs["print_setup_lines"](9999)
monkeypatch.setattr("headroom.cli.wrap._run_proxy_only_watcher", fake_watcher)
result = runner.invoke(main, ["wrap", "grok-build", "--port", "8787"])
assert result.exit_code == 0, result.output
config_file = tmp_path / ".grok" / "config.toml"
assert config_file.exists()
content = config_file.read_text(encoding="utf-8")
assert 'base_url = "http://127.0.0.1:9999/' in content
assert "http://127.0.0.1:8787/" not in content
assert "http://127.0.0.1:9999/" in result.output
assert "http://127.0.0.1:8787/" not in result.output
def test_wrap_grok_build_passes_xai_openai_api_url(monkeypatch, tmp_path: Path) -> None:
"""Grok Build must set proxy upstream to xAI (same as wrap grok).
Without openai_api_url, the proxy defaults to api.openai.com and Grok
session auth returns 401 on every chat completion.
"""
from headroom.providers.grok import DEFAULT_API_URL
_set_test_home(monkeypatch, tmp_path)
runner = CliRunner()
captured: dict = {}
def fake_watcher(**kwargs) -> None:
captured.update(kwargs)
kwargs["print_setup_lines"](kwargs["port"])
monkeypatch.setattr("headroom.cli.wrap._run_proxy_only_watcher", fake_watcher)
result = runner.invoke(main, ["wrap", "grok-build", "--port", "8787"])
assert result.exit_code == 0, result.output
assert captured.get("openai_api_url") == DEFAULT_API_URL
# Equality on the constant (not substring containment) keeps CodeQL
# incomplete-url-substring-sanitization quiet while pinning the host.
assert DEFAULT_API_URL == "https://api.x.ai"
expected_upstream = f" Proxy upstream (OpenAI-compatible): {DEFAULT_API_URL}"
upstream_lines = [
line
for line in result.output.splitlines()
if line.startswith(" Proxy upstream (OpenAI-compatible): ")
]
assert upstream_lines == [expected_upstream]
def test_wrap_rejects_retired_context_tool_flag(monkeypatch, tmp_path: Path) -> None:
"""A surviving --context-tool must fail loudly, not be silently ignored.
rtk / lean-ctx are gone, but the flag lives on in shell profiles, scripts and
CI jobs. Accepting it as a no-op would look like Headroom had quietly stopped
filtering; the user needs to be told the feature was removed.
"""
_set_test_home(monkeypatch, tmp_path)
runner = CliRunner()
with runner.isolated_filesystem(temp_dir=str(tmp_path)):
result = runner.invoke(
main,
["wrap", "codex", "--prepare-only", "--no-context-tool", "--no-mcp", "--no-serena"],
)
assert result.exit_code != 0
assert "have been removed from Headroom" in result.output
def test_wrap_rejects_retired_context_tool_env(monkeypatch, tmp_path: Path) -> None:
"""An exported HEADROOM_CONTEXT_TOOL fails too, with the same message.
The env var is the form most likely to be left behind in a shell rc, where
it would otherwise never surface.
"""
_set_test_home(monkeypatch, tmp_path)
monkeypatch.setenv("HEADROOM_CONTEXT_TOOL", "lean-ctx")
runner = CliRunner()
with runner.isolated_filesystem(temp_dir=str(tmp_path)):
result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--no-mcp", "--no-serena"])
assert result.exit_code != 0
assert "have been removed from Headroom" in result.output
def test_wrap_openclaw_prepare_only_emits_config_without_python_default() -> None:
runner = CliRunner()
result = runner.invoke(
main,
[
"wrap",
"openclaw",
"--prepare-only",
"--gateway-provider-id",
"codex",
"--gateway-provider-id",
"anthropic",
],
)
assert result.exit_code == 0, result.output
payload = json.loads(result.output)
assert payload["enabled"] is True
assert payload["config"]["proxyPort"] == 8787
assert payload["config"]["gatewayProviderIds"] == ["codex", "anthropic"]
assert "pythonPath" not in payload["config"]
def test_unwrap_openclaw_prepare_only_preserves_unmanaged_config() -> None:
runner = CliRunner()
existing_entry = json.dumps(
{
"enabled": True,
"config": {
"pythonPath": "C:\\Python312\\python.exe",
"proxyPort": 8787,
"customFlag": True,
},
}
)
result = runner.invoke(
main,
[
"unwrap",
"openclaw",
"--prepare-only",
"--existing-entry-json",
existing_entry,
],
)
assert result.exit_code == 0, result.output
payload = json.loads(result.output)
assert payload == {"enabled": False, "config": {"customFlag": True}}