fix(doctor): detect Codex routing via active provider base_url (#2618)

## Description

`headroom doctor` only treated Codex as routed when `config.toml`
contained a literal `[model_providers.headroom]` section. Safe installs
that keep a preserved provider ID (for example `codex-lb`) and only
point that provider's `base_url` at the local proxy were reported as not
routed, with a misleading wrap hint.

This change resolves the active `model_provider`, reads that section's
`base_url`, and classifies loopback routing the same way as other doctor
checks. The headroom section remains the fallback when no active
provider is set.

Closes #2614

## 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

- Resolve `model_provider` and scope `base_url` lookup to that provider
table in `check_codex_routing`
- Reuse `_classify_routing_url` for pass / port-mismatch / non-loopback
outcomes
- Keep best-effort WARN-not-crash behavior for missing or malformed
configs
- Add regression tests for preserved provider IDs and active-provider
precedence

## Testing

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

### Test Output

```text
$ PYTHONPATH=. python -m pytest -q tests/test_cli_doctor.py -o addopts=
71 passed, 1 warning in 0.78s

$ uvx --from ruff==0.15.17 ruff check headroom/cli/doctor.py tests/test_cli_doctor.py
All checks passed!

$ uvx --from ruff==0.15.17 ruff format --check headroom/cli/doctor.py tests/test_cli_doctor.py
2 files already formatted
```

## Real Behavior Proof

- Environment: Linux VPS, Python 3.11.15, shallow checkout of headroom
main at fix/doctor-codex-preserved-provider-id (cab1dde)
- Exact command / steps: Wrote a temp Codex config with `model_provider
= "codex-lb"` and `base_url = "http://127.0.0.1:8787/v1"`; ran
`PYTHONPATH=. python -m pytest -q
tests/test_cli_doctor.py::TestCodexRouting -o addopts=`; also ran full
`tests/test_cli_doctor.py` and ruff check/format on the two touched
files
- Observed result: Preserved-provider case now PASSes without a wrap
hint; port-mismatch WARNs with the wrong port; existing headroom-marker
and no-marker cases still pass; 71 doctor tests green
- Not tested: Live `headroom doctor` against a real Codex install on
this machine; mypy; full monorepo CI

## 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
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] 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
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

