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:
@@ -0,0 +1,146 @@
|
||||
"""Permission vocabulary and resolution.
|
||||
|
||||
The model is deliberately small: a flat set of named booleans, granted by an
|
||||
instance-wide baseline and widened by group membership. Permissions are a union
|
||||
across groups -- being in a second group can only ever grant more, never take
|
||||
away. That is the behaviour people expect, and the alternative (a deny that
|
||||
wins) makes "why can this user not do X" unanswerable without simulating every
|
||||
group.
|
||||
|
||||
Administrators bypass the whole thing. There is no permission that can be
|
||||
withheld from an admin, because an admin can grant it back to themselves in two
|
||||
clicks; pretending otherwise would be theatre.
|
||||
|
||||
Model *access* is separate and lives in models_visible_to(): a permission says
|
||||
what a user may do, model access says which models they may do it with.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from lembas.db.models import Connection, Model, User
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PermissionDef:
|
||||
key: str
|
||||
label: str
|
||||
description: str
|
||||
default: bool
|
||||
group: str
|
||||
|
||||
|
||||
# The order here is the order they render in the admin UI.
|
||||
PERMISSION_DEFS: tuple[PermissionDef, ...] = (
|
||||
PermissionDef(
|
||||
"chat.create", "Start chats", "Create new conversations.", True, "Chat"
|
||||
),
|
||||
PermissionDef(
|
||||
"chat.delete", "Delete chats", "Delete their own conversations.", True, "Chat"
|
||||
),
|
||||
PermissionDef(
|
||||
"chat.system_prompt",
|
||||
"Set system prompts",
|
||||
"Give an individual chat its own system prompt.",
|
||||
True,
|
||||
"Chat",
|
||||
),
|
||||
PermissionDef(
|
||||
"chat.params",
|
||||
"Adjust sampling",
|
||||
"Change temperature, top-p and similar per chat.",
|
||||
False,
|
||||
"Chat",
|
||||
),
|
||||
PermissionDef(
|
||||
"chat.model_select",
|
||||
"Choose the model",
|
||||
"Switch a chat to a different model. Without this, chats use the default.",
|
||||
True,
|
||||
"Chat",
|
||||
),
|
||||
PermissionDef(
|
||||
"folder.manage",
|
||||
"Manage folders",
|
||||
"Create, rename, nest and delete folders.",
|
||||
True,
|
||||
"Workspace",
|
||||
),
|
||||
)
|
||||
|
||||
PERMISSION_KEYS = tuple(d.key for d in PERMISSION_DEFS)
|
||||
DEFAULT_PERMISSIONS = {d.key: d.default for d in PERMISSION_DEFS}
|
||||
|
||||
|
||||
def permission_groups() -> dict[str, list[PermissionDef]]:
|
||||
"""Definitions bucketed by their UI section, preserving declaration order."""
|
||||
grouped: dict[str, list[PermissionDef]] = {}
|
||||
for definition in PERMISSION_DEFS:
|
||||
grouped.setdefault(definition.group, []).append(definition)
|
||||
return grouped
|
||||
|
||||
|
||||
def baseline_permissions(db: DBSession) -> dict[str, bool]:
|
||||
"""Instance-wide permissions for a user in no group at all."""
|
||||
from lembas.services import settings_store
|
||||
|
||||
stored = settings_store.get(db, "default_permissions") or {}
|
||||
return {key: bool(stored.get(key, DEFAULT_PERMISSIONS[key])) for key in PERMISSION_KEYS}
|
||||
|
||||
|
||||
def resolve(db: DBSession, user: User | None) -> dict[str, bool]:
|
||||
"""Effective permissions for a user."""
|
||||
if user is None:
|
||||
return dict.fromkeys(PERMISSION_KEYS, False)
|
||||
if user.is_admin:
|
||||
return dict.fromkeys(PERMISSION_KEYS, True)
|
||||
|
||||
effective = baseline_permissions(db)
|
||||
for group in user.groups:
|
||||
granted = group.permissions_json or {}
|
||||
for key in PERMISSION_KEYS:
|
||||
# Union: a group can only widen. Absent means "no opinion", not
|
||||
# "deny", so a group need only list what it adds.
|
||||
if granted.get(key):
|
||||
effective[key] = True
|
||||
return effective
|
||||
|
||||
|
||||
def has(db: DBSession, user: User | None, key: str) -> bool:
|
||||
return resolve(db, user).get(key, False)
|
||||
|
||||
|
||||
def models_visible_to(db: DBSession, user: User | None) -> list[Model]:
|
||||
"""Models a user may start a chat with, in display order.
|
||||
|
||||
A model is visible when it is enabled, its connection is enabled, and
|
||||
either it is public or the user belongs to one of its groups.
|
||||
"""
|
||||
query = (
|
||||
select(Model)
|
||||
.join(Connection)
|
||||
.where(Model.enabled.is_(True), Connection.enabled.is_(True))
|
||||
.order_by(Model.position, Model.model_id)
|
||||
)
|
||||
candidates = list(db.scalars(query))
|
||||
|
||||
if user is not None and user.is_admin:
|
||||
return candidates
|
||||
|
||||
if user is None:
|
||||
return []
|
||||
|
||||
member_of = {group.id for group in user.groups}
|
||||
return [
|
||||
model
|
||||
for model in candidates
|
||||
if model.public or member_of.intersection({g.id for g in model.groups})
|
||||
]
|
||||
|
||||
|
||||
def can_use_model(db: DBSession, user: User | None, model_id: str) -> bool:
|
||||
return any(model.model_id == model_id for model in models_visible_to(db, user))
|
||||
Reference in New Issue
Block a user