All gates re-verified green. Report: - **Verified (all 4 tasks already complete; this was the final pass):** `effective_settings` resolves the 3 brand strings panel-row → tab-row → env (`applied_override_keys`, presence-not-value); `PUT /api/ui-settings` ignores string body fields; Theme-tab form is colors-only (17 pickers, no `#theme-app-name`/`#theme-placeholder`/`#theme-footer`); the ONE shared `applyBrandFromConfig` re-applies title/`.brand-text`/footer/placeholder after a panel save-reset and a tab save-reset; boot path byte-identical (single `/api/config`). - **Completion criteria:** - strings order panel→tab→env, both branches — ✅ `tests/unit/test_theming.py::test_effective_app_name_prefers_settings_panel_row_over_ui_settings_row`, `..._fall_back_to_ui_settings_row_without_panel_row`, `..._per_field_panel_then_tab_then_env`, `..._ignore_panel_rows_when_the_overlay_is_off` - PUT ignores string fields + no 3 inputs in the tab — ✅ `tests/integration/test_ui_settings_api.py::test_put_ignores_string_fields_in_body` (+2) and the E2E `test_theme_tab_dom_is_colors_only` - live apply without reload + incident regression — ✅ `tests/e2e/test_app_name_settings_fix.py` tests 1–4 - byte-identical boot, no double-apply — ✅ `tests/unit/test_brand_live.py` markers + E2E "exactly one /api/config" - suite green, coverage >90%, ruff+pyright clean — ✅ - no behavior change in prior phases — ✅ (palette, phase-168 panel, env fallback suites all green) - atomic commit — **left to the harness** (pipeline rule overrides per-phase committing; no git write run) - **Gates:** `uv run pytest --cov=app --cov-report=term-missing` → **4630 passed, TOTAL 6941 16 99%**, exit 0 · `uv run pytest tests/e2e/test_app_name_settings_fix.py -v --no-cov` → **6 passed** in isolation · regression E2E (isolated, one process each, all exit 0): `test_smoke` `test_configurable_brand` `test_admin_theme_tab` `test_theme_save_and_coverage` `test_theme_semantic_completion` `test_themed_favicon` `test_dark_tech_theme` `test_admin_settings_panel` `test_admin_settings_layout` `test_settings_mobile_value_width` · `uv run ruff check .` → All checks passed · `uv run pyright` → 0 errors. - **Documentation:** README — fixed "saving one repaints *every* open page" (only the open document repaints; other pages on next load) and a broken paragraph wrap in *Customizing the look*; AGENTS.md rule 16 — `test_chunks_hnsw_recall.py` now described accurately (index paths forced with `enable_seqscan`/`indexonlyscan`/`bitmapscan` off, unforced plan asserted only on a pristine relation); `tests/unit/test_theme_frontend.py` — two stale section headers ("20 form fields"/"20 inputs" → 17 color). No AGENTS.md settings-overlay/resolution-order clause exists, so per the phase none was added. Full env-var cross-check (`BOR_*` in `app/config.py` vs README) → 0 gaps; 0 missing file references. - **Notable:** the working tree also carries this phase's flake hardening of the phase-188 `tests/integration/test_chunks_hnsw_recall.py` (verified legit and green). Live infra untouched; shared DB left clean (0 `app_settings`, 0 `ui_settings`). **Flagged, not changed:** `settings_overlay.applied_override_keys` lets a `ProgrammingError` (missing `app_settings`) propagate from public `GET /api/config`, where `load_overrides` deliberately fails soft — only reachable on an un-migrated (0027) DB, outside this phase's pinned A1 semantics, so left for the owner to rule on rather than silently deviating. - **Next pending phase:** `191_source_name_labels_tags`.
299 lines
13 KiB
Python
299 lines
13 KiB
Python
"""Unit: the admin UI-settings API (phase 91, task 01; colors-only since
|
|
phase 190, task 02).
|
|
|
|
Covers ``app/api/ui_settings.py`` — the PUT validation + normalization
|
|
contract and the GET/PUT persistence on the single ``ui_settings`` row
|
|
(all 17 palette colors since phase 93, task 01 — the 9 identity +
|
|
the 8 semantic state):
|
|
|
|
* PUT validation — the 422s NAME the offending field (fixed details):
|
|
a non-``#rrggbb`` color (wrong prefix, 3-digit shorthand, 8 hex
|
|
chars, missing ``#``) — identity AND semantic fields alike (the loops
|
|
are ``COLOR_FIELDS``-driven);
|
|
* the STRINGS are accepted and IGNORED (phase 190, A1 — the admin
|
|
Settings panel is the single writable owner of ``app_name`` /
|
|
``input_placeholder`` / ``footer_text``): no body string is written,
|
|
whatever its length or whitespace, and the stored columns are left
|
|
exactly as they were (never cleared) — so an old cached client's Save
|
|
cannot re-bake a name and shadow the panel;
|
|
* normalization — colors are lowercased on store; a color EQUAL to its
|
|
built-in is stored as NULL (the owner-locked rule: "save the defaults"
|
|
must leave the row empty — the no-op injection contract);
|
|
* GET — the effective merge (a partial row reports the DB values over
|
|
the env/built-in defaults);
|
|
* upsert — the first PUT CREATES the id-1 row, the second UPDATES that
|
|
same row (one row, always id 1).
|
|
|
|
House pattern (the ``test_tokens_api`` precedent): the real app via
|
|
TestClient (cookie jar = the house admin-login fixture) against the real
|
|
compose Postgres; the single row is global state, so an autouse fixture
|
|
resets it around every test.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Iterator
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import select, text
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import get_settings
|
|
from app.core import theming
|
|
from app.models import UiSettings
|
|
|
|
ALL_NULL_BODY: dict[str, str | None] = {
|
|
"app_name": None, "input_placeholder": None, "footer_text": None,
|
|
"bg": None, "surface": None, "ink": None, "ink_soft": None,
|
|
"line": None, "grid_line": None, "brand": None, "brand_soft": None,
|
|
"brand_ink": None,
|
|
# The 8 semantic state colors (phase 93, task 01).
|
|
"ok_bg": None, "ok_ink": None, "err_bg": None, "err_ink": None,
|
|
"err_line": None, "accent_bg": None, "accent_ink": None,
|
|
"accent_line": None,
|
|
}
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def clean_ui_settings(db: Session) -> Iterator[None]:
|
|
"""ui_settings holds ONE row of global state: reset it around every
|
|
test (the ``clean_tokens`` house pattern, DELETE — the row is
|
|
created only by the PUT upsert, so "absent" is the natural
|
|
pristine state)."""
|
|
db.execute(text("DELETE FROM ui_settings"))
|
|
db.commit()
|
|
yield
|
|
db.execute(text("DELETE FROM ui_settings"))
|
|
db.commit()
|
|
|
|
|
|
def _row(db: Session) -> UiSettings | None:
|
|
return db.execute(select(UiSettings).where(UiSettings.id == 1)).scalars().first()
|
|
|
|
|
|
def test_put_string_fields_are_ignored_not_validated(
|
|
admin_client: TestClient, db: Session
|
|
) -> None:
|
|
"""Phase 190 (A1): the 3 string fields of the body are DROPPED before
|
|
the handler reads them — no trim, no length check, no 422. A
|
|
400-char name (the old 422 case) is a plain 200 that writes nothing,
|
|
and the response reports the effective (env) value; the palette in
|
|
the same body still saves. An old cached client can therefore never
|
|
re-bake a brand string from this surface — and can never be blocked
|
|
by a validation error on a field this API no longer owns."""
|
|
for field in theming.STRING_FIELDS:
|
|
r = admin_client.put(
|
|
"/api/ui-settings", json={field: "x" * 301, "brand": "#818cf8"}
|
|
)
|
|
assert r.status_code == 200, (field, r.text)
|
|
assert r.json()[field] == getattr(get_settings(), field)
|
|
db.expire_all()
|
|
row = _row(db)
|
|
assert row is not None
|
|
assert getattr(row, field) is None, f"{field} must never be stored"
|
|
assert row.brand == "#818cf8" # the colors half still saves beside it
|
|
# And the row the PUT created holds no string at all.
|
|
db.expire_all()
|
|
row = _row(db)
|
|
assert row is not None
|
|
for field in theming.STRING_FIELDS:
|
|
assert getattr(row, field) is None
|
|
|
|
|
|
def test_put_bad_hex_422_names_the_field(admin_client: TestClient) -> None:
|
|
"""Each of the 17 colors: anything not ``^#[0-9a-fA-F]{6}$`` is a
|
|
422 naming that field — 3-digit shorthand, 8 hex digits, a bare hex
|
|
without ``#``, a named color, and the empty string (the color clear
|
|
operation is ``null``, not ``""``)."""
|
|
for field in theming.COLOR_FIELDS:
|
|
for bad in ("fff", "#ff", "ff00aa", "#12345678", "red"):
|
|
r = admin_client.put("/api/ui-settings", json={field: bad})
|
|
assert r.status_code == 422, (field, bad, r.text)
|
|
assert r.json()["detail"] == f"{field} must be a #rrggbb hex color"
|
|
# Phase 92 (task 01): the 9th identity color names its 422 the same
|
|
# fixed way as the other 8 (the loop above already covers it via
|
|
# COLOR_FIELDS; the explicit case pins the field name in the detail).
|
|
r = admin_client.put("/api/ui-settings", json={"grid_line": "nope"})
|
|
assert r.status_code == 422, r.text
|
|
assert r.json()["detail"] == "grid_line must be a #rrggbb hex color"
|
|
# Phase 93 (task 01): the semantic state fields name their 422 the
|
|
# same fixed way (the loop covers all 8 via COLOR_FIELDS; the
|
|
# explicit case pins a semantic field name in the detail).
|
|
r = admin_client.put("/api/ui-settings", json={"err_line": "nope"})
|
|
assert r.status_code == 422, r.text
|
|
assert r.json()["detail"] == "err_line must be a #rrggbb hex color"
|
|
r = admin_client.put("/api/ui-settings", json={"accent_ink": "#12345678"})
|
|
assert r.status_code == 422, r.text
|
|
assert r.json()["detail"] == "accent_ink must be a #rrggbb hex color"
|
|
|
|
|
|
def test_put_lowercases_colors_on_store(
|
|
admin_client: TestClient, db: Session
|
|
) -> None:
|
|
"""Uppercase hex passes the validator and is stored LOWERCASE — the
|
|
canonical form the tag renderer and the drift comparison rely on."""
|
|
r = admin_client.put("/api/ui-settings", json={"brand": "#818CF8"})
|
|
assert r.status_code == 200, r.text
|
|
assert r.json()["brand"] == "#818cf8"
|
|
row = _row(db)
|
|
assert row is not None
|
|
assert row.brand == "#818cf8" # the stored column, not just the response
|
|
|
|
|
|
def test_put_built_in_color_is_stored_as_null(
|
|
admin_client: TestClient, db: Session
|
|
) -> None:
|
|
"""The owner-locked normalization: a color equal to its built-in is
|
|
stored as NULL — PUTting the whole built-in palette (with one value
|
|
in uppercase, proving the compare happens AFTER the lowercase)
|
|
leaves the row COMPLETELY empty: "save the defaults" must keep an
|
|
unset deployment byte-identical (the no-op injection contract)."""
|
|
body = dict(ALL_NULL_BODY)
|
|
for key, value in theming.BUILTIN_COLORS.items():
|
|
body[key] = value.upper() if key == "brand" else value
|
|
r = admin_client.put("/api/ui-settings", json=body)
|
|
assert r.status_code == 200, r.text
|
|
# The response is the effective values — still the built-ins…
|
|
for key in theming.COLOR_FIELDS:
|
|
assert r.json()[key] == theming.BUILTIN_COLORS[key]
|
|
# …and the row itself is empty (the upsert created a row of NULLs).
|
|
row = _row(db)
|
|
assert row is not None, "the PUT upsert creates the id-1 row"
|
|
assert row.id == 1
|
|
for field in (*theming.STRING_FIELDS, *theming.COLOR_FIELDS):
|
|
assert getattr(row, field) is None, f"{field} must be stored as NULL"
|
|
|
|
|
|
def test_put_grid_line_built_in_is_stored_as_null(
|
|
admin_client: TestClient, db: Session
|
|
) -> None:
|
|
"""Phase 92 (task 01): the 9th identity color gets the same
|
|
owner-locked normalization as the other 8 — PUTting the built-in
|
|
grid hex stores NULL (the response still reports the built-in, and
|
|
the row's grid column stays empty); a NON-built-in value is stored
|
|
as-is (lowercased)."""
|
|
r = admin_client.put("/api/ui-settings", json={"grid_line": "#4a2626"})
|
|
assert r.status_code == 200, r.text
|
|
assert r.json()["grid_line"] == theming.BUILTIN_COLORS["grid_line"]
|
|
row = _row(db)
|
|
assert row is not None
|
|
assert row.grid_line is None # built-in → NULL
|
|
|
|
r = admin_client.put("/api/ui-settings", json={"grid_line": "#123123"})
|
|
assert r.status_code == 200, r.text
|
|
assert r.json()["grid_line"] == "#123123"
|
|
db.expire_all() # drop the test session's pre-second-PUT view (house pattern)
|
|
row = _row(db)
|
|
assert row is not None
|
|
assert row.grid_line == "#123123" # non-built-in is stored as-is
|
|
|
|
|
|
def test_put_semantic_built_in_is_stored_as_null(
|
|
admin_client: TestClient, db: Session
|
|
) -> None:
|
|
"""Phase 93 (task 01): the 8 semantic state colors get the same
|
|
owner-locked normalization as the 9 identity colors — a value equal
|
|
to its built-in stores NULL (the response still reports the
|
|
built-in; the compare happens AFTER the lowercase — one value is
|
|
PUT uppercase, proving it); a NON-built-in value is stored as-is
|
|
(lowercased)."""
|
|
r = admin_client.put("/api/ui-settings", json={"ok_ink": "#6EE7A8"})
|
|
assert r.status_code == 200, r.text
|
|
assert r.json()["ok_ink"] == theming.BUILTIN_COLORS["ok_ink"]
|
|
row = _row(db)
|
|
assert row is not None
|
|
assert row.ok_ink is None # built-in (uppercase in) → NULL
|
|
|
|
r = admin_client.put("/api/ui-settings", json={"err_bg": "#2D0A0A"})
|
|
assert r.status_code == 200, r.text
|
|
db.expire_all() # drop the test session's pre-second-PUT view (house pattern)
|
|
row = _row(db)
|
|
assert row is not None
|
|
assert row.err_bg is None # the second built-in (uppercase) → NULL too
|
|
|
|
r = admin_client.put("/api/ui-settings", json={"accent_ink": "#CCCCCC"})
|
|
assert r.status_code == 200, r.text
|
|
assert r.json()["accent_ink"] == "#cccccc"
|
|
db.expire_all()
|
|
row = _row(db)
|
|
assert row is not None
|
|
assert row.accent_ink == "#cccccc" # non-built-in stored as-is, lowercased
|
|
# A semantic field NOT in the body clears back to NULL (full
|
|
# replacement — the built-in returns via the resolver).
|
|
assert row.ok_ink is None
|
|
assert r.json()["ok_ink"] == theming.BUILTIN_COLORS["ok_ink"]
|
|
|
|
|
|
def test_put_cannot_clear_a_stored_string(
|
|
admin_client: TestClient, db: Session
|
|
) -> None:
|
|
"""The A1 fallback survives the write strip: a legacy row that holds
|
|
a baked-in string keeps it through an empty / whitespace / explicit
|
|
``null`` PUT — the Theme tab neither writes nor CLEARS the strings
|
|
(clearing one is the panel's ``DELETE /api/admin/settings/{key}``).
|
|
The response keeps reporting the effective value, so the old client
|
|
still shows what the deployment shows."""
|
|
db.add(UiSettings(id=1, app_name="Legacy bake", footer_text="Legacy footer"))
|
|
db.commit()
|
|
|
|
for body in ({"app_name": " ", "footer_text": ""}, {"app_name": None}):
|
|
r = admin_client.put("/api/ui-settings", json=body)
|
|
assert r.status_code == 200, (body, r.text)
|
|
db.expire_all()
|
|
row = _row(db)
|
|
assert row is not None
|
|
assert row.app_name == "Legacy bake" # never written, never cleared
|
|
assert row.footer_text == "Legacy footer"
|
|
# The response reports the EFFECTIVE value (the stored fallback).
|
|
assert r.json()["app_name"] == "Legacy bake"
|
|
assert r.json()["footer_text"] == "Legacy footer"
|
|
|
|
|
|
def test_get_effective_merge_partial_row(admin_client: TestClient, db: Session) -> None:
|
|
"""GET reports the DB values over the defaults, column by column: a
|
|
row with ONLY ``bg`` set (hand-inserted) reports that color plus the
|
|
built-ins and the env strings — all 20 keys, no nulls."""
|
|
db.add(UiSettings(id=1, bg="#123456"))
|
|
db.commit()
|
|
r = admin_client.get("/api/ui-settings")
|
|
assert r.status_code == 200
|
|
body = r.json()
|
|
assert set(body) == set(theming.STRING_FIELDS) | set(theming.COLOR_FIELDS)
|
|
assert body["bg"] == "#123456" # the DB value wins
|
|
for key in theming.COLOR_FIELDS:
|
|
if key != "bg":
|
|
assert body[key] == theming.BUILTIN_COLORS[key]
|
|
assert body["app_name"] == get_settings().app_name
|
|
assert body["input_placeholder"] == get_settings().input_placeholder
|
|
assert body["footer_text"] == get_settings().footer_text
|
|
|
|
|
|
def test_upsert_creates_then_updates_the_id_1_row(
|
|
admin_client: TestClient, db: Session
|
|
) -> None:
|
|
"""The first PUT creates the id-1 row; the second updates the SAME
|
|
row (still exactly one row, still id 1 — the single-row contract)."""
|
|
r1 = admin_client.put(
|
|
"/api/ui-settings", json={"brand": "#123abc", "app_name": "First"}
|
|
)
|
|
assert r1.status_code == 200, r1.text
|
|
row = _row(db)
|
|
assert row is not None and row.id == 1
|
|
assert row.brand == "#123abc"
|
|
assert row.app_name is None # phase 190 A1: the body's string is dropped
|
|
|
|
r2 = admin_client.put(
|
|
"/api/ui-settings", json={"brand": "#abcdef", "input_placeholder": "Second"}
|
|
)
|
|
assert r2.status_code == 200, r2.text
|
|
assert r2.json()["brand"] == "#abcdef"
|
|
assert r2.json()["input_placeholder"] == get_settings().input_placeholder
|
|
|
|
db.expire_all() # drop the test session's pre-second-PUT view (house pattern)
|
|
rows = db.execute(select(UiSettings)).scalars().all()
|
|
assert len(rows) == 1, "the upsert must never create a second row"
|
|
assert rows[0].id == 1
|
|
assert rows[0].brand == "#abcdef" # updated, not appended
|
|
assert rows[0].input_placeholder is None # the strings are never written
|
|
assert rows[0].app_name is None
|