Files
LLeMbas/src/lembas/api/preferences.py
T
Jaroslav Beneš 78e5717f77 An instance that can be somebody else's
A name, a tagline, a logo, a favicon and the launcher icons derived from it; the
Middle-earth strings as data; themes as token sets; and a stylesheet for what
none of that reaches. All four are on one page, in one settings group.

The snapshot is a Jinja global over a process-level cache, because render() has
no session and four render paths never reach it at all -- the sign-in page, the
error pages, the offline page and the SSE fragments. A context value would have
had to be threaded through every one and would still have missed those. It being
a global is also what lets mark() branch on an uploaded logo without any of its
six call sites learning about branding; the macro that renders the sidebar link
is called brandlink now, because a macro imported as `brand` shadows the global
for the whole template and took out every page at once.

Defaults in code and overrides in the database, as the prompt fragments do, with
one difference stated in the module: an empty fragment means off, an empty
flavour string means the shipped wording. And blanked rather than dropped --
settings_store.update merges, so an omitted key leaves what was stored last time
and "I typed the default back in" would store something different from "I changed
nothing".

A custom theme sets a handful of tokens and inherits the rest, and the
inheritance is a CSS fact: tokens.css matches [data-base="shire"] as well as
[data-theme="shire"], so a custom light theme lands on parchment rather than four
light colours on near-black. Values are validated on read rather than on save,
because a theme written straight into the settings table still has to produce a
stylesheet that parses -- a `}` in a value ends the rule and silently breaks
every rule after it. The soft variants are derived from the accent, or a changed
accent leaves focus rings in the old hue and reads as half-working.

/branding.css is a route, not an inline block: an external stylesheet has no HTML
context to escape from. The link carries a content hash, so a save is not left to
the browser's cache, and it is deliberately outside the service worker's precache
list, which is versioned by the release.

The instance name moved off /admin/general rather than being duplicated there.
An upgrade keeps it: the general row is read as a seed exactly while the branding
row has never mentioned the name, which is `key in row` and not `row[key] is
truthy` -- the two read alike would resurrect the old name underneath a cleared
one.

The theme list stops being a hard-coded pair in five places. Every failure mode
in that area is silent, so it is driven under a DOM stub as well as tested.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 15:42:25 +02:00

272 lines
10 KiB
Python

