Files
LLeMbas/src/lembas/api/folders.py
T
Jaroslav Beneš d6c87ac811 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>
2026-07-21 11:49:32 +02:00

124 lines
3.9 KiB
Python

"""Folder management."""
from __future__ import annotations
from fastapi import APIRouter, Depends, Form, HTTPException, Response, status
from sqlalchemy.orm import Session as DBSession
from lembas.api.deps import Db, RequiredUser, require_permission
from lembas.db.models import Folder
# 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
def _owned_folder(db: DBSession, folder_id: str, user_id: str) -> Folder:
folder = db.get(Folder, folder_id)
if folder is None or folder.user_id != user_id:
raise HTTPException(status.HTTP_404_NOT_FOUND, "That folder no longer exists.")
return folder
def _depth_of(db: DBSession, folder: Folder | None) -> int:
depth = 0
seen: set[str] = set()
while folder is not None and folder.id not in seen:
seen.add(folder.id)
depth += 1
folder = db.get(Folder, folder.parent_id) if folder.parent_id else None
return depth
def _refresh_sidebar() -> Response:
"""Tell the browser to reload so the tree re-renders.
The folder tree is recursive and a change can move any part of it, so
re-rendering the whole sidebar server-side is both simpler and less
error-prone than trying to patch individual nodes over the wire.
"""
response = Response(status_code=status.HTTP_204_NO_CONTENT)
response.headers["HX-Refresh"] = "true"
return response
@router.post("")
async def create_folder(
db: Db,
user: RequiredUser,
name: str = Form("New folder"),
parent_id: str = Form(""),
) -> Response:
parent = _owned_folder(db, parent_id, user.id) if parent_id else None
# A cap on nesting, so a runaway client cannot build a tree deep enough to
# blow the recursion limit in the template.
if parent is not None and _depth_of(db, parent) >= MAX_DEPTH:
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
f"Folders cannot be nested more than {MAX_DEPTH} deep.",
)
db.add(
Folder(
user_id=user.id,
name=name.strip()[:200] or "New folder",
parent_id=parent.id if parent else None,
)
)
db.commit()
return _refresh_sidebar()
@router.patch("/{folder_id}")
async def update_folder(
db: Db,
user: RequiredUser,
folder_id: str,
name: str | None = Form(None),
parent_id: str | None = Form(None),
collapsed: bool | None = Form(None),
) -> Response:
folder = _owned_folder(db, folder_id, user.id)
if name is not None and name.strip():
folder.name = name.strip()[:200]
if parent_id is not None:
new_parent = _owned_folder(db, parent_id, user.id) if parent_id else None
# Reparenting a folder into its own subtree would detach that subtree
# from the root and make it unreachable.
cursor = new_parent
while cursor is not None:
if cursor.id == folder.id:
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
"A folder cannot be moved inside itself.",
)
cursor = db.get(Folder, cursor.parent_id) if cursor.parent_id else None
folder.parent_id = new_parent.id if new_parent else None
if collapsed is not None:
folder.collapsed = collapsed
db.commit()
return _refresh_sidebar()
@router.delete("/{folder_id}")
async def delete_folder(db: Db, user: RequiredUser, folder_id: str) -> Response:
"""Delete a folder. Child folders go with it; chats do not.
Chats fall back to the unfiled list (the FK is ON DELETE SET NULL), because
losing a conversation to a mis-clicked folder delete is unforgivable.
"""
folder = _owned_folder(db, folder_id, user.id)
db.delete(folder)
db.commit()
return _refresh_sidebar()