# UI Routes and View Dispatch

## Overview

All UI routes are defined in `views.py`. The server uses a **data-driven registration model**: `_VIEW_ROUTES` is a list of route descriptors, and `_dispatch_view()` is the centralized dispatch function that handles cross-cutting concerns for every UI request.

`views.py` is intentionally organized into stable top-level sections: authentication (with the htmx helpers), home redirect, login and signup, lists, workers, neural networks, users, contributors, homepage and run lists, run mutation, run creation, run administration, run detail, and router registration.

## Route table

Routes are declared in `_VIEW_ROUTES` as tuples of:

```
(handler_function, path, config_dict)
```

Config keys:

| Key | Type | Description |
| --- | --- | --- |
| `renderer` | string | Jinja2 template name (e.g., `"tests.html.j2"`) |
| `require_csrf` | bool | Enforce CSRF validation on POST |
| `require_primary` | bool | Reject POST on non-primary instance (503) |
| `request_method` | string or tuple | Allowed HTTP methods (default: GET) |
| `http_cache` | int | `Cache-Control: max-age=` seconds |
| `direct` | bool | Bypass `_dispatch_view` (for pure redirects) |

At module load time, `_register_view_routes()` iterates over `_VIEW_ROUTES`, wraps each handler with `_dispatch_view()` (unless `direct=True`), and registers it on the FastAPI router.

When `request_method` is omitted, the route is read-only and registered as `GET` only. The small set of endpoints that render a form on `GET` and process it on `POST` opt into `GET, POST` explicitly, while pure mutations stay `POST` only. `HEAD` works on `GET` routes through middleware compatibility, but generic `OPTIONS` is not part of the UI route contract and returns `405`.

## Registered routes

| Path | Method(s) | Handler | Template | Notes |
| --- | --- | --- | --- | --- |
| `/` | GET | `home` | \-- | Redirects to `/tests` (direct) |
| `/login` | GET, POST | `login` | `login.html.j2` | CSRF |
| `/logout` | POST | `logout` | \-- | CSRF |
| `/signup` | GET, POST | `signup` | `signup.html.j2` | CSRF |
| `/tests` | GET | `tests` | `tests.html.j2` | Main dashboard; page 1 live run tables poll the same route via `?live=run_tables` |
| `/tests/run` | GET, POST | `tests_run` | `tests_run.html.j2` | CSRF, primary |
| `/tests/modify` | POST | `tests_modify` | \-- | CSRF, primary |
| `/tests/stop` | POST | `tests_stop` | \-- | CSRF, primary |
| `/tests/approve` | POST | `tests_approve` | \-- | CSRF, primary |
| `/tests/purge` | POST | `tests_purge` | \-- | CSRF, primary |
| `/tests/delete` | POST | `tests_delete` | \-- | CSRF, primary |
| `/tests/view/{id}` | GET | `tests_view` | `tests_view.html.j2` | Full detail page; renders server-owned Open Graph metadata with a query-free canonical URL and a Discord-oriented multi-line `og:description`; unfinished runs poll the merged detail fragment endpoint and the dedicated tasks endpoint |
| `/tests/view/{id}/detail` | GET | `tests_view_detail` | `tests_view_detail_fragment.html.j2` | Fragment-only; no page-head metadata; OOB refresh for ELO, run status, active-worker totals, detail, time, chi-square, and the retained SPSA data payload |
| `/tests/live_elo/{id}` | GET | `tests_live_elo` | `tests_live_elo.html.j2` | Live Elo page + dual-scale gauge |
| `/tests/stats/{id}` | GET | `tests_stats` | `tests_stats.html.j2` | HX: `tests_stats_content_fragment.html.j2`; active runs poll with the dedicated stats-page interval and visibility-aware refresh |
| `/tests/tasks/{id}` | GET | `tests_tasks` | `tasks_content_fragment.html.j2` | Fragment-only; updates the scrolling task table body and refreshes fixed controls/pagination OOB, with server-side sorting for every visible task column, one combined worker/info search filter, and 25-row pagination |
| `/tests/machines` | GET | `tests_machines` | `machines_fragment.html.j2` | Fragment-only, 10s cache |
| `/tests/live_elo_update/{id}` | GET | `live_elo_update` | `live_elo_fragment.html.j2` | Fragment-only (OOB) |
| `/tests/finished` | GET | `tests_finished` | `tests_finished.html.j2` | HX: `tests_finished_results_fragment` |
| `/tests/user/{username}` | GET | `tests_user` | `tests_user.html.j2` | HX: `tests_user_content_fragment`; page 1 live run tables poll the same route via `?live=run_tables` |
| `/actions` | GET | `actions` | `actions.html.j2` | Full page plus htmx content fragment; full-page responses render route-specific Open Graph metadata that preserves the current query string in `og:url` and summarizes the first visible action row |
| `/contributors` | GET | `contributors` | `contributors.html.j2` | HX: `contributors_content_fragment`; paginated (100/page) |
| `/contributors/monthly` | GET | `contributors_monthly` | `contributors.html.j2` | HX: `contributors_content_fragment`; paginated (100/page) |
| `/user/{username}` | GET, POST | `user` | `user.html.j2` | CSRF |
| `/user` | GET, POST | `user` | `user.html.j2` | CSRF |
| `/user_management` | GET | `user_management` | `user_management.html.j2` | HX: `user_management_content_fragment` |
| `/user_management/pending_count` | GET | `user_management_pending_count` | `pending_users_nav_fragment.html.j2` | Sidebar status fragment; the stable wrapper and poll triggers live in `base.html.j2`, and this route returns only the `Users` anchor HTML |
| `/workers/{worker_name}` | GET, POST | `workers` | `workers.html.j2` | CSRF; HX: `workers_content_fragment` |
| `/upload` | GET, POST | `upload` | `nn_upload.html.j2` | CSRF |
| `/nns` | GET | `nns` | `nns.html.j2` | HX: `nns_content_fragment` |
| `/sprt_calc` | GET | `sprt_calc` | `sprt_calc.html.j2` |  |
| `/rate_limits` | GET | `rate_limits` | `rate_limits.html.j2` |  |
| `/rate_limits/server` | GET | `rate_limits_server` | inline HTML response | Fragment-only |

