Commit Graph
2 Commits
Author SHA1 Message Date
02c4e922f7 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 head 420c2d636 and current author
response, including isolated workspace/port fixtures and live-marker
ordering/pruning regressions. Clean integration with upstream/main
2d3ee51846. 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>
2026-11-05 21:10:06 -06:00
Manmit Singh 942e916368 feat(cli): add headroom inspect to view original vs compressed content (#1595)
## Description

Headroom exposes plenty of *quantitative* compression telemetry (token
counts, ratios, `headroom perf`, `/metrics`) but no way to actually
**see what the compressor changed** in the content. That makes it hard
to trust compression or debug a quality regression ("did it drop
something I cared about?").

This adds a `headroom inspect` command (the issue's Option 1). It reads
the proxy's existing loopback `/transformations/feed` endpoint — which
already carries the pre/post-compression message snapshots when the
proxy runs with `--log-messages` — and renders, per request, the
original vs compressed content for each message with the changed
segments highlighted. No new dependencies (stdlib `difflib`).

```
headroom inspect                 # inspect the most recent request
headroom inspect --last 5        # the 5 most recent
headroom inspect --full          # include unchanged messages
headroom inspect --format json   # raw feed for offline tooling
```

Per request it shows the model, per-request token counts + savings, the
transforms applied, and a colorized unified diff of each changed message
(red = removed, green = added). Clear errors when no proxy is reachable
or when the proxy wasn't started with `--log-messages`.

Side-by-side / interactive rendering (the fuller form of Option 1) can
follow as a polish pass; this lands the core "see what changed"
capability on data Headroom already captures.

Closes #1267

## Type of Change

- [x] New feature (non-breaking change that adds functionality)

## Changes Made

- `headroom/cli/inspect.py`: new `inspect` command +
content-flattening/diff-render helpers.
- `headroom/cli/__init__.py`, `headroom/cli/main.py`: register the
command.
- `tests/test_cli_inspect.py`: unit tests (content extraction, the
no-proxy / no-`--log-messages` / empty-feed paths, text render, json
output).
- `wiki/cli.md`: document the command + options.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check`)
- [x] New tests added

### Test Output

```text
$ pytest tests/test_cli_inspect.py -q
7 passed

$ ruff check headroom/cli/ tests/test_cli_inspect.py
All checks passed!
```

## Real Behavior Proof

- Environment: repo main @ HEAD, local venv
- Exact command / steps: invoked the `inspect` command against a mocked
`/transformations/feed` payload (one request, a user message with a line
removed by SmartCrusher).
- Observed result: header shows `req-1 gpt-4o`, `tokens 100 → 40 (saved
60, 60.0%)`, `transforms: SmartCrusher`, and a unified diff with the
removed line on the original side; no-proxy and missing-`--log-messages`
cases raise actionable errors; `--format json` emits the raw feed.
- Not tested: live end-to-end against a real proxy with `--log-messages`
(the data source — the feed endpoint — is exercised via the mocked
payload that mirrors its shape).

## 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 made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove the feature works
2026-07-15 19:58:38 +00:00