1d3f6c450b
Four features, plus the schema machinery they needed. **Schema sync.** The first live instance had data in it, and create_all only creates missing *tables* -- a new column silently never appeared. db/migrations.py now diffs the declared models against the database and ALTER TABLE ... ADD COLUMN for what is missing, deriving a backfill default from the column type (SQLite refuses a NOT NULL column without one, and a Python-side `default=dict` cannot be expressed in DDL). Verified against a copy of the live database: eight changes applied, all rows preserved, second run a no-op. Renames, drops and retypes are still manual and say so. **Permissions.** A flat set of named booleans: an instance baseline widened by each group the user belongs to. A group grants and never denies -- with denies, "why can this user not do X" cannot be answered without simulating every group. Admins bypass entirely, because an admin can grant it back to themselves in two clicks and pretending otherwise is theatre. Model *access* is separate: public, or granted to groups. The picker is not the boundary -- switching a chat to a model you cannot reach is a 403. **Model settings.** Ordering, pinned-first, an instance default and a per-user default, display names, descriptions, capability flags, and uploaded images. Images are stored and served locally rather than by URL: a remote URL makes every page render a request to a third party. Uploads are validated by magic number, not the declared content type, and stored under a random name. Models with no image get a generated initial whose hue is derived from the model id, so it is stable. **Reasoning display.** Streams into its own collapsible block above the answer, labelled "Thought for 14 seconds", collapsed once finished, and never replayed as context on the next turn. Two sources: the reasoning_content delta field, and <think> tags inline in content -- the latter needs a streaming splitter because the tags arrive split across chunks. Models emitting no reasoning show nothing, via a :has() rule rather than JavaScript. Verified against qwen35-9b on llama-swap: 694 reasoning events, 52 answer tokens, cleanly separated. Two bugs found and fixed while testing: - A bare `Mapped[list]` relationship is treated by SQLAlchemy as a scalar and returns None instead of []. It needs the element type. - FastAPI substitutes the default for an empty form value, so with `x: str | None = Form(None)` a submitted `x=` is indistinguishable from an absent field. That silently broke clearing a system prompt or a temperature. update_chat now reads the raw form and checks key presence. 143 tests, ruff clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
145 lines
4.3 KiB
Python
145 lines
4.3 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
|
|
pinned = [m for m in models if m.pinned]
|
|
return {
|
|
"models": models,
|
|
"pinned_models": pinned,
|
|
# Excludes the pinned ones: they already have their own optgroup, and
|
|
# listing a model twice gives the <select> two options with the same
|
|
# value, both marked selected.
|
|
"other_models": [m for m in models if not m.pinned] if pinned else models,
|
|
"current_model": current,
|
|
}
|
|
|
|
|
|
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):
|
|
return render(
|
|
request,
|
|
"chat/index.html",
|
|
{
|
|
"chat": None,
|
|
"messages": [],
|
|
**_chat_context(db, user, None),
|
|
**_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
|
|
}
|
|
|
|
return render(
|
|
request,
|
|
"chat/index.html",
|
|
{
|
|
"chat": chat,
|
|
"messages": messages,
|
|
"bodies": bodies,
|
|
**_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),
|
|
},
|
|
)
|