## Sidebar status links

The sidebar contains two visibility-aware status links:

- `Users` is rendered inside the stable `#pending-users-nav` wrapper in `base.html.j2`. Full pages include the current count server-side, and that same wrapper mounts the visibility-aware htmx poll to `/user_management/pending_count`; the fragment route itself returns only the anchor HTML.
- `GitHub Rate Limits` uses separate cadences: `POLL_RATE_LIMITS_GITHUB_S` for the browser-side GitHub rate-limit poll in shared JavaScript, which updates the sidebar link on full pages and also updates the `/rate_limits` client row when that page is open, and `POLL_RATE_LIMITS_SERVER_S` for the `/rate_limits/server` htmx row. The sidebar link itself is rendered directly in `base.html.j2`.

Route notes: - **Fragment-only**: endpoint always returns a fragment template (no full page). - **HX**: dual-mode endpoint; returns the named fragment when `HX-Request: true` is present and the request does not announce itself as a history restore, a full-document swap, or a top-level navigation; otherwise renders the full-page template. - **OOB**: fragment contains `hx-swap-oob` attributes for multi-element updates.

## Tests Repository URL Contract

The `Tests Repository` field used on `/signup`, `/user`, and `/tests/run` accepts a GitHub repository URL with or without a trailing slash.

Server-side behavior:

- raw form validation accepts either `https://github.com/<user>/<repo>` or `https://github.com/<user>/<repo>/`
- user profile data is canonicalized to the slash-free form
- persisted user and run validation requires the slash-free canonical form
- run data uses the slash-free form in `run["args"]["tests_repo"]`

Canonical stored value:

- `https://github.com/<user>/<repo>`

This keeps GitHub compare links and worker download URLs stable even when the submitted form value includes a trailing slash.

## `/tests/view/{id}/detail` live detail contract

The test detail page keeps its live summary and detail data synchronized through the fragment-only `/tests/view/{id}/detail` endpoint. This endpoint is the live detail-page poll contract.

The full detail page uses a visibility-aware htmx poller with:

- `hx-get="/tests/view/{id}/detail"`
- `hx-include="#tests-view-detail-expected"`
- `hx-swap="none"`

The response updates these regions out of band:

- `#tests-view-detail-expected`, the hidden input the next poll sends back
- `#elo-<run_id>`
- `#run-status-<run_id>`
- `#tasks-totals`
- `#tests-view-details`
- `#tests-view-time`
- `#tests-view-stats` for non-SPSA runs
- `#spsa-data-<run_id>` for SPSA runs

Page-head metadata contract:

- The full `/tests/view/{id}` page owns `<title>`, Open Graph tags, and the optional `theme-color` meta tag.
- The `/tests/view/{id}` `og:description` is emitted as plain multi-line text so Discord previews preserve the run-summary layout without literal backticks.
- The fragment-only `/tests/view/{id}/detail` endpoint never renders or updates page-head metadata.
- Shared links and social preview clients must fetch the full page URL, not the fragment URL.

For SPSA runs, the detail fragment updates the existing `#spsa-data-<run_id>` node in place. The page-owned `spsa.js` controller keeps the chart shell mounted, draws the chart at a fixed 1000x500 size inside the scrollable container, skips redraws when the embedded JSON payload is unchanged, and redraws changed payloads in place without replacing the chart shell. The full `/tests/view/{id}` page also remembers the `% c` checkbox with a browser cookie, so the checkbox reopens in its previous mode while live detail polling continues to update only the embedded SPSA data node.

The full `/tests/view/{id}` page also loads a dedicated client-side diff renderer for the inline Diff panel. That asset is page-scoped and is not part of the `/tests/view/{id}/detail` fragment contract.

The request submits the page's current canonical `expected` state from a server-owned hidden input:

- `active`
- `paused`
- `pending`

Server behavior for htmx polling:

- `200` returns fresh OOB detail content.
- `204` keeps the current DOM when the run is still paused or pending.
- When the run is terminal, the `200` response also carries `<div id="tests-view-detail-poller" hx-swap-oob="delete"></div>`, which removes the poller and stops the poll.

## `/tests/live_elo/{id}` gauge scale contract

The Live Elo page renders three Google gauges (LOS, LLR, Elo) and keeps the details table in sync through `/tests/live_elo_update/{id}` OOB swaps.

