Users, groups, permissions, model settings and reasoning display
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>
This commit is contained in:
+6
-17
@@ -193,12 +193,17 @@ async def _refresh_models(db: DBSession, connection: Connection) -> tuple[int, s
|
||||
existing = {model.model_id: model for model in connection.models}
|
||||
seen: set[str] = set()
|
||||
|
||||
# New models land after everything already ordered, rather than all at
|
||||
# position 0 where they would sort by id and shuffle the existing list.
|
||||
next_position = (db.scalar(select(func.coalesce(func.max(Model.position), -1))) or -1) + 1
|
||||
|
||||
for entry in discovered:
|
||||
model_id = str(entry["id"])[:300]
|
||||
seen.add(model_id)
|
||||
if model_id in existing:
|
||||
continue
|
||||
db.add(Model(connection_id=connection.id, model_id=model_id))
|
||||
db.add(Model(connection_id=connection.id, model_id=model_id, position=next_position))
|
||||
next_position += 1
|
||||
|
||||
# Models that vanished upstream are dropped, so the picker never offers
|
||||
# something the endpoint will reject.
|
||||
@@ -219,19 +224,3 @@ async def delete_connection(db: Db, user: AdminUser, connection_id: str) -> Resp
|
||||
db.delete(connection)
|
||||
db.commit()
|
||||
return RedirectResponse("/admin/connections", status_code=status.HTTP_303_SEE_OTHER)
|
||||
|
||||
|
||||
@router.get("/models")
|
||||
async def models_page(request: Request, db: Db, user: AdminUser):
|
||||
connections = _connections(db)
|
||||
return render(request, "admin/models.html", {"connections": connections})
|
||||
|
||||
|
||||
@router.post("/models/{model_id}/toggle")
|
||||
async def toggle_model(db: Db, user: AdminUser, model_id: str) -> Response:
|
||||
model = db.get(Model, model_id)
|
||||
if model is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "That model no longer exists.")
|
||||
model.enabled = not model.enabled
|
||||
db.commit()
|
||||
return RedirectResponse("/admin/models", status_code=status.HTTP_303_SEE_OTHER)
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Model administration: ordering, defaults, images, access and capabilities."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, File, Form, HTTPException, Request, Response, UploadFile, status
|
||||
from fastapi.responses import FileResponse, RedirectResponse
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from lembas.api.deps import AdminUser, Db, RequiredUser
|
||||
from lembas.db.models import Connection, Group, Model
|
||||
from lembas.services import settings_store, uploads
|
||||
from lembas.web.templating import render
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["admin-models"])
|
||||
|
||||
CAPABILITIES = ("reasoning", "vision", "tools")
|
||||
|
||||
|
||||
def _model(db: DBSession, model_id: str) -> Model:
|
||||
model = db.get(Model, model_id)
|
||||
if model is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "That model no longer exists.")
|
||||
return model
|
||||
|
||||
|
||||
def _ordered(db: DBSession) -> list[Model]:
|
||||
return list(
|
||||
db.scalars(
|
||||
select(Model).join(Connection).order_by(Model.position, Model.model_id)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _renumber(db: DBSession) -> None:
|
||||
"""Rewrite positions to 0..n-1.
|
||||
|
||||
Keeps the numbers dense so a move is always a swap with a neighbour, and
|
||||
stops repeated reordering drifting into large sparse values.
|
||||
"""
|
||||
for index, model in enumerate(_ordered(db)):
|
||||
model.position = index
|
||||
db.commit()
|
||||
|
||||
|
||||
# --- The admin page ----------------------------------------------------------
|
||||
@router.get("/admin/models")
|
||||
async def models_page(request: Request, db: Db, user: AdminUser, saved: str = ""):
|
||||
models = _ordered(db)
|
||||
return render(
|
||||
request,
|
||||
"admin/models.html",
|
||||
{
|
||||
"models": models,
|
||||
"groups": list(db.scalars(select(Group).order_by(Group.name))),
|
||||
"connections": list(db.scalars(select(Connection).order_by(Connection.name))),
|
||||
"default_model": settings_store.get(db, "default_model") or "",
|
||||
"capabilities": CAPABILITIES,
|
||||
"saved": saved,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/admin/models/{model_id}")
|
||||
async def update_model(
|
||||
db: Db,
|
||||
user: AdminUser,
|
||||
model_id: str,
|
||||
display_name: str = Form(""),
|
||||
description: str = Form(""),
|
||||
enabled: bool = Form(False),
|
||||
pinned: bool = Form(False),
|
||||
public: bool = Form(False),
|
||||
group_ids: list[str] = Form(default=[]),
|
||||
capability: list[str] = Form(default=[]),
|
||||
) -> Response:
|
||||
model = _model(db, model_id)
|
||||
|
||||
model.display_name = display_name.strip()[:300]
|
||||
model.description = description.strip()[:2000]
|
||||
model.enabled = enabled
|
||||
model.pinned = pinned
|
||||
model.public = public
|
||||
|
||||
# Absent checkboxes are simply missing from a form post, so the submitted
|
||||
# list IS the complete new state -- rebuild rather than merge.
|
||||
model.capabilities_json = {name: (name in capability) for name in CAPABILITIES}
|
||||
|
||||
if public:
|
||||
# Group rows would be dead weight and misleading in the UI.
|
||||
model.groups = []
|
||||
else:
|
||||
model.groups = list(db.scalars(select(Group).where(Group.id.in_(group_ids or []))))
|
||||
|
||||
db.commit()
|
||||
log.info("model %s updated by %s", model.model_id, user.email)
|
||||
return RedirectResponse("/admin/models?saved=Model+saved.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/admin/models/{model_id}/move")
|
||||
async def move_model(
|
||||
db: Db, user: AdminUser, model_id: str, direction: str = Form(...)
|
||||
) -> Response:
|
||||
"""Swap a model with its neighbour."""
|
||||
model = _model(db, model_id)
|
||||
ordered = _ordered(db)
|
||||
index = next((i for i, m in enumerate(ordered) if m.id == model.id), None)
|
||||
|
||||
if index is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "That model no longer exists.")
|
||||
|
||||
target = index - 1 if direction == "up" else index + 1
|
||||
if 0 <= target < len(ordered):
|
||||
ordered[index], ordered[target] = ordered[target], ordered[index]
|
||||
for position, item in enumerate(ordered):
|
||||
item.position = position
|
||||
db.commit()
|
||||
|
||||
return RedirectResponse("/admin/models", status_code=303)
|
||||
|
||||
|
||||
@router.post("/admin/models/{model_id}/default")
|
||||
async def set_default_model(db: Db, user: AdminUser, model_id: str) -> Response:
|
||||
"""Make a model the instance default for new chats."""
|
||||
model = _model(db, model_id)
|
||||
settings_store.update(db, {"default_model": model.model_id})
|
||||
log.info("default model set to %s by %s", model.model_id, user.email)
|
||||
return RedirectResponse(
|
||||
f"/admin/models?saved={model.label}+is+now+the+default.", status_code=303
|
||||
)
|
||||
|
||||
|
||||
@router.post("/admin/models/{model_id}/image")
|
||||
async def upload_model_image(
|
||||
db: Db, user: AdminUser, model_id: str, image: UploadFile = File(...)
|
||||
) -> Response:
|
||||
model = _model(db, model_id)
|
||||
payload = await image.read()
|
||||
|
||||
try:
|
||||
filename = uploads.save_model_image(payload, image.content_type or "")
|
||||
except uploads.UploadError as exc:
|
||||
return RedirectResponse(f"/admin/models?saved={exc}", status_code=303)
|
||||
|
||||
# Remove the old file rather than orphaning it in the uploads directory.
|
||||
if model.image_path:
|
||||
uploads.delete_model_image(model.image_path)
|
||||
|
||||
model.image_path = filename
|
||||
db.commit()
|
||||
return RedirectResponse("/admin/models?saved=Image+updated.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/admin/models/{model_id}/image/delete")
|
||||
async def delete_model_image(db: Db, user: AdminUser, model_id: str) -> Response:
|
||||
model = _model(db, model_id)
|
||||
if model.image_path:
|
||||
uploads.delete_model_image(model.image_path)
|
||||
model.image_path = ""
|
||||
db.commit()
|
||||
return RedirectResponse("/admin/models?saved=Image+removed.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/admin/models/bulk")
|
||||
async def bulk_models(
|
||||
db: Db, user: AdminUser, action: str = Form(...), model_ids: list[str] = Form(default=[])
|
||||
) -> Response:
|
||||
"""Enable or disable several models at once.
|
||||
|
||||
A freshly refreshed connection can advertise dozens of models; turning them
|
||||
off one at a time is not a reasonable way to spend an afternoon.
|
||||
"""
|
||||
models = list(db.scalars(select(Model).where(Model.id.in_(model_ids or []))))
|
||||
for model in models:
|
||||
if action == "enable":
|
||||
model.enabled = True
|
||||
elif action == "disable":
|
||||
model.enabled = False
|
||||
elif action == "public":
|
||||
model.public = True
|
||||
model.groups = []
|
||||
elif action == "private":
|
||||
model.public = False
|
||||
db.commit()
|
||||
_renumber(db)
|
||||
return RedirectResponse(
|
||||
f"/admin/models?saved={len(models)}+model(s)+updated.", status_code=303
|
||||
)
|
||||
|
||||
|
||||
# --- Serving model images ----------------------------------------------------
|
||||
@router.get("/uploads/models/{filename}")
|
||||
async def model_image(user: RequiredUser, filename: str) -> Response:
|
||||
"""Serve a stored model avatar.
|
||||
|
||||
Behind the auth guard: these are instance assets, not public files, and
|
||||
the path resolution in uploads refuses anything outside the directory.
|
||||
"""
|
||||
path = uploads.model_image_path(filename)
|
||||
if path is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "No such image.")
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=uploads.media_type_for(filename),
|
||||
# Filenames are random and content-addressed in practice, so a long
|
||||
# cache is safe: a new image gets a new name.
|
||||
headers={"Cache-Control": "private, max-age=604800"},
|
||||
)
|
||||
@@ -0,0 +1,268 @@
|
||||
"""User and group administration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Form, HTTPException, Request, Response, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from lembas.api.deps import AdminUser, Db
|
||||
from lembas.db.models import ROLE_ADMIN, ROLE_PENDING, ROLE_USER, Group, Model, User
|
||||
from lembas.security import permissions
|
||||
from lembas.security.passwords import hash_password, validate_password
|
||||
from lembas.security.sessions import revoke_all_for_user
|
||||
from lembas.services import settings_store
|
||||
from lembas.web.templating import render
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin-users"])
|
||||
|
||||
ROLES = (ROLE_ADMIN, ROLE_USER, ROLE_PENDING)
|
||||
|
||||
|
||||
def _user(db: DBSession, user_id: str) -> User:
|
||||
found = db.get(User, user_id)
|
||||
if found is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "That user no longer exists.")
|
||||
return found
|
||||
|
||||
|
||||
def _group(db: DBSession, group_id: str) -> Group:
|
||||
found = db.get(Group, group_id)
|
||||
if found is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "That group no longer exists.")
|
||||
return found
|
||||
|
||||
|
||||
def _admin_count(db: DBSession) -> int:
|
||||
return db.scalar(
|
||||
select(func.count()).select_from(User).where(User.role == ROLE_ADMIN, User.active.is_(True))
|
||||
)
|
||||
|
||||
|
||||
def _would_orphan_the_instance(db: DBSession, user: User) -> bool:
|
||||
"""True if changing this user would leave nobody able to administer.
|
||||
|
||||
An instance with no active administrator can only be recovered from the
|
||||
command line, so every path that could cause it is blocked in the UI.
|
||||
"""
|
||||
return user.role == ROLE_ADMIN and user.active and _admin_count(db) <= 1
|
||||
|
||||
|
||||
# --- Users -------------------------------------------------------------------
|
||||
@router.get("/users")
|
||||
async def users_page(request: Request, db: Db, user: AdminUser, q: str = "", saved: str = ""):
|
||||
query = select(User).order_by(User.created_at)
|
||||
if q.strip():
|
||||
pattern = f"%{q.strip()}%"
|
||||
query = query.where(or_(User.name.ilike(pattern), User.email.ilike(pattern)))
|
||||
|
||||
return render(
|
||||
request,
|
||||
"admin/users.html",
|
||||
{
|
||||
"users": list(db.scalars(query)),
|
||||
"groups": list(db.scalars(select(Group).order_by(Group.name))),
|
||||
"roles": ROLES,
|
||||
"q": q,
|
||||
"saved": saved,
|
||||
"admin_count": _admin_count(db),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/users")
|
||||
async def create_user(
|
||||
db: Db,
|
||||
user: AdminUser,
|
||||
name: str = Form(...),
|
||||
email: str = Form(...),
|
||||
password: str = Form(...),
|
||||
role: str = Form(ROLE_USER),
|
||||
) -> Response:
|
||||
"""Create an account directly, without going through registration."""
|
||||
email = email.strip().lower()
|
||||
if (problem := validate_password(password)) is not None:
|
||||
return RedirectResponse(f"/admin/users?saved={problem}", status_code=303)
|
||||
if db.scalar(select(User).where(User.email == email)) is not None:
|
||||
return RedirectResponse(
|
||||
"/admin/users?saved=That+email+is+already+registered.", status_code=303
|
||||
)
|
||||
|
||||
db.add(
|
||||
User(
|
||||
name=name.strip()[:120] or email,
|
||||
email=email,
|
||||
password_hash=hash_password(password),
|
||||
role=role if role in ROLES else ROLE_USER,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
log.info("%s created account %s", user.email, email)
|
||||
return RedirectResponse(f"/admin/users?saved=Created+{email}.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/users/{user_id}")
|
||||
async def update_user(
|
||||
db: Db,
|
||||
user: AdminUser,
|
||||
user_id: str,
|
||||
name: str = Form(...),
|
||||
role: str = Form(ROLE_USER),
|
||||
active: bool = Form(False),
|
||||
group_ids: list[str] = Form(default=[]),
|
||||
) -> Response:
|
||||
target = _user(db, user_id)
|
||||
|
||||
losing_admin = target.role == ROLE_ADMIN and (role != ROLE_ADMIN or not active)
|
||||
if losing_admin and _would_orphan_the_instance(db, target):
|
||||
return RedirectResponse(
|
||||
"/admin/users?saved=That+is+the+only+administrator.+Promote+someone+else+first.",
|
||||
status_code=303,
|
||||
)
|
||||
|
||||
target.name = name.strip()[:120] or target.name
|
||||
target.role = role if role in ROLES else target.role
|
||||
target.active = active
|
||||
target.groups = list(db.scalars(select(Group).where(Group.id.in_(group_ids or []))))
|
||||
|
||||
# A deactivated or demoted user must lose their live sessions immediately,
|
||||
# otherwise the change only takes effect when their cookie happens to expire.
|
||||
if not active:
|
||||
revoke_all_for_user(db, target)
|
||||
|
||||
db.commit()
|
||||
log.info("%s updated account %s (role=%s active=%s)", user.email, target.email, role, active)
|
||||
return RedirectResponse(f"/admin/users?saved=Saved+{target.email}.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/password")
|
||||
async def reset_password(
|
||||
db: Db, user: AdminUser, user_id: str, password: str = Form(...)
|
||||
) -> Response:
|
||||
target = _user(db, user_id)
|
||||
if (problem := validate_password(password)) is not None:
|
||||
return RedirectResponse(f"/admin/users?saved={problem}", status_code=303)
|
||||
|
||||
target.password_hash = hash_password(password)
|
||||
db.commit()
|
||||
# Everywhere that account was signed in is now signed out. An admin reset
|
||||
# usually means the account is compromised or the person is gone.
|
||||
revoke_all_for_user(db, target)
|
||||
log.info("%s reset the password for %s", user.email, target.email)
|
||||
return RedirectResponse(
|
||||
f"/admin/users?saved=Password+reset+for+{target.email}.+Sessions+revoked.",
|
||||
status_code=303,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/delete")
|
||||
async def delete_user(db: Db, user: AdminUser, user_id: str) -> Response:
|
||||
target = _user(db, user_id)
|
||||
|
||||
if target.id == user.id:
|
||||
return RedirectResponse(
|
||||
"/admin/users?saved=You+cannot+delete+your+own+account.", status_code=303
|
||||
)
|
||||
if _would_orphan_the_instance(db, target):
|
||||
return RedirectResponse(
|
||||
"/admin/users?saved=That+is+the+only+administrator.", status_code=303
|
||||
)
|
||||
|
||||
email = target.email
|
||||
# Chats and folders cascade; that is the point of deleting an account.
|
||||
db.delete(target)
|
||||
db.commit()
|
||||
log.info("%s deleted account %s", user.email, email)
|
||||
return RedirectResponse(f"/admin/users?saved=Deleted+{email}.", status_code=303)
|
||||
|
||||
|
||||
# --- Groups ------------------------------------------------------------------
|
||||
@router.get("/groups")
|
||||
async def groups_page(request: Request, db: Db, user: AdminUser, saved: str = ""):
|
||||
return render(
|
||||
request,
|
||||
"admin/groups.html",
|
||||
{
|
||||
"groups": list(db.scalars(select(Group).order_by(Group.name))),
|
||||
"users": list(db.scalars(select(User).order_by(User.name))),
|
||||
"models": list(db.scalars(select(Model).order_by(Model.position, Model.model_id))),
|
||||
"permission_groups": permissions.permission_groups(),
|
||||
"baseline": permissions.baseline_permissions(db),
|
||||
"saved": saved,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/groups")
|
||||
async def create_group(db: Db, user: AdminUser, name: str = Form(...)) -> Response:
|
||||
name = name.strip()[:120]
|
||||
if not name:
|
||||
return RedirectResponse("/admin/groups?saved=A+group+needs+a+name.", status_code=303)
|
||||
if db.scalar(select(Group).where(Group.name == name)) is not None:
|
||||
return RedirectResponse(
|
||||
"/admin/groups?saved=A+group+with+that+name+already+exists.", status_code=303
|
||||
)
|
||||
|
||||
db.add(Group(name=name))
|
||||
db.commit()
|
||||
log.info("%s created group %s", user.email, name)
|
||||
return RedirectResponse(f"/admin/groups?saved=Created+{name}.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/groups/{group_id}")
|
||||
async def update_group(
|
||||
db: Db,
|
||||
user: AdminUser,
|
||||
group_id: str,
|
||||
name: str = Form(...),
|
||||
description: str = Form(""),
|
||||
permission: list[str] = Form(default=[]),
|
||||
user_ids: list[str] = Form(default=[]),
|
||||
model_ids: list[str] = Form(default=[]),
|
||||
) -> Response:
|
||||
group = _group(db, group_id)
|
||||
|
||||
group.name = name.strip()[:120] or group.name
|
||||
group.description = description.strip()[:1000]
|
||||
# The submitted checkbox list is the complete new state; absent means the
|
||||
# group does not grant that permission, not that it denies it.
|
||||
group.permissions_json = {key: True for key in permission if key in permissions.PERMISSION_KEYS}
|
||||
group.users = list(db.scalars(select(User).where(User.id.in_(user_ids or []))))
|
||||
group.models = list(db.scalars(select(Model).where(Model.id.in_(model_ids or []))))
|
||||
|
||||
db.commit()
|
||||
log.info("%s updated group %s", user.email, group.name)
|
||||
return RedirectResponse(f"/admin/groups?saved=Saved+{group.name}.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/groups/{group_id}/delete")
|
||||
async def delete_group(db: Db, user: AdminUser, group_id: str) -> Response:
|
||||
group = _group(db, group_id)
|
||||
name = group.name
|
||||
# Members and model links go with it; the users themselves are untouched.
|
||||
db.delete(group)
|
||||
db.commit()
|
||||
log.info("%s deleted group %s", user.email, name)
|
||||
return RedirectResponse(f"/admin/groups?saved=Deleted+{name}.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/permissions/defaults")
|
||||
async def save_baseline(
|
||||
db: Db, user: AdminUser, permission: list[str] = Form(default=[])
|
||||
) -> Response:
|
||||
"""The permissions every user has before any group widens them."""
|
||||
settings_store.update(
|
||||
db,
|
||||
{
|
||||
"default_permissions": {
|
||||
key: (key in permission) for key in permissions.PERMISSION_KEYS
|
||||
}
|
||||
},
|
||||
)
|
||||
log.info("%s changed the baseline permissions", user.email)
|
||||
return RedirectResponse("/admin/groups?saved=Default+permissions+saved.", status_code=303)
|
||||
+151
-28
@@ -4,19 +4,27 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from fastapi import APIRouter, Form, HTTPException, Request, status
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request, status
|
||||
from fastapi.responses import HTMLResponse, Response, StreamingResponse
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from lembas.api.deps import Db, RequiredUser
|
||||
from lembas.api.deps import Db, RequiredUser, require_permission
|
||||
from lembas.db.models import ROLE_ASSISTANT, ROLE_USER, Chat, Message, User
|
||||
from lembas.db.session import session_scope
|
||||
from lembas.security import permissions
|
||||
from lembas.services import chat as chat_service
|
||||
from lembas.services import sse
|
||||
from lembas.services.llm.openai_client import LLMError, delta_text, stream_chat
|
||||
from lembas.services.llm.openai_client import (
|
||||
LLMError,
|
||||
delta_reasoning,
|
||||
delta_text,
|
||||
stream_chat,
|
||||
)
|
||||
from lembas.services.markdown import escape_text, render_markdown
|
||||
from lembas.services.reasoning import REASONING, ReasoningSplitter
|
||||
from lembas.web.templating import render, templates
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -33,9 +41,9 @@ def _owned_chat(db: DBSession, chat_id: str, user_id: str) -> Chat:
|
||||
return chat
|
||||
|
||||
|
||||
@router.post("")
|
||||
@router.post("", dependencies=[Depends(require_permission("chat.create"))])
|
||||
async def create_chat(db: Db, user: RequiredUser, folder_id: str = Form("")) -> Response:
|
||||
chosen = chat_service.default_model(db)
|
||||
chosen = chat_service.default_model(db, user)
|
||||
chat = Chat(
|
||||
user_id=user.id,
|
||||
folder_id=folder_id or None,
|
||||
@@ -130,7 +138,9 @@ async def _generate(chat_id: str, message_id: str) -> AsyncIterator[str]:
|
||||
be closed by the time the first token arrives.
|
||||
"""
|
||||
accumulated: list[str] = []
|
||||
thinking: list[str] = []
|
||||
error: str | None = None
|
||||
reasoning_ms = 0
|
||||
|
||||
with session_scope() as db:
|
||||
chat = db.get(Chat, chat_id)
|
||||
@@ -140,6 +150,12 @@ async def _generate(chat_id: str, message_id: str) -> AsyncIterator[str]:
|
||||
return
|
||||
|
||||
first_user_text = ""
|
||||
# Handles models that emit <think> tags inline in content rather than
|
||||
# using the reasoning_content field.
|
||||
splitter = ReasoningSplitter()
|
||||
started = time.monotonic()
|
||||
reasoning_started: float | None = None
|
||||
|
||||
try:
|
||||
endpoint, model_id = chat_service.resolve_endpoint(db, chat)
|
||||
payload = chat_service.build_request(db, chat, upto=message)
|
||||
@@ -149,14 +165,42 @@ async def _generate(chat_id: str, message_id: str) -> AsyncIterator[str]:
|
||||
)
|
||||
|
||||
async for chunk in stream_chat(endpoint, payload):
|
||||
# A dedicated reasoning field is unambiguous; take it as-is.
|
||||
thought = delta_reasoning(chunk)
|
||||
if thought:
|
||||
if reasoning_started is None:
|
||||
reasoning_started = time.monotonic()
|
||||
thinking.append(thought)
|
||||
yield sse.event("reasoning", escape_text(thought))
|
||||
await asyncio.sleep(0)
|
||||
|
||||
text = delta_text(chunk)
|
||||
if not text:
|
||||
continue
|
||||
accumulated.append(text)
|
||||
yield sse.event("token", escape_text(text))
|
||||
# Hand control back so the event is flushed rather than
|
||||
# batched behind a fast generator.
|
||||
await asyncio.sleep(0)
|
||||
|
||||
for kind, piece in splitter.feed(text):
|
||||
if kind == REASONING:
|
||||
if reasoning_started is None:
|
||||
reasoning_started = time.monotonic()
|
||||
thinking.append(piece)
|
||||
yield sse.event("reasoning", escape_text(piece))
|
||||
else:
|
||||
# First answer token ends the thinking phase.
|
||||
if reasoning_started is not None and not reasoning_ms:
|
||||
reasoning_ms = int((time.monotonic() - reasoning_started) * 1000)
|
||||
accumulated.append(piece)
|
||||
yield sse.event("token", escape_text(piece))
|
||||
# Hand control back so the event is flushed rather than
|
||||
# batched behind a fast generator.
|
||||
await asyncio.sleep(0)
|
||||
|
||||
for kind, piece in splitter.flush():
|
||||
if kind == REASONING:
|
||||
thinking.append(piece)
|
||||
yield sse.event("reasoning", escape_text(piece))
|
||||
else:
|
||||
accumulated.append(piece)
|
||||
yield sse.event("token", escape_text(piece))
|
||||
|
||||
except LLMError as exc:
|
||||
error = exc.message
|
||||
@@ -165,6 +209,7 @@ async def _generate(chat_id: str, message_id: str) -> AsyncIterator[str]:
|
||||
# The reader navigated away or closed the tab. Keep whatever was
|
||||
# produced so the partial reply is still there on reload.
|
||||
message.content = "".join(accumulated)
|
||||
message.reasoning = "".join(thinking)
|
||||
message.complete = True
|
||||
db.commit()
|
||||
raise
|
||||
@@ -172,9 +217,22 @@ async def _generate(chat_id: str, message_id: str) -> AsyncIterator[str]:
|
||||
error = "Something went wrong while generating this reply."
|
||||
log.exception("unexpected generation failure for chat %s: %s", chat_id, exc)
|
||||
|
||||
if reasoning_started is not None and not reasoning_ms:
|
||||
# Reasoning ran to the end without an answer following it.
|
||||
reasoning_ms = int((time.monotonic() - reasoning_started) * 1000)
|
||||
|
||||
message.content = "".join(accumulated)
|
||||
message.reasoning = "".join(thinking)
|
||||
message.reasoning_ms = reasoning_ms
|
||||
message.error = error or ""
|
||||
message.complete = True
|
||||
log.debug(
|
||||
"chat %s: %d chars answer, %d chars reasoning, %.1fs total",
|
||||
chat_id,
|
||||
len(message.content),
|
||||
len(message.reasoning),
|
||||
time.monotonic() - started,
|
||||
)
|
||||
|
||||
if not chat.title_generated and (accumulated or error):
|
||||
chat.title = (
|
||||
@@ -208,38 +266,103 @@ async def _generate(chat_id: str, message_id: str) -> AsyncIterator[str]:
|
||||
|
||||
|
||||
@router.patch("/{chat_id}")
|
||||
async def update_chat(
|
||||
db: Db,
|
||||
user: RequiredUser,
|
||||
chat_id: str,
|
||||
title: str | None = Form(None),
|
||||
folder_id: str | None = Form(None),
|
||||
model_id: str | None = Form(None),
|
||||
) -> Response:
|
||||
chat = _owned_chat(db, chat_id, user.id)
|
||||
async def update_chat(request: Request, db: Db, user: RequiredUser, chat_id: str) -> Response:
|
||||
"""Partially update a chat.
|
||||
|
||||
if title is not None:
|
||||
cleaned = title.strip()[:300]
|
||||
The raw form is read rather than declaring Form() parameters because
|
||||
FastAPI substitutes the default for an empty form value, which makes
|
||||
"field absent" and "field submitted empty" indistinguishable. That
|
||||
difference is exactly what this endpoint needs: an empty system prompt or
|
||||
temperature means *clear it*, not *leave it alone*.
|
||||
"""
|
||||
chat = _owned_chat(db, chat_id, user.id)
|
||||
allowed = permissions.resolve(db, user)
|
||||
form = await request.form()
|
||||
|
||||
if "title" in form:
|
||||
cleaned = str(form["title"]).strip()[:300]
|
||||
if cleaned:
|
||||
chat.title = cleaned
|
||||
# An explicit rename must not be overwritten by auto-titling later.
|
||||
chat.title_generated = True
|
||||
|
||||
if folder_id is not None:
|
||||
chat.folder_id = folder_id or None
|
||||
if "folder_id" in form:
|
||||
chat.folder_id = str(form["folder_id"]) or None
|
||||
|
||||
if model_id is not None and model_id:
|
||||
chat.model_id = model_id
|
||||
model_id = str(form.get("model_id", "")).strip()
|
||||
|
||||
if model_id:
|
||||
if not allowed.get("chat.model_select"):
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN, "You may not change the model for a chat."
|
||||
)
|
||||
# Checked against what this user can reach, not merely what exists --
|
||||
# otherwise the picker is advisory and a crafted request bypasses it.
|
||||
match = next(
|
||||
(m for m in chat_service.available_models(db) if m.model_id == model_id), None
|
||||
(m for m in chat_service.available_models(db, user) if m.model_id == model_id),
|
||||
None,
|
||||
)
|
||||
chat.connection_id = match.connection_id if match else None
|
||||
if match is None:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "That model is not available to you.")
|
||||
chat.model_id = model_id
|
||||
chat.connection_id = match.connection_id
|
||||
|
||||
if "system_prompt" in form:
|
||||
if not allowed.get("chat.system_prompt"):
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN, "You may not set a system prompt."
|
||||
)
|
||||
chat.system_prompt = str(form["system_prompt"]).strip()[:8000]
|
||||
|
||||
submitted_params = {name: form[name] for name in _PARAM_RANGES if name in form}
|
||||
if submitted_params:
|
||||
if not allowed.get("chat.params"):
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN, "You may not change sampling parameters."
|
||||
)
|
||||
chat.params_json = {
|
||||
**(chat.params_json or {}),
|
||||
**_clean_params(**{k: str(v) for k, v in submitted_params.items()}),
|
||||
}
|
||||
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.delete("/{chat_id}")
|
||||
# Bounds are the ones every provider agrees on. Out-of-range values are
|
||||
# dropped rather than clamped: silently changing what someone typed is worse
|
||||
# than ignoring it, and the form shows what actually stuck on reload.
|
||||
_PARAM_RANGES: dict[str, tuple[type, float, float]] = {
|
||||
"temperature": (float, 0.0, 2.0),
|
||||
"top_p": (float, 0.0, 1.0),
|
||||
"max_tokens": (int, 1, 1_000_000),
|
||||
}
|
||||
|
||||
|
||||
def _clean_params(**submitted: str | None) -> dict[str, float | int | None]:
|
||||
"""Parse sampling parameters, dropping anything unusable.
|
||||
|
||||
An empty string means "unset this and let the provider default apply", so
|
||||
it maps to None rather than being ignored.
|
||||
"""
|
||||
cleaned: dict[str, float | int | None] = {}
|
||||
for name, raw in submitted.items():
|
||||
if raw is None:
|
||||
continue
|
||||
if not raw.strip():
|
||||
cleaned[name] = None
|
||||
continue
|
||||
caster, low, high = _PARAM_RANGES[name]
|
||||
try:
|
||||
value = caster(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if low <= value <= high:
|
||||
cleaned[name] = value
|
||||
return cleaned
|
||||
|
||||
|
||||
@router.delete("/{chat_id}", dependencies=[Depends(require_permission("chat.delete"))])
|
||||
async def delete_chat(db: Db, user: RequiredUser, chat_id: str) -> Response:
|
||||
chat = _owned_chat(db, chat_id, user.id)
|
||||
db.delete(chat)
|
||||
|
||||
@@ -78,6 +78,27 @@ def require_admin(user: RequiredUser) -> User:
|
||||
AdminUser = Annotated[User, Depends(require_admin)]
|
||||
|
||||
|
||||
def require_permission(key: str):
|
||||
"""Dependency factory guarding a route behind a named permission.
|
||||
|
||||
@router.post("", dependencies=[Depends(require_permission("chat.create"))])
|
||||
|
||||
Administrators always pass; see lembas.security.permissions for why.
|
||||
"""
|
||||
|
||||
def guard(db: Db, user: RequiredUser) -> User:
|
||||
from lembas.security import permissions
|
||||
|
||||
if not permissions.has(db, user, key):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You do not have permission to do that.",
|
||||
)
|
||||
return user
|
||||
|
||||
return guard
|
||||
|
||||
|
||||
def is_htmx(request: Request) -> bool:
|
||||
return request.headers.get("HX-Request") == "true"
|
||||
|
||||
|
||||
@@ -2,13 +2,18 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Form, HTTPException, Response, status
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Response, status
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from lembas.api.deps import Db, RequiredUser
|
||||
from lembas.api.deps import Db, RequiredUser, require_permission
|
||||
from lembas.db.models import Folder
|
||||
|
||||
router = APIRouter(prefix="/api/folders", tags=["folders"])
|
||||
# Every route here manages folders, so the guard belongs on the router.
|
||||
router = APIRouter(
|
||||
prefix="/api/folders",
|
||||
tags=["folders"],
|
||||
dependencies=[Depends(require_permission("folder.manage"))],
|
||||
)
|
||||
|
||||
MAX_DEPTH = 8
|
||||
|
||||
|
||||
+29
-4
@@ -9,6 +9,7 @@ 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
|
||||
@@ -16,6 +17,26 @@ 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.
|
||||
|
||||
@@ -40,7 +61,11 @@ def _sidebar_context(db: DBSession, user: User) -> dict:
|
||||
.order_by(Chat.pinned.desc(), Chat.updated_at.desc())
|
||||
)
|
||||
)
|
||||
return {"folders": folders, "unfiled_chats": unfiled}
|
||||
return {
|
||||
"folders": folders,
|
||||
"unfiled_chats": unfiled,
|
||||
"can": permissions.resolve(db, user),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
@@ -56,7 +81,7 @@ async def chat_index(request: Request, db: Db, user: RequiredUser):
|
||||
{
|
||||
"chat": None,
|
||||
"messages": [],
|
||||
"models": chat_service.available_models(db),
|
||||
**_chat_context(db, user, None),
|
||||
**_sidebar_context(db, user),
|
||||
},
|
||||
)
|
||||
@@ -90,7 +115,7 @@ async def chat_detail(request: Request, db: Db, user: RequiredUser, chat_id: str
|
||||
"chat": chat,
|
||||
"messages": messages,
|
||||
"bodies": bodies,
|
||||
"models": chat_service.available_models(db),
|
||||
**_chat_context(db, user, chat),
|
||||
**_sidebar_context(db, user),
|
||||
},
|
||||
)
|
||||
@@ -111,9 +136,9 @@ async def settings_page(
|
||||
"settings.html",
|
||||
{
|
||||
"chat": None,
|
||||
"models": chat_service.available_models(db),
|
||||
"error": error,
|
||||
"saved": saved,
|
||||
**_chat_context(db, user, None),
|
||||
**_sidebar_context(db, user),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -37,6 +37,35 @@ async def set_theme(db: Db, user: RequiredUser, theme: str = Body(..., embed=Tru
|
||||
return {"ok": True, "theme": theme}
|
||||
|
||||
|
||||
@router.post("/default-model")
|
||||
async def set_default_model(
|
||||
db: Db, user: RequiredUser, model_id: str = Form("")
|
||||
) -> Response:
|
||||
"""Choose which model new chats start with.
|
||||
|
||||
An empty value clears the choice and falls back to the instance default.
|
||||
Validated against what this user can actually reach, so a model they lose
|
||||
access to cannot linger as a preference that silently fails later.
|
||||
"""
|
||||
from lembas.security import permissions
|
||||
|
||||
model_id = model_id.strip()
|
||||
if model_id and not permissions.can_use_model(db, user, model_id):
|
||||
return RedirectResponse(
|
||||
"/settings?error=That+model+is+not+available+to+you.", status_code=303
|
||||
)
|
||||
|
||||
settings_map = {**(user.settings_json or {})}
|
||||
if model_id:
|
||||
settings_map["default_model"] = model_id
|
||||
else:
|
||||
settings_map.pop("default_model", None)
|
||||
user.settings_json = settings_map
|
||||
db.commit()
|
||||
|
||||
return RedirectResponse("/settings?saved=Default+model+updated.", status_code=303)
|
||||
|
||||
|
||||
@router.post("/password")
|
||||
async def change_password(
|
||||
request: Request,
|
||||
|
||||
Reference in New Issue
Block a user