"""Per-user preferences set from the browser."""
from __future__ import annotations
import contextlib
import logging
from fastapi import APIRouter, Body, Form, Request, status
from fastapi.responses import RedirectResponse, Response
from lembas.api.deps import Db, RequiredUser
from lembas.config import settings
from lembas.security.passwords import hash_password, validate_password, verify_password
from lembas.security.sessions import COOKIE_NAME, create_session, revoke_all_for_user
from lembas.services.schedule import clock
log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/preferences", tags=["preferences"])
# The built-in pair used to be spelled out here, and in four other places. It is
# one server-resolved list now, because an administrator can define a theme and a
# hard-coded pair would refuse it -- silently, since this route answers a
# rejection with `{"ok": false}` that nothing displays.
def themes() -> tuple[str, ...]:
from lembas.services import branding
return branding.snapshot().theme_ids
@router.post("/theme")
async def set_theme(db: Db, user: RequiredUser, theme: str = Body(..., embed=True)) -> dict:
"""Mirror the browser's theme choice onto the account.
localStorage is the source of truth for the current tab; this is what makes
the choice follow the user to another browser, and what lets the server
render the right theme on first paint instead of flashing the default.
"""
if theme not in themes():
return {"ok": False, "detail": "Unknown theme."}
# Replaced rather than mutated in place: SQLAlchemy only reliably detects
# a change to a JSON column when the whole value is reassigned.
user.settings_json = {**(user.settings_json or {}), "theme": theme}
db.commit()
return {"ok": True, "theme": theme}
@router.post("/timezone")
async def set_timezone(db: Db, user: RequiredUser, timezone: str = Form("")) -> Response:
"""Which zone this person's schedules fire in, and what time they are told it is.
Empty is a real answer -- "whatever the server is set to" -- rather than an
unset field, which is why it is stored as "" instead of being removed. An
unrecognised name is refused rather than stored and fallen back from later:
a schedule that quietly fires in the wrong zone is the failure this whole
field exists to prevent, and the one place to catch it is the write.
"""
chosen = (timezone or "").strip()
if chosen and not clock.known(chosen):
return RedirectResponse(
"/settings?error=timezone", status_code=status.HTTP_303_SEE_OTHER
)
user.settings_json = {**(user.settings_json or {}), clock.SETTING_KEY: chosen}
db.commit()
return RedirectResponse("/settings?saved=timezone", status_code=status.HTTP_303_SEE_OTHER)
# Which CSS variables a browser is allowed to set from here, and how far. An
# open dict would let a page store anything under somebody's account and have
# it read back on every load; a width outside these bounds would hand them a
# panel they cannot see to drag back.
LAYOUT_BOUNDS = {
"--terminal-width": (384, 2400),
"--canvas-width": (384, 2400),
"--inspector-width": (280, 2400),
"--sidebar-width": (200, 800),
}
@router.post("/layout")
async def set_layout(db: Db, user: RequiredUser, widths: dict = Body(...)) -> dict:
"""Remember how wide somebody dragged the panels.
Same two tiers as the theme: `localStorage` is the truth for the tab that
did the dragging, and this is what carries it to another browser. Unknown
names are dropped rather than refused -- an older browser sending a key a
newer release removed should not fail the request.
"""
kept: dict[str, int] = {}
for name, raw in (widths or {}).items():
bounds = LAYOUT_BOUNDS.get(str(name))
if bounds is None:
continue
try:
value = int(float(raw))
except (TypeError, ValueError):
continue
kept[str(name)] = min(max(value, bounds[0]), bounds[1])
settings = {**(user.settings_json or {})}
settings["layout"] = {**(settings.get("layout") or {}), **kept}
user.settings_json = settings
db.commit()
return {"ok": True, "layout": kept}
@router.post("/sidebar-kind")
async def set_sidebar_kind(
request: Request, db: Db, user: RequiredUser, kind: str = Form("")
) -> Response:
"""Switch the sidebar between ordinary chats and agent chats.
Saves and re-renders in one round trip, because the two cannot be allowed to
disagree: a switch that stored a choice and left the tree showing the other
side would look broken, and re-rendering without storing would lose it on the
next navigation. The tree comes back as a fragment rather than an `HX-Refresh`
-- a full reload is what `api/folders.py` does for a structural change, and it
would throw away the folder open/closed state on every flick of the switch,
which is the same thing `/api/chats/unread` avoids by swapping out of band.
An unrecognised value is refused rather than stored: `sidebar_kind` reads it
back as "chat" anyway, so storing it would be a preference that silently
does nothing.
"""
from lembas.api.pages import sidebar_context
from lembas.db.models import KINDS
from lembas.web.templating import templates
if kind not in KINDS:
return Response(status_code=status.HTTP_400_BAD_REQUEST)
user.settings_json = {**(user.settings_json or {}), "sidebar_kind": kind}
db.commit()
return templates.TemplateResponse(
request,
"partials/_sidebar_tree.html",
# `oob` brings the New chat button along out of band. It sits above the
# scroll area rather than inside the tree, so a swap of the tree alone
# left it saying "New chat" while agent chats were listed underneath.
{"chat": None, "user": user, "oob": True, **sidebar_context(db, user)},
)
@router.post("/default-model")
async def set_default_model(
db: Db, user: RequiredUser, model_id: str = Form("")
) -> Response:
"""Choose which model new chats start with.
An empty value clears the choice and falls back to the instance default.
Validated against what this user can actually reach, so a model they lose
access to cannot linger as a preference that silently fails later.
"""
from lembas.security import permissions
model_id = model_id.strip()
if model_id and not permissions.can_use_model(db, user, model_id):
return RedirectResponse(
"/settings?error=That+model+is+not+available+to+you.", status_code=303
)
settings_map = {**(user.settings_json or {})}
if model_id:
settings_map["default_model"] = model_id
else:
settings_map.pop("default_model", None)
user.settings_json = settings_map
db.commit()
return RedirectResponse("/settings?saved=Default+model+updated.", status_code=303)
@router.post("/audio")
async def set_audio(
db: Db,
user: RequiredUser,
voice: str = Form(""),
speed: str = Form(""),
language: str = Form(""),
autoplay: bool = Form(False),
) -> Response:
"""Per-reader audio choices, overriding the instance defaults.
The voice is deliberately not checked against the discovered list. Voices
come and go when a speech server is reconfigured, and rejecting a saved
preference because a list fetched a moment ago did not mention it would be
a confusing failure with no obvious fix.
"""
chosen: dict[str, object] = {"autoplay": autoplay}
if voice.strip():
chosen["voice"] = voice.strip()[:120]
if language.strip():
chosen["language"] = language.strip()[:16]
if speed.strip():
# An unreadable speed leaves the default in place rather than failing:
# nothing else on the form should be lost to a typo in one field.
with contextlib.suppress(ValueError):
chosen["speed"] = min(max(float(speed), 0.25), 4.0)
# Whole-dict reassignment: an in-place edit of a JSON column is not
# reliably detected as a change.
user.settings_json = {**(user.settings_json or {}), "audio": chosen}
db.commit()
return RedirectResponse("/settings?saved=Audio+preferences+updated.", status_code=303)
@router.post("/password")
async def change_password(
request: Request,
db: Db,
user: RequiredUser,
current_password: str = Form(...),
new_password: str = Form(...),
confirm_password: str = Form(...),
) -> Response:
"""Change your own password.
Every other session is revoked on success. If the reason for changing a
password is that someone else knows it, leaving their session alive would
defeat the point.
"""
def back(message: str, ok: bool = False) -> Response:
from urllib.parse import quote
field = "saved" if ok else "error"
return RedirectResponse(
f"/settings?{field}={quote(message)}", status_code=status.HTTP_303_SEE_OTHER
)
if not verify_password(current_password, user.password_hash):
log.info("failed password change for %s: current password wrong", user.email)
return back("Your current password is not correct.")
if new_password != confirm_password:
return back("The new passwords do not match.")
if (problem := validate_password(new_password)) is not None:
return back(problem)
if verify_password(new_password, user.password_hash):
return back("That is already your password.")
user.password_hash = hash_password(new_password)
db.commit()
revoke_all_for_user(db, user)
token = create_session(
db,
user,
user_agent=request.headers.get("user-agent", ""),
ip_address=request.client.host if request.client else "",
)
log.info("password changed for %s; other sessions revoked", user.email)
# revoke_all_for_user killed this session too, so hand back a fresh cookie
# -- otherwise changing your password would sign you out of the tab you are
# standing in.
response = back("Password changed. Any other sessions have been signed out.", ok=True)
response.set_cookie(
COOKIE_NAME,
token,
max_age=settings.session_ttl,
httponly=True,
samesite="lax",
secure=False,
path="/",
)
return response