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>
This commit is contained in:
Jaroslav Beneš
2026-08-06 15:42:25 +02:00
parent 46066150d9
commit 78e5717f77
67 changed files with 1887 additions and 117 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
"""LLeMbas - a Middle-earth themed web UI for OpenAI-compatible LLM endpoints."""
__version__ = "0.9.3"
__version__ = "0.9.4"
-2
View File
@@ -55,7 +55,6 @@ async def general_page(request: Request, db: Db, user: AdminUser, saved: bool =
async def save_general(
db: Db,
user: AdminUser,
instance_name: str = Form("LLeMbas"),
allow_signup: bool = Form(False),
system_prompt: str = Form(""),
compact_threshold: int = Form(95),
@@ -69,7 +68,6 @@ async def save_general(
settings_store.update(
db,
{
"instance_name": instance_name.strip()[:120] or "LLeMbas",
"allow_signup": allow_signup,
"system_prompt": system_prompt.strip()[:8000],
# 0 is "never"; anything else is clamped into a band where it can
+207
View File
@@ -0,0 +1,207 @@
"""Making an instance somebody else's.
One page, four cards, one settings group. Everything it writes goes through
`branding.stored_only`, so a field left at its shipped wording is never written
down and a later release can still improve it — the prompt-fragment rule, and
the reason this page can afford to render every flavour string as an editable
box without freezing all of them the first time somebody presses Save.
`branding.forget()` after every write, and this is the only module that calls
it. The snapshot is a process-level cache read by a Jinja global; a save that
did not drop it would take effect on the next restart, which is the shape of
failure this codebase keeps cataloguing.
"""
from __future__ import annotations
import logging
from fastapi import APIRouter, File, Form, Request, Response, UploadFile, status
from fastapi.responses import RedirectResponse
from lembas.api.deps import AdminUser, Db
from lembas.services import branding as branding_service
from lembas.services import settings_store, uploads
from lembas.web.templating import render
log = logging.getLogger(__name__)
router = APIRouter(prefix="/admin/customization", tags=["admin-branding"])
MAX_CUSTOM_CSS = 40_000
def _page(request: Request, db: Db, saved: str = "", error: str = "") -> Response:
values = settings_store.get_group(db, branding_service.BRANDING)
brand = branding_service.for_db(db)
return render(
request,
"admin/customization.html",
{
"values": values,
"current": brand,
# The flavour table drives the form, so a string added in code
# appears here with its default in the box and no template change.
"flavour": [
{
"key": key,
"label": label,
"hint": hint,
"default": default,
"value": str(values.get(f"text_{key}") or ""),
}
for key, (label, hint, default) in branding_service.FLAVOUR.items()
],
"tokens": branding_service.THEME_TOKENS,
"custom_themes": [t for t in brand.themes if not t.built_in],
"bases": [name for name, _, _ in branding_service.BUILT_IN],
"saved": saved,
"error": error,
},
)
@router.get("")
async def customization_page(request: Request, db: Db, user: AdminUser, saved: str = ""):
return _page(request, db, saved=saved)
def _write(db: Db, changes: dict) -> None:
"""Store a change and drop the cache, in that order and always together."""
settings_store.update(db, changes, key=branding_service.BRANDING)
branding_service.forget()
@router.post("/identity")
async def save_identity(
request: Request,
db: Db,
user: AdminUser,
instance_name: str = Form(""),
tagline: str = Form(""),
logo: UploadFile | None = File(None),
favicon: UploadFile | None = File(None),
remove_logo: bool = Form(False),
remove_favicon: bool = Form(False),
) -> Response:
stored = settings_store.get_group(db, branding_service.BRANDING)
changes: dict = {
"instance_name": instance_name.strip()[:120],
"tagline": tagline.strip()[:200],
}
if remove_logo:
for name in (stored.get("logo_path"), *(stored.get("icon_paths") or {}).values()):
uploads.delete_branding_image(str(name or ""))
changes["logo_path"] = ""
changes["icon_paths"] = {}
if remove_favicon:
uploads.delete_branding_image(str(stored.get("favicon_path") or ""))
changes["favicon_path"] = ""
try:
if logo is not None and logo.filename:
payload = await logo.read()
changes["logo_path"] = uploads.save_branding_image(payload, logo.content_type or "")
# Derived here rather than on demand: a launcher asks for a 512px
# PNG and will not scale one itself, and doing it per request would
# mean resizing an image on the path that serves it.
changes["icon_paths"] = uploads.derive_icons(payload)
if favicon is not None and favicon.filename:
payload = await favicon.read()
changes["favicon_path"] = uploads.save_branding_image(
payload, favicon.content_type or ""
)
except uploads.UploadError as exc:
return _page(request, db, error=str(exc))
_write(db, branding_service.stored_only(changes))
log.info("branding identity changed by %s", user.email)
return RedirectResponse(
"/admin/customization?saved=Identity+saved.", status_code=status.HTTP_303_SEE_OTHER
)
@router.post("/flavour")
async def save_flavour(request: Request, db: Db, user: AdminUser) -> Response:
"""The Middle-earth strings.
Read from the raw form rather than declared as parameters, because the set
is `branding.FLAVOUR` and a parameter list would be a second copy of it that
goes stale the first time a string is added. A key that was not submitted is
left alone; one submitted empty falls back to its default, which is what
makes "clear the box" mean "give me the shipped wording back" rather than
"show nothing here".
"""
form = await request.form()
changes = {
f"text_{key}": str(form.get(f"text_{key}") or "").strip()[:400]
for key in branding_service.FLAVOUR
if f"text_{key}" in form
}
_write(db, branding_service.stored_only(changes))
return RedirectResponse(
"/admin/customization?saved=Wording+saved.", status_code=status.HTTP_303_SEE_OTHER
)
@router.post("/css")
async def save_css(db: Db, user: AdminUser, custom_css: str = Form("")) -> Response:
_write(db, {"custom_css": custom_css.strip()[:MAX_CUSTOM_CSS]})
log.info("custom CSS changed by %s", user.email)
return RedirectResponse(
"/admin/customization?saved=Stylesheet+saved.", status_code=status.HTTP_303_SEE_OTHER
)
@router.post("/themes")
async def save_themes(request: Request, db: Db, user: AdminUser) -> Response:
"""Every custom theme, replaced wholesale.
One form for the lot rather than a row each, because a theme is a handful of
colours and the whole set fits on a screen — and because replacing the list
means a theme removed here is gone, with no reconciliation between what was
posted and what was stored.
Nothing is validated here beyond shape. `branding._theme_from` validates on
every **read**, so a theme written straight into the settings table by hand,
or stored by an earlier version, still has to produce a stylesheet that
parses. Validating only on save would put that guarantee in the wrong place.
"""
form = await request.form()
themes = []
for index in range(_theme_count(form)):
theme_id = str(form.get(f"theme_{index}_id") or "").strip().lower()
if not theme_id:
continue
themes.append(
{
"id": theme_id,
"label": str(form.get(f"theme_{index}_label") or "").strip(),
"base": str(form.get(f"theme_{index}_base") or "moria"),
"tokens": {
name: value
for name, _ in branding_service.THEME_TOKENS
if (value := str(form.get(f"theme_{index}_{name}") or "").strip())
},
}
)
_write(db, {"themes": themes})
log.info("%d custom theme(s) saved by %s", len(themes), user.email)
return RedirectResponse(
"/admin/customization?saved=Themes+saved.", status_code=status.HTTP_303_SEE_OTHER
)
def _theme_count(form) -> int:
"""How many theme blocks the form carried.
Counted from the submitted keys rather than from a hidden field, so a form
rendered by an older page still saves what it holds.
"""
indices = [
int(key.split("_")[1])
for key in form
if key.startswith("theme_") and key.split("_")[1].isdigit()
]
return max(indices) + 1 if indices else 0
+65
View File
@@ -0,0 +1,65 @@
"""Serving what an administrator customised.
Both routes here are deliberately **unauthenticated**, and for the same reason
the manifest and the offline page are: the sign-in page needs the logo before
anybody has signed in, and a browser fetches a stylesheet and a launcher icon
outside any page's session.
What that exposes is a file an administrator uploaded on purpose to be shown to
everybody, under a random filename, in a format that cannot execute in an
`<img>` — `services/uploads.py:ALLOWED_TYPES` is what makes the last part true,
and it is why SVG is not in it.
"""
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Response, status
from fastapi.responses import FileResponse
from lembas.services import branding as branding_service
from lembas.services import uploads
router = APIRouter(tags=["branding"])
@router.get("/branding.css", include_in_schema=False)
async def branding_css() -> Response:
"""The custom themes and the custom CSS.
A route rather than an inline `<style>` in `base.html`, which is a security
property before it is a caching one: an external stylesheet has no HTML
context to escape from, so an administrator's CSS cannot become markup
however it is written. Inline, the same text would be one `</style>` away
from being a script on every page.
Cached hard and busted by a query string. `base.html` links this with
`?v={{ brand.revision }}`, a hash of everything below, so the URL changes
exactly when the stylesheet does. Without that the browser's cache is what
decides when a rebrand takes effect, which is a save that looks like it
worked and did nothing.
"""
brand = branding_service.snapshot()
return Response(
branding_service.stylesheet(brand),
media_type="text/css",
headers={"Cache-Control": "public, max-age=604800"},
)
@router.get("/branding/{filename}", include_in_schema=False)
async def branding_asset(filename: str) -> Response:
"""A logo, a favicon, or a launcher icon derived from one."""
path = uploads.branding_image_path(filename)
if path is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "No such file.")
return FileResponse(
path,
media_type=uploads.media_type_for(filename),
# Public, unlike a model avatar: this is served to somebody who is not
# signed in, so there is nothing private to keep out of a shared cache.
# Names are random, so a replacement is a new URL.
headers={
"Cache-Control": "public, max-age=604800",
"X-Content-Type-Options": "nosniff",
},
)
+17 -4
View File
@@ -23,6 +23,7 @@ from lembas.db.models import (
)
from lembas.security import permissions
from lembas.services import audio as audio_service
from lembas.services import branding as branding_service
from lembas.services import canvas as canvas_service
from lembas.services import chat as chat_service
from lembas.services import compaction as compaction_service
@@ -443,19 +444,31 @@ async def manifest(db: Db) -> Response:
else would be wrong on the one screen that is hardest to correct: the
launcher.
"""
name = settings_store.get(db, "instance_name") or "LLeMbas"
brand = branding_service.for_db(db)
icons = brand.icon_paths
return JSONResponse(
{
"id": "/",
"name": name,
"short_name": name[:12],
"description": "A web UI for your language models.",
"name": brand.name,
"short_name": brand.name[:12],
"description": brand.tagline or "A web UI for your language models.",
"start_url": "/chat",
"scope": "/",
"display": "standalone",
"background_color": THEME_COLOUR["moria"],
"theme_color": THEME_COLOUR["moria"],
# An uploaded logo's derived icons, or the shipped ones. Whole-set
# rather than per size: a manifest listing two custom icons and one
# shipped is a launcher tile that changes when the device picks a
# different size, which reads as a bug in the install.
"icons": [
{"src": f"/branding/{icons['icon-192']}", "sizes": "192x192",
"type": "image/png", "purpose": "any"},
{"src": f"/branding/{icons['icon-512']}", "sizes": "512x512",
"type": "image/png", "purpose": "any"},
{"src": f"/branding/{icons['maskable']}", "sizes": "512x512",
"type": "image/png", "purpose": "maskable"},
] if icons.get("icon-192") and icons.get("icon-512") and icons.get("maskable") else [
{"src": "/static/img/icon-192.png", "sizes": "192x192",
"type": "image/png", "purpose": "any"},
{"src": "/static/img/icon-512.png", "sizes": "512x512",
+9 -2
View File
@@ -18,7 +18,14 @@ log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/preferences", tags=["preferences"])
THEMES = ("moria", "shire")
# 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")
@@ -29,7 +36,7 @@ async def set_theme(db: Db, user: RequiredUser, theme: str = Body(..., embed=Tru
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:
if theme not in themes():
return {"ok": False, "detail": "Unknown theme."}
# Replaced rather than mutated in place: SQLAlchemy only reliably detects
+17 -7
View File
@@ -16,6 +16,7 @@ from lembas.api import (
admin,
admin_agents,
admin_audio,
admin_branding,
admin_images,
admin_models,
admin_prompts,
@@ -27,6 +28,7 @@ from lembas.api import (
agents,
audio,
auth,
branding,
canvas,
chats,
files,
@@ -181,6 +183,7 @@ def create_app() -> FastAPI:
app.include_router(admin_users.router)
app.include_router(admin_models.router)
app.include_router(admin_audio.router)
app.include_router(admin_branding.router)
app.include_router(admin_search.router)
app.include_router(admin_schedules.router)
app.include_router(admin_images.router)
@@ -189,6 +192,7 @@ def create_app() -> FastAPI:
app.include_router(admin_tools.router)
app.include_router(admin_agents.router)
app.include_router(push.router)
app.include_router(branding.router)
register_error_handlers(app)
return app
@@ -219,7 +223,7 @@ def register_error_handlers(app: FastAPI) -> None:
{
"status_code": exc.status_code,
"detail": exc.detail,
"flavour": ERROR_FLAVOUR.get(exc.status_code, ERROR_FLAVOUR[500]),
"flavour": error_flavour(exc.status_code),
},
status_code=exc.status_code,
)
@@ -233,18 +237,24 @@ def register_error_handlers(app: FastAPI) -> None:
request,
"error.html",
{"status_code": 500, "detail": "Something went wrong.",
"flavour": ERROR_FLAVOUR[500]},
"flavour": error_flavour(500)},
status_code=500,
)
# Flavour lives in error pages, empty states and theme names -- never in the
# functional UI. See CLAUDE.md.
ERROR_FLAVOUR = {
403: "Speak, friend, and enter. This door is not yours to open.",
404: "Not all those who wander are lost. This page, however, is.",
500: "The Road goes ever on, but this stretch of it has washed out.",
}
#
# The three lines themselves moved into `services/branding.py` with the rest of
# what an administrator can replace. What is left here is the mapping from a
# status code to which of them, which is not something anybody would want to
# edit. `snapshot()` never raises, so an error page can still render its error
# on an instance whose database is the thing that broke.
def error_flavour(status_code: int) -> str:
from lembas.services import branding
text = branding.snapshot().text
return text.get(f"error_{status_code}") or text["error_500"]
app = create_app()
+506
View File
@@ -0,0 +1,506 @@
"""What this installation is called, and what it looks like.
An instance can be somebody else's. That means four separate things, and they
are separate because they fail differently:
- an **identity** — a name, a tagline, a logo, a favicon, the icons a launcher
shows;
- **flavour text** — the Middle-earth lines, which live in the artwork, the
empty states, the loading lines and the error pages and nowhere else (see the
flavour rule in CLAUDE.md), and which somebody rebranding needs to be able to
replace without editing templates;
- **themes**, which are token sets rather than stylesheets, because the
invariant that no component hard-codes a colour is what makes a third one
compose at all;
- **arbitrary CSS**, for the things the first three do not reach.
## Defaults in code, overrides in the database
The prompt-fragment rule, applied again and for the same reason: text equal to
its default is never stored, so a later release improving a default still
reaches an instance whose administrator once pressed Save. `stored_only` is what
enforces it, and every save goes through it.
## Why a snapshot, and why a Jinja global
`web/templating.py:render()` has no database session, and the login page, the
error pages, the offline page and the SSE path do not go through it at all. A
context value would therefore have to be threaded through every one of those,
and the ones that bypass `render()` could not be reached at all.
So this is a **process-level cache** behind a lazy proxy registered as a Jinja
global. One query per process, and after every save; every render path gets it
including the ones that never see a `Request`. `forget()` is called by the admin
page and by nothing else.
The cost of being a cache is stated rather than discovered: with several
workers, a save in one is not seen by the others until each next reads. That is
already true of this application for other reasons -- see the "one worker" note
in PLAN.md -- and this does not make it worse.
"""
from __future__ import annotations
import hashlib
import logging
import re
from dataclasses import dataclass, field
from typing import Any
from lembas.services import settings_store
log = logging.getLogger(__name__)
BRANDING = settings_store.BRANDING
DEFAULT_NAME = "LLeMbas"
# --- Flavour ------------------------------------------------------------------
# Every Middle-earth string in the interface, with its current wording as the
# default. Keyed rather than positional so a template names what it wants, and
# a key nobody has overridden costs nothing to store.
#
# The label is what the admin page calls the field; the hint says where it is
# seen, because a string with no context is one nobody can safely rewrite.
FLAVOUR: dict[str, tuple[str, str, str]] = {
"login_tagline": (
"Under the sign-in mark",
"The one line on the sign-in page, beneath the name.",
"Waybread for the long road of thought.",
),
"chat_empty": (
"Empty chat",
"Above the composer on a chat with nothing in it yet.",
"Speak, friend, and enter.",
),
"offline_title": (
"Offline heading",
"The page the service worker shows when the server cannot be reached.",
"No road from here",
),
"offline_line": (
"Offline line",
"Beneath that heading. The sentence below it is functional and is not "
"editable here.",
"The Road goes ever on and on — but not without a connection.",
),
"error_403": (
"403 — not yours",
"Shown on a page somebody is not allowed to see.",
"Speak, friend, and enter. This door is not yours to open.",
),
"error_404": (
"404 — not found",
"Shown on a page that does not exist.",
"Not all those who wander are lost. This page, however, is.",
),
"error_500": (
"500 — something broke",
"Shown when something went wrong on the server.",
"The Road goes ever on, but this stretch of it has washed out.",
),
"theme_moria": (
"Dark theme name",
"What the built-in dark theme is called, in the settings screen and in "
"the /theme command.",
"Moria",
),
"theme_shire": (
"Light theme name",
"What the built-in light theme is called.",
"Shire",
),
}
# --- Themes -------------------------------------------------------------------
# The two built-ins. `css` is empty for both: their tokens are declared in
# tokens.css, which is the one place colours live, and duplicating them here so
# that a custom theme could "inherit" would be exactly the second copy that
# rule exists to prevent. A custom theme inherits by naming a base instead --
# see `theme_css` below.
SCHEME_DARK = "dark"
SCHEME_LIGHT = "light"
BUILT_IN = (
("moria", SCHEME_DARK, "#101317"),
("shire", SCHEME_LIGHT, "#F6F1E4"),
)
# What a custom theme may set. A curated handful rather than every token a
# theme block declares: sixty colour pickers is not a feature, and everything
# left out inherits from the base, which is what makes a theme that changes
# four things four things long.
#
# `--accent-soft`, `--leaf-soft` and `--danger-soft` are deliberately absent and
# are derived instead: they are the same colour at 14% and an administrator who
# changed the accent without them would get focus rings in the old hue, which
# looks like the setting half-working.
THEME_TOKENS: tuple[tuple[str, str], ...] = (
("bg", "Page background"),
("bg-sunken", "Behind the page — the sidebar and panel gutters"),
("surface", "Cards, menus and the composer"),
("surface-raised", "Anything sitting on a surface"),
("surface-hover", "A surface under the pointer"),
("border", "Ordinary borders"),
("border-strong", "Borders that have to be seen"),
("ink", "Body text"),
("ink-muted", "Secondary text"),
("ink-faint", "Hints and timestamps"),
("accent", "Links, focus and interactive accents"),
("accent-hover", "The accent under the pointer"),
("accent-ink", "Text on top of the accent"),
("leaf", "The brand accent and the assistant's mark"),
("danger", "Errors and destructive actions"),
("success", "Confirmations and unread dots"),
("warning", "Warnings"),
("bubble-user", "Behind your own messages"),
("code-bg", "Behind code"),
)
THEME_TOKEN_NAMES = tuple(name for name, _ in THEME_TOKENS)
# A colour, and nothing else. Values reach a stylesheet, so a `}` in one would
# end the rule and silently break every rule after it -- and `url(…)` in a
# colour slot is a request to a third party from every page. Anything that does
# not match is dropped rather than corrected: a colour nobody can read is a
# setting that did not take, and that is visible, while a mangled one is not.
_COLOUR = re.compile(
r"^(#[0-9a-fA-F]{3,8}"
r"|rgba?\([0-9,.\s%/]+\)"
r"|hsla?\([0-9,.\s%/deg]+\)"
r"|[a-z]{3,20})$"
)
# An id that can be an attribute value and a CSS selector without quoting.
_THEME_ID = re.compile(r"^[a-z][a-z0-9-]{0,23}$")
@dataclass(frozen=True)
class Theme:
"""One theme somebody can choose."""
id: str
label: str
scheme: str
# Which built-in it starts from. A custom theme sets a handful of tokens and
# inherits the rest, and that inheritance is a CSS fact: tokens.css matches
# `[data-base="shire"]` as well as `[data-theme="shire"]`, so a custom light
# theme carries `data-base="shire"` and gets the whole parchment palette
# underneath its own four colours. Without it a light custom theme would be
# four light colours on Moria's near-black surfaces.
base: str = "moria"
tokens: dict[str, str] = field(default_factory=dict)
colour: str = ""
built_in: bool = False
@dataclass(frozen=True)
class Branding:
"""Everything a page needs to know about whose instance this is."""
name: str = DEFAULT_NAME
tagline: str = ""
logo_path: str = ""
favicon_path: str = ""
icon_paths: dict[str, str] = field(default_factory=dict)
custom_css: str = ""
text: dict[str, str] = field(default_factory=dict)
themes: tuple[Theme, ...] = ()
@property
def theme_ids(self) -> tuple[str, ...]:
return tuple(theme.id for theme in self.themes)
@property
def theme_list(self) -> str:
"""`id:base` pairs, space separated, for the `data-themes` attribute.
One attribute rather than a JSON island, because two things in the
browser need it — `/theme` validating a name, and `applyTheme` setting
`data-base` alongside `data-theme` — and both want a list they can split
rather than a document they have to parse.
"""
return " ".join(f"{theme.id}:{theme.base}" for theme in self.themes)
def theme(self, theme_id: str) -> Theme:
for theme in self.themes:
if theme.id == theme_id:
return theme
return self.themes[0]
@property
def revision(self) -> str:
"""A short hash of everything `/branding.css` is built from.
It goes in that link's query string, so the URL changes exactly when the
stylesheet does. Without it the browser's cache is the thing deciding
when a rebrand takes effect, which is the failure this codebase keeps
cataloguing: a save that looks like it worked and did nothing.
"""
material = repr((self.custom_css, [(t.id, t.base, sorted(t.tokens.items())) for t in
self.themes]))
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:12]
# --- Reading ------------------------------------------------------------------
def defaults() -> dict[str, Any]:
return {
"instance_name": "",
"tagline": "",
"logo_path": "",
"favicon_path": "",
# Derived from the logo at save time, so a launcher gets real PNGs at
# the sizes it asks for rather than one image the browser is told to
# scale. Empty means the shipped artwork is used.
"icon_paths": {},
"custom_css": "",
"themes": [],
**{f"text_{key}": "" for key in FLAVOUR},
}
def _theme_from(raw: dict[str, Any]) -> Theme | None:
"""One stored custom theme, or None if it is not usable.
Every field is validated on read rather than trusted from the row: a theme
stored by an earlier version, or written straight into the settings table,
still has to produce a stylesheet that parses.
"""
theme_id = str(raw.get("id") or "").strip().lower()
if not _THEME_ID.match(theme_id) or theme_id in {name for name, _, _ in BUILT_IN}:
return None
base = str(raw.get("base") or "moria")
if base not in {name for name, _, _ in BUILT_IN}:
base = "moria"
tokens = {
name: value
for name, value in (raw.get("tokens") or {}).items()
if name in THEME_TOKEN_NAMES and _COLOUR.match(str(value).strip())
}
scheme = next(s for name, s, _ in BUILT_IN if name == base)
return Theme(
id=theme_id,
label=str(raw.get("label") or theme_id).strip()[:60] or theme_id,
scheme=scheme,
base=base,
tokens=tokens,
colour=tokens.get("bg", ""),
)
def build(values: dict[str, Any]) -> Branding:
"""A snapshot from a settings group. Pure, so it can be tested without a
database and used by the preview on the admin page."""
text = {
key: str(values.get(f"text_{key}") or "").strip() or default
for key, (_, _, default) in FLAVOUR.items()
}
themes = [
Theme(
id=theme_id,
label=text[f"theme_{theme_id}"],
scheme=scheme,
base=theme_id,
colour=colour,
built_in=True,
)
for theme_id, scheme, colour in BUILT_IN
]
seen = {theme.id for theme in themes}
for raw in values.get("themes") or []:
if not isinstance(raw, dict):
continue
theme = _theme_from(raw)
if theme is not None and theme.id not in seen:
seen.add(theme.id)
themes.append(theme)
return Branding(
name=str(values.get("instance_name") or "").strip() or DEFAULT_NAME,
tagline=str(values.get("tagline") or "").strip(),
logo_path=str(values.get("logo_path") or ""),
favicon_path=str(values.get("favicon_path") or ""),
icon_paths=dict(values.get("icon_paths") or {}),
custom_css=str(values.get("custom_css") or ""),
text=text,
themes=tuple(themes),
)
_CACHE: Branding | None = None
def snapshot() -> Branding:
"""The current branding, from a process-level cache.
Never raises. An error page that cannot render because branding could not be
read is a failure that hides the failure it was about to report, so a
database that is not there yet answers with the defaults.
"""
global _CACHE
if _CACHE is not None:
return _CACHE
try:
from lembas.db.session import session_scope
with session_scope() as db:
_CACHE = _read(db)
except Exception: # noqa: BLE001 - defaults are a usable answer, an exception is not
log.debug("could not read branding; using defaults", exc_info=True)
return build(defaults())
return _CACHE
def _read(db) -> Branding:
"""The two groups this is assembled from.
`instance_name` lived in the general group before there was a branding one,
and an upgrade must not quietly rename somebody's instance back to LLeMbas.
So the stored general value is a **seed**, and the test for it is whether the
branding row has said anything about the name at all -- `key in row`, not
`row[key] is truthy`. An empty stored name is somebody clearing the box,
which has to mean the default; a *missing* one is an instance that has never
seen this page. Reading the two the same way would resurrect the old name
underneath a cleared one, which is the failure a cleared reasoning effort
already documents.
That is why this reads the raw row rather than `get_group`, which fills in
defaults and so cannot tell absent from empty.
"""
from lembas.db.models import Setting
values = settings_store.get_group(db, BRANDING)
row = db.get(Setting, BRANDING)
said = isinstance(row, Setting) and isinstance(row.value, dict) and "instance_name" in row.value
if not said:
legacy = settings_store.get_group(db, settings_store.GENERAL).get("instance_name")
if legacy:
values = {**values, "instance_name": legacy}
return build(values)
def forget() -> None:
"""Drop the cache. Called by the admin page's save, and by tests."""
global _CACHE
_CACHE = None
def for_db(db) -> Branding:
"""The snapshot, seeded from a session the caller already has open.
Same value as `snapshot()`; this only spares the extra session on the first
render after a restart, where one is already in hand.
"""
global _CACHE
if _CACHE is None:
_CACHE = _read(db)
return _CACHE
# --- Writing ------------------------------------------------------------------
def stored_only(values: dict[str, Any]) -> dict[str, Any]:
"""Blank anything equal to its shipped wording, so it is not an override.
The prompt-fragment rule, and the reason it is a **blank rather than a
dropped key**: `settings_store.update` merges, so omitting a key leaves
whatever was stored last time. Dropping one would make "I typed the default
back in" and "I changed nothing" store different things, and make clearing a
box do nothing at all.
Empty is the not-overridden marker because `build` reads `stored or
default`. That is deliberately *not* the fragment convention, where an empty
override means the fragment is off: a fragment being off is a state somebody
wants, and a heading with no words is not.
"""
return {
key: ("" if _is_shipped(key, value) else value) for key, value in values.items()
}
def _is_shipped(key: str, value: Any) -> bool:
if key.startswith("text_"):
entry = FLAVOUR.get(key[len("text_") :])
return entry is not None and value == entry[2]
return value == defaults().get(key)
# --- The stylesheet -----------------------------------------------------------
def _soft(colour: str, alpha: str = "0.14") -> str:
"""A colour at low opacity, for the `*-soft` tokens.
Derived rather than asked for: they are the same colour at 14%, and an
administrator who set an accent without them would get focus rings and
selected states in the old hue -- which reads as the setting half-working
rather than as a field they missed.
Only hex is understood. Anything else answers "" and the base theme's own
soft value stands, which is the right failure: a wrong soft colour is worse
than an unchanged one.
"""
value = colour.strip()
if not value.startswith("#"):
return ""
digits = value[1:]
if len(digits) == 3:
digits = "".join(c * 2 for c in digits)
if len(digits) not in (6, 8):
return ""
try:
r, g, b = (int(digits[i : i + 2], 16) for i in (0, 2, 4))
except ValueError:
return ""
return f"rgba({r}, {g}, {b}, {alpha})"
def theme_css(theme: Theme) -> str:
"""One custom theme as a rule.
Two selectors' worth of work in one: the block sets what was chosen, and the
`data-base` attribute on <html> is what brings the rest of the base theme's
palette with it. Written here and served from `/branding.css`, which loads
after `tokens.css`, so these win on order at equal specificity.
"""
if not theme.tokens:
return ""
lines = [f" --{name}: {value};" for name, value in theme.tokens.items()]
for name, alpha in (("accent", "0.14"), ("leaf", "0.14"), ("danger", "0.14")):
soft = _soft(theme.tokens.get(name, ""), alpha)
if soft:
lines.append(f" --{name}-soft: {soft};")
return f':root[data-theme="{theme.id}"] {{\n' + "\n".join(lines) + "\n}\n"
def stylesheet(brand: Branding) -> str:
"""Everything `/branding.css` serves.
A route rather than an inline `<style>`, and that is a security property as
much as a caching one: an external stylesheet has no HTML context to escape
from, so an administrator's CSS cannot become markup however it is written.
Inline, the same text would be one `</style>` away from being a script.
"""
parts = [
"/* Generated by LLeMbas from the customization settings. */",
*(theme_css(theme) for theme in brand.themes if not theme.built_in),
]
if brand.custom_css.strip():
parts += ["/* Custom CSS. */", brand.custom_css.strip(), ""]
return "\n".join(part for part in parts if part)
__all__ = [
"BRANDING",
"BUILT_IN",
"DEFAULT_NAME",
"FLAVOUR",
"THEME_TOKENS",
"THEME_TOKEN_NAMES",
"Branding",
"Theme",
"build",
"defaults",
"for_db",
"forget",
"snapshot",
"stored_only",
"stylesheet",
"theme_css",
]
+2 -2
View File
@@ -39,7 +39,7 @@ from sqlalchemy import select
from sqlalchemy.orm import Session as DBSession
from lembas.db.models import KIND_TASK, User
from lembas.services import prompts, settings_store
from lembas.services import branding, prompts, settings_store
from lembas.services.library import memories as memories_service
from lembas.services.library import skills as skills_service
from lembas.services.schedule import clock
@@ -192,7 +192,7 @@ def context_variables(
# nobody has chosen one, which drops the line rather than printing the
# server's zone as though it were a decision.
"timezone": clock.name_for(user),
"instance_name": str(settings_store.get(db, "instance_name") or "LLeMbas"),
"instance_name": branding.for_db(db).name,
"user_name": (user.name or "") if user is not None else "",
"model_name": "",
# What this request will actually allow, so the model is not told a
+20 -1
View File
@@ -32,6 +32,7 @@ AGENTS = "agents"
IMAGES = "images"
SCHEDULES = "schedules"
SUBAGENTS = "subagents"
BRANDING = "branding"
def _general_defaults() -> dict[str, Any]:
@@ -40,7 +41,12 @@ def _general_defaults() -> dict[str, Any]:
# When on, new accounts land in the `pending` role and cannot sign in
# until an administrator approves them. Reserved for the users pass.
"require_approval": False,
"instance_name": "LLeMbas",
# `instance_name` used to be here and now lives in the BRANDING group,
# with the rest of what makes an instance somebody else's. The key is
# deliberately not listed any more: an upgraded instance still has it in
# its stored general row, and `branding.snapshot` reads that once as a
# seed. Leaving a default here as well would give the name two sources
# and no answer to which one wins.
# Applied to every chat that has no model or chat prompt of its
# own. See services.chat.effective_system_prompt.
"system_prompt": "",
@@ -382,9 +388,22 @@ _DEFAULTS: dict[str, Any] = {
IMAGES: _images_defaults,
SCHEDULES: _schedules_defaults,
SUBAGENTS: _subagents_defaults,
# Whose instance this is. The defaults live in `services/branding.py`
# beside the code that reads them, because every one of them is paired with
# a label and a hint for the admin page and splitting the three across two
# modules is how one of them goes stale.
BRANDING: lambda: _branding_defaults(),
}
def _branding_defaults() -> dict[str, Any]:
"""Imported inside the call: `services/branding.py` imports this module for
the group key, so a top-level import back is a cycle."""
from lembas.services import branding
return branding.defaults()
def defaults(key: str = GENERAL) -> dict[str, Any]:
"""The built-in values for a settings group, with nothing stored applied."""
factory = _DEFAULTS.get(key)
+145
View File
@@ -98,6 +98,151 @@ def delete_model_image(filename: str) -> None:
path.unlink(missing_ok=True)
# --- Branding assets -----------------------------------------------------------
# The logo, the favicon and the launcher icons derived from them. A separate
# directory from the model avatars because the *route* differs: these are served
# unauthenticated, since the sign-in page and the web app manifest both need
# them and neither has a session to check.
#
# SVG stays excluded, and this is where somebody will most want it. Every entry
# in ALLOWED_TYPES is a format that cannot execute in an `<img>`; an SVG can, and
# these are the one set of files served to somebody who is not signed in.
# What a launcher asks for, and what `<link rel="apple-touch-icon">` wants.
# Generated from the uploaded logo rather than asked for separately: an
# administrator who has a logo has said everything they need to say, and five
# upload fields to fill in by hand is how three of them end up wrong.
ICON_SIZES: dict[str, int] = {
"icon-192": 192,
"icon-512": 512,
"apple-touch": 180,
"favicon": 32,
}
# The maskable icon has to survive being cropped to a circle, so the artwork
# sits inside the safe zone with the background showing around it. 80% is the
# standard's own guidance and is what the shipped icon already uses.
MASKABLE_SIZE = 512
MASKABLE_INSET = 0.8
def branding_dir() -> Path:
path = settings.uploads_dir / "branding"
path.mkdir(parents=True, exist_ok=True)
return path
def save_branding_image(payload: bytes, declared_type: str) -> str:
"""Validate and store a logo or favicon. Returns the stored filename."""
if not payload:
raise UploadError("The file was empty.")
if len(payload) > MAX_BYTES:
raise UploadError(f"Images must be under {MAX_BYTES // (1024 * 1024)} MB.")
actual = _detect(payload)
if actual is None:
raise UploadError(
"That does not look like a PNG, JPEG, WEBP or GIF image. "
"SVG is deliberately not accepted: these files are served to people "
"who are not signed in, and an SVG can carry a script."
)
if declared_type and declared_type.split(";")[0].strip() != actual:
log.info("upload declared %s but is actually %s", declared_type, actual)
filename = f"{secrets.token_hex(16)}{ALLOWED_TYPES[actual]}"
(branding_dir() / filename).write_bytes(payload)
return filename
def derive_icons(payload: bytes) -> dict[str, str]:
"""Launcher icons from an uploaded logo, at the sizes a browser asks for.
Best-effort: an instance whose logo cannot be resized keeps the shipped
icons, which is a worse launcher tile and not a broken install. Pillow is
already a dependency (`services/files.py` uses it for attachments), so this
adds nothing to install.
Every output is PNG regardless of what came in, because that is what a
manifest icon has to be, and RGBA so a logo with a transparent background
stays one.
"""
try:
import io
from PIL import Image
except Exception: # noqa: BLE001 - Pillow missing is not a failed save
log.info("Pillow unavailable; keeping the shipped launcher icons")
return {}
try:
with Image.open(io.BytesIO(payload)) as source:
source.load()
image = source.convert("RGBA")
except Exception: # noqa: BLE001 - a file we stored but cannot read
log.info("could not read the uploaded logo for icons", exc_info=True)
return {}
paths: dict[str, str] = {}
for name, size in ICON_SIZES.items():
paths[name] = _write_png(_fitted(image, size, size), f"{name}")
# Cropped to a circle on Android, so the artwork is inset and the corners
# are filled rather than transparent -- a transparent maskable icon is
# rendered as a black square by some launchers.
canvas = _new_canvas(MASKABLE_SIZE, image)
inner = _fitted(image, int(MASKABLE_SIZE * MASKABLE_INSET), int(MASKABLE_SIZE * MASKABLE_INSET))
offset = (MASKABLE_SIZE - inner.width) // 2, (MASKABLE_SIZE - inner.height) // 2
canvas.alpha_composite(inner, offset)
paths["maskable"] = _write_png(canvas, "maskable")
return paths
def _fitted(image, width: int, height: int):
from PIL import Image
return image.copy().resize((width, height), Image.LANCZOS)
def _new_canvas(size: int, source):
"""A square the colour of the logo's top-left pixel, or transparent.
Sampling one pixel rather than averaging: a logo on a flat background gets
that background, which is what the inset needs, and a logo on a transparent
one gets transparency, which the composite below then fills.
"""
from PIL import Image
corner = source.getpixel((0, 0))
fill = corner if isinstance(corner, tuple) and len(corner) == 4 else (0, 0, 0, 0)
return Image.new("RGBA", (size, size), fill)
def _write_png(image, label: str) -> str:
import io
buffer = io.BytesIO()
image.save(buffer, format="PNG", optimize=True)
filename = f"{label}-{secrets.token_hex(8)}.png"
(branding_dir() / filename).write_bytes(buffer.getvalue())
return filename
def branding_image_path(filename: str) -> Path | None:
"""Resolve a stored branding filename, refusing anything outside the dir."""
if not filename or "/" in filename or "\\" in filename or filename.startswith("."):
return None
path = (branding_dir() / filename).resolve()
try:
path.relative_to(branding_dir().resolve())
except ValueError:
return None
return path if path.is_file() else None
def delete_branding_image(filename: str) -> None:
path = branding_image_path(filename)
if path is not None:
path.unlink(missing_ok=True)
def media_type_for(filename: str) -> str:
suffix = Path(filename).suffix.lower()
for media_type, extension in ALLOWED_TYPES.items():
+11 -1
View File
@@ -238,7 +238,17 @@
reads as clinical rather than as paper.
---------------------------------------------------------------------------
*/
:root[data-theme="shire"] {
/*
`[data-base="shire"]` as well as `[data-theme="shire"]`, and that second
selector is what makes a custom theme possible. A custom theme is a handful of
token overrides served from /branding.css; everything it does not set has to
come from somewhere, and Moria's block above matches bare `:root` so it always
applies. Without this a custom *light* theme would be four light colours on
near-black surfaces. `<html>` carries both attributes -- see base.html and
app.js:applyTheme.
*/
:root[data-theme="shire"],
:root[data-base="shire"] {
color-scheme: light;
--bg: #F6F1E4;
+41 -7
View File
@@ -9,19 +9,44 @@
"use strict";
var THEME_KEY = "lembas-theme";
var THEMES = ["moria", "shire"];
/* --- Theme -------------------------------------------------------------
Stored locally so the choice applies instantly and survives being signed
out, and mirrored to the server so it follows the user to another device.
The server call is best-effort: a failure must not undo the local switch. */
The server call is best-effort: a failure must not undo the local switch.
The list used to be a literal pair here, and in four other places. It comes
from `data-themes` on <html> now -- "id:base" pairs, space separated --
because an administrator can define one, and a hard-coded pair would refuse
it silently: applyTheme would return, the button would do nothing, and
nothing anywhere would say why. */
function themes() {
var raw = document.documentElement.dataset.themes || "moria:moria shire:shire";
var map = {};
raw.split(/\s+/).forEach(function (entry) {
var parts = entry.split(":");
if (parts[0]) map[parts[0]] = parts[1] || "moria";
});
return map;
}
function themeNames() {
return Object.keys(themes());
}
function currentTheme() {
return document.documentElement.dataset.theme || THEMES[0];
return document.documentElement.dataset.theme || themeNames()[0];
}
function applyTheme(name) {
if (THEMES.indexOf(name) === -1) return;
var known = themes();
if (!Object.prototype.hasOwnProperty.call(known, name)) return;
document.documentElement.dataset.theme = name;
/* Both attributes, always. `data-base` is what makes a custom theme inherit
its built-in palette -- tokens.css matches it as well as `data-theme` --
so setting only the first leaves a custom light theme's four colours on
Moria's near-black surfaces. */
document.documentElement.dataset.base = known[name];
try {
localStorage.setItem(THEME_KEY, name);
} catch (e) { /* private mode */ }
@@ -36,9 +61,13 @@
if (bg) meta.setAttribute("content", bg);
}
/* The toggle names where it is going, not where it is. With more than two
themes "the next one" is the honest description, because naming it would
mean carrying every label into the browser for a label nobody reads
twice. */
document.querySelectorAll("[data-theme-toggle]").forEach(function (el) {
el.setAttribute("aria-label", name === "moria" ? "Switch to Shire (light)"
: "Switch to Moria (dark)");
el.setAttribute("aria-label", known[name] === "moria" ? "Switch to the light theme"
: "Switch to the dark theme");
});
/* For anything holding colours as values rather than reading them from a
@@ -56,8 +85,13 @@
}
}
/* Round the list rather than between two names. With only the built-in pair
this is exactly what it always did; with a third defined it reaches it,
which a hard-coded flip never could. */
function toggleTheme() {
applyTheme(currentTheme() === "moria" ? "shire" : "moria");
var names = themeNames();
var at = names.indexOf(currentTheme());
applyTheme(names[(at + 1) % names.length] || names[0]);
}
/* --- Textarea autosize -------------------------------------------------
+22 -4
View File
@@ -161,10 +161,18 @@
{
name: "theme",
summary: "Switch theme",
argument: "moria | shire",
/* Read from the document rather than written here, for the reason
app.js's own list is: an administrator can define a theme, and a
literal pair would leave `/theme dusk` silently toggling instead. */
argument: function () {
return (document.documentElement.dataset.themes || "moria:moria shire:shire")
.split(/\s+/).map(function (entry) { return entry.split(":")[0]; }).join(" | ");
},
run: function (rest) {
var wanted = (rest || "").trim().toLowerCase();
if (wanted === "moria" || wanted === "shire") window.lembas.applyTheme(wanted);
var known = (document.documentElement.dataset.themes || "").split(/\s+/)
.map(function (entry) { return entry.split(":")[0]; });
if (wanted && known.indexOf(wanted) !== -1) window.lembas.applyTheme(wanted);
else window.lembas.toggleTheme();
}
},
@@ -411,7 +419,8 @@
body.className = "picker__option-body";
var name = document.createElement("span");
name.className = "picker__option-name";
name.textContent = "/" + command.name + (command.argument ? " " + command.argument : "");
var hint = argumentOf(command);
name.textContent = "/" + command.name + (hint ? " " + hint : "");
var summary = document.createElement("span");
summary.className = "picker__option-note";
summary.textContent = command.summary;
@@ -482,11 +491,20 @@
dialog.showModal();
}
/* A command's argument hint, which is usually a literal and is sometimes
worked out from the page -- `/theme` lists the themes that exist, and those
are an administrator's to define. Resolved in the two places that render
it, so a command may be either without either caring. */
function argumentOf(command) {
var value = command.argument;
return typeof value === "function" ? value() : (value || "");
}
function helpSheet() {
var rows = available().map(function (command) {
return (
"<tr><td class='mono'>/" + command.name +
(command.argument ? " " + escapeText(command.argument) : "") +
(argumentOf(command) ? " " + escapeText(argumentOf(command)) : "") +
"</td><td>" + escapeText(command.summary) + "</td></tr>"
);
});
+33 -4
View File
@@ -2,7 +2,7 @@
Shared template macros.
Import at the top of any template that needs them:
{% from "_macros.html" import icon, brand, mark %}
{% from "_macros.html" import icon, brandlink, mark %}
#}
{# An icon from the inlined sprite. `name` omits the "i-" prefix. #}
@@ -16,8 +16,21 @@
because ids are document-global: two marks on one page with the same ids
means the second silently reuses the first one's gradients.
#}
{#
An uploaded logo replaces it, the same way `model_avatar` branches. The branch
is inside the macro rather than at each of the six call sites, so a logo
reaches the sidebar, the sign-in page, the offline page and every empty state
at once -- and so the one place that has to know the fallback exists is here.
`brand` is a Jinja global, so it is available inside a macro with nothing
passed in. That is the whole reason it is a global: a macro has no context.
#}
{% macro mark(cls="brand-mark", uid="a") -%}
<svg class="{{ cls }}" viewBox="0 0 64 64" role="img" aria-label="LLeMbas">
{% if brand.logo_path %}
<img class="{{ cls }}" src="/branding/{{ brand.logo_path }}" alt="{{ brand.name }}"
width="64" height="64">
{% else %}
<svg class="{{ cls }}" viewBox="0 0 64 64" role="img" aria-label="{{ brand.name }}">
<defs>
<linearGradient id="mk-{{ uid }}-w" x1="0" y1="0" x2="0.3" y2="1">
<stop offset="0" stop-color="#7FB758"/>
@@ -50,15 +63,25 @@
<path d="M21 46 Q30.5 34.5 46 18" fill="none" stroke="#57734F"
stroke-opacity="0.5" stroke-width="1.5" stroke-linecap="round"/>
</svg>
{% endif %}
{%- endmacro %}
{#
The wordmark as live text rather than the outlined SVG: it stays selectable,
searchable and readable to a screen reader, and scales with the user's font
size. The capitals spelling LLM take the leaf accent.
size.
The accent on the capitals spelling LLM is only meaningful for the shipped
name, so it is applied only when the name *is* the shipped one. Guessing which
letters of somebody else's name to highlight would produce "InTernal AI" —
worse than plain text, and worse in a way nobody would think to look for.
#}
{% macro wordmark() -%}
{% if brand.name == "LLeMbas" %}
<span class="brand-llm">LL</span>e<span class="brand-llm">M</span>bas
{%- else -%}
{{ brand.name }}
{%- endif %}
{%- endmacro %}
{#
@@ -80,7 +103,13 @@
{% endif %}
{%- endmacro %}
{% macro brand(href="/", uid="a") -%}
{#
The brand link in a sidebar. Named `brandlink` and not `brand`, because
`brand` is the Jinja global holding this instance's identity -- and a macro
imported under that name shadows it for the whole template, which took out
every page that imports this one at once.
#}
{% macro brandlink(href="/", uid="a") -%}
<a class="sidebar__brand" href="{{ href }}">
{{ mark(uid=uid) }}
<span>{{ wordmark() }}</span>
+7 -2
View File
@@ -1,5 +1,5 @@
{% extends "base.html" %}
{% from "_macros.html" import icon, brand %}
{% from "_macros.html" import icon, brandlink %}
{#
Shared chrome for the admin area: its own narrow nav rather than the chat
sidebar, so administration is visibly a different place from chatting.
@@ -16,7 +16,7 @@
<div class="shell">
<aside class="sidebar">
<div class="sidebar__header">
{{ brand(uid="admin") }}
{{ brandlink(uid="admin") }}
</div>
<nav class="sidebar__scroll" aria-label="Administration">
@@ -26,6 +26,11 @@
{{ icon("gear", "icon--sm") }}
<span class="nav-item__label">General</span>
</a>
<a class="nav-item {{ 'is-active' if section == 'customization' }}"
href="/admin/customization">
{{ icon("sun", "icon--sm") }}
<span class="nav-item__label">Customization</span>
</a>
<a class="nav-item {{ 'is-active' if section == 'connections' }}"
href="/admin/connections">
{{ icon("server", "icon--sm") }}
+2 -2
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "agents" %}
{% block title %}Agents - LLeMbas{% endblock %}
{% block title %}Agents - {{ brand.name }}{% endblock %}
{% block heading %}Agents{% endblock %}
{% block admin_content %}
@@ -18,7 +18,7 @@
<span>
There is no sandbox to configure, and that is deliberate: containment is
whatever host somebody points a connection at. A container built for the
job is a very different thing from a key to a live server, and LLeMbas
job is a very different thing from a key to a live server, and {{ brand.name }}
cannot tell them apart. What a model reads — a web page, a file, the output
of the last command — is untrusted, and in <strong>Auto</strong> mode
nothing stands between that and a command running.
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "audio" %}
{% block title %}Audio - LLeMbas{% endblock %}
{% block title %}Audio - {{ brand.name }}{% endblock %}
{% block heading %}Audio{% endblock %}
{% block admin_content %}
@@ -2,13 +2,13 @@
{% from "_macros.html" import icon %}
{% set section = "connections" %}
{% block title %}Connections - LLeMbas{% endblock %}
{% block title %}Connections - {{ brand.name }}{% endblock %}
{% block heading %}Connections{% endblock %}
{% block admin_content %}
<p class="admin-lede">
Any endpoint that speaks the OpenAI HTTP API: OpenAI itself, or a local
runner such as LM Studio, vLLM, llama.cpp or Ollama. LLeMbas asks each one
runner such as LM Studio, vLLM, llama.cpp or Ollama. {{ brand.name }} asks each one
for its model list and offers those models in the chat picker.
</p>
@@ -0,0 +1,229 @@
{% extends "admin/_layout.html" %}
{% from "_macros.html" import icon %}
{% set section = "customization" %}
{% block title %}Customization - {{ brand.name }}{% endblock %}
{% block heading %}Customization{% endblock %}
{% block admin_content %}
<p class="admin-lede">
What this installation is called and what it looks like. Every box below ships
with a default; leaving one alone means it is <em>not</em> stored, so a later
release can still improve the wording. Clearing a box gives you the shipped
version back rather than nothing.
</p>
{% if error %}
<div class="alert alert--error">{{ icon("warning", "icon--sm") }} <span>{{ error }}</span></div>
{% endif %}
{% if saved %}
<div class="alert alert--success">{{ icon("check", "icon--sm") }} <span>{{ saved }}</span></div>
{% endif %}
{# --- Identity ------------------------------------------------------------- #}
<form method="post" action="/admin/customization/identity" enctype="multipart/form-data"
class="form-grid">
<section class="card">
<h2 class="card__title">Identity</h2>
<div class="field">
<label class="field__label" for="instance-name">Name</label>
<input class="input" id="instance-name" name="instance_name"
value="{{ values.instance_name }}" maxlength="120" placeholder="LLeMbas">
<p class="field__hint">
Shown in the sidebar, in every page title, in the launcher when this is
installed as an app, and to the model — it is told which installation it
is answering in. Empty means <strong>LLeMbas</strong>.
</p>
</div>
<div class="field">
<label class="field__label" for="tagline">Tagline</label>
<input class="input" id="tagline" name="tagline"
value="{{ values.tagline }}" maxlength="200">
<p class="field__hint">
One line, used in the page description. The sign-in page has a line of
its own under <strong>Wording</strong> below.
</p>
</div>
<div class="field">
<label class="field__label" for="logo">Logo</label>
{% if current.logo_path %}
<p class="field__hint" style="margin-bottom: var(--sp-2)">
<img src="/branding/{{ current.logo_path }}" alt="" width="48" height="48"
style="vertical-align: middle; border-radius: var(--radius)">
<label class="checkbox" style="display: inline-flex; margin-left: var(--sp-3)">
<input type="checkbox" name="remove_logo" value="true">
<span>Remove it</span>
</label>
</p>
{% endif %}
<input class="input" id="logo" name="logo" type="file"
accept="image/png,image/jpeg,image/webp,image/gif">
<p class="field__hint">
Replaces the leaf mark everywhere it appears. PNG, JPEG, WEBP or GIF,
under 2 MB, square. <strong>SVG is deliberately not accepted</strong>:
these files are served to people who are not signed in, and an SVG can
carry a script. The launcher icons are made from this automatically.
</p>
</div>
<div class="field">
<label class="field__label" for="favicon">Favicon</label>
{% if current.favicon_path %}
<p class="field__hint" style="margin-bottom: var(--sp-2)">
<img src="/branding/{{ current.favicon_path }}" alt="" width="16" height="16"
style="vertical-align: middle">
<label class="checkbox" style="display: inline-flex; margin-left: var(--sp-3)">
<input type="checkbox" name="remove_favicon" value="true">
<span>Remove it</span>
</label>
</p>
{% endif %}
<input class="input" id="favicon" name="favicon" type="file"
accept="image/png,image/jpeg,image/webp,image/gif">
<p class="field__hint">
Optional. Without one, a logo you upload is used at 32px, and without
that the shipped leaf.
</p>
</div>
</section>
<div class="btn-row">
<button class="btn btn--primary" type="submit">Save identity</button>
</div>
</form>
{# --- Wording -------------------------------------------------------------- #}
<form method="post" action="/admin/customization/flavour" class="form-grid">
<section class="card">
<h2 class="card__title">Wording</h2>
<p class="field__hint">
The lines with a bit of character in them. They live in the empty states,
the error pages and the sign-in screen — never in the functional interface,
where a button says what it does. Replace them with your own, or leave them.
</p>
{% for entry in flavour %}
<div class="field">
<label class="field__label" for="text-{{ entry.key }}">{{ entry.label }}</label>
<input class="input" id="text-{{ entry.key }}" name="text_{{ entry.key }}"
value="{{ entry.value }}" maxlength="400"
placeholder="{{ entry.default }}">
<p class="field__hint">{{ entry.hint }}</p>
</div>
{% endfor %}
</section>
<div class="btn-row">
<button class="btn btn--primary" type="submit">Save wording</button>
</div>
</form>
{# --- Themes --------------------------------------------------------------- #}
{#
Three blocks, always rendered, so adding a theme needs no JavaScript: an empty
id means that block is not a theme. Saving replaces the whole list, which is
what makes removing one a matter of clearing its id.
#}
<form method="post" action="/admin/customization/themes" class="form-grid">
<section class="card">
<h2 class="card__title">Themes</h2>
<p class="field__hint">
A theme is a set of colours, not a stylesheet — nothing in this interface
hard-codes one, so a third palette composes with everything. Pick which
built-in it starts from and change only what you want; everything left
empty is inherited. The soft variants behind focus rings and selected rows
are worked out from the accent, so you do not have to.
</p>
{% for index in range(3) %}
{% set existing = custom_themes[index] if index < custom_themes | length else none %}
<div class="card" style="margin-top: var(--sp-4)">
<h3 class="section-title">
{{ existing.label if existing else "A theme of your own" }}
</h3>
<div class="field-row">
<div class="field">
<label class="field__label" for="theme-{{ index }}-id">Id</label>
<input class="input" id="theme-{{ index }}-id" name="theme_{{ index }}_id"
value="{{ existing.id if existing else '' }}" maxlength="24"
pattern="[a-z][a-z0-9-]*" placeholder="dusk">
<p class="field__hint">
Lowercase letters, digits and hyphens. Clear it to remove the theme.
</p>
</div>
<div class="field">
<label class="field__label" for="theme-{{ index }}-label">Name</label>
<input class="input" id="theme-{{ index }}-label" name="theme_{{ index }}_label"
value="{{ existing.label if existing else '' }}" maxlength="60"
placeholder="Dusk">
</div>
<div class="field">
<label class="field__label" for="theme-{{ index }}-base">Starts from</label>
<select class="input" id="theme-{{ index }}-base" name="theme_{{ index }}_base">
{% for base in bases %}
<option value="{{ base }}"
{{ 'selected' if existing and existing.base == base }}>{{ base }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="field-row">
{% for name, description in tokens %}
<div class="field">
<label class="field__label" for="theme-{{ index }}-{{ name }}">
{{ description }}
</label>
<input class="input" id="theme-{{ index }}-{{ name }}"
name="theme_{{ index }}_{{ name }}" type="text"
value="{{ existing.tokens.get(name, '') if existing else '' }}"
maxlength="40" placeholder="inherited"
spellcheck="false">
<p class="field__hint"><code>--{{ name }}</code></p>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</section>
<div class="btn-row">
<button class="btn btn--primary" type="submit">Save themes</button>
</div>
</form>
{# --- Stylesheet ----------------------------------------------------------- #}
<form method="post" action="/admin/customization/css" class="form-grid">
<section class="card">
<h2 class="card__title">Stylesheet</h2>
<p class="field__hint">
Served as <code>/branding.css</code> after everything else, so these rules
win. It is a file rather than a block inside the page on purpose: a
stylesheet has no markup around it to escape from. Reach for the themes
above first — a colour set there follows both palettes, and a rule here
follows neither.
</p>
<div class="field">
<label class="field__label" for="custom-css">CSS</label>
<textarea class="input textarea" id="custom-css" name="custom_css" rows="10"
spellcheck="false"
placeholder=".sidebar__brand { letter-spacing: 0.02em; }"
>{{ values.custom_css }}</textarea>
<p class="field__hint">
Up to 40,000 characters. Nothing here is validated: a rule that does not
parse is dropped by the browser, quietly, as it would be in any
stylesheet.
</p>
</div>
</section>
<div class="btn-row">
<button class="btn btn--primary" type="submit">Save stylesheet</button>
</div>
</form>
{% endblock %}
+12 -10
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "general" %}
{% block title %}General - LLeMbas{% endblock %}
{% block title %}General - {{ brand.name }}{% endblock %}
{% block heading %}General{% endblock %}
{% block admin_content %}
@@ -15,16 +15,18 @@
<div class="alert alert--success">{{ icon("check", "icon--sm") }} <span>Settings saved.</span></div>
{% endif %}
{#
The instance name used to be here. It lives on Customization now, with the
logo, the wording and the themes -- one field, one page. Left as a link rather
than duplicated: two controls writing one value is how each becomes the answer
to "why did my change not stick?".
#}
<p class="admin-lede">
The name, the logo, the wording and the themes are on
<a href="/admin/customization">Customization</a>.
</p>
<form method="post" action="/admin/general">
<section class="card">
<h2 class="card__title">Identity</h2>
<div class="field">
<label class="field__label" for="instance-name">Instance name</label>
<input class="input" id="instance-name" name="instance_name"
value="{{ values.instance_name }}" maxlength="120">
<p class="field__hint">Shown in the browser tab and on the sign-in page.</p>
</div>
</section>
<section class="card">
<h2 class="card__title">Default system prompt</h2>
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon, model_avatar %}
{% set section = "groups" %}
{% block title %}Groups &amp; permissions - LLeMbas{% endblock %}
{% block title %}Groups &amp; permissions - {{ brand.name }}{% endblock %}
{% block heading %}Groups &amp; permissions{% endblock %}
{% block admin_content %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "images" %}
{% block title %}Image generation - LLeMbas{% endblock %}
{% block title %}Image generation - {{ brand.name }}{% endblock %}
{% block heading %}Image generation{% endblock %}
{% block admin_content %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "mcp" %}
{% block title %}MCP servers - LLeMbas{% endblock %}
{% block title %}MCP servers - {{ brand.name }}{% endblock %}
{% block heading %}MCP servers{% endblock %}
{% block admin_content %}
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "mcp" %}
{% block title %}{{ "New server" if is_new else server.name }} - LLeMbas{% endblock %}
{% block title %}{{ "New server" if is_new else server.name }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ "New MCP server" if is_new else server.name }}{% endblock %}
{% block admin_content %}
@@ -186,7 +186,7 @@
</div>
<p class="field__hint">
Tick the second only for a server on your own network. It is what stops
this being aimed at LLeMbas itself, a router, or a metadata endpoint.
this being aimed at {{ brand.name }} itself, a router, or a metadata endpoint.
</p>
</div>
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon, model_avatar %}
{% set section = "models" %}
{% block title %}{{ model.label }} - Models - LLeMbas{% endblock %}
{% block title %}{{ model.label }} - Models - {{ brand.name }}{% endblock %}
{% block heading %}{{ model.label }}{% endblock %}
{% block admin_content %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon, model_avatar %}
{% set section = "models" %}
{% block title %}Models - LLeMbas{% endblock %}
{% block title %}Models - {{ brand.name }}{% endblock %}
{% block heading %}Models{% endblock %}
{% block admin_content %}
+2 -2
View File
@@ -2,12 +2,12 @@
{% from "_macros.html" import icon %}
{% set section = "prompts" %}
{% block title %}Prompts - LLeMbas{% endblock %}
{% block title %}Prompts - {{ brand.name }}{% endblock %}
{% block heading %}Prompts{% endblock %}
{% block admin_content %}
<p class="admin-lede">
Everything LLeMbas puts in front of a model on its own: what day it is, how to
Everything {{ brand.name }} puts in front of a model on its own: what day it is, how to
use each tool, what it has been asked to remember. These sit above whichever
system prompt was authored for the instance, the model or the chat — that
prompt still wins where the two disagree. Clear a box to leave that piece out
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "schedules" %}
{% block title %}Scheduling - LLeMbas{% endblock %}
{% block title %}Scheduling - {{ brand.name }}{% endblock %}
{% block heading %}Scheduling{% endblock %}
{% block admin_content %}
+3 -3
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "search" %}
{% block title %}Web search - LLeMbas{% endblock %}
{% block title %}Web search - {{ brand.name }}{% endblock %}
{% block heading %}Web search{% endblock %}
{% block admin_content %}
@@ -112,7 +112,7 @@
<h2 class="card__title">Saving links</h2>
<p class="card__lede">
Applies to the composer's <strong>Link</strong> option and to anything the
model fetches: LLeMbas retrieves the page and keeps its text.
model fetches: {{ brand.name }} retrieves the page and keeps its text.
</p>
<div class="field">
<label class="checkbox">
@@ -136,7 +136,7 @@
</label>
<p class="field__hint">
Off by default, and worth leaving off. This server can reach your
router, your other services and LLeMbas itself; the address to fetch can
router, your other services and {{ brand.name }} itself; the address to fetch can
come from a model, which can be talked into things by a web page it just
read. Turn this on only if you actually want to archive pages from your
own network.
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "suggestions" %}
{% block title %}Suggestions - LLeMbas{% endblock %}
{% block title %}Suggestions - {{ brand.name }}{% endblock %}
{% block heading %}Suggestions{% endblock %}
{% block admin_content %}
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "tools" %}
{% block title %}{{ "New tool" if is_new else tool.name }} - LLeMbas{% endblock %}
{% block title %}{{ "New tool" if is_new else tool.name }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ "New tool" if is_new else tool.name }}{% endblock %}
{% block admin_content %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "tools" %}
{% block title %}Tools - LLeMbas{% endblock %}
{% block title %}Tools - {{ brand.name }}{% endblock %}
{% block heading %}Tools{% endblock %}
{% block admin_content %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "users" %}
{% block title %}Users - LLeMbas{% endblock %}
{% block title %}Users - {{ brand.name }}{% endblock %}
{% block heading %}Users{% endblock %}
{% block admin_content %}
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "images" %}
{% block title %}{{ workflow.name or "New workflow" }} - LLeMbas{% endblock %}
{% block title %}{{ workflow.name or "New workflow" }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ workflow.name or "New workflow" }}{% endblock %}
{% block admin_content %}
+1 -1
View File
@@ -4,7 +4,7 @@
Connections, kept by the person who owns them.
Shares the chat sidebar with the library for the same reason: this is part of
using LLeMbas, not administering it. You come here to add a machine and go
using {{ brand.name }}, not administering it. You come here to add a machine and go
straight back to a conversation.
#}
+1 -1
View File
@@ -1,7 +1,7 @@
{% extends "agents/_layout.html" %}
{% from "_macros.html" import icon %}
{% block title %}{{ "New connection" if is_new else profile.name }} - LLeMbas{% endblock %}
{% block title %}{{ "New connection" if is_new else profile.name }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ "New connection" if is_new else profile.name }}{% endblock %}
{% block agents_content %}
+2 -2
View File
@@ -1,7 +1,7 @@
{% extends "agents/_layout.html" %}
{% from "_macros.html" import icon %}
{% block title %}Connections - LLeMbas{% endblock %}
{% block title %}Connections - {{ brand.name }}{% endblock %}
{% block heading %}Connections{% endblock %}
{% block actions %}
<a class="btn btn--primary btn--sm" href="/agents/new">
@@ -21,7 +21,7 @@
<span>
Whatever this connection can reach, a model in an agent chat can reach. A
container built for the job, with one project mounted into it, is a very
different thing from a key to a machine you care about — and LLeMbas cannot
different thing from a key to a machine you care about — and {{ brand.name }} cannot
tell them apart.
</span>
</div>
+2 -2
View File
@@ -1,7 +1,7 @@
{% extends "base.html" %}
{% from "_macros.html" import icon, mark, wordmark %}
{% block title %}Sign in - LLeMbas{% endblock %}
{% block title %}Sign in - {{ brand.name }}{% endblock %}
{% block body %}
<main class="auth">
@@ -9,7 +9,7 @@
<div class="auth__brand">
{{ mark(cls="brand-mark", uid="auth") }}
<h1 class="auth__title">{{ wordmark() }}</h1>
<p class="auth__subtitle">Waybread for the long road of thought.</p>
<p class="auth__subtitle">{{ brand.text.login_tagline }}</p>
</div>
{% if error %}
+1 -1
View File
@@ -1,7 +1,7 @@
{% extends "base.html" %}
{% from "_macros.html" import icon, mark, wordmark %}
{% block title %}{% if first_run %}Set up LLeMbas{% else %}Create an account{% endif %}{% endblock %}
{% block title %}{% if first_run %}Set up {{ brand.name }}{% else %}Create an account{% endif %}{% endblock %}
{% block body %}
<main class="auth">
+37 -4
View File
@@ -1,13 +1,33 @@
<!doctype html>
<html lang="en" data-theme="{{ theme }}"{% if layout %} style="{{ layout }}"{% endif %}>
{#
`data-base` is what makes a custom theme inherit: tokens.css matches
`[data-base="shire"]` as well as `[data-theme="shire"]`, so a custom light
theme gets the whole parchment palette underneath its own handful of colours.
Without it, four light colours would sit on Moria's near-black surfaces.
`data-themes` is the list of `id:base` pairs, which is what the browser needs
in order to set both attributes when somebody switches -- one attribute to
split rather than a JSON island to parse.
#}
<html lang="en" data-theme="{{ theme }}" data-base="{{ brand.theme(theme).base }}"
data-themes="{{ brand.theme_list }}"{% if layout %} style="{{ layout }}"{% endif %}>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}LLeMbas{% endblock %}</title>
<meta name="description" content="LLeMbas - a web UI for your language models.">
<title>{% block title %}{{ brand.name }}{% endblock %}</title>
<meta name="description" content="{{ brand.tagline or brand.name ~ ' — a web UI for your language models.' }}">
<meta name="color-scheme" content="dark light">
{# An uploaded favicon wins; then the icon derived from an uploaded logo; then
the shipped leaf. Three rungs rather than two because somebody who uploads a
logo and no favicon still expects the tab to change. #}
{% if brand.favicon_path %}
<link rel="icon" href="/branding/{{ brand.favicon_path }}">
{% elif brand.icon_paths.favicon %}
<link rel="icon" href="/branding/{{ brand.icon_paths.favicon }}">
{% else %}
<link rel="icon" href="{{ url_for('static', path='img/favicon.svg') }}" type="image/svg+xml">
{% endif %}
{#
Installing as an app. The manifest is a route, not a file, because it carries
@@ -17,14 +37,27 @@
#}
<link rel="manifest" href="/manifest.webmanifest">
<meta name="theme-color" content="#101317">
{% if brand.icon_paths['apple-touch'] %}
<link rel="apple-touch-icon" href="/branding/{{ brand.icon_paths['apple-touch'] }}">
{% else %}
<link rel="apple-touch-icon" href="{{ url_for('static', path='img/apple-touch-icon-180.png') }}">
{% endif %}
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="LLeMbas">
<meta name="apple-mobile-web-app-title" content="{{ brand.name }}">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="stylesheet" href="{{ url_for('static', path='css/tokens.css') }}">
<link rel="stylesheet" href="{{ url_for('static', path='css/app.css') }}">
{#
Last, so an administrator's rules win, and before {% block head %} so a page's
own stylesheet still comes after it. The query string is a hash of everything
the route builds, so the URL changes exactly when the stylesheet does -- with a
fixed URL the browser's cache would be what decided when a rebrand took effect.
Deliberately NOT in the service worker's precache list for the same reason:
that cache is versioned by the release, and branding changes between releases.
#}
<link rel="stylesheet" href="/branding.css?v={{ brand.revision }}">
{% block head %}{% endblock %}
{#
@@ -8,7 +8,7 @@
itself all came from a model that may have been reading somebody else's file
a moment ago.
Deliberately attributed to the model rather than styled as if LLeMbas were
Deliberately attributed to the model rather than styled as if {{ brand.name }} were
asking. A question that looks like it came from the application is a question
people answer with things they would not tell a chatbot.
+1 -1
View File
@@ -63,7 +63,7 @@
<header class="msg__meta">
<span class="msg__author">
{% if message.role == "assistant" %}
{{ speaking_model.label if speaking_model else "LLeMbas" }}
{{ speaking_model.label if speaking_model else brand.name }}
{% elif machine %}
Background job
{% else %}
+3 -3
View File
@@ -1,7 +1,7 @@
{% extends "base.html" %}
{% from "_macros.html" import icon, mark, model_avatar %}
{% block title %}{{ chat.title if chat else "New chat" }} - LLeMbas{% endblock %}
{% block title %}{{ chat.title if chat else "New chat" }} - {{ brand.name }}{% endblock %}
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', path='css/chat.css') }}">
@@ -286,7 +286,7 @@
<h2 class="empty__title">No models available</h2>
<p class="empty__text">
{% if user.is_admin %}
Add an OpenAI-compatible connection and LLeMbas will load its models.
Add an OpenAI-compatible connection and {{ brand.name }} will load its models.
{% else %}
No model connections have been set up yet. Ask an administrator.
{% endif %}
@@ -305,7 +305,7 @@
<div class="thread__intro">
{{ mark(cls="empty__mark", uid="intro") }}
<h2 class="empty__title">What would you ask?</h2>
<p class="empty__text">Speak, friend, and enter.</p>
<p class="empty__text">{{ brand.text.chat_empty }}</p>
{# Only on a chat that does not exist yet. An empty chat someone
opened on purpose already has a model and a prompt chosen. #}
+1 -1
View File
@@ -1,7 +1,7 @@
{% extends "base.html" %}
{% from "_macros.html" import mark %}
{% block title %}{{ status_code }} - LLeMbas{% endblock %}
{% block title %}{{ status_code }} - {{ brand.name }}{% endblock %}
{% block body %}
<main class="auth">
+1 -1
View File
@@ -14,7 +14,7 @@
an absent one are the same request.
#}
{% block title %}{{ folder.name }} - LLeMbas{% endblock %}
{% block title %}{{ folder.name }} - {{ brand.name }}{% endblock %}
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', path='css/chat.css') }}">
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "knowledge" %}
{% block title %}{{ base.name }} - LLeMbas{% endblock %}
{% block title %}{{ base.name }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ base.name }}{% endblock %}
{% block library_content %}
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "knowledge" %}
{% block title %}Knowledge - LLeMbas{% endblock %}
{% block title %}Knowledge - {{ brand.name }}{% endblock %}
{% block heading %}Knowledge{% endblock %}
{% block library_content %}
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "knowledge" %}
{% block title %}{{ document.title }} - LLeMbas{% endblock %}
{% block title %}{{ document.title }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ document.title }}{% endblock %}
{% block library_content %}
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "notes" %}
{% block title %}{{ note.title if note else "New note" }} - LLeMbas{% endblock %}
{% block title %}{{ note.title if note else "New note" }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ note.title if note else "New note" }}{% endblock %}
{% block library_content %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "notes" %}
{% block title %}Notes - LLeMbas{% endblock %}
{% block title %}Notes - {{ brand.name }}{% endblock %}
{% block heading %}Notes{% endblock %}
{% block actions %}
<a class="btn btn--primary btn--sm" href="/library/notes/new">{{ icon("plus", "icon--sm") }} New note</a>
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "skills" %}
{% block title %}{{ skill.name if skill else "New skill" }} - LLeMbas{% endblock %}
{% block title %}{{ skill.name if skill else "New skill" }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ skill.name if skill else "New skill" }}{% endblock %}
{% block library_content %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "skills" %}
{% block title %}Skills - LLeMbas{% endblock %}
{% block title %}Skills - {{ brand.name }}{% endblock %}
{% block heading %}Skills{% endblock %}
{% block actions %}
<a class="btn btn--primary btn--sm" href="/library/skills/new">{{ icon("plus", "icon--sm") }} New skill</a>
+1 -1
View File
@@ -10,7 +10,7 @@
is the whole reason this is a `Chat` with a different `kind`.
#}
{% block title %}Messages - LLeMbas{% endblock %}
{% block title %}Messages - {{ brand.name }}{% endblock %}
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', path='css/chat.css') }}">
+4 -4
View File
@@ -8,18 +8,18 @@
flavour belongs -- see the flavour rule in CLAUDE.md.
#}
{% block title %}Offline - LLeMbas{% endblock %}
{% block title %}Offline - {{ brand.name }}{% endblock %}
{% block body %}
<main class="auth">
<div class="auth__card" style="text-align: center">
{{ mark(cls="empty__mark", uid="offline") }}
<h1 class="auth__title" style="margin-top: var(--sp-4)">No road from here</h1>
<h1 class="auth__title" style="margin-top: var(--sp-4)">{{ brand.text.offline_title }}</h1>
<p class="empty__text" style="margin: var(--sp-3) auto var(--sp-5)">
The Road goes ever on and on — but not without a connection.
{{ brand.text.offline_line }}
</p>
<p class="text-sm muted" style="margin-bottom: var(--sp-5)">
LLeMbas answers from your server, so there is nothing to read until it can
{{ brand.name }} answers from your server, so there is nothing to read until it can
be reached again.
</p>
<button class="btn btn--primary" type="button" onclick="window.location.reload()">
@@ -1,4 +1,4 @@
{% from "_macros.html" import icon, brand, model_avatar %}
{% from "_macros.html" import icon, brandlink, model_avatar %}
{#
Sidebar: brand, new chat, pinned models, the folder tree, then unfiled chats.
@@ -8,7 +8,7 @@
#}
<aside class="sidebar" id="sidebar">
<div class="sidebar__header">
{{ brand(uid="side") }}
{{ brandlink(uid="side") }}
</div>
{% include "partials/_sidebar_actions.html" %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "reports" %}
{% block title %}{{ report.title }} - LLeMbas{% endblock %}
{% block title %}{{ report.title }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ report.title }}{% endblock %}
{% block actions %}
<a class="btn btn--sm" href="/reports">{{ icon("chevron-left", "icon--sm") }} All reports</a>
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "reports" %}
{% block title %}Reports - LLeMbas{% endblock %}
{% block title %}Reports - {{ brand.name }}{% endblock %}
{% block heading %}Reports{% endblock %}
{% block reports_content %}
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "scheduled" %}
{% block title %}{{ schedule.title }} - LLeMbas{% endblock %}
{% block title %}{{ schedule.title }} - {{ brand.name }}{% endblock %}
{% block heading %}{{ schedule.title }}{% endblock %}
{% block actions %}
<a class="btn btn--sm" href="/chat/{{ schedule.chat_id }}">Open its chat</a>
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "scheduled" %}
{% block title %}Scheduled - LLeMbas{% endblock %}
{% block title %}Scheduled - {{ brand.name }}{% endblock %}
{% block heading %}Scheduled{% endblock %}
{% block actions %}
<a class="btn btn--primary btn--sm" href="/scheduled/new">
+1 -1
View File
@@ -2,7 +2,7 @@
{% from "_macros.html" import icon %}
{% set section = "scheduled" %}
{% block title %}New scheduled task - LLeMbas{% endblock %}
{% block title %}New scheduled task - {{ brand.name }}{% endblock %}
{% block heading %}What do you want to schedule?{% endblock %}
{% block actions %}
<a class="btn btn--sm" href="/scheduled">Cancel</a>
+13 -6
View File
@@ -1,7 +1,7 @@
{% extends "base.html" %}
{% from "_macros.html" import icon, model_avatar %}
{% block title %}Your settings - LLeMbas{% endblock %}
{% block title %}Your settings - {{ brand.name }}{% endblock %}
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', path='css/chat.css') }}">
@@ -167,13 +167,20 @@
<p class="card__lede">
Saved to this browser and to your account, so it follows you.
</p>
{#
A loop rather than two buttons, because an administrator can
define more. The names come from the branding snapshot, so a
theme renamed on Customization is renamed here without this
template knowing there was ever a fixed pair.
#}
<div class="btn-row">
<button class="btn" type="button" onclick="window.lembas.applyTheme('moria')">
{{ icon("moon", "icon--sm") }} Moria — dark
</button>
<button class="btn" type="button" onclick="window.lembas.applyTheme('shire')">
{{ icon("sun", "icon--sm") }} Shire — light
{% for entry in brand.themes %}
<button class="btn" type="button"
onclick="window.lembas.applyTheme('{{ entry.id }}')">
{{ icon("moon" if entry.scheme == "dark" else "sun", "icon--sm") }}
{{ entry.label }} — {{ entry.scheme }}
</button>
{% endfor %}
</div>
</div>
+32 -1
View File
@@ -68,16 +68,47 @@ templates.env.globals["tool_icon"] = tool_labels.icon_for
templates.env.globals["message_steps"] = steps_service.for_message
class _Brand:
"""Whose instance this is, as a Jinja global.
A **global** and not a context value, because `render()` has no database
session and four render paths never reach it at all -- the login page, the
error pages, the offline page and the SSE fragments. Threading it through
every one of those would still leave the ones that bypass `render()`.
A proxy rather than the snapshot itself, because a global is bound once at
import and the snapshot changes when an administrator saves. Every attribute
goes through `branding.snapshot()`, which is a process-level cache: one
query per process, and one after each save.
"""
def __getattr__(self, name: str):
from lembas.services import branding
return getattr(branding.snapshot(), name)
templates.env.globals["brand"] = _Brand()
def resolve_theme(user: User | None) -> str:
"""Theme to render with on the server.
Only ever a first guess: the inline script in base.html corrects it from
localStorage before first paint. Getting it close server-side is what stops
a signed-in user seeing a flash of the wrong theme on every navigation.
Validated against the themes that actually exist rather than against a
hard-coded pair, or a custom theme would be stored on the account, refused
here, and rendered as Moria on every page load until localStorage corrected
it -- a flash on every navigation, which is what this function exists to
prevent.
"""
from lembas.services import branding
if user is not None:
chosen = (user.settings_json or {}).get("theme")
if chosen in ("moria", "shire"):
if chosen in branding.snapshot().theme_ids:
return chosen
return settings.default_theme