feat(web): customizable placeholder, footer text, and color theme via BOR_* env vars

BOR_INPUT_PLACEHOLDER / BOR_FOOTER_TEXT / BOR_THEME (+ the indigo.css example theme); authoring guide: frontend/assets/themes/README.md, docs: README 'Customizing the look'.
This commit is contained in:
2026-09-01 12:04:06 -04:00
parent baefcde668
commit c738105932
17 changed files with 1057 additions and 73 deletions
+74
View File
@@ -397,3 +397,77 @@ def test_docs_branchs_garbage_ignored_when_repo_unset(
s = _settings()
assert s.docs_configured is False
assert s.docs_branch == "bor docs.." # stored verbatim, never used
# --- UI customization (phase 62, TODO L3) ---
def test_ui_customization_defaults_are_the_phase_61_copy() -> None:
"""UNSET => byte-identical to the phase-61 neutral UI: the locked
phase-61 copy is the DEFAULT (composer placeholder + footer line),
and an empty theme = the built-in dark-tech palette."""
s = _settings()
assert s.input_placeholder == "Ask me anything…"
assert s.footer_text == "Powered by self-hosted models"
assert s.theme == ""
def test_ui_customization_env_overrides(monkeypatch: pytest.MonkeyPatch) -> None:
"""The three settings honor their ``BOR_`` env vars
(``BOR_INPUT_PLACEHOLDER`` / ``BOR_FOOTER_TEXT`` / ``BOR_THEME``);
placeholder/footer accept any string (empty is legal — the brand
layer then keeps the template default)."""
monkeypatch.setenv("BOR_INPUT_PLACEHOLDER", "Ask the vault…")
monkeypatch.setenv("BOR_FOOTER_TEXT", "Powered by my own models")
monkeypatch.setenv("BOR_THEME", "indigo.css")
s = _settings()
assert s.input_placeholder == "Ask the vault…"
assert s.footer_text == "Powered by my own models"
assert s.theme == "indigo.css"
monkeypatch.setenv("BOR_INPUT_PLACEHOLDER", "")
assert _settings().input_placeholder == "" # empty stands
def test_theme_validator_accepts_empty_and_bare_css_filename() -> None:
"""Phase 62 (A5): empty = the built-in palette; a bare lowercase
``.css`` filename (the ``indigo.css`` example) is the only
non-empty shape — dashes/underscores/digits are legal tokens."""
assert _settings().theme == "" # "" passes
assert _settings(theme="indigo.css").theme == "indigo.css"
assert _settings(theme="dark-2026_v2.css").theme == "dark-2026_v2.css"
@pytest.mark.parametrize(
("bad", "match"),
[
# uppercase — the shape is lowercase-only
("Indigo.css", "Indigo.css"),
# path escape — a theme is a filename, never a path
("../evil.css", r"\.\./evil\.css"),
("a/b.css", r"a/b\.css"),
("/abs.css", r"got '/abs\.css'"),
# a missing extension is not a theme file
("indigo", r"got 'indigo'"), # must not match the example text
],
)
def test_theme_validator_rejects_malformed_naming_the_value(
bad: str,
match: str,
) -> None:
"""A typo in ``BOR_THEME`` must kill startup, not silently 404 at
runtime — the rejection names the offending value (the phase-56
fail-loud house style) alongside the allowed shape."""
with pytest.raises(ValidationError, match=match):
_settings(theme=bad)
def test_bor_theme_env_malformed_fails_startup_naming_value(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The startup path: a malformed ``BOR_THEME`` in the environment
fails Settings construction loudly (the app builds its settings at
import time, so this is a refused boot), naming the value — the
E2E boots-check lands in task 05."""
monkeypatch.setenv("BOR_THEME", "../evil.css")
with pytest.raises(ValidationError, match=r"\.\./evil\.css"):
_settings()
+54
View File
@@ -95,6 +95,60 @@ def test_brand_js_reskins_title_brand_text_prose_and_attributes() -> None:
assert marker in js, f"the attribute pass must cover {marker}"
def test_brand_js_applies_phase_62_customization_from_the_same_fetch() -> None:
"""Phase 62 (owner-locked 2026-09-01, TODO L3): the SAME settled
/api/config answer also drives the three customization keys — the
#message-input placeholder, every .footer-text node, and the theme
stylesheet link (inserted right after the styles.css link, guarded
by #theme-override, degrading with a console.warn on 404 — A5).
No second network call: the keys ride the existing boot fetch."""
js = _text(BRAND_JS)
assert js.count('= fetch("/api/config"') == 1, (
"the three keys must ride the existing boot fetch — no new call"
)
# 5. The composer placeholder (chat page only — the null guard
# no-ops on every other page).
assert 'document.querySelector("#message-input")' in js
assert "input_placeholder" in js
# 6. The footer line on all 9 pages (the phase-61 hook) — via
# textContent: an operator string can't inject markup.
assert 'document.querySelectorAll(".footer-text")' in js
assert "footer_text" in js
# 7. The theme link: /assets/themes/<name>, inserted right after
# the styles.css link, tagged #theme-override (the idempotency
# guard), with the A5 degradation warn.
assert '"/assets/themes/"' in js
assert 'link.id = "theme-override"' in js
assert 'getElementById("theme-override")' in js
assert 'insertAdjacentElement("afterend", link)' in js
assert "link.onerror" in js
assert '"brand: theme " + themeName' in js
# The styles.css finder must survive the phase-33/54 cache-bust
# rewrite: the SERVED HTML carries the asset ref with a
# ?v=<token> query (and el.href is the absolute URL), so the match
# has to run on the RAW attribute path with query/fragment
# stripped — el.href.endsWith(…) would silently skip the insertion
# (the theme never applied; found by the task-05 E2E).
assert 'getAttribute("href")' in js
assert "split(/[?#]/)[0]" in js
assert 'endsWith("styles.css")' in js
assert "el.href.endsWith" not in js
# The empty-skip no-op contract: each key is guarded before any
# DOM write, so an unset deployment stays byte-identical.
for guard in ("if (placeholder) {", "if (footerText) {", "if (themeName) {"):
assert guard in js, (
f"an empty value must skip its application ({guard})"
)
# Independence: the phase-62 block sits AFTER the app_name passes
# in the same .then — never gated by the name.
assert js.index("// 4. Attributes:") < js.index("// Phase 62"), (
"the customization keys must apply after the app_name block, "
"even when the name is the default/empty"
)
# The app_name literal default pin still holds.
assert 'window.BOR_BRAND = "Brain of Reese"' in js
def test_page_scripts_keep_the_default_literal_exactly_once() -> None:
"""The fallback literal lives in the page scripts' brand() reads —
exactly one copy per file (a second copy could drift out of sync)."""
+6 -1
View File
@@ -51,7 +51,12 @@ def test_app_config_dict_carries_the_docs_flag() -> None:
s = _settings()
body = app_config(s)
assert set(body) == {"app_name", "version", "docs_repo_configured"}
# Phase 62 (task 01): the response grew to the six-key set — the
# phase-62 UI customization keys ride the SAME endpoint.
assert set(body) == {
"app_name", "version", "docs_repo_configured",
"input_placeholder", "footer_text", "theme",
}
assert body["docs_repo_configured"] is s.docs_configured
assert body["docs_repo_configured"] is False
+195
View File
@@ -0,0 +1,195 @@
"""Unit: the phase-62 example theme (``frontend/assets/themes/``) and
the Containerfile line that ships it (A7).
No Python logic exists for this task — the mechanism lives in
``brand.js`` (pinned by test_frontend_brand.py) and the theme is a
drop-in stylesheet. Like the other frontend-adjacent unit files, this
module pins the assets as text, so a silent regression (a theme file
gaining a selector, a declaration drifting, the Containerfile line
vanishing) is caught without a browser. The browser-visible layer
(computed ``--brand``, the inserted ``<link>``) is E2E-gated by
``tests/e2e/test_ui_customization.py`` (task 05).
"""
from __future__ import annotations
import re
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
FRONTEND = REPO_ROOT / "frontend"
THEMES = FRONTEND / "assets" / "themes"
INDIGO = THEMES / "indigo.css"
GUIDE = THEMES / "README.md"
CONTAINERFILE = REPO_ROOT / "Containerfile"
#: The 8 identity variables a theme may override — and the EXACT set
#: indigo.css ships (the semantic families accent/ok/err are states,
#: not identity: a theme that overrides them stops being honest).
IDENTITY_VARS = (
"--bg",
"--surface",
"--ink",
"--ink-soft",
"--line",
"--brand",
"--brand-soft",
"--brand-ink",
)
INDIGO_VALUES: dict[str, str] = {
"--bg": "#0a0e1a",
"--surface": "#111726",
"--ink": "#e6e9f0",
"--ink-soft": "#a8b0c8",
"--line": "#232c44",
"--brand": "#818cf8",
"--brand-soft": "#1a1f38",
"--brand-ink": "#c7d2fe",
}
def _text(path: Path) -> str:
return path.read_text(encoding="utf-8")
def _strip_comments(css: str) -> str:
"""Drop ``/* … */`` comments — the pins assert against declarations,
not prose."""
return re.sub(r"/\*.*?\*/", "", css, flags=re.S)
def _declarations(css: str) -> dict[str, str]:
"""The ``--name: value`` declarations of the (single) ``:root``
block, in file order."""
return dict(re.findall(r"(--[a-z-]+)\s*:\s*([^;]+);", css))
def test_example_theme_files_exist() -> None:
"""The example theme and its authoring guide ship in the static
dir (served at /assets/themes/… in dev AND in the image)."""
assert INDIGO.is_file(), f"missing example theme: {INDIGO}"
assert GUIDE.is_file(), f"missing authoring guide: {GUIDE}"
def test_indigo_starts_with_a_single_root_block_and_nothing_else() -> None:
"""The whole file is ONE ``:root`` block (the cascade is the entire
mechanism): after stripping comments the first non-whitespace
content is ``:root``, and no other rule, selector, or declaration
exists anywhere in the file."""
css = _strip_comments(_text(INDIGO))
assert css.lstrip().startswith(":root"), (
"indigo.css must start with the :root block (after its header "
"comment) — nothing may precede it"
)
assert re.fullmatch(r"\s*:root\s*\{[^{}]*\}\s*", css, re.S) is not None, (
"indigo.css must be exactly one :root block — no selectors, "
"no @media, no nested or extra rules"
)
def test_indigo_overrides_exactly_the_eight_identity_variables() -> None:
"""EXACTLY the 8 identity overrides with the locked values — no
other declarations (a 9th declaration here would be the theme
reaching past the palette), and the semantic families
(accent/ok/err) must be untouched (they encode states)."""
decls = _declarations(_strip_comments(_text(INDIGO)))
assert set(decls) == set(IDENTITY_VARS), (
f"indigo.css must override exactly the 8 identity variables, got "
f"{sorted(decls)}"
)
for name in IDENTITY_VARS:
assert decls[name].strip() == INDIGO_VALUES[name], (
f"{name} drifted from the locked value "
f"{INDIGO_VALUES[name]!r}, got {decls[name].strip()!r}"
)
for family in ("--accent-", "--ok-", "--err-"):
assert not any(k.startswith(family) for k in decls), (
f"semantic {family}* variables must stay the built-in "
f"theme (they encode states)"
)
def test_indigo_identity_pairs_meet_wcag_aa() -> None:
"""The five identity text/background pairs, computed from the file's
OWN hex values (not re-typed), each meet WCAG 2.1 AA (>= 4.5:1) —
AGENTS.md rule 5. The pairs are the ones the layout actually pairs:
ink on bg/surface, ink-soft on surface, the dark bg ink on brand
(text on brand buttons is --bg, never white — the built-in's
documented 3.7:1 trap), brand-ink on surface."""
decls = _declarations(_strip_comments(_text(INDIGO)))
def lum(hexcolor: str) -> float:
h = hexcolor.lstrip("#")
chans = (int(h[i : i + 2], 16) / 255.0 for i in (0, 2, 4))
lin = [
c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
for c in chans
]
r, g, b = lin
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def ratio(fg: str, bg: str) -> float:
l1, l2 = lum(fg), lum(bg)
return (max(l1, l2) + 0.05) / (min(l1, l2) + 0.05)
pairs = (
("ink on bg", decls["--ink"], decls["--bg"]),
("ink on surface", decls["--ink"], decls["--surface"]),
("ink-soft on surface", decls["--ink-soft"], decls["--surface"]),
("bg ink on brand", decls["--bg"], decls["--brand"]),
("brand-ink on surface", decls["--brand-ink"], decls["--surface"]),
)
for name, fg, bg in pairs:
r = ratio(fg, bg)
assert r >= 4.5, f"{name}: {r:.2f}:1 < 4.5:1 (WCAG 2.1 AA)"
def test_containerfile_ships_the_whole_themes_directory() -> None:
"""A7: stage 1 copies the WHOLE themes directory (no per-file
esbuild — a future theme file needs no Containerfile edit), and it
does so AFTER the styles.css minify line (so the served /assets/
tree is complete before the pages cp)."""
cf = _text(CONTAINERFILE)
stage1 = cf.split("AS frontend", 1)[1].split("\nFROM", 1)[0]
lines = stage1.splitlines()
cp_idxs = [
i
for i, ln in enumerate(lines)
if re.search(r"\bcp\s+-r\s+\./assets/themes\s+/out/assets/themes\b", ln)
]
assert len(cp_idxs) == 1, (
"stage 1 must ship the themes directory with exactly one "
"'cp -r ./assets/themes /out/assets/themes' line"
)
styles_idxs = [
i for i, ln in enumerate(lines) if "esbuild ./assets/styles.css" in ln
]
assert len(styles_idxs) == 1, "stage 1 must minify styles.css"
assert cp_idxs[0] > styles_idxs[0], (
"the themes cp must come AFTER the styles.css minify line"
)
cp_line = lines[cp_idxs[0]]
assert "--bundle" not in cp_line and "esbuild" not in cp_line, (
"A7: the themes directory is copied verbatim — no per-file "
"esbuild minify"
)
def test_authoring_guide_pins_the_contract() -> None:
"""The guide documents the load path (BOR_THEME → /api/config →
brand.js link after styles.css), the filename validator regex, the
8-variable table, the 4.5:1 bar, the never-white-on-brand trap,
and the A7 rebuild story (a new file needs no Containerfile edit)."""
guide = _text(GUIDE)
for marker in (
"BOR_THEME",
"/api/config",
"styles.css",
r"^[a-z0-9_-]+\.css$",
"4.5:1",
"white-on-brand",
"cp -r ./assets/themes /out/assets/themes",
):
assert marker in guide, f"themes/README.md must document {marker!r}"
for var in IDENTITY_VARS:
assert var in guide, f"the variable table must list {var}"