The Elo gauge supports two display modes:

- Fixed mode (default without a saved choice): fixed gauge range `[-4, +4]` for visual consistency.
- Dynamic mode: auto range chosen from the smallest symmetric power-of-two interval that covers the current Elo value and confidence interval.

Switching modes:

- Clicking the Elo gauge toggles between fixed and dynamic mode.
- Keyboard activation on the Elo gauge (`Enter` or `Space`) also toggles modes.
- The chosen mode is saved in the `live_elo_mode` cookie.

Value display rule:

- The gauge reports the real uncapped Elo value from the server.
- In fixed mode, the gauge needle is visually limited by the selected range.

## `/tests/stats/{id}` raw statistics contract

The raw statistics page is dual-mode:

- Full-page navigation renders `tests_stats.html.j2`.
- A fragment request (see [Detection](<#detection-_is_hx_requestrequest>)) renders `tests_stats_content_fragment.html.j2`.

The page shell keeps a visibility-aware poller for unfinished non-SPSA runs:

- `every[document.visibilityState === 'visible'] {{ poll.tests_stats }}s`
- `visibilitychange[document.visibilityState === 'visible'] from:document`

Server behavior for htmx polling:

- `200` when the run is active, returning the refreshed stats fragment.
- `204` when the run is not active but not terminal, keeping the current DOM.
- When the run is terminal (`finished` or `failed`), the `200` response also carries `<div id="tests-stats-poller" hx-swap-oob="delete"></div>`, which removes the poller and stops the poll.

Layout contract:

- the shared fragment preserves the original heading-and-table statistics presentation from the page shell;
- genuinely tabular data, such as SPRT bounds, remains a table;
- SPSA runs render an informational message instead of raw statistics.

## htmx fragment dispatch

Dual-mode endpoints (marked **HX** in the route table) serve either a full HTML page or a fragment, from the same URL, based on request headers.

### Detection: `_is_hx_request(request)`

Returns `True` when the request carries `HX-Request: true` and announces none of the following, case-insensitively:

1. `HX-History-Restore-Request: true` -- a back navigation. htmx 4 keeps no page snapshots, so it refetches the pushed URL and swaps the response into `<body>`. The restore passes its own request object, which replaces the core headers: the request carries `HX-History-Restore-Request: true` and `HX-Request-Type: full`, and no `HX-Request`, `HX-Source` or `Accept`. The missing `HX-Request` already rejects it; this check names the case.
2. `HX-Request-Type: full` -- a swap scoped to the whole document, which is what a boosted navigation asks for.
3. `Sec-Fetch-Mode: navigate` -- a real top-level navigation. htmx never issues one, so this catches a browser prefetch or a proxy replaying `HX-Request`. It is the only signal here that page script cannot forge.

The check rejects `full` rather than requiring `partial` on purpose. Requiring it would tie every dual-mode endpoint to one htmx 4 header keeping its name, and the failure would be silent and total: whole pages swapped into the `<div>`s that asked for a fragment.

### Rendering: `_render_hx_fragment(request, template_name, context)`

Convenience wrapper that checks `_is_hx_request()` and, when true, renders the fragment template via `render_template_to_response()`. Returns `None` for non-htmx requests, allowing the caller to fall through to full-page rendering. Typical usage:

```
return (
    _render_hx_fragment(request, "my_fragment.html.j2", context)
    or context
)
```

Or, when the htmx context differs from the full-page context:

```
hx = _render_hx_fragment(request, "my_fragment.html.j2", hx_context)
if hx:
    return hx
return full_page_context
```

### `Vary` header

`_dispatch_view()` appends `Vary: HX-Request, HX-History-Restore-Request, HX-Request-Type, Sec-Fetch-Mode` to every GET response, fragment and full-page alike. The tokens are the four headers `_is_hx_request()` reads, declared once in `FRAGMENT_REQUEST_HEADERS`, so adding a signal to the decision is one edit rather than two that can drift.

Every one of them selects a representation: drop a token and a shared cache may serve a stored fragment to a request that the same URL answers with a whole page. RFC 9111 section 4.1 requires the selecting header fields to be named.

## `_dispatch_view()` pipeline

For every UI request (except `direct` routes), `_dispatch_view()` handles the following steps in order:

1. **Request context assembly** -- calls `get_request_context(request)` to load the session and DB handles.
2. **POST body parsing** -- `await request.form()` with configured limits (`max_files=2`, `max_fields=200`, `max_part_size=200MB`).
3. **CSRF enforcement** -- if `require_csrf` is set, validates the token from the form field or `X-CSRF-Token` header against the session token.
4. **`_ViewContext` construction** -- bundles request, session, POST data, path params, and DB handles into a single object passed to the handler.
5. **Primary-instance guard** -- if `require_primary` is set and the instance is not primary, returns a 503 HTML response.
6. **Handler execution** -- `await run_in_threadpool(fn, shim)` runs the sync handler body in the threadpool.
7. **Response passthrough** -- if the handler returns a `Response` (a redirect, an htmx fragment, an `HTMLResponse`), it is returned as is, with the session commit, the HTTP cache headers, and on GET the `Vary` tokens and a default `Cache-Control: no-cache, private`.
8. **Template rendering** -- a `response_status` of 204 returns an empty 204; otherwise, if `renderer` is set, `render_template_to_response()` renders the Jinja2 template with the handler's dict, and a route without a renderer returns an empty 204.
9. **Session commit** -- `commit_session_response()` applies remember/forget flags to the cookie.
10. **HTTP cache headers** -- `apply_http_cache()` sets `Cache-Control` if configured.
11. **Vary header** -- one token per header the fragment decision reads is appended to every GET response (see htmx fragment dispatch above), with a default `Cache-Control: no-cache, private`.
12. **Response headers** -- custom headers from the handler are propagated.

## Session handling

### Storage

`FishtestSessionMiddleware` (pure ASGI) manages session persistence. Session data lives in `request.scope["session"]` as a plain dict, wrapped by `CookieSession` for helper access.

### Cookie format

- Signed with `itsdangerous.TimestampSigner`.
- Cookie name: `fishtest_session`.
- Encoding: base64(JSON(session\_data)), signed.
- Maximum cookie size: 3800 bytes (enforced; flash messages are trimmed if exceeded).
- SameSite: `lax`.

Cookie ownership is split intentionally:

- `http/settings.py` owns cookie policy values such as size limits and persistence windows.
- `http/cookie_session.py` owns the session cookie transport contract such as the cookie name, SameSite default, secret resolution, and request-scope override helpers.
- `http/ui_cookies.py` owns browser-readable non-auth UI cookie names, shared low-level parsing helpers, and the raw `Set-Cookie` formatting reused by UI views.

### Session keys

| Key | Type | Description |
| --- | --- | --- |
| `user` | string | Authenticated username |
| `csrf_token` | string | CSRF token (generated on first access) |
| `flashes` | dict | Flash message queues (`error`, `warning`, default) |
| `created_at` | string | ISO timestamp of session creation |
| `remember_max_age` | int | Cookie max-age in seconds after a "remember me" login |

### Per-request overrides

- `scope["session_max_age"]` -- overrides cookie `Max-Age` (used by "remember me": 400 days, `SESSION_REMEMBER_ME_MAX_AGE_SECONDS`).
- `scope["session_secure"]` -- overrides the `Secure` flag.
- `scope["session_force_clear"]` -- forces an expired cookie on the response (used by logout).

## Cookie workflow

The UI uses two cookie families with different ownership and lifecycles:

- **Session/auth cookie** -- `fishtest_session`, emitted by `FishtestSessionMiddleware`.
- **UI state cookies** -- lightweight browser-side preferences such as `theme`, `contributors_findme`, `machines_state`, and the homepage workers filters. These non-auth UI cookies use the shared `400 days` max-age policy from `UI_STATE_COOKIE_MAX_AGE_SECONDS` and stay separate from the signed session payload.

### Session cookie lifecycle

1. `FishtestSessionMiddleware` reads `fishtest_session` at request start and decodes the signed JSON payload into `scope["session"]`.
2. `load_session()` wraps that dict in `CookieSession` and sets `created_at` when it is missing; the CSRF token is created on first access.
3. `build_template_context()` calls `session.get_csrf_token()` on every render, pages and fragments alike. The middleware emits `Set-Cookie` whenever the session dict is non-empty, so every `_dispatch_view` response sets the session cookie.
4. On login, `remember()` writes `session["user"]` and optionally stores a persistent max-age marker for "remember me" behavior.
5. On logout, `forget()` clears the session and marks the response to emit an expired cookie.
6. `commit_session_response()` translates those flags into request-scope overrides, and `FishtestSessionMiddleware` finally appends the `Set-Cookie` header on the outbound response.

### UI state cookie lifecycle

UI state cookies are intentionally separate from the signed session payload. They are written through shared server or browser helpers because they do not carry authentication state:

- `theme` is written through `writeUiCookie()` in `static/js/application.js` and controls light or dark presentation. The same cookie is read during full-page renders so the server can emit the matching theme before first paint.
- `login_remember_me` is written by `POST /login` and mirrored by `static/js/application.js` through the shared browser cookie helper when the checkbox changes. It keeps the login form's explicit opt-out state across browser restarts without changing the signed auth-cookie lifetime.
- `master_only` is mirrored by the shared checkbox-cookie handler in `static/js/application.js` using `data-ui-cookie-*` attributes from `nns_content_fragment.html.j2`. The `/nns` form also submits an explicit false fallback so unchecked htmx requests do not depend on cookie timing.
- `contributors_findme` is written by `static/js/contributors.js` and preserves rank-jump mode across contributors pages.
- `machines_state` is written by `static/js/tests_homepage.js` and preserves whether the homepage workers panel is expanded. Opening the panel also triggers an immediate `/tests/machines` refresh instead of waiting for the next periodic poll.
- `machines_sort`, `machines_order`, `machines_page`, `machines_q`, and `machines_my_workers` are written server-side through `http/ui_cookies.py` from `views_machines.py` when `/tests/machines` normalizes the current filter state.
- `active_run_filters` is written by `static/js/active_run_filters.js` and preserves the Active runs filter selection across the three dimensions (test type, time control, and threads).
- `active_run_filters_panel` is written by `static/js/active_run_filters.js` and preserves whether the expandable Active runs filter controls are shown.
- `<prefix>pending_state`, `<prefix>paused_state`, `<prefix>failed_state`, `<prefix>active_state` and `<prefix>finished_state` are written by the toggle handler in `static/js/application.js` and preserve which run-table panels are collapsed.
- `live_elo_mode` is written by `static/js/live_elo.js` and preserves the Elo gauge mode.
- `spsa_percentage` is mirrored by the shared checkbox-cookie handler from the `% c` checkbox of the SPSA section.
- `tasks_state` preserves whether the tasks panel of the detail page is collapsed; `tasks_sort`, `tasks_order`, `tasks_view` and `tasks_q` are written server-side when `/tests/tasks/{id}` normalizes its controls.

This split keeps auth/session semantics on the server-controlled signed cookie while letting low-risk UI preferences remain simple, readable browser state.

## CSRF protection

- A token is generated per session on first access (`CookieSession.get_csrf_token()`).
- Validated on every UI POST when `require_csrf` is set in the route config.
- The token can be submitted as:
- A form field `csrf_token`.
- An HTTP header `X-CSRF-Token`.
- Validation uses `secrets.compare_digest()` for timing-safe comparison.
- Failure raises HTTP 403.

## Authentication

### Login flow

1. `GET /login` renders the Remember me checkbox checked by default.
2. If the `login_remember_me` UI cookie stores an explicit opt-out, the same page renders the checkbox unchecked on later visits.
3. User submits username/password to `POST /login`.
4. `UserDb.authenticate()` validates credentials.
5. On success, `remember(request, username)` sets `session["user"]`.
6. Checked Remember me emits a persistent signed session cookie using the shared remember-me lifetime. Unchecked login keeps the auth cookie scoped to the current browser session.
7. `POST /login` also refreshes `login_remember_me` so the user's explicit checkbox choice survives later browser starts.
8. Redirect to the `next` parameter, else the `came_from` parameter, else the current URL (`/` when that is the login page itself).

### Logout flow

1. `POST /logout` calls `forget(request)`.
2. Session dict is cleared and `session_force_clear` is set.
3. Redirect to `/tests`.

### Access control

- `ensure_logged_in(request)` checks `session["user"]`. If absent, redirects to `/login` with a flash message.
- Group-based authorization: `userdb.get_user_groups(username)` returns group memberships. The `has_permission("approve_run")` method checks for `"group:approvers"`.

## URL generation

- Templates write route paths literally and read `request.url` where they need the current address; no route carries a `name=`, and no template calls `url_for`.
- `static_url(path)` maps to `/static/{path}` with a cache-busting query parameter (SHA-384 hash of file content).
- Navigation URLs are provided as a `urls` dict in the base template context.

## Navigation behavior

- The sidebar `Users` link shows `Users (N)` when `N` users are pending approval.
- With JavaScript enabled, that link refreshes its pending-user count periodically while the tab is visible and refreshes again when the tab becomes visible via `visibilitychange`.
- The sidebar `GitHub Rate Limits` link keeps its text fixed and reflects the browser-side GitHub client budget used by pages that read the token from local storage.
- When the client budget falls below the current warning threshold, the link switches to the same red status styling used by the pending-users sidebar item.
- The sidebar reuses the last known client warning state from local storage on first paint, so page navigation does not flash the link back to its normal color before the client poll completes.
- The browser-side GitHub poll runs on every page that renders the sidebar, pauses while the tab is hidden, refreshes immediately on `visibilitychange`, window `focus`, and bfcache `pageshow`, and then resumes its normal cadence from that activation point.
- When JavaScript is unavailable, the same link still works as normal navigation and the count refreshes on the next full-page render.

## Adding a new UI route

1. Write a sync handler function that receives a `_ViewContext` and returns either a dict (for template rendering) or a `RedirectResponse`.
2. Add an entry to `_VIEW_ROUTES`:

   ```
   (my_handler, "/my/path", {"renderer": "mypage.html.j2", "require_csrf": True})
   ```
3. Create the Jinja2 template in `templates/`.
4. Add a contract test in the route family's `tests/test_views_*.py` module (for example `test_views_actions.py`), and the route's methods in `test_views_routes.py`.

## Homepage workers (`/tests/machines`) query parameters

The homepage workers fragment (`/tests/machines`) supports URL-driven state for server sorting, paging, and lightweight filtering.

| Parameter | Values | Default |
| --- | --- | --- |
| `sort` | `last_active`, `machine`, `cores`, `uuid`, `mnps`, `ram`, `system`, `arch`, `compiler`, `python`, `worker`, `running_on` | `last_active` |
| `order` | `asc`, `desc` | column default |
| `page` | integer `>= 1` | `1` |
| `q` | free-text filter matched against any displayed machine column | empty |
| `my_workers` | `1`, `true`, `on`, `yes` | absent/false |

Behavior notes:

- Sorting is server-authoritative and stable with username asc tie-breaks.
- Pagination is enabled with page size `500`; links are omitted for one-page result sets.
- `my_workers` only applies for authenticated users; anonymous requests ignore this filter.
- `q` performs case-insensitive substring matching across all displayed table columns (machine, cores, UUID, MNps, RAM, system, arch, compiler, python, worker, running-on, and last-active text).
- Polling includes the current homepage filter-form state (`hx-include`), so sort/filter/page settings persist across periodic refreshes, including while the `q` search filter remains active.
- Filter controls (`q`, `my_workers`) are rendered on `/tests` outside the swapped machines fragment to avoid input focus/caret glitches during table refresh swaps.
- `/tests/machines` responses persist the effective `sort`, `order`, `page`, `q`, and `my_workers` values in cookies, so returning to `/tests` restores the last machines filter state.
- Workers counter semantics are stable across `/tests`, `/tests/machines`, and the page-1 `/tests?live=run_tables` OOB updates:
- no active filters: `Workers - <total>`
- active `q` and/or `my_workers`: `Workers - <total> (<filtered>)`
- When workers filters are active and the Workers panel is collapsed, `/tests` and its page-1 live run-table fragment recompute the filtered value from the current machine snapshot instead of reusing the last cookie-backed filtered count.
- Machines sorting is fully server-authoritative; there is no client-side header sorter.

## Active runs type filter

The Active runs panel on `/tests` provides client-side checkboxes for filtering visible runs. The controls use a compact ellipsis toggle plus three independent dimensions matching the new-test submission page:

| Dimension | Checkboxes | Classification |
| --- | --- | --- |
| Test type | SPRT, SPSA, NumGames | `spsa` if SPSA params present; `sprt` if SPRT bounds present; `numgames` otherwise |
| Time control | STC, LTC | `get_tc_ratio(tc, threads) > 4` → LTC; else STC |
| Threads | ST, SMP | `threads > 1` → SMP; else ST |

An "All" master checkbox checks or unchecks all dimension checkboxes.

Filtering uses AND between dimensions and OR within each dimension: a row is visible when it matches at least one checked value in **every** dimension.

Behavior notes:

- Each table row carries three `data-*` attributes (`data-test-type`, `data-time-control`, `data-threads`) with a single value per dimension, computed by the server template.
- After the page is loaded, filtering remains client-side and uses those server-rendered attributes.
- The filter controls sit inside the Active panel's collapse section (matching the workers table filter placement).
- The Active filter bar remains visible even when there are zero active runs, so users can inspect or change persisted filter state before new runs appear.
- The ellipsis toggle shows or hides the filter controls without leaving the Active panel.
- Checkboxes are grouped by dimension with small text labels (Type, TC, Threads). On desktop the controls stay on one inline row. On mobile the ellipsis stays pinned at the left while the filter grid opens beside it, with the All checkbox on the first row and aligned checkbox columns.
- The "All" checkbox uses the indeterminate state when some (but not all) checkboxes are checked.
- The Active header keeps parentheses whenever a non-`All` filter state is active, even when the filtered count equals the total. Parentheses disappear only when the effective filter state is truly `All`.
- The panel header count updates to show both total and filtered counts when a filter is active: "Active - N (M) tests".
- Filter state is persisted in the `active_run_filters` cookie using the shared long-lived UI-cookie policy (`path=/`, `SameSite=Lax`). When all checkboxes are checked the cookie is cleared.
- On page reload, `/tests` restores the cookie-backed filter state in the first HTML response, including the checkbox state, filtered count text, and initial row-hide CSS. Hidden categories therefore do not flash briefly before the browser restores the filter logic.
- Active-row zebra striping follows the same visible-row pattern as the other filtered tables. The Active filter logic keeps the visible rows contiguous in tbody order, so the normal alternating darker or lighter `table-striped` pattern stays correct after checkbox changes and after homepage polling replaces the Active tbody. The striping contract does not depend on hidden categories retaining their original sibling positions.
- Clearing every checkbox persists as an explicit empty selection, so reloads keep the Active panel empty until categories are enabled again.
- The filter panel open/closed state is persisted in the `active_run_filters_panel` cookie.
- Filters are re-applied after htmx OOB swap updates to the active runs tbody, so periodic poll refreshes respect the current filter state.
- Notification bell buttons initialize from browser-local follow state after page load and stay hidden until that state is known, which avoids transient wrong bell icons during reload.

## User management (`/user_management`) query parameters

The user-management page supports URL-driven server-authoritative table state.

| Parameter | Values | Default |
| --- | --- | --- |
| `group` | `all`, `pending`, `blocked`, `idle`, `approvers` | `pending` |
| `sort` | `username`, `registration`, `groups`, `email` | `registration` |
| `order` | `asc`, `desc` | column default |
| `page` | integer `>= 1` | `1` |
| `q` | free-text filter matched against username column | empty |
| `view` | `paged`, `all` | `paged` |

Behavior notes:

- Sorting is server-authoritative and stable with username tie-breaks.
- Pagination uses page size `25` in paged view.
- `view=all` returns all matching rows up to a hard cap (`5000`) and hides pagination controls.
- `q` performs case-insensitive substring matching on username only.
- User-management filtering stays on the userdb path: the base list comes from `request.userdb.get_users()`, while pending/blocked subsets come from the cached `get_pending()` / `get_blocked()` helpers.
- htmx requests target `#user-management-content` and keep URL state via `hx-push-url="true"`.
- The outer GET form keeps `sort`, `order`, and `view` in hidden inputs. htmx fragment responses refresh those hidden inputs out of band so later group or filter changes preserve the current table state.
- Table sorting is fully server-authoritative; there is no client-side header sorter.

## Workers management (`/workers/show`) query parameters

The blocked-workers table supports URL-driven server-authoritative state.

| Parameter | Values | Default |
| --- | --- | --- |
| `filter` | `all-workers`, `le-5days`, `gt-5days` | `le-5days` |
| `sort` | `worker`, `last_changed`, `events`, `email` | `last_changed` |
| `order` | `asc`, `desc` | column default |
| `page` | integer `>= 1` | `1` |
| `q` | free-text filter matched against worker column | empty |
| `view` | `paged`, `all` | `paged` |

Behavior notes:

- `filter` keeps the server-side time-window behavior.
- Sorting is server-authoritative and stable with worker-name tie-breaks.
- Pagination uses page size `25` in paged view.
- `view=all` returns all matching rows up to a hard cap (`5000`) and hides pagination controls.
- `q` performs case-insensitive substring matching on worker name only.
- Non-approver users cannot sort by `email`; unsupported values fall back to default server sort.
- htmx requests target `#workers-content` and keep URL state via `hx-push-url="true"`.
- Sort-header links are dual-mode (`href` + `hx-get`): workers sorting swaps `#workers-content` with `hx-push-url="true"` when htmx is active, and still degrades to full-page navigation.
- The outer GET form keeps `sort`, `order`, and `view` in hidden inputs. htmx fragment responses refresh those hidden inputs out of band so later filter changes preserve the current table state.
- Table sorting is fully server-authoritative; there is no client-side header sorter.

## Contributors query parameters

The contributors pages (`/contributors` and `/contributors/monthly`) support URL-driven state for server sorting, search, paging, full view, and rank jump.

| Parameter | Values | Default |
| --- | --- | --- |
| `search` | one-shot go-to query (exact username first, then first substring match) | empty |
| `sort` | `cpu_hours`, `username`, `last_updated`, `games_per_hour`, `games`, `tests`, `tests_repo` | `cpu_hours` |
| `order` | `asc`, `desc` | column default |
| `page` | integer `>= 1` | `1` |
| `view` | `paged`, `all` | `paged` |
| `findme` | any non-empty value (`findme=0` included) | absent |
| `highlight` | username | empty |

Behavior notes:

- Sorting is server-authoritative and stable with username asc tie-breaks.
- Rank is global for the filtered+sorted dataset (not page-local loop index).
- `findme=1` redirects authenticated users to the page containing their row and sets `highlight=<username>#me`.
- `view=all` returns all rows up to a hard cap (`5000`) and hides pagination.
- `search` is consumed as one-shot navigation intent and is not preserved in pagination/sort/view links, preventing repeated jumps during later browsing.
- `/contributors` and `/contributors/monthly` stay on the userdb fast path: the all-time page reads from `userdb.user_cache`, and the monthly page reads from `userdb.top_month`, a rolling cache rebuilt from unfinished runs (pending and active) plus finished runs started within the last 30 days.
- Sort-header links are dual-mode (`href` + `hx-get`): contributors sorting swaps `#contributors-content` with `hx-push-url="true"` when htmx is active, and still works as normal navigation when JavaScript is unavailable.
- The outer search form keeps `sort`, `order`, and `view` as hidden inputs. htmx fragment responses refresh those inputs out of band so later search or rank-jump requests do not replay stale table state.

## Neural networks (`/nns`) query parameters

The neural network repository page (`/nns`) supports URL-driven state for search and paging.

| Parameter | Values | Default |
| --- | --- | --- |
| `network_name` | literal network name substring (case-insensitive) | empty |
| `user` | literal uploader username substring (case-insensitive) | empty |
| `master_only` | `1`, `true`, `on`, `yes` | absent/false |
| `sort` | `time`, `name`, `user`, `first_test`, `last_test`, `downloads` | `time` |
| `order` | `asc`, `desc` | `desc` |
| `view` | `paged`, `all` | `paged` |
| `page` | integer `>= 1` | `1` |

Behavior notes:

- The page renders four summary cards above the table for the current filtered result set: Nets, Master nets, Contributors, and Downloads.
- The explanatory CC0 and default-net copy is rendered under the summary cards and above the paged or all view controls.
- Sorting is server-authoritative and deterministic.
- Sort-header links are dual-mode (`href` + `hx-get`): sorting swaps `#nns-content` with `hx-push-url="true"` when htmx is active, with plain-link fallback preserved.
- Pagination links follow the same dual-mode contract.
- Search inputs are htmx-triggered (`input changed delay`) and also support explicit submit for keyboard and non-JS flows.
- `network_name` and `user` are treated as literal substring filters; regex metacharacters have no special meaning.
- htmx updates target `#nns-content` and push updated query URLs for back/forward and shareable links.
- The filter form is rendered inside `#nns-content`, under the explanatory copy and above the paged or all switch, so htmx responses keep the full page order aligned with the other card pages: cards, text, filters, view switch, pagination, table, pagination.
- `master_only` checkbox preference is persisted in a cookie and reused when the query parameter is not present. The form also submits an explicit false fallback so unchecked htmx requests and cookie persistence stay aligned.
- Table sorting is fully server-authoritative; there is no client-side header sorter.

## Actions (`/actions`) query parameters

The actions log supports URL-driven server-authoritative filtering, paging, and sort state on the canonical `/actions` route.

| Parameter | Values | Default |
| --- | --- | --- |
| `action` | action name filter | empty |
| `user` | username substring | empty |
| `text` | Mongo text-search query | empty |
| `run_id` | run id | empty |
| `page` | integer `>= 1` | `1` |
| `max_count` | positive integer, capped by auth state | route policy |
| `sort` | `time`, `event`, `source`, `target`, `comment` | `time` |
| `order` | `asc`, `desc` | `desc` for `time`, otherwise column default |
| `before` | action timestamp cursor for time-link deep links | absent |

Behavior notes:

- Sorting is server-authoritative. The default `time desc` path stays on the indexed fast query; explicit alternate sorts materialize and sort the capped working set server-side.
- Anonymous requests are capped at `5000` actions. Authenticated requests without an explicit `max_count` default to `50000`; explicit `max_count` values are preserved in the URL and hidden form state.
- htmx requests target `#actions-content` and keep URL state via `hx-push-url="true"`.
- The visible filters auto-submit on select change and search/input events.
- The username field follows the same pattern as the other username filters in the UI: it is a plain `<input type="search">` in the main `/actions` GET form.
- `user` matches case-insensitive username substrings, not only exact names.
- When multiple usernames match a fragment, prefix matches are ranked before inner-substring matches, and ties stay recent-first within each username.
- Typing pauses trigger the existing debounced htmx form request, so results refresh from `GET /actions?...` without a separate suggestions endpoint, popup, or second swap target.
- To keep that debounced path fast on large historical logs, `/actions` resolves substring matches from a short-lived cached distinct username list built from the actions collection, refreshes it once on a no-match lookup, then fetches the matching rows by exact username query while keeping the active `action`, `text`, `run_id`, and time-cursor filters applied on each exact-username fetch. This differs from `/contributors` and `/user_management`, which can stay on userdb-backed sources because they only need current user records.
- The summary line reports both the visible row count on the current page and the total matching row count, so pagination does not imply every match is currently rendered.
- The time link remains a normal anchor because it is a shareable deep link into the log timeline, not just a local fragment action.
- Full-page `/actions` responses emit server-owned Open Graph metadata. Unlike `/tests/view/{id}`, the preview keeps the current query string in `og:url` because the filters, time cursor, and explicit `max_count` define the shared log slice; the title and description summarize the first visible action row.

## Finished Tests (`/tests/finished`) query parameters

The finished tests page supports URL-driven server-authoritative filtering, pagination, and htmx fragment refresh on the canonical `/tests/finished` route.

| Parameter | Values | Default |
| --- | --- | --- |
| `success_only` | `1` to show green results only | absent |
| `yellow_only` | `1` to show yellow results only | absent |
| `ltc_only` | `1` to show LTC results only | absent |
| `sort` | `time` | `time` |
| `order` | `desc` | `desc` |
| `user` | case-insensitive username substring | empty |
| `text` | text search on the run info; `info_regex` is read as an alias | empty |
| `mode` | `search` for the search form, which ignores the three filters above | absent |
| `max_count` | positive integer, capped by auth state | route policy |
| `page` | integer `>= 1` | `1` |

Behavior notes:

- htmx requests target `#tests-finished-content` and keep URL state via `hx-push-url="true"`.
- Finished tests currently use a fixed recent-first order, but still carry the explicit `sort=time` and `order=desc` query parameters so the URL contract stays aligned with the actions page.
- htmx tab clicks refresh the results target directly and refresh the tab strip out of band so the active-tab styling stays aligned with the pushed URL.
- The username input auto-submits on debounced input and native search clear events.
- The run-info text-search input auto-submits on debounced input and native search clear events.
- In search mode, the username and free-text fields rely on the shared Bootstrap grid sizing used by the other standalone filter pages. The page does not apply a dedicated width override to the free-text control.
- `user` resolves case-insensitive username substrings from a short-lived cached username list on the users collection, then queries the matching usernames through the exact-username finished-run path.
- When multiple usernames match a fragment, prefix matches are ranked before inner-substring matches, and ties stay recent-first within each username.
- Finished rows without a usable `last_updated` value sort after timestamped rows in the merged recent-first result, and equal fallback rows stay stable by run id.
- `text` alone runs a MongoDB `$text` query against the run info of finished runs. With a `user` filter it runs a case-insensitive `$regex` on `args.info` instead, so the username index serves the query.
- `/actions` and `/tests/finished` share the same `max_count` query parameter for result caps. `/tests/user/{username}` applies no cap: it carries no filter, so a `max_count` there is stripped by redirect.
- Anonymous search requests use the anonymous finished-run search cap. Authenticated search requests use the authenticated finished-run default. Explicit `max_count` values are preserved in the URL and hidden form state.
- Navigation mode (no filters active) is uncapped — `max_count` is not used.
- Stale `max_count` values in navigation-mode URLs are stripped via redirect.
- The summary line reports both the visible row count on the current page and the total matching finished-run count. Deleted runs are excluded from both the displayed rows and the total count.
- Oversized `max_count` values are clamped to MongoDB's signed 64-bit integer range before they reach pymongo.