- Scoped to doctor routing detection only; no wrap/install writer
changes
- mypy not run on this VPS for this change

Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
AxelRay
2026-09-09 13:36:11 -05:00
committed by GitHub
co-authored by JD Davis
parent 3eba2d6066
commit 4794d688a9
2 changed files with 91 additions and 23 deletions
+39 -23
View File
@@ -49,7 +49,8 @@ FAIL = "fail"
SKIP = "skip"
_LOOPBACK_URL_RE = re.compile(r"https?://(?:127\.0\.0\.1|localhost):(\d+)")
_CODEX_BASE_URL_RE = re.compile(r'base_url\s*=\s*"https?://(?:127\.0\.0\.1|localhost):(\d+)')
_CODEX_BASE_URL_RE = re.compile(r'(?m)^[ \t]*base_url\s*=\s*"([^"\r\n]+)"')
_CODEX_MODEL_PROVIDER_RE = re.compile(r'(?m)^[ \t]*model_provider\s*=\s*"([^"\r\n]+)"')
# Ollama's fixed default port. `ollama launch claude` writes
# ``ANTHROPIC_BASE_URL=http://127.0.0.1:11434`` into the launched Claude Code
@@ -402,9 +403,10 @@ def check_wrap_marker_staleness(settings_path: Path) -> CheckResult:
def check_codex_routing(config_path: Path, port: int) -> CheckResult:
"""Is Codex configured to route through the proxy?
Detection keys on the ``[model_providers.headroom]`` section, which both
writers emit (install's persistent block and wrap's auto-injected block).
Substring matching keeps malformed TOML a WARN instead of a crash.
Detection prefers the active ``model_provider`` section's loopback
``base_url``, while retaining the ``[model_providers.headroom]`` fallback
emitted by persistent and wrap installs. Best-effort matching keeps
malformed TOML a WARN instead of a crash.
"""
name = "codex"
if not config_path.exists():
@@ -418,42 +420,56 @@ def check_codex_routing(config_path: Path, port: int) -> CheckResult:
text = config_path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
return CheckResult(name=name, status=WARN, summary=f"could not read {config_path}: {exc}")
if "[model_providers.headroom]" not in text:
active_match = _CODEX_MODEL_PROVIDER_RE.search(text)
provider_id = active_match.group(1) if active_match else "headroom"
base_url = _codex_provider_base_url(text, provider_id)
if base_url is None:
return CheckResult(
name=name,
status=WARN,
summary="not routed (no Headroom provider in config.toml)",
summary="not routed (no active provider base_url in config.toml)",
hint="wrap it: headroom wrap codex",
)
match = _CODEX_BASE_URL_RE.search(text)
if match and int(match.group(1)) != port:
return CheckResult(
name=name,
status=WARN,
summary=f"routed to port {match.group(1)}, but doctor probed port {port}",
hint=f"re-run with: headroom doctor --port {match.group(1)}",
)
routing = _classify_routing_url(name, base_url, port, source=str(config_path))
if routing.status != PASS:
return routing
# Routed, but Codex may still attach no credentials. A ChatGPT-OAuth user
# needs `requires_openai_auth = true` in the provider block or Codex sends
# no Authorization header at all and every request 401s with "Missing
# bearer" (#3206). That failure is invisible from here -- the proxy is up,
# the block is present -- so this check is the only place it can surface.
if _codex_block_missing_openai_auth(text, config_path):
# needs `requires_openai_auth = true` in the active provider block or Codex
# sends no Authorization header and every request fails with 401 (#3206).
if _codex_block_missing_openai_auth(text, config_path, provider_id):
return CheckResult(
name=name,
status=WARN,
summary="routed, but Codex will send no Authorization (missing requires_openai_auth)",
hint="re-run: headroom wrap codex (or headroom init codex) to rewrite the block",
)
return CheckResult(name=name, status=PASS, summary=f"routed ({config_path})")
return routing
def _codex_block_missing_openai_auth(text: str, config_path: Path) -> bool:
def _codex_provider_base_url(text: str, provider_id: str) -> str | None:
section_match = re.search(
rf"(?m)^[ \t]*\[model_providers\.{re.escape(provider_id)}\][ \t]*(?:#.*)?$",
text,
)
if section_match is None:
return None
section = text[section_match.end() :]
next_section = re.search(r"(?m)^[ \t]*\[", section)
if next_section is not None:
section = section[: next_section.start()]
base_url_match = _CODEX_BASE_URL_RE.search(section)
return base_url_match.group(1) if base_url_match else None
def _codex_block_missing_openai_auth(
text: str, config_path: Path, provider_id: str = "headroom"
) -> bool:
"""ChatGPT-OAuth Codex routed without ``requires_openai_auth`` (#3206)."""
start = text.find("[model_providers.headroom]")
section = f"[model_providers.{provider_id}]"
start = text.find(section)
if start == -1:
return False
rest = text[start + len("[model_providers.headroom]") :]
rest = text[start + len(section) :]
end = rest.find("\n[")
block = rest if end == -1 else rest[:end]
if "requires_openai_auth" in block:
+52
View File
@@ -468,6 +468,44 @@ class TestCodexRouting:
)
assert check_codex_routing(path, 8787).status == PASS
def test_preserved_provider_id_right_port_passes(self, tmp_path):
path = tmp_path / "config.toml"
path.write_text(
'model_provider = "codex-lb"\n'
"[model_providers.codex-lb]\n"
'base_url = "http://127.0.0.1:8787/v1"\n',
encoding="utf-8",
)
result = check_codex_routing(path, 8787)
assert result.status == PASS
assert result.hint is None
def test_preserved_provider_id_port_mismatch_warns(self, tmp_path):
path = tmp_path / "config.toml"
path.write_text(
'model_provider = "codex-lb"\n'
"[model_providers.codex-lb]\n"
'base_url = "http://localhost:9999/v1"\n',
encoding="utf-8",
)
result = check_codex_routing(path, 8787)
assert result.status == WARN
assert "9999" in result.summary
def test_active_provider_takes_precedence_over_headroom_block(self, tmp_path):
path = tmp_path / "config.toml"
path.write_text(
'model_provider = "corp"\n'
"[model_providers.corp]\n"
'base_url = "https://gateway.corp.example/v1"\n'
"[model_providers.headroom]\n"
'base_url = "http://127.0.0.1:8787/v1"\n',
encoding="utf-8",
)
result = check_codex_routing(path, 8787)
assert result.status == WARN
assert "gateway.corp.example" in result.summary
def test_port_mismatch_warns(self, tmp_path):
path = tmp_path / "config.toml"
path.write_text(
@@ -526,6 +564,20 @@ class TestCodexRouting:
assert check_codex_routing(path, 8787).status == PASS
def test_preserved_provider_id_without_requires_openai_auth_warns(self, tmp_path):
path = tmp_path / "config.toml"
path.write_text(
'model_provider = "codex-lb"\n'
"[model_providers.codex-lb]\n"
'base_url = "http://127.0.0.1:8787/v1"\n',
encoding="utf-8",
)
self._chatgpt_auth(tmp_path)
result = check_codex_routing(path, 8787)
assert result.status == WARN
assert "Authorization" in result.summary
def test_api_key_user_without_requires_openai_auth_still_passes(self, tmp_path):
"""API-key users must not be nagged -- the flag would break them (#406)."""
path = self._routed(tmp_path, requires_auth=False)