Files
ducoterra 9188be259b
Build and Push Containers / build-and-push-app (push) Successful in 1m56s
Build and Push Containers / build-and-push-db (push) Successful in 11s
phase: 93_theme_semantic_completion
All verification is complete. Final report:

**Phase 93 — Theme semantic completion: FINAL VERIFICATION PASS — ALL GREEN**

- Verified full implementation in tree: migration `0016` (8 nullable semantic columns, applied at head), 17-var `BUILTIN_COLORS`/`COLOR_FIELDS`/`effective_settings`, API validation, `#view-theme` State-colors fieldset (17 pickers), `theme.js` FIELDS/PAIRS (5→8), `.page-head` surface panel (6 shell views + doc-edit + shared.html; login card / document sticky header audited as already-surfaced), mock_llm `content: None` fix
- Fixed 2 pre-existing defects (both fail identically on baseline `d4f38ad`, proven via worktree A/B): `test_nav_rename_sources` — expected nav tail missing the phase-91 "Theme" link; `test_stale_ui_copy` — now truncates `saved_chats` before/after (house `test_suggestion_chips` pattern) so the seed-chip contract is deterministic on the shared dev DB (owner's 22 saved chats triggered phase-80 last-3-questions)
- Tests: `uv run pytest --cov=app --cov-report=term-missing` → **1868 passed, app/ 99%** (>90% ✓); `uv run ruff check .` → clean; `uv run pyright` → **0 errors**
- E2E: dedicated `uv run pytest tests/e2e/test_theme_semantic_completion.py -v --no-cov` → **8/8 in isolation** (all-gray 17-color theme: zero residual color on saved-result/Stale/Revoked/Local/tool-call elements, text labels intact, gray heads non-transparent, pre-paint tag, Reset → byte-identical no-tag); 15 theme/header/nav/responsive suites green in isolation; full 85-file combined run: only the 2 fixed pre-existing failures + 1 combined-run artifact (`test_sync_upload_progress`, green in isolation)
- Completion criteria: (1) monochrome E2E ✓ (2) default byte-identical, no `#bor-theme` tag ✓ (3) all page heads on solid surface ✓ (4) suite/coverage/lint/E2E green ✓ (5) phases 01–92 no behavior change ✓ (6) commit left to harness per protocol
- Notable: cleaned stray uvicorn leftovers from prior implementation pass (owner's `--reload` dev server untouched); no deviations from the phase design
- Next pending phase: `94_ls_tree_drilldown`
2026-09-10 16:43:08 -04:00

141 lines
5.7 KiB
Python

"""UI settings admin API (phase 91, task 01).
The persistence surface of the admin Theme tab (the tab itself lands in
tasks 04/05): the single ``ui_settings`` row (id 1) that stores what the
admin sets — the app name, input placeholder, footer text, and the 17
palette colors (the 9 identity colors + the 8 semantic state colors,
phase 93 — B3 revised). The whole router sits behind
:func:`app.core.auth.require_admin` (router-wide ``dependencies`` — the
:mod:`app.api.tokens` pattern): anonymous callers AND token users get
403 on every route (only the admin themes the deployment).
Routes (under ``/api`` via the ``main`` registration):
* ``GET /api/ui-settings`` — the EFFECTIVE values (the resolver's
DB-over-env / DB-over-built-in merge, B1): a missing row reports the
env strings + the built-in palette, so a fresh tab shows the live
theme. Creates nothing.
* ``PUT /api/ui-settings`` — a FULL replacement of the row: each
string is trimmed (empty → NULL, >300 → 422 naming the field), each
color must match ``^#[0-9a-fA-F]{6}$`` (lowercased on store, else 422
naming the field), and — the owner-locked normalization — a color
equal to its built-in is stored as NULL, so "save the defaults"
leaves the row empty and the served HTML stays byte-identical (the
no-op injection contract, task 02). Upserts the id-1 row (SELECT →
update-or-insert); a concurrent PUT is single-admin — last writer
wins. Returns the new effective values.
"""
from __future__ import annotations
import re
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.config import Settings, get_settings
from app.core import theming
from app.core.auth import require_admin
from app.db import get_db
from app.models import UiSettings
from app.schemas import UiSettingsIn, UiSettingsOut
router = APIRouter(
prefix="/ui-settings",
tags=["ui-settings"],
dependencies=[Depends(require_admin)], # phase 91: the Theme tab is admin-only
)
#: The ``#rrggbb`` shape the color pickers produce (case-insensitive;
#: lowercased on store so the stored/tagged hex is canonical).
_HEX_COLOR = re.compile(r"^#[0-9a-fA-F]{6}$")
#: The strings' column length (mirrors ``ui_settings`` VARCHAR(300)).
_MAX_STRING_LEN = 300
def _validate_strings(payload: UiSettingsIn) -> dict[str, str | None]:
"""Trim the 3 display strings: empty after the trim → ``None``
(the clear operation), >300 chars after the trim → 422 naming the
field (the house fixed-detail style — the detail never varies by
value beyond naming the field)."""
values: dict[str, str | None] = {}
for field in theming.STRING_FIELDS:
raw = getattr(payload, field)
if raw is None:
values[field] = None
continue
value = raw.strip()
if len(value) > _MAX_STRING_LEN:
raise HTTPException(
status_code=422, detail=f"{field} is too long (max 300)"
)
values[field] = value or None
return values
def _validate_colors(payload: UiSettingsIn) -> dict[str, str | None]:
"""Validate + normalize the 17 palette colors (the 9 identity +
the 8 semantic state — all ``COLOR_FIELDS``-driven, phase 93):
strict ``#rrggbb`` (else 422 naming the field), lowercased on
store, and a value equal to its BUILT-IN is stored as ``None`` —
the owner-locked normalization that keeps "save the defaults"
byte-identical (the row stays empty, the no-op injection
contract)."""
values: dict[str, str | None] = {}
for field in theming.COLOR_FIELDS:
raw = getattr(payload, field)
if raw is None:
values[field] = None
continue
if _HEX_COLOR.fullmatch(raw) is None:
raise HTTPException(
status_code=422, detail=f"{field} must be a #rrggbb hex color"
)
value = raw.lower()
values[field] = None if value == theming.BUILTIN_COLORS[field] else value
return values
@router.get("", response_model=UiSettingsOut)
def get_ui_settings(
settings: Settings = Depends(get_settings), # noqa: B008
db: Session = Depends(get_db), # noqa: B008
) -> UiSettingsOut:
"""The effective UI settings — DB-over-env / DB-over-built-in (B1).
Reads only: a missing row means "defaults" (the env strings + the
built-in palette), so a fresh deployment's tab shows the live theme
with an empty row, and nothing is ever upserted by a read.
"""
return UiSettingsOut(**theming.effective_settings(db, settings))
@router.put("", response_model=UiSettingsOut)
def update_ui_settings(
payload: UiSettingsIn,
settings: Settings = Depends(get_settings), # noqa: B008
db: Session = Depends(get_db), # noqa: B008
) -> UiSettingsOut:
"""Replace the single row with the body's 20 values (validated and
normalized — see the module docstring), then report the new
effective values.
Upsert on the id-1 row (SELECT → update-or-insert; the Python-side
``default=1`` supplies the PK on the insert). Concurrency is
single-admin (one owner, one tab) — the last writer wins and no
lock is taken: a lost race just means the other admin's PUT is the
effective one.
"""
strings = _validate_strings(payload)
colors = _validate_colors(payload)
row = db.execute(select(UiSettings).where(UiSettings.id == 1)).scalars().first()
if row is None:
row = UiSettings(id=1)
db.add(row)
for field in theming.STRING_FIELDS:
setattr(row, field, strings[field])
for field in theming.COLOR_FIELDS:
setattr(row, field, colors[field])
db.commit()
return UiSettingsOut(**theming.effective_settings(db, settings))