Files
headroom/tests/test_dashboard_settings_select_playwright.py
Kenneth WongandKenneth Wong 20ce054f8d fix(dashboard): show the effective value in settings enum selects (#4032)
## Description

The settings page (`/dashboard/settings`) showed the wrong value in
every enum select. A proxy running `mode=cache` with
`savings_profile=coding` displayed **Proxy mode: token** and **Savings
profile: agent-90**, which are the first entries of each field's
`choices` tuple. `/settings/schema` returned the right effective values
the whole time. Only the rendered select was wrong, so an operator
reading the page saw a posture the proxy wasn't running.

Cause: each select builds its `<option>` elements with an `x-for` nested
inside it. When `x-model` first writes `values[field.key]`, those
options don't exist yet, so the browser falls back to the first option
once they render.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/dashboard/templates/settings.html`: bind `:selected="choice
=== values[field.key]"` on each enum `<option>`, so the option matching
the model is selected whenever the options render. `x-model` still
handles user changes.
- `tests/test_dashboard_settings_select_playwright.py` (new): drives the
real settings page in Chromium against a stubbed `/settings/schema`
whose effective values differ from the first choice. It asserts that
both selects display the effective value, and that choosing an option
still updates the Alpine model. It reuses `_fulfill_static_asset` from
the existing dashboard Playwright tests.

## Testing

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

### Test Output

```text
# Before: origin/main's settings.html with the new test
$ pytest tests/test_dashboard_settings_select_playwright.py -q
E   AssertionError: Locator expected to have Value 'cache'
E   Actual value: token
FAILED tests/test_dashboard_settings_select_playwright.py::test_enum_selects_display_the_effective_value
1 failed, 1 passed in 9.56s

# After: this branch, the new test plus the neighbouring dashboard/settings suites
$ pytest tests/test_dashboard_settings_select_playwright.py tests/test_dashboard_poll_guard_playwright.py \
    tests/test_dashboard_accessibility.py tests/test_dashboard_static_assets.py tests/test_proxy_settings_endpoints.py -q
52 passed, 1 warning in 14.57s

$ ruff check tests/test_dashboard_settings_select_playwright.py headroom/dashboard
All checks passed!
$ ruff format --check tests/test_dashboard_settings_select_playwright.py
1 file already formatted
```

## Real Behavior Proof

- Environment: macOS (Apple Silicon), a local `headroom proxy --port
8787` in default `--mode cache` with no savings profile set (effective
`coding`), Playwright 1.63.0 Chromium, dark color scheme.
- Exact command / steps: Open `http://127.0.0.1:8787/dashboard/settings`
at 1440px and at 390px wide, then read each enum select's value with
`locator.input_value()` and capture console errors.
- Observed result: before this change the page showed `token` /
`agent-90` while `/settings/schema` returned `{"mode": "cache",
"savings_profile": "coding"}`. After it, both widths show `mode=cache
profile=coding`, with no console or page errors and no horizontal scroll
(`scrollWidth` 1440 and 390).
- Not tested: Firefox and WebKit; a stored value that is no longer one
of the field's `choices`, where the select still falls back to the
browser's first option, as before.

## Runtime Rollout Safety

- Rollout-managed feature(s): none. This is a dashboard template fix.
- Minimum rollout channel: stable.
- Stable/default behavior changed: only what the settings page's enum
selects display on load. The settings API, the values saved and the save
diff are unchanged.
- Kill switch / disable path: none needed; display only.
- Unsafe override required: no.
- Qualification impact: none expected.
- Rollback path: revert this commit.

## 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
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

Not attached. The Real Behavior Proof above reads the selected values
directly.

## Additional Notes

- Documentation: no docs describe the settings page's select behaviour,
so none changed.
- Type checking: not run, since the change is a template plus a test
file.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4032"
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 -->

Co-authored-by: Kenneth Wong <17061293+KennethWKZ@users.noreply.github.com>
2026-10-08 10:30:34 -05:00

111 lines
3.5 KiB
Python

"""The settings page's enum selects show the effective value.
Each select's ``<option>`` elements come from an ``x-for`` nested inside the
select, so they do not exist yet when ``x-model`` first writes the value.
Without a per-option ``:selected`` binding the browser falls back to the first
option: a proxy running ``mode=cache``/``savings_profile=coding`` displayed
``token``/``agent-90``, the first entry of each choices tuple.
"""
from __future__ import annotations
import json
from urllib.parse import urlsplit
import pytest
from headroom.dashboard import get_settings_html
from tests.test_dashboard_cache_ttl_playwright import _fulfill_static_asset
playwright = pytest.importorskip("playwright.sync_api")
Page = playwright.Page
expect = playwright.expect
sync_playwright = playwright.sync_playwright
def _enum_field(key: str, label: str, choices: list[str], default: str) -> dict:
return {
"key": key,
"env": f"HEADROOM_{key.upper()}",
"label": label,
"group": "Compression",
"type": "enum",
"choices": choices,
"default": default,
"help": "",
"secret": False,
"manifest_managed": False,
"minimum": None,
"maximum": None,
"tier": "basic",
"env_override": False,
"runtime_override": False,
"stored": None,
}
# Effective values deliberately differ from the first choice of each field.
_SCHEMA = {
"groups": ["Compression"],
"fields": [
_enum_field("mode", "Proxy mode", ["token", "cache"], "cache"),
_enum_field(
"savings_profile",
"Savings profile",
["agent-90", "balanced", "coding", "general"],
"coding",
),
],
"values": {"mode": "cache", "savings_profile": "coding"},
"supervised": False,
}
def _open_settings(page: Page) -> None: # type: ignore[valid-type]
settings_html = get_settings_html()
def handler(route) -> None: # type: ignore[no-untyped-def]
path = urlsplit(route.request.url).path
if path == "/settings/ui":
route.fulfill(status=200, content_type="text/html", body=settings_html)
return
if _fulfill_static_asset(route, path):
return
if path == "/settings/schema":
route.fulfill(status=200, content_type="application/json", body=json.dumps(_SCHEMA))
return
route.fulfill(status=404, body="")
page.route("**/*", handler)
page.goto("http://headroom.local/settings/ui")
page.wait_for_load_state("networkidle")
def _select_for(page: Page, label: str): # type: ignore[no-untyped-def,valid-type]
return page.locator("label", has_text=label).locator("select")
def test_enum_selects_display_the_effective_value() -> None:
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
_open_settings(page)
expect(_select_for(page, "Proxy mode")).to_have_value("cache")
expect(_select_for(page, "Savings profile")).to_have_value("coding")
browser.close()
def test_choosing_an_option_still_updates_the_model() -> None:
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
_open_settings(page)
_select_for(page, "Savings profile").select_option("balanced")
values = page.evaluate("() => Alpine.$data(document.body).values")
assert values["savings_profile"] == "balanced"
assert values["mode"] == "cache"
browser.close()