mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(cli): resolve active proxy port for read commands (#3522)
## 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>
This commit is contained in:
co-authored by
Copilot
JerrettDavis
parent
05431b264f
commit
02c4e922f7
@@ -357,12 +357,24 @@ The recommended way to install rust is using `rustup`. You can find the official
|
||||
Headroom serves a live savings dashboard while the proxy is running. Open it with:
|
||||
|
||||
```bash
|
||||
headroom dashboard # opens http://localhost:8787/dashboard in your browser
|
||||
headroom dashboard # opens the running proxy's dashboard in your browser
|
||||
headroom dashboard --no-open # just print the URL
|
||||
```
|
||||
|
||||
Or browse to `http://localhost:8787/dashboard` directly (use `--port` / `HEADROOM_PORT` if you
|
||||
run the proxy on a different port).
|
||||
With no `--port`, `headroom dashboard`, `headroom inspect` and the runtime probe used by
|
||||
`headroom learn` auto-detect the port of the most recently started live wrap session before
|
||||
falling back to `8787`. This matters because
|
||||
`headroom wrap ...` does not always land on `8787` — a Copilot-subscription session
|
||||
takes a dedicated port, and any wrap falls forward to the next free port when `8787`
|
||||
is busy, so a session can be serving on `8788` while `8787` is stale or empty.
|
||||
|
||||
Pass `--port` (or set `HEADROOM_PORT`) to target a specific proxy explicitly; an
|
||||
explicit value always wins over auto-detection. `headroom doctor` keeps the requested
|
||||
port and reports a live proxy found elsewhere, including one associated with a wrap
|
||||
session marker, so you can rerun it with the suggested `--port`.
|
||||
|
||||
If nothing is listening on the resolved port, the command prints a warning
|
||||
instead of silently opening a dead page.
|
||||
|
||||
## Next steps
|
||||
|
||||
|
||||
@@ -37,6 +37,35 @@ curl http://localhost:8787/health
|
||||
ps aux | grep headroom
|
||||
```
|
||||
|
||||
### Dashboard / doctor point at the wrong port
|
||||
|
||||
**Symptom**: `headroom wrap ...` reports the proxy on `8788` (or another port), but
|
||||
`headroom dashboard` opens `http://127.0.0.1:8787/dashboard`, which shows nothing.
|
||||
|
||||
`wrap` does not always use `8787`: a Copilot-subscription session takes a dedicated
|
||||
port so it never claims the shared one, and any wrap falls forward to the next free
|
||||
port when `8787` is already bound.
|
||||
|
||||
`headroom dashboard` and `headroom inspect` auto-detect the most recently started live
|
||||
wrap session, so this normally resolves itself. `headroom doctor` keeps the requested port
|
||||
and reports a live proxy found elsewhere, along with the command to rerun it against that
|
||||
port. If a read command still lands on the wrong port, an explicit value is overriding
|
||||
detection — check it:
|
||||
|
||||
```bash
|
||||
# An exported HEADROOM_PORT always wins over auto-detection
|
||||
echo $HEADROOM_PORT
|
||||
|
||||
# Which ports have live wrap sessions registered
|
||||
ls ~/.headroom/clients/
|
||||
|
||||
# Confirm which one actually answers
|
||||
curl -s http://127.0.0.1:8788/health
|
||||
|
||||
# Force a specific port
|
||||
headroom dashboard --port 8788
|
||||
```
|
||||
|
||||
### Proxy returns errors for some requests
|
||||
|
||||
**Symptom**: Some requests work, others fail with 502/503.
|
||||
|
||||
@@ -1247,8 +1247,8 @@ def doctor(
|
||||
live_elsewhere = None
|
||||
if livez is None:
|
||||
# Cheap, bounded: only ports Headroom recorded (HEADROOM_PORT, 8787,
|
||||
# deployment manifests, the project's wrap marker) and the ports the
|
||||
# agents are configured for, probed in parallel.
|
||||
# deployment manifests, project wrap markers, live client markers, and
|
||||
# ports agents are configured for), probed in parallel.
|
||||
live_elsewhere = find_live_proxy_elsewhere(
|
||||
port,
|
||||
manifests=manifests,
|
||||
|
||||
@@ -12,7 +12,6 @@ from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import json
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
@@ -117,8 +116,10 @@ def _render_request(transformation: dict[str, Any], *, full: bool) -> None:
|
||||
"-p",
|
||||
default=None,
|
||||
type=click.IntRange(1, 65535),
|
||||
envvar="HEADROOM_PORT",
|
||||
help="Proxy port to query (default: 8787, env: HEADROOM_PORT)",
|
||||
help=(
|
||||
"Proxy port to query. Defaults to auto-detecting the most recently "
|
||||
"started live wrap session (falls back to 8787). Env: HEADROOM_PORT."
|
||||
),
|
||||
)
|
||||
@click.option(
|
||||
"--last",
|
||||
@@ -152,9 +153,10 @@ def inspect_cmd(port: int | None, last: int, output_format: str, full: bool) ->
|
||||
headroom inspect --full Include unchanged messages
|
||||
headroom inspect --format json Raw feed for piping into another tool
|
||||
"""
|
||||
from headroom.cli.port_discovery import resolve_read_port
|
||||
from headroom.install.health import probe_json
|
||||
|
||||
resolved_port = port if port is not None else int(os.environ.get("HEADROOM_PORT", "8787"))
|
||||
resolved_port, _origin = resolve_read_port(port)
|
||||
base_url = f"http://127.0.0.1:{resolved_port}"
|
||||
payload = probe_json(f"{base_url}/transformations/feed?limit={last}", timeout=5.0)
|
||||
|
||||
|
||||
@@ -603,7 +603,9 @@ def _activate_output_shaper(
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
resolved_port = _local_proxy_port(port)
|
||||
from headroom.cli.port_discovery import resolve_read_port
|
||||
|
||||
resolved_port, _origin = resolve_read_port(port)
|
||||
overrides = {"HEADROOM_OUTPUT_SHAPER": "1"}
|
||||
if verbosity_level is not None:
|
||||
overrides["HEADROOM_VERBOSITY_LEVEL"] = verbosity_level
|
||||
|
||||
@@ -9,8 +9,9 @@ other ports Headroom itself recorded, so the CLI can warn -- or, on a TTY, ask
|
||||
-- instead of guessing.
|
||||
|
||||
Discovery is deliberately bounded: loopback only, a handful of candidate ports
|
||||
(the requested/default port, ``HEADROOM_PORT``, 8787, deployment-manifest ports
|
||||
and the project's wrap marker), probed concurrently with a sub-second timeout.
|
||||
(the requested/default port, ``HEADROOM_PORT``, 8787, live wrap-client markers,
|
||||
deployment-manifest ports and the project's wrap marker), probed concurrently
|
||||
with a sub-second timeout.
|
||||
It never scans port ranges. ``HEADROOM_PORT_DISCOVERY=0`` disables it.
|
||||
"""
|
||||
|
||||
@@ -26,11 +27,15 @@ from typing import Any
|
||||
|
||||
import click
|
||||
|
||||
from headroom import fsutil, paths
|
||||
from headroom._subprocess import identity_mismatch, pid_alive, proc_identity
|
||||
|
||||
DEFAULT_PROXY_PORT = 8787
|
||||
PORT_ENV = "HEADROOM_PORT"
|
||||
DISCOVERY_ENV = "HEADROOM_PORT_DISCOVERY"
|
||||
_PROBE_TIMEOUT_SECONDS = 0.5
|
||||
_MAX_CANDIDATES = 8
|
||||
_MAX_CLIENT_MARKER_CANDIDATES = 3
|
||||
_HEADROOM_SERVICE = "headroom-proxy"
|
||||
_LOOPBACK_PORT_RE = re.compile(r"^https?://(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)")
|
||||
|
||||
@@ -96,6 +101,75 @@ def _wrap_marker_ports(cwd: Path | None) -> list[int]:
|
||||
return [port] if port is not None else []
|
||||
|
||||
|
||||
def _marker_pid_reused(marker: Path, pid: int) -> bool:
|
||||
try:
|
||||
payload = json.loads(fsutil.read_text(marker))
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
if not isinstance(payload, dict):
|
||||
return False
|
||||
return identity_mismatch(
|
||||
payload.get("start_src"),
|
||||
payload.get("start_time"),
|
||||
pid,
|
||||
identity_fn=proc_identity,
|
||||
)
|
||||
|
||||
|
||||
def live_client_pids(port: int) -> list[int]:
|
||||
"""Live wrap-client PIDs for ``port``, pruning dead and recycled markers."""
|
||||
clients_dir = paths.proxy_clients_dir(port)
|
||||
if not clients_dir.exists():
|
||||
return []
|
||||
live: list[int] = []
|
||||
for marker in clients_dir.glob("*.json"):
|
||||
try:
|
||||
pid = int(marker.stem)
|
||||
except ValueError:
|
||||
continue
|
||||
if not pid_alive(pid) or _marker_pid_reused(marker, pid):
|
||||
try:
|
||||
marker.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
continue
|
||||
live.append(pid)
|
||||
return live
|
||||
|
||||
|
||||
def _marker_started_at(port: int, pid: int) -> float:
|
||||
marker = paths.proxy_clients_dir(port) / f"{pid}.json"
|
||||
try:
|
||||
payload = json.loads(fsutil.read_text(marker))
|
||||
except (OSError, ValueError):
|
||||
return 0.0
|
||||
if not isinstance(payload, dict):
|
||||
return 0.0
|
||||
started_at = payload.get("started_at")
|
||||
return float(started_at) if isinstance(started_at, int | float) else 0.0
|
||||
|
||||
|
||||
def live_client_proxy_ports() -> list[tuple[int, float]]:
|
||||
"""Return live-client ports, newest marker first as ``(port, started_at)``."""
|
||||
clients_dir = paths.workspace_dir() / "clients"
|
||||
try:
|
||||
entries = list(clients_dir.iterdir())
|
||||
except OSError:
|
||||
return []
|
||||
candidates: list[tuple[int, float]] = []
|
||||
for entry in entries:
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
port = _valid_port(entry.name)
|
||||
if port is None:
|
||||
continue
|
||||
pids = live_client_pids(port)
|
||||
if pids:
|
||||
candidates.append((port, max(_marker_started_at(port, pid) for pid in pids)))
|
||||
candidates.sort(key=lambda item: item[1], reverse=True)
|
||||
return candidates
|
||||
|
||||
|
||||
def candidate_ports(
|
||||
requested: int,
|
||||
*,
|
||||
@@ -113,6 +187,8 @@ def candidate_ports(
|
||||
ordered.extend(extra)
|
||||
ordered.extend(_manifest_ports(manifests))
|
||||
ordered.extend(_wrap_marker_ports(cwd))
|
||||
# Bounded and last so stale wrap sessions can't evict recorded deployments.
|
||||
ordered.extend(port for port, _ in live_client_proxy_ports()[:_MAX_CLIENT_MARKER_CANDIDATES])
|
||||
seen: list[int] = []
|
||||
for port in ordered:
|
||||
if port not in seen:
|
||||
@@ -186,6 +262,52 @@ def find_live_proxy_elsewhere(
|
||||
return next((port for port in alive if port != requested), None)
|
||||
|
||||
|
||||
def resolve_read_port(
|
||||
explicit: int | None, *, default: int = DEFAULT_PROXY_PORT
|
||||
) -> tuple[int, str]:
|
||||
"""Resolve a read-only command's proxy port, preferring the latest live wrap."""
|
||||
if explicit is not None:
|
||||
return explicit, "explicit"
|
||||
|
||||
raw_env_port = (os.environ.get(PORT_ENV) or "").strip()
|
||||
if raw_env_port:
|
||||
try:
|
||||
parsed = int(raw_env_port)
|
||||
except ValueError:
|
||||
raise click.ClickException(
|
||||
f"{PORT_ENV} must be an integer, got {raw_env_port!r}"
|
||||
) from None
|
||||
if not 1 <= parsed <= 65535:
|
||||
raise click.ClickException(f"{PORT_ENV} must be between 1 and 65535, got {parsed}")
|
||||
return parsed, "env"
|
||||
|
||||
if not discovery_enabled():
|
||||
return default, "default"
|
||||
|
||||
marker_ports = [port for port, _ in live_client_proxy_ports()[:_MAX_CLIENT_MARKER_CANDIDATES]]
|
||||
healthy_markers = live_ports(marker_ports, probe=proxy_is_healthy)
|
||||
if healthy_markers:
|
||||
return healthy_markers[0], "discovered"
|
||||
|
||||
already_probed = set(marker_ports)
|
||||
|
||||
def _probe_unchecked(port: int) -> bool:
|
||||
return port not in already_probed and proxy_is_healthy(port)
|
||||
|
||||
live_port = find_live_proxy_elsewhere(default, probe=_probe_unchecked)
|
||||
if live_port is not None:
|
||||
return live_port, "discovered"
|
||||
return default, "default"
|
||||
|
||||
|
||||
def proxy_is_healthy(port: int, timeout: float = 1.0) -> bool:
|
||||
"""True if ``/health`` identifies a live Headroom proxy on ``port``."""
|
||||
from headroom.install.health import probe_json
|
||||
|
||||
payload = probe_json(f"http://127.0.0.1:{port}/health", timeout=timeout)
|
||||
return payload is not None and payload.get("service") == _HEADROOM_SERVICE
|
||||
|
||||
|
||||
def _is_interactive() -> bool:
|
||||
try:
|
||||
return sys.stdin.isatty() and sys.stdout.isatty()
|
||||
|
||||
+24
-5
@@ -295,21 +295,40 @@ def _refuse_busy_port(host: str, port: int, *, workers: int) -> None:
|
||||
@click.option(
|
||||
"--port",
|
||||
"-p",
|
||||
default=8787,
|
||||
default=None,
|
||||
type=click.IntRange(1, 65535),
|
||||
envvar="HEADROOM_PORT",
|
||||
help="Proxy port (default: 8787, env: HEADROOM_PORT)",
|
||||
help=(
|
||||
"Proxy port. Defaults to auto-detecting the most recently started live "
|
||||
"wrap session (falls back to 8787). Env: HEADROOM_PORT."
|
||||
),
|
||||
)
|
||||
@click.option("--no-open", is_flag=True, help="Print the URL instead of opening a browser")
|
||||
def dashboard(port: int, no_open: bool) -> None:
|
||||
def dashboard(port: int | None, no_open: bool) -> None:
|
||||
"""Open the Headroom savings dashboard in your browser.
|
||||
|
||||
Requires a running proxy (start one with `headroom proxy` or `headroom wrap ...`).
|
||||
|
||||
With no ``--port``/``HEADROOM_PORT``, the port is auto-detected from live wrap
|
||||
sessions (e.g. a session bumped to 8788 because 8787 was taken) so the dashboard
|
||||
URL matches whatever proxy is actually running.
|
||||
"""
|
||||
import webbrowser
|
||||
|
||||
url = f"http://127.0.0.1:{port}/dashboard"
|
||||
from headroom.cli.port_discovery import proxy_is_healthy, resolve_read_port
|
||||
|
||||
resolved_port, origin = resolve_read_port(port)
|
||||
url = f"http://127.0.0.1:{resolved_port}/dashboard"
|
||||
if origin == "discovered":
|
||||
click.echo(f" Detected live proxy on port {resolved_port}")
|
||||
click.echo(f" Dashboard: {url}")
|
||||
if not proxy_is_healthy(resolved_port):
|
||||
click.secho(
|
||||
f" Warning: no proxy responding on port {resolved_port}. "
|
||||
"Start one with `headroom proxy` or `headroom wrap ...`, "
|
||||
"or pass --port explicitly.",
|
||||
fg="yellow",
|
||||
err=True,
|
||||
)
|
||||
if not no_open:
|
||||
try:
|
||||
webbrowser.open(url)
|
||||
|
||||
@@ -5669,6 +5669,10 @@ def _launch_tool(
|
||||
port_holder[0] = actual_port
|
||||
_push_runtime_env(actual_port, no_proxy)
|
||||
|
||||
# Let Headroom commands launched inside the wrapped session target the
|
||||
# proxy's actual port, including fallback/dedicated-session ports.
|
||||
env["HEADROOM_PORT"] = str(actual_port)
|
||||
|
||||
# If port fell back, update environment URLs to point at the actual port.
|
||||
if actual_port != port:
|
||||
for k, v in dict(env).items():
|
||||
@@ -6376,6 +6380,7 @@ def claude(
|
||||
click.echo()
|
||||
|
||||
env = os.environ.copy()
|
||||
env["HEADROOM_PORT"] = str(actual_port)
|
||||
if use_vertex:
|
||||
# Claude Code stays in Vertex mode (keeps CLAUDE_CODE_USE_VERTEX,
|
||||
# ANTHROPIC_VERTEX_PROJECT_ID, CLOUD_ML_REGION, ADC — all inherited);
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""CLI-level tests for `headroom dashboard` port auto-detection.
|
||||
|
||||
Regression coverage for: `headroom wrap copilot` (isolated-subscription path)
|
||||
starting the proxy on 8788 while `headroom dashboard` kept defaulting to the
|
||||
hardcoded 8787, so the printed/opened URL pointed at nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
from headroom import paths as paths_mod
|
||||
from headroom.cli.main import main
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def runner() -> CliRunner:
|
||||
return CliRunner()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def clients_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
workspace = tmp_path / "workspace"
|
||||
monkeypatch.setattr(paths_mod, "workspace_dir", lambda: workspace)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_PORT_DISCOVERY", raising=False)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
return workspace / "clients"
|
||||
|
||||
|
||||
def _write_marker(clients_root: Path, port: int, pid: int, *, started_at: float = 0.0) -> None:
|
||||
marker = clients_root / str(port) / f"{pid}.json"
|
||||
marker.parent.mkdir(parents=True, exist_ok=True)
|
||||
marker.write_text(json.dumps({"pid": pid, "started_at": started_at}))
|
||||
|
||||
|
||||
def test_dashboard_falls_back_to_8787_with_no_live_session(
|
||||
runner: CliRunner, clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from headroom.cli import port_discovery as pd
|
||||
|
||||
# Stub the health probe: without this the test would make a real request to
|
||||
# 127.0.0.1:8787 and pass/fail depending on whether the developer happens to
|
||||
# have a proxy running.
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: False)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
|
||||
result = runner.invoke(main, ["dashboard", "--no-open"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "http://127.0.0.1:8787/dashboard" in result.output
|
||||
assert "Warning" in result.output # nothing is actually listening
|
||||
|
||||
|
||||
def test_dashboard_discovers_live_session_on_fallback_port(
|
||||
runner: CliRunner, clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Pins the reported bug: wrap started the proxy on 8788, dashboard must follow."""
|
||||
from headroom.cli import port_discovery as pd
|
||||
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=100.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: port == 8788)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
|
||||
result = runner.invoke(main, ["dashboard", "--no-open"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "http://127.0.0.1:8788/dashboard" in result.output
|
||||
assert "Detected live proxy on port 8788" in result.output
|
||||
assert "Warning" not in result.output
|
||||
|
||||
|
||||
def test_dashboard_explicit_port_overrides_discovery(
|
||||
runner: CliRunner, clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from headroom.cli import port_discovery as pd
|
||||
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=100.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
|
||||
|
||||
result = runner.invoke(main, ["dashboard", "--no-open", "--port", "9999"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "http://127.0.0.1:9999/dashboard" in result.output
|
||||
assert "Detected live proxy" not in result.output
|
||||
|
||||
|
||||
def test_dashboard_env_port_overrides_discovery(
|
||||
runner: CliRunner, clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from headroom.cli import port_discovery as pd
|
||||
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=100.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
|
||||
monkeypatch.setenv("HEADROOM_PORT", "7000")
|
||||
|
||||
result = runner.invoke(main, ["dashboard", "--no-open"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "http://127.0.0.1:7000/dashboard" in result.output
|
||||
@@ -127,6 +127,14 @@ class TestCodexHome:
|
||||
|
||||
|
||||
class TestPortDiscovery:
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolate_live_client_discovery(
|
||||
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / "workspace"))
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_PORT_DISCOVERY", raising=False)
|
||||
|
||||
def test_default_port_reads_env(self) -> None:
|
||||
assert pd.default_port({}) == 8787
|
||||
assert pd.default_port({"HEADROOM_PORT": "9100"}) == 9100
|
||||
@@ -146,6 +154,36 @@ class TestPortDiscovery:
|
||||
)
|
||||
assert ports == [8787, 9100, 9200, 9300]
|
||||
|
||||
def test_candidates_order_live_client_markers_by_recency(
|
||||
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
clients = tmp_path / "workspace" / "clients"
|
||||
markers = {
|
||||
3001: (9000, 100.0),
|
||||
3002: (9001, 200.0),
|
||||
3003: (9002, 300.0),
|
||||
}
|
||||
for pid, (port, started_at) in markers.items():
|
||||
marker = clients / str(port) / f"{pid}.json"
|
||||
marker.parent.mkdir(parents=True, exist_ok=True)
|
||||
marker.write_text(json.dumps({"pid": pid, "started_at": started_at}), encoding="utf-8")
|
||||
dead_marker = clients / "9002" / "3003.json"
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: pid != 3003)
|
||||
|
||||
marker_path = tmp_path / ".claude" / ".headroom_wrap_marker.json"
|
||||
marker_path.parent.mkdir()
|
||||
marker_path.write_text(json.dumps({"port": 9300}), encoding="utf-8")
|
||||
ports = pd.candidate_ports(
|
||||
8787,
|
||||
environ={"HEADROOM_PORT": "9100"},
|
||||
manifests=[_manifest("profile", 9200)],
|
||||
cwd=tmp_path,
|
||||
extra=[9400],
|
||||
)
|
||||
|
||||
assert ports == [8787, 9100, 9400, 9200, 9300, 9001, 9000]
|
||||
assert not dead_marker.exists()
|
||||
|
||||
def test_candidates_are_bounded(self, tmp_path: Path) -> None:
|
||||
manifests = [_manifest(str(i), 10000 + i) for i in range(50)]
|
||||
ports = pd.candidate_ports(8787, environ={}, manifests=manifests, cwd=tmp_path)
|
||||
@@ -607,6 +645,33 @@ class TestDoctorAdditions:
|
||||
assert "port 9200" in proxy["summary"]
|
||||
assert "headroom doctor --port 9200" in proxy["hint"]
|
||||
|
||||
def test_doctor_names_live_proxy_from_client_marker(
|
||||
self, home: Path, tmp_path: Path, monkeypatch
|
||||
) -> None:
|
||||
marker = tmp_path / "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(pd, "pid_alive", lambda pid: pid == 4242)
|
||||
|
||||
def fake_probe(url: str, timeout: float = 2.0) -> dict[str, Any] | None:
|
||||
if url == "http://127.0.0.1:8788/livez":
|
||||
return {"service": "headroom-proxy", "alive": True, "version": "1"}
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(doctor_mod, "probe_json", fake_probe)
|
||||
monkeypatch.setattr(doctor_mod, "list_manifests", lambda: [])
|
||||
monkeypatch.setattr(doctor_mod, "check_deployments", lambda manifests: None)
|
||||
monkeypatch.setattr(doctor_mod, "claude_settings_path", lambda: home / "settings.json")
|
||||
monkeypatch.setattr(doctor_mod, "savings_path", lambda: home / "savings.json")
|
||||
|
||||
result = CliRunner().invoke(main, ["doctor", "--json"])
|
||||
|
||||
payload = json.loads(result.output)
|
||||
assert payload["port"] == 8787
|
||||
proxy = next(c for c in payload["checks"] if c["name"] == "proxy")
|
||||
assert "port 8788" in proxy["summary"]
|
||||
assert "headroom doctor --port 8788" in proxy["hint"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# wrap selfheal: warn (never repoint) when a live proxy exists elsewhere
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Unit tests for live wrap-client port discovery.
|
||||
|
||||
`headroom wrap copilot` (isolated-subscription path) or a plain port-busy
|
||||
fallback can start the proxy on a port other than 8787. Read-only commands
|
||||
(`dashboard`, `doctor`, `inspect`, `learn`) need to find that real port from
|
||||
the wrap-client marker files instead of blindly defaulting to 8787. These
|
||||
tests pin the discovery/resolution contract directly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from headroom import paths as paths_mod
|
||||
from headroom.cli import port_discovery as pd
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def clients_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Redirect ``paths.workspace_dir()`` (and therefore ``proxy_clients_dir``,
|
||||
which is built from it) into a throwaway tmp tree."""
|
||||
workspace = tmp_path / "workspace"
|
||||
monkeypatch.setattr(paths_mod, "workspace_dir", lambda: workspace)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_PORT_DISCOVERY", raising=False)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
return workspace / "clients"
|
||||
|
||||
|
||||
def _write_marker(clients_root: Path, port: int, pid: int, *, started_at: float = 0.0) -> Path:
|
||||
marker = clients_root / str(port) / f"{pid}.json"
|
||||
marker.parent.mkdir(parents=True, exist_ok=True)
|
||||
marker.write_text(json.dumps({"pid": pid, "started_at": started_at}))
|
||||
return marker
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# live_client_pids / live_client_proxy_ports
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_no_markers_means_no_live_ports(clients_root: Path) -> None:
|
||||
assert pd.live_client_proxy_ports() == []
|
||||
assert pd.live_client_pids(8787) == []
|
||||
|
||||
|
||||
def test_live_marker_is_discovered(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
_write_marker(clients_root, 8788, pid=4242, started_at=100.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: pid == 4242)
|
||||
|
||||
assert pd.live_client_pids(8788) == [4242]
|
||||
assert pd.live_client_proxy_ports() == [(8788, 100.0)]
|
||||
|
||||
|
||||
def test_dead_marker_is_pruned_and_not_counted(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
marker = _write_marker(clients_root, 8788, pid=999, started_at=100.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: False)
|
||||
|
||||
assert pd.live_client_pids(8788) == []
|
||||
assert pd.live_client_proxy_ports() == []
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
def test_recycled_pid_marker_is_pruned(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
marker = _write_marker(clients_root, 8788, pid=999, started_at=100.0)
|
||||
marker.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"pid": 999,
|
||||
"started_at": 100.0,
|
||||
"start_src": "psutil",
|
||||
"start_time": 1.0,
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proc_identity", lambda pid: ("psutil", 100.0))
|
||||
|
||||
assert pd.live_client_pids(8788) == []
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
def test_multiple_ports_sorted_newest_first(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
_write_marker(clients_root, 8787, pid=1, started_at=50.0)
|
||||
_write_marker(clients_root, 8788, pid=2, started_at=200.0)
|
||||
_write_marker(clients_root, 8790, pid=3, started_at=100.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
|
||||
assert pd.live_client_proxy_ports() == [(8788, 200.0), (8790, 100.0), (8787, 50.0)]
|
||||
|
||||
|
||||
def test_non_numeric_client_dirs_are_ignored(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
(clients_root / "not-a-port").mkdir(parents=True)
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
|
||||
assert pd.live_client_proxy_ports() == [(8788, 1.0)]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# resolve_read_port
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_explicit_port_always_wins(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
|
||||
|
||||
assert pd.resolve_read_port(9999) == (9999, "explicit")
|
||||
|
||||
|
||||
def test_env_var_wins_over_discovery(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
|
||||
monkeypatch.setenv("HEADROOM_PORT", "7000")
|
||||
|
||||
assert pd.resolve_read_port(None) == (7000, "env")
|
||||
|
||||
|
||||
def test_no_markers_falls_back_to_default(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: False)
|
||||
|
||||
assert pd.resolve_read_port(None) == (8787, "default")
|
||||
|
||||
|
||||
def test_healthy_live_marker_is_discovered(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: port == 8788)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
|
||||
assert pd.resolve_read_port(None) == (8788, "discovered")
|
||||
|
||||
|
||||
def test_unhealthy_marker_falls_back_to_default(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A live client marker with no proxy actually answering /health must not
|
||||
be trusted — falls back to the historical default instead of a dead URL."""
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: False)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
|
||||
assert pd.resolve_read_port(None) == (8787, "default")
|
||||
|
||||
|
||||
def test_newest_session_preferred_when_multiple_healthy(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
_write_marker(clients_root, 8787, pid=1, started_at=50.0)
|
||||
_write_marker(clients_root, 8788, pid=2, started_at=200.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
|
||||
assert pd.resolve_read_port(None) == (8788, "discovered")
|
||||
|
||||
|
||||
def test_falls_through_to_next_candidate_when_newest_is_unhealthy(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The newest session wins only if it is actually reachable; a stale/dead
|
||||
newest candidate must not shadow an older but healthy one."""
|
||||
_write_marker(clients_root, 8787, pid=1, started_at=50.0)
|
||||
_write_marker(clients_root, 8788, pid=2, started_at=200.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: port == 8787)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
|
||||
assert pd.resolve_read_port(None) == (8787, "discovered")
|
||||
|
||||
|
||||
def test_discovery_disabled_falls_back_to_default(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
|
||||
monkeypatch.setenv("HEADROOM_PORT_DISCOVERY", "0")
|
||||
|
||||
assert pd.resolve_read_port(None) == (8787, "default")
|
||||
|
||||
|
||||
def test_invalid_env_port_is_rejected(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("HEADROOM_PORT", "not-a-number")
|
||||
|
||||
with pytest.raises(click.ClickException, match="HEADROOM_PORT must be an integer"):
|
||||
pd.resolve_read_port(None)
|
||||
|
||||
|
||||
def test_out_of_range_env_port_is_rejected(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setenv("HEADROOM_PORT", "70000")
|
||||
|
||||
with pytest.raises(click.ClickException, match="HEADROOM_PORT must be between 1 and 65535"):
|
||||
pd.resolve_read_port(None)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# proxy_is_healthy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_proxy_is_healthy_true_when_health_reachable(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from headroom.install import health
|
||||
|
||||
monkeypatch.setattr(
|
||||
health,
|
||||
"probe_json",
|
||||
lambda url, timeout=1.0: {"service": "headroom-proxy", "status": "healthy"},
|
||||
)
|
||||
assert pd.proxy_is_healthy(8787) is True
|
||||
|
||||
|
||||
def test_proxy_is_healthy_false_when_unreachable(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from headroom.install import health
|
||||
|
||||
monkeypatch.setattr(health, "probe_json", lambda url, timeout=1.0: None)
|
||||
assert pd.proxy_is_healthy(8787) is False
|
||||
|
||||
|
||||
def test_proxy_is_healthy_rejects_unrelated_json_service(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
from headroom.install import health
|
||||
|
||||
monkeypatch.setattr(
|
||||
health,
|
||||
"probe_json",
|
||||
lambda url, timeout=1.0: {"service": "something-else", "status": "healthy"},
|
||||
)
|
||||
assert pd.proxy_is_healthy(8787) is False
|
||||
|
||||
|
||||
def test_stale_markers_do_not_hide_healthy_deployment(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Many live-but-unhealthy wrap sessions must not evict a recorded deployment."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from headroom.install import state
|
||||
|
||||
for offset in range(7):
|
||||
_write_marker(clients_root, 8800 + offset, pid=100 + offset, started_at=float(offset))
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
monkeypatch.setattr(state, "list_manifests", lambda: [SimpleNamespace(port=9200)])
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: port == 9200)
|
||||
|
||||
ports = pd.candidate_ports(8787, environ={}, cwd=clients_root.parent)
|
||||
assert 9200 in ports
|
||||
assert len([p for p in ports if 8800 <= p <= 8806]) == pd._MAX_CLIENT_MARKER_CANDIDATES
|
||||
assert pd.resolve_read_port(None) == (9200, "discovered")
|
||||
|
||||
|
||||
def test_marker_ports_are_probed_concurrently_once(
|
||||
clients_root: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
import threading
|
||||
|
||||
_write_marker(clients_root, 8788, pid=1, started_at=300.0)
|
||||
_write_marker(clients_root, 8789, pid=2, started_at=200.0)
|
||||
_write_marker(clients_root, 8790, pid=3, started_at=100.0)
|
||||
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
|
||||
barrier = threading.Barrier(3, timeout=2)
|
||||
calls: list[int] = []
|
||||
|
||||
def probe(port: int, **_: object) -> bool:
|
||||
calls.append(port)
|
||||
if port in {8788, 8789, 8790}:
|
||||
barrier.wait() # deadlocks (BrokenBarrierError) unless probed concurrently
|
||||
return port in {8789, 8790}
|
||||
|
||||
monkeypatch.setattr(pd, "proxy_is_healthy", probe)
|
||||
|
||||
assert pd.resolve_read_port(None) == (8789, "discovered")
|
||||
assert sorted(calls) == [8788, 8789, 8790]
|
||||
@@ -62,12 +62,16 @@ def _invoke_wrap_claude(
|
||||
*,
|
||||
env: dict[str, str],
|
||||
extra_args: tuple[str, ...] = (),
|
||||
actual_port: int | None = None,
|
||||
) -> tuple[dict[str, Any], str]:
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
_clear_claude_mode_env(monkeypatch)
|
||||
monkeypatch.setattr(wrap_mod.shutil, "which", lambda _name: "/usr/bin/claude")
|
||||
monkeypatch.setattr(wrap_mod, "_register_proxy_client", lambda _port, session_token=None: None)
|
||||
monkeypatch.setattr(
|
||||
wrap_mod, "_unregister_proxy_client", lambda _port, session_token=None: None
|
||||
)
|
||||
monkeypatch.setattr(wrap_mod, "_make_cleanup", lambda _holder, _port: lambda: None)
|
||||
monkeypatch.setattr(wrap_mod.signal, "signal", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(wrap_mod, "_push_runtime_env", lambda *_args, **_kwargs: None)
|
||||
@@ -91,6 +95,8 @@ def _invoke_wrap_claude(
|
||||
def fake_ensure_proxy(*args: object, **kwargs: object) -> tuple[None, int]:
|
||||
captured["ensure_args"] = args
|
||||
captured["ensure_kwargs"] = kwargs
|
||||
if actual_port is not None:
|
||||
return None, actual_port
|
||||
return None, args[0] if args else 8787
|
||||
|
||||
def fake_run(cmd: list[str], *, env: dict[str, str]) -> _Completed:
|
||||
@@ -144,6 +150,15 @@ def test_wrap_claude_plain_mode_warns_about_remote_control_gate(
|
||||
assert "#746" in output and "#1158" in output
|
||||
|
||||
|
||||
def test_wrap_claude_exports_actual_proxy_port(
|
||||
runner: CliRunner, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
captured, _output = _invoke_wrap_claude(runner, monkeypatch, env={}, actual_port=8788)
|
||||
|
||||
assert captured["child_env"]["HEADROOM_PORT"] == "8788"
|
||||
assert captured["child_env"]["ANTHROPIC_BASE_URL"].startswith("http://127.0.0.1:8788")
|
||||
|
||||
|
||||
def test_wrap_claude_plain_mode_api_key_auth_skips_remote_control_warning(
|
||||
runner: CliRunner, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
|
||||
@@ -1147,6 +1147,74 @@ def test_no_proxy_does_not_create_startup_lock(monkeypatch: pytest.MonkeyPatch)
|
||||
assert entered is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _launch_tool — the wrapped agent inherits the *real* proxy port via
|
||||
# HEADROOM_PORT, so `headroom dashboard` run inside that session lands on the
|
||||
# right proxy even when wrap fell back off the requested port.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _launch_tool_capturing_env(
|
||||
monkeypatch: pytest.MonkeyPatch, *, requested_port: int, actual_port: int
|
||||
) -> dict[str, str]:
|
||||
"""Drive `_launch_tool` with everything external stubbed, return the child env."""
|
||||
captured: dict[str, dict[str, str]] = {}
|
||||
|
||||
class _Result:
|
||||
returncode = 0
|
||||
|
||||
def fake_run(cmd, env=None, **kwargs): # type: ignore[no-untyped-def]
|
||||
captured["env"] = dict(env or {})
|
||||
return _Result()
|
||||
|
||||
monkeypatch.setattr(wrap_mod, "_ensure_proxy", lambda *a, **kw: (None, actual_port))
|
||||
monkeypatch.setattr(wrap_mod, "_register_proxy_client", lambda port: None)
|
||||
monkeypatch.setattr(wrap_mod, "_unregister_proxy_client", lambda port: None)
|
||||
monkeypatch.setattr(wrap_mod, "_push_runtime_env", lambda port, no_proxy: None)
|
||||
monkeypatch.setattr(wrap_mod, "_make_cleanup", lambda holder, port: lambda *a, **kw: None)
|
||||
monkeypatch.setattr(wrap_mod, "_configure_quiet_cli_env", lambda env: [])
|
||||
monkeypatch.setattr(wrap_mod, "_print_telemetry_notice", lambda: None)
|
||||
monkeypatch.setattr(wrap_mod.signal, "signal", lambda *a, **kw: None)
|
||||
monkeypatch.setattr(wrap_mod.subprocess, "run", fake_run)
|
||||
|
||||
runner = CliRunner()
|
||||
|
||||
@click.command()
|
||||
def _cmd() -> None:
|
||||
wrap_mod._launch_tool(
|
||||
binary="fake-agent",
|
||||
args=(),
|
||||
env={"ANTHROPIC_BASE_URL": f"http://127.0.0.1:{requested_port}"},
|
||||
port=requested_port,
|
||||
no_proxy=False,
|
||||
tool_label="FAKE",
|
||||
env_vars_display=[],
|
||||
)
|
||||
|
||||
result = runner.invoke(_cmd)
|
||||
assert result.exit_code == 0, result.output
|
||||
return captured["env"]
|
||||
|
||||
|
||||
def test_launch_tool_exports_headroom_port_to_child() -> None:
|
||||
"""The wrapped agent must see HEADROOM_PORT even with no port fallback."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
env = _launch_tool_capturing_env(mp, requested_port=8787, actual_port=8787)
|
||||
|
||||
assert env["HEADROOM_PORT"] == "8787"
|
||||
|
||||
|
||||
def test_launch_tool_exports_actual_port_after_fallback() -> None:
|
||||
"""Regression: wrap bumped to 8788 (e.g. copilot-subscription proxy), so the
|
||||
child env must advertise 8788 — not the 8787 that was merely requested."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
env = _launch_tool_capturing_env(mp, requested_port=8787, actual_port=8788)
|
||||
|
||||
assert env["HEADROOM_PORT"] == "8788"
|
||||
# The existing URL-rewrite behaviour must keep working alongside it.
|
||||
assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8788"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("argv", "expected"),
|
||||
[
|
||||
|
||||
@@ -991,7 +991,7 @@ class TestDoctorCommand:
|
||||
|
||||
def test_json_output_parses(self, runner, isolated, monkeypatch):
|
||||
monkeypatch.setattr(doctor_mod, "probe_json", self._probe(LIVEZ_OK, STATS_OK))
|
||||
result = runner.invoke(main, ["doctor", "--json"])
|
||||
result = runner.invoke(main, ["doctor", "--json", "--port", "8787"])
|
||||
payload = json.loads(result.output)
|
||||
assert payload["port"] == 8787
|
||||
assert {c["name"] for c in payload["checks"]} >= {"proxy", "version", "budget"}
|
||||
|
||||
@@ -11,10 +11,12 @@ 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
|
||||
|
||||
|
||||
@@ -103,3 +105,31 @@ def test_json_format_emits_raw_feed() -> None:
|
||||
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
|
||||
|
||||
@@ -1096,3 +1096,34 @@ def test_proxy_process_needs_a_start_time(overrides: dict, expected: tuple | Non
|
||||
payload = {"timestamp": _HEALTH_NOW, "uptime_seconds": now - _STARTED_AT, **overrides}
|
||||
|
||||
assert _proxy_process(payload, {"pid": 4242}) == expected
|
||||
|
||||
|
||||
def test_activate_output_shaper_uses_resolved_proxy_port(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
import urllib.request
|
||||
|
||||
from headroom.cli import port_discovery
|
||||
from headroom.cli.learn import _activate_output_shaper
|
||||
|
||||
requested_urls: list[str] = []
|
||||
|
||||
class Response:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
def read(self) -> bytes:
|
||||
return b"{}"
|
||||
|
||||
def urlopen(request, **kwargs):
|
||||
requested_urls.append(request.full_url)
|
||||
return Response()
|
||||
|
||||
monkeypatch.setattr(port_discovery, "resolve_read_port", lambda port: (8788, "discovered"))
|
||||
monkeypatch.setattr(urllib.request, "urlopen", urlopen)
|
||||
|
||||
assert _activate_output_shaper() == ("live", 8788, {})
|
||||
assert requested_urls == ["http://127.0.0.1:8788/admin/runtime-env"]
|
||||
|
||||
+1
-1
@@ -384,7 +384,7 @@ headroom inspect --format json # raw feed for piping into another tool
|
||||
|
||||
| Option | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `--port` / `-p` | `8787` | Proxy port to query (env: `HEADROOM_PORT`) |
|
||||
| `--port` / `-p` | auto-detected, else `8787` | Proxy port to query. Defaults to the most recently started live wrap session (env: `HEADROOM_PORT`) |
|
||||
| `--last` | `1` | Number of most-recent requests to show |
|
||||
| `--format` | `text` | `text` renders a highlighted diff; `json` emits the raw feed |
|
||||
| `--full` | off | Include messages the compressor left unchanged |
|
||||
|
||||
Reference in New Issue
Block a user