Files
headroom/tests/test_tray_core.py
JD DavisandCopilot e9301f34c1 feat(tray): opt-in system tray icon with savings counter, dashboard and update alert (#4726)
## Description

Adds an **opt-in system tray icon** for Headroom while it runs (Windows
first; macOS/Linux planned). The icon is the Headroom logomark and its
right-click menu shows a compact savings counter (tokens and estimated $
saved), opens the dashboard, alerts when an update is available, and
lets you quit.

Closes #

## Type of Change

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

- New `headroom/tray/` package: `core.py` (GUI-free stats
polling/formatting), `icon.py` (logomark drawn with Pillow, no binary
assets in the wheel), `app.py` (pystray app), `launcher.py` (spawns the
tray as a child of the proxy).
- `headroom proxy --tray` starts the tray with the proxy; `headroom tray
--port N` attaches to a running proxy.
- Menu: live `▼ tokens · ~$ saved` counter (from `/stats` →
`persistent_savings.lifetime`, polled every 5s), Open Dashboard, "Update
available" (only when newer; reuses `headroom.update_check`, honours
`HEADROOM_UPDATE_CHECK=off`; one-time notification), Quit.
- Icon states: normal, orange dot when an update exists, grey when the
proxy is offline.
- New optional extra `headroom-ai[tray]` (`pystray`, `pillow`).
Unsupported platform / missing extra: `--tray` prints why and the proxy
starts normally.
- Docs: `docs/content/docs/system-tray.mdx` + nav entry; screenshots in
`docs/public/assets/tray/`.

