mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 18:41:07 +08:00
## Description `headroom wrap copilot` can intentionally start a dedicated proxy on port 8788 (or fall forward when 8787 is busy), but read-only CLI commands previously defaulted directly to 8787. As a result, `headroom dashboard` could open a dead or unrelated dashboard even though the wrapped session reported its proxy on 8788. This change extends the shared `headroom/cli/port_discovery.py` resolver (introduced by #3855) to include live wrap-client markers, preferring the newest healthy session while preserving explicit `--port` and `HEADROOM_PORT` overrides. Closes: N/A (no matching open issue found) ## 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) - [x] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Extended the shared port discovery module from #3855 with live wrap-client marker validation (PID liveness and reuse checks), newest-session ordering, and `/health` verification. - Updated `dashboard`, `inspect`, and the runtime probe used by `learn` to follow the newest healthy live wrap session after explicit and `HEADROOM_PORT` overrides. - Kept `doctor`'s requested-port behavior; it now reports a healthy proxy discovered from wrap-client markers elsewhere, with a `--port` hint. - Added a warning when `dashboard` cannot reach the resolved port. - Exported the actual proxy port as `HEADROOM_PORT` into every wrapped agent environment. - Reused #3855's port-discovery module rather than introducing a parallel resolver. - Added regression coverage for stale/recycled markers, multiple sessions, explicit/environment overrides, dashboard output, doctor diagnostics, inspect/learn routing, and wrapped child environments. - Documented automatic discovery and wrong-port troubleshooting. ## 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 pytest tests/test_cli/test_proxy_port_discovery.py \ tests/test_cli/test_dashboard_port_discovery.py \ tests/test_cli/test_port_alignment.py \ tests/test_cli/test_wrap_helpers.py \ tests/test_cli_doctor.py tests/test_cli_inspect.py tests/test_cli_learn.py -q 267 passed in 5.49s $ uv run ruff check . All checks passed! $ uv run ruff format --check . 1677 files already formatted $ uv run mypy headroom/cli/port_discovery.py headroom/cli/proxy.py \ headroom/cli/doctor.py headroom/cli/inspect.py headroom/cli/learn.py Success: no issues found in 5 source files $ uv run pre-commit run --all-files Sync plugin versions.....................................................Passed Verify Ruff version alignment............................................Passed check for merge conflicts................................................Passed ruff (legacy alias)......................................................Passed ruff format..............................................................Passed mypy.....................................................................Passed ``` After the first rebase, `make ci-precheck` completed `cargo fmt --check` and `cargo clippy --workspace -- -D warnings`, then stalled in the existing Rust Magika/detection tests (multiple tests exceeded 60 seconds). The same stall recurred during the push hook; it was stopped after confirming the affected suite. The final rebase onto #3883 was followed by the Python/CLI regression suite and all repository pre-commit gates above, but not another Rust test run. ## Real Behavior Proof - Environment: Ubuntu 22.04.5 LTS x86_64; Python 3.10.12; uv 0.12.10; Headroom proxy 0.40.0-dev, started on isolated port 18788 with an isolated live-client marker. - Exact command / steps: Started an isolated process that wrote its live PID marker and launched `headroom proxy --port 18788` under a temporary workspace, with `HEADROOM_PORT` unset; then ran `env -u HEADROOM_PORT -u HEADROOM_PORT_DISCOVERY HEADROOM_WORKSPACE_DIR=/tmp/headroom-port-discovery-proof-20260930/workspace ./.venv/bin/headroom dashboard --no-open` and curled `http://127.0.0.1:18788/dashboard`. ```text $ env -u HEADROOM_PORT -u HEADROOM_PORT_DISCOVERY \ HEADROOM_WORKSPACE_DIR=/tmp/headroom-port-discovery-proof-20260930/workspace \ ./.venv/bin/headroom dashboard --no-open Detected live proxy on port 18788 Dashboard: http://127.0.0.1:18788/dashboard $ curl --max-time 5 -sS -o /dev/null -w '%{http_code}\n' \ http://127.0.0.1:18788/dashboard 200 # Proxy health before discovery returned: service=headroom-proxy status=healthy ready=true ``` - Observed result: With `HEADROOM_PORT` unset, the CLI selected the marker-associated healthy proxy on 18788, printed the matching dashboard URL, and the endpoint returned HTTP 200. The earlier manual run with a real wrapped Copilot session also confirmed discovery on 8788 before this rebase. - Not tested: Starting a new interactive `wrap copilot` session after this rebase (avoided launching an agent); Windows/macOS PID-identity behavior; multiple simultaneous real proxies; browser UI launch. Unit tests cover marker ordering, PID reuse, and explicit/environment overrides. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A. - Stable/default behavior changed: `dashboard`, `inspect`, and `learn` now follow the newest healthy live wrap proxy when no port override is set; `doctor` remains on the requested/default port and reports a live proxy elsewhere. - Kill switch / disable path: Pass `--port`, set `HEADROOM_PORT`, or set `HEADROOM_PORT_DISCOVERY=0` to bypass automatic discovery. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert this commit; commands return to the fixed 8787 default. ## 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 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 - [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 ## Screenshots (if applicable) N/A — terminal output above captures the behavior. ## Additional Notes Port discovery is integrated into #3855's shared `port_discovery.py`; candidates are accepted only when `/health` identifies `service: headroom-proxy`, so an unrelated local JSON service cannot be mistaken for a Headroom proxy. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3522" 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 --> ### Maintainer current-main requalification Exact head `e66a6393f83278aa07e9965f5b87fed820603677`, upstream main `2d3ee51846435ef5b320eea4806af14e602b0d8c`. Re-reviewed latest integration head420c2d636and current author response, including isolated workspace/port fixtures and live-marker ordering/pruning regressions. Clean integration with upstream/main2d3ee51846. Explicit CLI ports and HEADROOM_PORT retain precedence; discovery bounds candidate probes, verifies Headroom health identity, prefers newest live wrap markers, and preserves configured-agent discovery. No new PR-specific correctness blocker found in scope. All 436 dashboard/port/discovery/wrap/doctor/inspect/learn/release/version/MCP tests pass. All 14 changed Python files pass Ruff check/format; whitespace passes. Previous cached-read freeze-boundary failure was independently reproduced on main and is not a contributor-code blocker. Maintainers handle fresh exact-head qualification and distinguish inherited failures; no contributor CI execution requested. Existing native extension supported startup, not a fresh native build. No contributor discovery logic rewritten; nothing merged. Exact-head hosted checks are being handled by maintainers. No new finding in the reviewed scope; formal approval awaits exact-head hosted qualification; nothing merged. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
136 lines
4.6 KiB
Python
136 lines
4.6 KiB
Python
"""Tests for the `headroom inspect` command (issue #1267).
|
|
|
|
The command reads the proxy's loopback ``/transformations/feed`` endpoint and
|
|
renders original-vs-compressed content. Tests stub ``probe_json`` so no proxy
|
|
is required.
|
|
|
|
Tests invoke the real top-level CLI (``main``) so the shipped command path —
|
|
including subcommand registration — is exercised, not just the command object.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
from click.testing import CliRunner
|
|
|
|
from headroom import paths as paths_mod
|
|
from headroom.cli.inspect import _extract_text, _role
|
|
|
|
|
|
def _run(args: list[str]):
|
|
from headroom.cli.main import main
|
|
|
|
return CliRunner().invoke(main, ["inspect", *args])
|
|
|
|
|
|
def test_extract_text_handles_str_and_blocks() -> None:
|
|
assert _extract_text("hello") == "hello"
|
|
assert _extract_text([{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]) == "a\nb"
|
|
# Nested tool_result content.
|
|
assert _extract_text([{"type": "tool_result", "content": [{"text": "x"}]}]) == "x"
|
|
# Unknown block falls back to JSON, never silently dropped.
|
|
assert "foo" in _extract_text([{"weird": "foo"}])
|
|
assert _extract_text(None) == ""
|
|
|
|
|
|
def test_role_extraction() -> None:
|
|
assert _role({"role": "user"}) == "user"
|
|
assert _role("not a dict") == "?"
|
|
|
|
|
|
def test_no_proxy_errors_cleanly() -> None:
|
|
with patch("headroom.install.health.probe_json", return_value=None):
|
|
result = _run([])
|
|
assert result.exit_code != 0
|
|
assert "No reachable proxy" in result.output
|
|
|
|
|
|
def test_log_messages_disabled_hint() -> None:
|
|
payload = {"transformations": [], "log_full_messages": False}
|
|
with patch("headroom.install.health.probe_json", return_value=payload):
|
|
result = _run([])
|
|
assert result.exit_code != 0
|
|
assert "--log-messages" in result.output
|
|
|
|
|
|
def test_empty_feed_message() -> None:
|
|
payload = {"transformations": [], "log_full_messages": True}
|
|
with patch("headroom.install.health.probe_json", return_value=payload):
|
|
result = _run([])
|
|
assert result.exit_code == 0
|
|
assert "No requests recorded" in result.output
|
|
|
|
|
|
def _feed_payload() -> dict:
|
|
return {
|
|
"log_full_messages": True,
|
|
"transformations": [
|
|
{
|
|
"request_id": "req-1",
|
|
"model": "gpt-4o",
|
|
"input_tokens_original": 100,
|
|
"input_tokens_optimized": 40,
|
|
"tokens_saved": 60,
|
|
"savings_percent": 60.0,
|
|
"transforms_applied": ["SmartCrusher"],
|
|
"request_messages": [
|
|
{"role": "user", "content": "line one\nline two\nline three"},
|
|
],
|
|
"compressed_messages": [
|
|
{"role": "user", "content": "line one\nline three"},
|
|
],
|
|
}
|
|
],
|
|
}
|
|
|
|
|
|
def test_text_render_shows_diff_and_header() -> None:
|
|
with patch("headroom.install.health.probe_json", return_value=_feed_payload()):
|
|
result = _run([])
|
|
assert result.exit_code == 0
|
|
out = result.output
|
|
assert "req-1" in out
|
|
assert "gpt-4o" in out
|
|
assert "SmartCrusher" in out
|
|
# The removed line shows up on the original side of the diff.
|
|
assert "line two" in out
|
|
|
|
|
|
def test_json_format_emits_raw_feed() -> None:
|
|
with patch("headroom.install.health.probe_json", return_value=_feed_payload()):
|
|
result = _run(["--format", "json"])
|
|
assert result.exit_code == 0
|
|
parsed = json.loads(result.output)
|
|
assert parsed[0]["request_id"] == "req-1"
|
|
|
|
|
|
def test_inspect_uses_the_live_wrap_marker_port(tmp_path: Path, monkeypatch) -> None:
|
|
from headroom.cli import port_discovery
|
|
|
|
workspace = tmp_path / "workspace"
|
|
marker = workspace / "clients" / "8788" / "4242.json"
|
|
marker.parent.mkdir(parents=True)
|
|
marker.write_text(json.dumps({"pid": 4242, "started_at": 100.0}), encoding="utf-8")
|
|
monkeypatch.setattr(paths_mod, "workspace_dir", lambda: workspace)
|
|
monkeypatch.setattr(port_discovery, "pid_alive", lambda pid: pid == 4242)
|
|
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
|
monkeypatch.delenv("HEADROOM_PORT_DISCOVERY", raising=False)
|
|
|
|
requested_urls: list[str] = []
|
|
|
|
def probe(url: str, timeout: float = 1.0):
|
|
requested_urls.append(url)
|
|
if url.endswith("/health"):
|
|
return {"service": "headroom-proxy"}
|
|
return _feed_payload()
|
|
|
|
with patch("headroom.install.health.probe_json", side_effect=probe):
|
|
result = _run([])
|
|
|
|
assert result.exit_code == 0, result.output
|
|
assert "http://127.0.0.1:8788/health" in requested_urls
|
|
assert "http://127.0.0.1:8788/transformations/feed?limit=1" in requested_urls
|