Files
LLeMbas/src/lembas/api/pages.py
T
Jaroslav Beneš 7b67568f2c Fix bulk actions, create chats lazily, rework the UI
Seven reported problems.

**Bulk model actions 404'd.** /admin/models/{model_id} was registered
before /admin/models/bulk, and FastAPI matches in registration order, so
"bulk" was parsed as a model id. Moved above the parameterised route,
with a comment saying why, and a regression test.

**Empty chats piled up.** There is now no endpoint that creates one.
"New chat" is a link to /chat, which renders a composer with no row
behind it, and POST /api/chats/start writes the chat together with its
first message. Opening one and walking away leaves nothing.

**Pinning meant two different things.** The picker is now always in the
administrator's position order; pinned models get shortcuts in the chat
sidebar and nothing else. A picker whose order silently differs from the
admin screen is just confusing.

**Model images were missing in chat.** Assistant bubbles now show the
avatar of the model that actually wrote the turn -- which is not always
the model the chat is set to now -- falling back to the LLeMbas mark.
The picker shows it too.

**No global or per-model system prompt.** Three layers now: instance
(Admin -> General), model (Admin -> Models), chat. Precedence, not
concatenation: most specific wins outright. Stacking them reads well in
a settings screen and badly in practice, because two layers that
disagree give the model contradictory instructions and nobody can tell
which is losing. The chat panel shows the inherited prompt as
placeholder text so "leave empty to inherit" is not a guess.

**Alignment and button sizing.** Added --control-h and friends to
tokens.css; every button, input and select takes its height from them,
so a mixed row is flush by construction rather than by per-instance
nudging. Icon buttons are square at that height. Added .btn-row,
.card__header/.card__footer and .grid so pages stop carrying inline
styles, and moved every admin page onto them.

**Settings needed structure.** The user settings page is now tabbed
(Account / Models / Appearance / Security) using radio inputs and
sibling selectors -- no JavaScript, and the browser keeps the chosen tab
across a re-render.

Caught while checking: the chat.css surgery had deleted the attachment,
chip and dropzone rules. Restored, and there is now a check that every
literal class used in a template has a CSS rule.

197 tests, ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 12:59:52 +02:00

176 lines
5.7 KiB
Python

"""Full-page routes: the chat shell and the user's own settings."""
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from sqlalchemy import select
from sqlalchemy.orm import Session as DBSession
from lembas.api.deps import Db, RequiredUser
from lembas.db.models import Chat, Folder, Message, User
from lembas.security import permissions
from lembas.services import chat as chat_service
from lembas.services.markdown import render_markdown
from lembas.web.templating import render
router = APIRouter(tags=["pages"])
def _chat_context(db: DBSession, user: User, chat: Chat | None) -> dict:
"""Model lists and permissions every chat page needs.
Pinned and unpinned are split here rather than in the template so the
picker's optgroups stay a plain loop.
"""
models = chat_service.available_models(db, user)
current = next((m for m in models if m.model_id == chat.model_id), None) if chat else None
return {
"models": models,
# For the sidebar shortcuts only. The picker lists `models` in the
# administrator's order, pinned or not.
"pinned_models": [m for m in models if m.pinned],
"current_model": current,
# Assistant bubbles show the avatar of the model that wrote them, which
# may not be the model the chat is set to now. Keyed by model_id, the
# denormalised value stored on each message.
"models_by_id": {m.model_id: m for m in models},
}
def _sidebar_context(db: DBSession, user: User) -> dict:
"""Folder tree plus the chats that belong to no folder.
Only root folders are queried; children come through the relationship and
render recursively in the template.
"""
folders = list(
db.scalars(
select(Folder)
.where(Folder.user_id == user.id, Folder.parent_id.is_(None))
.order_by(Folder.position, Folder.name)
)
)
unfiled = list(
db.scalars(
select(Chat)
.where(
Chat.user_id == user.id,
Chat.folder_id.is_(None),
Chat.archived.is_(False),
)
.order_by(Chat.pinned.desc(), Chat.updated_at.desc())
)
)
return {
"folders": folders,
"unfiled_chats": unfiled,
"can": permissions.resolve(db, user),
}
@router.get("/")
async def home(user: RequiredUser):
return RedirectResponse("/chat", status_code=status.HTTP_303_SEE_OTHER)
@router.get("/chat")
async def chat_index(request: Request, db: Db, user: RequiredUser, model: str = ""):
"""A composer with no chat behind it yet.
`?model=` preselects one, which is how the pinned shortcuts work without
creating a row for a chat that may never be sent.
"""
context = _chat_context(db, user, None)
preselected = next(
(m for m in context["models"] if m.model_id == model), None
) or (context["models"][0] if context["models"] else None)
return render(
request,
"chat/index.html",
{
"chat": None,
"messages": [],
"bodies": {},
**context,
"current_model": preselected,
**_sidebar_context(db, user),
},
)
@router.get("/chat/{chat_id}")
async def chat_detail(request: Request, db: Db, user: RequiredUser, chat_id: str):
chat = db.get(Chat, chat_id)
if chat is None or chat.user_id != user.id:
raise HTTPException(status.HTTP_404_NOT_FOUND, "That chat no longer exists.")
messages = list(
db.scalars(
select(Message).where(Message.chat_id == chat.id).order_by(Message.created_at)
)
)
# Markdown is rendered once here rather than in the template so the same
# helper produces the page and the streamed final frame -- one code path,
# no chance of the two disagreeing.
bodies = {
message.id: render_markdown(message.content)
for message in messages
if message.role == "assistant" and message.content
}
# What the chat would use if its own prompt were empty, so the settings
# panel can show it as placeholder text rather than leaving the user to
# guess what "inherited" means.
inherited, inherited_from = "", ""
current = next(
(m for m in chat_service.available_models(db, user) if m.model_id == chat.model_id), None
)
if current is not None and (current.system_prompt or "").strip():
inherited, inherited_from = current.system_prompt.strip(), "model"
else:
from lembas.services import settings_store
instance_prompt = (settings_store.get(db, "system_prompt") or "").strip()
if instance_prompt:
inherited, inherited_from = instance_prompt, "instance"
return render(
request,
"chat/index.html",
{
"chat": chat,
"messages": messages,
"bodies": bodies,
"inherited_prompt": inherited,
"inherited_from": inherited_from,
**_chat_context(db, user, chat),
**_sidebar_context(db, user),
},
)
@router.get("/settings")
async def settings_page(
request: Request,
db: Db,
user: RequiredUser,
error: str = "",
saved: str = "",
):
# error/saved arrive as query parameters because the password form redirects
# back here: a POST that re-rendered in place would re-submit on refresh.
return render(
request,
"settings.html",
{
"chat": None,
"error": error,
"saved": saved,
**_chat_context(db, user, None),
**_sidebar_context(db, user),
},
)