## 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
> python -m ruff check headroom\tray headroom\cli tests\test_tray_core.py
All checks passed!
> python -m mypy headroom\tray headroom\cli\tray.py
Success: no issues found in 7 source files
> python -m pytest tests\test_tray_core.py tests\cli tests\test_offline_egress_chokepoint.py tests\test_proxy\test_settings_store.py -q
293 passed, 2 skipped
```

(Scoped runs; I did not run the full suite or `mypy headroom` over the
whole package.)

## Real Behavior Proof

- Environment: Windows 11, Python 3.13.13, 3840x2160 display, `pystray`
+ `pillow` 12.3.0, branch based on `upstream/main` @ 1da8930ab.
- Exact command / steps: run the 4 steps below.
1. `HEADROOM_UPDATE_CHECK=off`, then `python -m headroom.cli proxy
--tray --port 8799`
2. Confirmed `GET /health` → 200 and a `python -m headroom.tray --host
127.0.0.1 --port 8799 --owns-proxy` child process.
3. Opened the taskbar overflow, right-clicked the Headroom icon,
captured the menu (below).
  4. Clicked **Quit Headroom**.
- Observed result: icon appeared with the logomark; menu showed `▼ 256M
tokens · ~$765.96 saved` (my real lifetime savings store), **Open
Dashboard**, **Quit Headroom**. After Quit, `/health` no longer
responded (proxy shut down gracefully).
- Not tested: the real update toast and "Update available" menu item
(covered only by a unit test of `available_update()` and a rendered
icon); clicking Open Dashboard / double-click default action; macOS and
Linux (intentionally unsupported for now); HiDPI/light-theme variations;
`headroom tray` standalone Exit in the UI.

## Runtime Rollout Safety

- Rollout-managed feature(s): None (not rollout-channel gated).
- Minimum rollout channel: N/A
- Stable/default behavior changed: No. Off by default; only active with
`--tray`.
- Kill switch / disable path: omit `--tray` (or pass `--no-tray`).
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: revert this PR; the new extra and command are additive.

## 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
- [ ] New and existing unit tests pass locally with my changes (only
`tests/test_tray_core.py` and `tests/cli` were run)
- [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)

**Tray icon** (left: real icon in the Windows taskbar overflow, zoomed;
then rendered states: live, update available, proxy offline)

![Tray icon
states](https://raw.githubusercontent.com/JerrettDavis/headroom/3e824653772642c95fded190b454fff82f2ce86a/docs/public/assets/tray/tray-icon.png)

**Right-click menu** (real capture)

![Tray right-click
menu](https://raw.githubusercontent.com/JerrettDavis/headroom/3e824653772642c95fded190b454fff82f2ce86a/docs/public/assets/tray/tray-menu.png)

**How to use**

```bash
pip install "headroom-ai[tray]"
headroom proxy --tray        
headroom tray --port 8787    # attach to an already-running proxy
```

Windows hides new tray icons in the `^` overflow next to the clock; drag
the icon onto the taskbar to pin it, then right-click. Full guide:
`docs/content/docs/system-tray.mdx`.

## Feature spec

- **API surface**: `headroom proxy --tray/--no-tray`, `headroom tray
--port N`, extra `headroom-ai[tray]`. No change to existing behavior
when the flag is absent.
- **User stories**: Given the proxy runs with `--tray`, when I
right-click the icon, then I see tokens/$ saved, Open Dashboard and
Quit. Edge: given the proxy is down, the icon turns grey and the tooltip
says offline.
- **Failure modes / recovery**: unsupported platform or missing extra
prints a reason and the proxy starts normally; the tray child exits when
the proxy dies (stdin EOF); a stats fetch failure shows the offline
state and retries every 5s. Quit sends SIGINT for graceful shutdown
without a force-exit deadline.
- **Security**: tray only polls the local proxy `/stats`; no network
calls of its own (update info read from the existing cache; honours
`HEADROOM_UPDATE_CHECK=off`); child is spawned with a fixed argv.

## Dependency justification

- **Why**: `pystray` is the standard cross-platform tray library
(Win/macOS/Linux); `pillow` is required by it for icons and lets us draw
the logomark with no binary assets. No existing dep provides a tray.
- **Maintainers**: pystray (moses-palmer), BSD/LGPL, stable ~0.19.5
releases; Pillow (python-pillow org), very active, frequent security
releases.
- **Install surface**: optional extra only (not default). pystray pulls
`six`, plus pywin32-free ctypes on Windows; Pillow ships prebuilt
wheels. No install-time network access.
- **Why these versions**: `pystray>=0.19.5` is the current release
(required new functionality); `pillow>=12.3.0` matches the repo pin
level already used elsewhere to avoid known CVEs.

## Additional Notes

- The menu screenshot shows my real local savings numbers.
- The Quit item stops the proxy only when the tray was started via
`headroom proxy --tray`; the standalone `headroom tray` shows "Exit" and
only closes the tray.
- Follow-ups: macOS/Linux backends (pystray needs the main thread on
macOS, hence the child-process design).

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 19:40:55 -06:00

177 lines
5.7 KiB
Python

from __future__ import annotations
import pytest
from headroom.tray import core
from headroom.tray.core import Snapshot
@pytest.mark.parametrize(
("n", "expected"),
[
(0, "0"),
(950, "950"),
(1_000, "1.00K"),
(12_345, "12.3K"),
(999_999, "1.00M"),
(4_560_000, "4.56M"),
(1_200_000_000, "1.20B"),
],
)
def test_format_tokens(n: int, expected: str) -> None:
assert core.format_tokens(n) == expected
def test_format_usd() -> None:
assert core.format_usd(0) == "$0.00"
assert core.format_usd(1234.5) == "$1,234.50"
assert core.format_usd(25_000) == "$25.0K"
def test_parse_stats_sums_input_and_output_savings() -> None:
snap = core.parse_stats(
{
"persistent_savings": {
"lifetime": {
"tokens_saved": 1000,
"output_tokens_saved": 500,
"compression_savings_usd": 1.5,
"output_savings_usd": 0.25,
"requests": 7,
}
}
}
)
assert snap == Snapshot(online=True, tokens_saved=1500, usd_saved=1.75, requests=7)
def test_parse_stats_tolerates_missing_keys() -> None:
assert core.parse_stats({}) == Snapshot(online=True)
def test_fetch_snapshot_offline_never_raises() -> None:
assert core.fetch_snapshot("http://127.0.0.1:1", timeout=0.2).online is False
def test_base_url_maps_wildcard_and_ipv6() -> None:
assert core.base_url("0.0.0.0", 8787) == "http://127.0.0.1:8787"
assert core.base_url("::1", 9) == "http://[::1]:9"
def test_tooltip_capped_and_mentions_update() -> None:
text = core.tooltip(Snapshot(online=True, tokens_saved=2000, usd_saved=3), "9.9.9")
assert "2.00K" in text and "9.9.9" in text and len(text) <= 127
assert "offline" in core.tooltip(Snapshot())
def test_available_update(monkeypatch: pytest.MonkeyPatch) -> None:
import headroom.update_check as uc
monkeypatch.setattr(uc, "is_update_check_enabled", lambda: True)
monkeypatch.setattr(uc, "_is_source_checkout", lambda: False)
monkeypatch.setattr(uc, "_in_docker", lambda: False)
monkeypatch.setattr(uc, "installed_version", lambda: "1.0.0")
monkeypatch.setattr(uc, "read_cache", lambda: {"latest_version": "1.2.0"})
assert core.available_update() == "1.2.0"
monkeypatch.setattr(uc, "read_cache", lambda: {"latest_version": "1.0.0"})
assert core.available_update() is None
monkeypatch.setattr(uc, "_in_docker", lambda: True)
monkeypatch.setattr(uc, "read_cache", lambda: {"latest_version": "1.2.0"})
assert core.available_update() is None
def test_icon_renders_all_states() -> None:
pytest.importorskip("PIL")
from headroom.tray.icon import render_icon
for online in (True, False):
for update in (True, False):
assert render_icon(online=online, update=update, size=32).size == (32, 32)
@pytest.mark.parametrize(
("url", "expected"),
[
("http://127.0.0.1:8787", True),
("http://localhost:8787", True),
("http://[::1]:8787", True),
("http://example.com:8787", False),
("http://10.0.0.5:8787", False),
("https://127.0.0.1:8787", False),
("http://127.0.0.1.evil.com:8787", False),
],
)
def test_is_loopback_url(url: str, expected: bool) -> None:
assert core.is_loopback_url(url) is expected
def test_fetch_snapshot_refuses_remote_host_even_when_offline(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("HEADROOM_OFFLINE", "1")
calls: list[object] = []
monkeypatch.setattr(core._OPENER, "open", lambda *a, **k: calls.append(a))
monkeypatch.setattr("urllib.request.urlopen", lambda *a, **k: calls.append(a))
assert core.fetch_snapshot(core.base_url("example.com", 8787)).online is False
assert calls == []
def test_fetch_snapshot_does_not_follow_redirects_off_loopback() -> None:
import http.server
import threading
hits: list[str] = []
class Target(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None:
hits.append(self.path)
self.send_response(200)
self.end_headers()
self.wfile.write(b'{"persistent_savings": {"lifetime": {"tokens_saved": 5}}}')
def log_message(self, *args: object) -> None:
pass
target = http.server.HTTPServer(("127.0.0.1", 0), Target)
class Redirector(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None:
self.send_response(302)
self.send_header("Location", f"http://127.0.0.1:{target.server_port}/stats")
self.end_headers()
def log_message(self, *args: object) -> None:
pass
redirector = http.server.HTTPServer(("127.0.0.1", 0), Redirector)
servers = (target, redirector)
for server in servers:
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
snap = core.fetch_snapshot(f"http://127.0.0.1:{redirector.server_port}", timeout=2)
finally:
for server in servers:
server.shutdown()
server.server_close()
assert snap.online is False
assert hits == []
def test_quit_requests_sigint_without_scheduling_a_hard_exit(
monkeypatch: pytest.MonkeyPatch,
) -> None:
import os
import signal
import threading
from headroom.tray import launcher
raised: list[int] = []
monkeypatch.setattr(signal, "raise_signal", raised.append)
monkeypatch.setattr(os, "_exit", lambda code: pytest.fail("hard exit must not be forced"))
monkeypatch.setattr(
threading, "Timer", lambda *a, **k: pytest.fail("no force-exit timer allowed")
)
launcher.request_graceful_shutdown()
assert raised == [signal.SIGINT]