Files
headroom/tests/test_cli/test_wrap_omp.py
Glen JungandJerrett Davis fae1e849cb fix(wrap): route OMP OpenAI providers through Headroom (#2755)
## Description

`headroom wrap omp` advertised OMP support but only redirected OMP's
`anthropic` provider. OMP models under `openai` and
`openai-codex`—including the current `openai-codex/gpt-5.6-sol`
model—kept their native endpoints and bypassed Headroom.

This change adds reversible `models.yml` base URL overrides for both
OpenAI provider IDs while preserving the existing Anthropic route,
provider credentials/headers, custom models, byte-for-byte backup, and
`headroom unwrap omp` behavior.

Follow-up to #1811.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that 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

- Route `providers.openai.baseUrl` through the project-prefixed Headroom
`/v1` endpoint.
- Route `providers.openai-codex.baseUrl` through the same endpoint; OMP
appends `/codex/responses`, which Headroom already supports for HTTP and
WebSocket traffic.
- Preserve all existing provider fields and the established
backup/reinject/unwrap contract.
- Show all three managed provider routes at launch and document the
expanded OMP support.
- Extend the existing OMP wrap tests for fresh injection, user-config
preservation, reinjection, and CLI display.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ uv run --extra dev pytest -q tests/test_cli/test_wrap_omp.py
15 passed in 0.31s

$ uv run --extra dev ruff check .
All checks passed!

$ uv run --extra dev ruff format --check .
1343 files already formatted

$ uv run --extra dev mypy headroom
Success: no issues found in 511 source files
```

The full pytest suite was started but not completed: after roughly 17
minutes it was still running unrelated Codex unwrap tests that
repeatedly install/index Serena. No failure was observed before
cancellation; the affected OMP suite is green.

## Real Behavior Proof

- Environment: macOS Darwin 25.4 arm64 (Apple M5 Pro), Python 3.13.13,
CLI code from this branch, published Headroom 0.33.0 proxy on port 8787,
OMP 17.2.7, `openai-codex/gpt-5.6-sol` with stored ChatGPT/Codex OAuth.
- Exact command / steps: Run the command below against the existing
proxy, then inspect `/stats` and the managed `models.yml`.
  1. Start or reuse the local proxy on `127.0.0.1:8787`.
  2. Run:
     ```bash
headroom wrap omp --no-proxy -- -p "Reply with exactly:
HEADROOM_OMP_CODEX_OK" \
       --model openai-codex/gpt-5.6-sol --no-session --no-tools \
--no-extensions --no-skills --no-rules --thinking off --max-time 30s
     ```
  3. Inspect `/stats` and the managed `~/.omp/agent/models.yml`.
- Observed result: OMP returned the expected sentinel, Headroom recorded
one new project request, and all three provider overrides were present.
  - Wrap printed all three routes:
    ```text
    providers.anthropic.baseUrl=http://127.0.0.1:8787/p/headroom
    providers.openai.baseUrl=http://127.0.0.1:8787/p/headroom/v1
    providers.openai-codex.baseUrl=http://127.0.0.1:8787/p/headroom/v1
    ```
  - OMP returned exactly `HEADROOM_OMP_CODEX_OK`.
- Headroom `/stats` recorded the new request under project `headroom`
(`requests` increased from 2 to 3;
`last_activity_at=2026-08-04T02:14:07Z`).
- The managed `models.yml` contained all three overrides; the pristine
backup remained the restore source.
- The running 0.33.0 proxy does not contain the project-prefixed
WebSocket fix from #2379, so this proves fallback-capable request
completion rather than a clean WebSocket upgrade.
- Not tested: a clean project-prefixed WebSocket upgrade against a
release containing #2379; live `openai` API-key request; Windows/Linux;
a long interactive or explicitly isolated WebSocket session; completion
of the full unrelated pytest suite.

## Review Readiness

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

An independent review pass found no correctness or security findings
(confidence 0.96).

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes —
affected tests pass; full suite did not finish as documented above
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title

## Screenshots (if applicable)

N/A — terminal evidence is included above.

## Additional Notes

Release prerequisite: Headroom 0.33.0 has a `/p/<project>` WebSocket
upgrade bug that returns 403 before routing. It was independently fixed
and merged in #2379 (`789a4f3060aa33a5bae82680968c3e367fa2db83`). This
PR builds on `main`, which already contains that fix; stable interactive
OMP WebSocket routing requires a release/backport containing #2379.

The OpenAI API-key provider and ChatGPT/Codex OAuth provider
intentionally share the local `/v1` base URL. Headroom distinguishes
PAYG API keys from Codex OAuth JWT/account headers and forwards each
request to the correct upstream.
<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2755"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
2026-11-03 22:29:59 -06:00

322 lines
12 KiB
Python

"""Tests for `headroom wrap omp` / `headroom unwrap omp`.
Covers the omp runtime override contract (fresh-create vs merge-preserving
injection, pristine backups, re-injection idempotency, restore statuses) and
the CLI wiring that drives it. Every test isolates omp's agent directory via
``PI_CODING_AGENT_DIR`` and runs from a tmp cwd so the real ``~/.omp`` is
never touched.
"""
from __future__ import annotations
from pathlib import Path
from unittest.mock import patch
import pytest
import yaml
from click.testing import CliRunner
from headroom.cli.main import main
from headroom.providers.omp import (
MANAGED_MARKER,
backup_path,
build_launch_env,
inject_models_override,
models_yml_path,
restore_models_override,
)
@pytest.fixture
def runner() -> CliRunner:
return CliRunner()
@pytest.fixture
def omp_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Isolate omp's agent dir under tmp_path and run from a tmp cwd.
Returns the ``models.yml`` path the runtime resolves to.
"""
agent_dir = tmp_path / "omp-agent"
agent_dir.mkdir()
monkeypatch.setenv("PI_CODING_AGENT_DIR", str(agent_dir))
monkeypatch.chdir(tmp_path)
return agent_dir / "models.yml"
# ---------------------------------------------------------------------------
# runtime: path resolution
# ---------------------------------------------------------------------------
def test_models_yml_path_honors_pi_coding_agent_dir(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
custom = tmp_path / "relocated-agent"
monkeypatch.setenv("PI_CODING_AGENT_DIR", str(custom))
monkeypatch.chdir(tmp_path)
assert models_yml_path() == custom / "models.yml"
# ---------------------------------------------------------------------------
# runtime: injection
# ---------------------------------------------------------------------------
def test_inject_fresh_create_writes_managed_marker_and_no_backup(omp_home: Path) -> None:
models_file, base_url = inject_models_override(8787, "proj")
assert models_file == omp_home
assert base_url == "http://127.0.0.1:8787/p/proj"
text = models_file.read_text(encoding="utf-8")
providers = yaml.safe_load(text)["providers"]
openai_base_url = "http://127.0.0.1:8787/p/proj/v1"
assert MANAGED_MARKER in text
assert providers["anthropic"]["baseUrl"] == base_url
assert providers["openai"]["baseUrl"] == openai_base_url
assert providers["openai-codex"]["baseUrl"] == openai_base_url
# Nothing pre-existed, so there is nothing to snapshot.
assert not backup_path(models_file).exists()
def test_inject_over_existing_backs_up_pristine_and_merges(omp_home: Path) -> None:
original = (
"providers:\n"
" anthropic:\n"
" apiKey: sk-user-secret\n"
" openai:\n"
" baseUrl: https://api.openai.com/v1\n"
" apiKey: sk-user-openai\n"
" openai-codex:\n"
" baseUrl: https://chatgpt.com/backend-api/codex\n"
" oauth: true\n"
"models:\n"
" - id: my-custom-model\n"
)
omp_home.write_bytes(original.encode("utf-8"))
_, base_url = inject_models_override(8787, "proj")
# Pre-wrap file is snapshotted byte-for-byte.
assert backup_path(omp_home).read_bytes() == original.encode("utf-8")
merged = yaml.safe_load(omp_home.read_text(encoding="utf-8"))
assert merged["providers"]["anthropic"]["baseUrl"] == base_url
openai_base_url = "http://127.0.0.1:8787/p/proj/v1"
assert merged["providers"]["openai"]["baseUrl"] == openai_base_url
assert merged["providers"]["openai"]["apiKey"] == "sk-user-openai"
assert merged["providers"]["openai-codex"]["baseUrl"] == openai_base_url
assert merged["providers"]["openai-codex"]["oauth"] is True
# Only supported provider base URLs are set; every other user key survives.
assert merged["providers"]["anthropic"]["apiKey"] == "sk-user-secret"
assert merged["models"] == [{"id": "my-custom-model"}]
assert MANAGED_MARKER in omp_home.read_text(encoding="utf-8")
def test_reinject_new_port_regenerates_from_pristine_backup(omp_home: Path) -> None:
original = "providers:\n anthropic:\n apiKey: sk-user-secret\n"
omp_home.write_bytes(original.encode("utf-8"))
backup = backup_path(omp_home)
inject_models_override(8787, "proj")
assert backup.read_bytes() == original.encode("utf-8")
_, base_url_9999 = inject_models_override(9999, "proj")
# Re-injection never clobbers the pristine pre-wrap backup.
assert backup.read_bytes() == original.encode("utf-8")
merged = yaml.safe_load(omp_home.read_text(encoding="utf-8"))
assert base_url_9999 == "http://127.0.0.1:9999/p/proj"
assert merged["providers"]["anthropic"]["baseUrl"] == base_url_9999
assert merged["providers"]["openai"]["baseUrl"] == "http://127.0.0.1:9999/p/proj/v1"
assert merged["providers"]["openai-codex"]["baseUrl"] == "http://127.0.0.1:9999/p/proj/v1"
# Regenerated from the backup, so user creds still survive the new port.
assert merged["providers"]["anthropic"]["apiKey"] == "sk-user-secret"
# ---------------------------------------------------------------------------
# runtime: restore
# ---------------------------------------------------------------------------
def test_restore_restores_pristine_and_removes_backup(omp_home: Path) -> None:
original = "providers:\n anthropic:\n apiKey: sk-user-secret\n"
omp_home.write_bytes(original.encode("utf-8"))
inject_models_override(8787, "proj")
assert restore_models_override() == "restored"
assert omp_home.read_bytes() == original.encode("utf-8")
assert not backup_path(omp_home).exists()
def test_restore_removes_wrap_created_file(omp_home: Path) -> None:
inject_models_override(8787, "proj") # fresh create → no backup
assert omp_home.exists()
assert restore_models_override() == "removed"
assert not omp_home.exists()
assert not backup_path(omp_home).exists()
def test_restore_noop_when_nothing_managed(omp_home: Path) -> None:
assert restore_models_override() == "noop"
def test_restore_leaves_unmanaged_file_untouched(omp_home: Path) -> None:
user_content = "providers:\n anthropic:\n apiKey: sk-user-secret\n"
omp_home.write_bytes(user_content.encode("utf-8"))
assert restore_models_override() == "noop"
# A models.yml the wrap does not manage is never modified or deleted.
assert omp_home.read_bytes() == user_content.encode("utf-8")
assert not backup_path(omp_home).exists()
# ---------------------------------------------------------------------------
# runtime: launch env
# ---------------------------------------------------------------------------
def test_build_launch_env_passes_env_through_and_emits_display(omp_home: Path) -> None:
source = {"PATH": "/usr/bin", "ANTHROPIC_BASE_URL": "https://api.anthropic.com"}
env, display = build_launch_env(8787, source, project="proj")
# The redirects live in models.yml, so env is a verbatim copy — notably
# ANTHROPIC_BASE_URL is NOT rewritten to the proxy.
assert env == source
assert env is not source # a copy, so caller's environ can't be mutated
assert display == [
"models.yml: providers.anthropic.baseUrl=http://127.0.0.1:8787/p/proj",
"models.yml: providers.openai.baseUrl=http://127.0.0.1:8787/p/proj/v1",
"models.yml: providers.openai-codex.baseUrl=http://127.0.0.1:8787/p/proj/v1",
]
# ---------------------------------------------------------------------------
# CLI: wrap omp
# ---------------------------------------------------------------------------
def test_wrap_omp_missing_binary_exits_with_install_hint(runner: CliRunner, omp_home: Path) -> None:
with patch("headroom.cli.wrap.shutil.which", return_value=None):
result = runner.invoke(main, ["wrap", "omp"])
assert result.exit_code == 1
assert "npm install -g @oh-my-pi/pi-coding-agent" in result.output
# Fail fast before mutating omp's config.
assert not omp_home.exists()
def test_wrap_omp_happy_path_injects_before_launch(runner: CliRunner, omp_home: Path) -> None:
captured: dict[str, object] = {}
def fake_launch_tool(**kwargs: object) -> None:
captured.update(kwargs)
# Prove models.yml is on disk BEFORE omp is launched.
captured["models_text_at_launch"] = (
omp_home.read_text(encoding="utf-8") if omp_home.exists() else None
)
with (
patch("headroom.cli.wrap.shutil.which", return_value="omp"),
patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool),
):
result = runner.invoke(main, ["wrap", "omp", "--", "-p", "fix the bug"])
assert result.exit_code == 0, result.output
assert captured["tool_label"] == "OMP"
assert captured["agent_type"] == "omp"
assert captured["args"] == ("-p", "fix the bug")
text_at_launch = captured["models_text_at_launch"]
assert isinstance(text_at_launch, str)
assert MANAGED_MARKER in text_at_launch
providers = yaml.safe_load(text_at_launch)["providers"]
base_url = providers["anthropic"]["baseUrl"]
openai_base_url = providers["openai"]["baseUrl"]
assert base_url.startswith("http://127.0.0.1:8787/p/")
assert openai_base_url == f"{base_url}/v1"
assert providers["openai-codex"]["baseUrl"] == openai_base_url
display = captured["env_vars_display"]
assert isinstance(display, list)
assert f"models.yml: providers.anthropic.baseUrl={base_url}" in display
assert f"models.yml: providers.openai.baseUrl={openai_base_url}" in display
assert f"models.yml: providers.openai-codex.baseUrl={openai_base_url}" in display
def test_wrap_omp_does_not_write_agents_md(
runner: CliRunner, omp_home: Path, tmp_path: Path
) -> None:
"""`wrap omp` redirects via models.yml only; it never authors AGENTS.md."""
with (
patch("headroom.cli.wrap.shutil.which", return_value="omp"),
patch("headroom.cli.wrap._launch_tool"),
):
result = runner.invoke(main, ["wrap", "omp"])
assert result.exit_code == 0, result.output
assert not (tmp_path / "AGENTS.md").exists()
# ---------------------------------------------------------------------------
# CLI: unwrap omp
# ---------------------------------------------------------------------------
def test_unwrap_omp_restores_pristine_and_stops_proxy(runner: CliRunner, omp_home: Path) -> None:
original = "providers:\n anthropic:\n apiKey: sk-user-secret\n"
omp_home.write_bytes(original.encode("utf-8"))
inject_models_override(8787, "proj")
stopped: list[int] = []
with patch(
"headroom.cli.wrap._stop_local_proxy_for_unwrap",
side_effect=lambda port: stopped.append(port) or "not_running",
):
result = runner.invoke(main, ["unwrap", "omp"])
assert result.exit_code == 0, result.output
assert "Restored pre-wrap models.yml" in result.output
assert omp_home.read_bytes() == original.encode("utf-8")
assert not backup_path(omp_home).exists()
# A real restore (not a noop) attempts to stop the proxy on the given port.
assert stopped == [8787]
def test_unwrap_omp_removes_wrap_created_file(runner: CliRunner, omp_home: Path) -> None:
inject_models_override(8787, "proj") # fresh create → no backup
stopped: list[int] = []
with patch(
"headroom.cli.wrap._stop_local_proxy_for_unwrap",
side_effect=lambda port: stopped.append(port) or "not_running",
):
result = runner.invoke(main, ["unwrap", "omp", "--port", "9191"])
assert result.exit_code == 0, result.output
assert "Removed wrap-created models.yml" in result.output
assert not omp_home.exists()
assert stopped == [9191]
def test_unwrap_omp_noop_leaves_unmanaged_and_skips_proxy_stop(
runner: CliRunner, omp_home: Path
) -> None:
user_content = "providers:\n anthropic:\n apiKey: sk-user-secret\n"
omp_home.write_bytes(user_content.encode("utf-8"))
with patch("headroom.cli.wrap._stop_local_proxy_for_unwrap") as stop_proxy:
result = runner.invoke(main, ["unwrap", "omp"])
assert result.exit_code == 0, result.output
assert "nothing to restore" in result.output
# Unmanaged file is left exactly as the user had it.
assert omp_home.read_bytes() == user_content.encode("utf-8")
# noop status → the proxy is left running (the `status != "noop"` guard).
stop_proxy.assert_not_called()