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>
This commit is contained in:
Jaroslav Beneš
2026-07-21 12:59:52 +02:00
parent bdce2764b1
commit 7b67568f2c
30 changed files with 1264 additions and 536 deletions
+37
View File
@@ -83,6 +83,43 @@ def registered(client: TestClient) -> dict[str, str]:
return credentials
@pytest.fixture
def make_chat(db: Session):
"""Create a chat row directly, as scaffolding for other tests.
Chats are normally created by POST /api/chats/start along with their first
exchange -- there is deliberately no endpoint that makes an empty one. Most
tests want a chat to act on, not that flow, so they get one straight from
the database rather than having to subtract an opening turn from every
assertion. The flow itself is covered in test_chat.py.
"""
from sqlalchemy import select
from lembas.db.models import Chat, Model, User
def _create(email: str | None = None, model_id: str | None = None) -> str:
user = (
db.scalar(select(User).where(User.email == email))
if email
else db.scalars(select(User).order_by(User.created_at)).first()
)
model = (
db.scalar(select(Model).where(Model.model_id == model_id))
if model_id
else db.scalars(select(Model).order_by(Model.position)).first()
)
chat = Chat(
user_id=user.id,
model_id=model.model_id if model else "",
connection_id=model.connection_id if model else None,
)
db.add(chat)
db.commit()
return chat.id
return _create
@pytest.fixture
def user_id(db: Session, registered: dict[str, str]) -> str:
"""The registered user's id.
+3 -1
View File
@@ -101,7 +101,9 @@ def test_htmx_requests_get_a_redirect_header_not_a_login_page(
):
"""An htmx request must never swap a login form into a fragment of the UI."""
client.post("/auth/logout", follow_redirects=False)
response = client.post("/api/chats", headers={"HX-Request": "true"})
response = client.post(
"/api/chats/start", data={"content": "hi"}, headers={"HX-Request": "true"}
)
assert response.status_code == 204
assert response.headers["HX-Redirect"] == "/auth/login"
+59 -18
View File
@@ -144,22 +144,61 @@ def _add_connection(db) -> Connection:
return connection
def test_new_chat_redirects_to_its_own_url(client: TestClient, db, registered):
# --- Starting a chat ---------------------------------------------------------
def test_starting_a_chat_creates_it_and_redirects(client: TestClient, db, registered):
_add_connection(db)
response = client.post("/api/chats", headers={"HX-Request": "true"})
response = client.post("/api/chats/start", data={"content": "Hello there"})
assert response.status_code == 204
assert response.headers["HX-Redirect"].startswith("/chat/")
chat = db.scalar(select(Chat))
assert chat.model_id == "test-model"
messages = db.scalars(select(Message).order_by(Message.created_at)).all()
assert [m.role for m in messages] == ["user", "assistant"]
assert messages[0].content == "Hello there"
def test_new_chat_picks_up_the_default_model(client: TestClient, db, registered):
def test_starting_with_nothing_creates_no_chat(client: TestClient, db, registered):
"""The whole point of lazy creation: an abandoned composer leaves nothing."""
_add_connection(db)
client.post("/api/chats", headers={"HX-Request": "true"})
assert client.post("/api/chats/start", data={"content": " "}).status_code == 204
assert db.scalar(select(Chat)) is None
def test_visiting_the_chat_page_creates_nothing(client: TestClient, db, registered):
_add_connection(db)
assert client.get("/chat").status_code == 200
assert db.scalar(select(Chat)) is None
def test_starting_a_chat_honours_the_requested_model(client: TestClient, db, registered):
"""The pinned-model shortcuts pass ?model=, which arrives here."""
connection = _add_connection(db)
db.add(Model(connection_id=connection.id, model_id="other-model", position=5))
db.commit()
client.post("/api/chats/start", data={"content": "hi", "model_id": "other-model"})
assert db.scalar(select(Chat)).model_id == "other-model"
def test_starting_a_chat_ignores_a_model_you_cannot_reach(client: TestClient, db, registered):
connection = _add_connection(db)
db.add(Model(connection_id=connection.id, model_id="secret", position=5, public=False))
db.commit()
client.post("/auth/logout", follow_redirects=False)
client.post(
"/auth/register",
data={"name": "Sam", "email": "sam@shire.test", "password": "potatoes-po-ta-toes"},
follow_redirects=False,
)
client.post("/api/chats/start", data={"content": "hi", "model_id": "secret"})
assert db.scalar(select(Chat)).model_id == "test-model"
def test_posting_a_message_stores_both_turns(client: TestClient, db, registered):
def test_posting_a_message_stores_both_turns(client: TestClient, db, registered, make_chat):
_add_connection(db)
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
response = client.post(f"/api/chats/{chat_id}/messages", data={"content": "Hello there"})
assert response.status_code == 200
@@ -174,16 +213,18 @@ def test_posting_a_message_stores_both_turns(client: TestClient, db, registered)
assert "sse-connect" in response.text
def test_empty_message_is_ignored(client: TestClient, db, registered):
def test_empty_message_is_ignored(client: TestClient, db, registered, make_chat):
_add_connection(db)
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
assert client.post(f"/api/chats/{chat_id}/messages", data={"content": " "}).status_code == 204
assert db.scalar(select(Message)) is None
def test_a_chat_belonging_to_someone_else_is_not_found(client: TestClient, db, registered):
def test_a_chat_belonging_to_someone_else_is_not_found(
client: TestClient, db, registered, make_chat
):
_add_connection(db)
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
client.post("/auth/logout", follow_redirects=False)
client.post(
@@ -195,9 +236,9 @@ def test_a_chat_belonging_to_someone_else_is_not_found(client: TestClient, db, r
assert client.get(f"/chat/{chat_id}").status_code == 404
def test_renaming_a_chat_stops_it_being_auto_titled(client: TestClient, db, registered):
def test_renaming_a_chat_stops_it_being_auto_titled(client: TestClient, db, registered, make_chat):
_add_connection(db)
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
client.patch(f"/api/chats/{chat_id}", data={"title": "My own title"})
chat = db.get(Chat, chat_id)
@@ -206,9 +247,9 @@ def test_renaming_a_chat_stops_it_being_auto_titled(client: TestClient, db, regi
assert chat.title_generated is True
def test_deleting_a_chat_removes_its_messages(client: TestClient, db, registered):
def test_deleting_a_chat_removes_its_messages(client: TestClient, db, registered, make_chat):
_add_connection(db)
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
client.post(f"/api/chats/{chat_id}/messages", data={"content": "Hello"})
client.delete(f"/api/chats/{chat_id}")
@@ -216,13 +257,13 @@ def test_deleting_a_chat_removes_its_messages(client: TestClient, db, registered
assert db.scalar(select(Message)) is None
def test_deleting_a_folder_keeps_the_chats_inside_it(client: TestClient, db, registered):
def test_deleting_a_folder_keeps_the_chats_inside_it(client: TestClient, db, registered, make_chat):
"""Losing a conversation to a mis-clicked folder delete is unforgivable."""
_add_connection(db)
client.post("/api/folders", data={"name": "Quests"})
folder = db.scalar(select(Folder))
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
client.patch(f"/api/chats/{chat_id}", data={"folder_id": folder.id})
client.delete(f"/api/folders/{folder.id}")
@@ -296,10 +337,10 @@ def test_system_prompt_leads_the_message_list(db, user_id):
def test_streaming_reports_an_unreachable_endpoint_in_the_thread(
client: TestClient, db, registered
):
, make_chat):
"""A failed turn must never be an unexplained blank bubble."""
_add_connection(db) # points at 127.0.0.1:1, which refuses connections
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
client.post(f"/api/chats/{chat_id}/messages", data={"content": "Hello"})
message = db.scalar(select(Message).where(Message.role == "assistant"))
+6 -5
View File
@@ -83,7 +83,7 @@ def pdf_bytes(pages: list[str]) -> bytes:
@pytest.fixture
def chat_with_model(client: TestClient, db, registered):
def chat_with_model(client: TestClient, db, registered, make_chat):
"""A chat whose model has vision turned on."""
connection = Connection(name="T", base_url="http://127.0.0.1:1", api_key_encrypted=encrypt(""))
db.add(connection)
@@ -96,8 +96,7 @@ def chat_with_model(client: TestClient, db, registered):
)
)
db.commit()
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
return chat_id
return make_chat()
# --- Type detection and processing -------------------------------------------
@@ -326,7 +325,9 @@ def test_a_truly_empty_message_is_still_ignored(client: TestClient, db, chat_wit
assert db.scalar(select(Message)) is None
def test_you_cannot_attach_someone_elses_file(client: TestClient, db, chat_with_model):
def test_you_cannot_attach_someone_elses_file(
client: TestClient, db, chat_with_model, make_chat
):
"""A forged id must not pull another user's file into a conversation."""
client.post("/api/files", files={"file": ("mine.txt", b"secret", "text/plain")})
stolen = db.scalar(select(Attachment))
@@ -337,7 +338,7 @@ def test_you_cannot_attach_someone_elses_file(client: TestClient, db, chat_with_
data={"name": "Sam", "email": "sam@shire.test", "password": "potatoes-po-ta-toes"},
follow_redirects=False,
)
their_chat = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
their_chat = make_chat(email="sam@shire.test")
client.post(
f"/api/chats/{their_chat}/messages",
data={"content": "gimme", "file_ids": [stolen.id]},
+135 -19
View File
@@ -99,7 +99,7 @@ def test_a_group_can_grant_back_what_the_baseline_removed(db, plain_user):
# --- Enforcement through the API ---------------------------------------------
def test_creating_a_chat_is_refused_without_permission(client: TestClient, db, plain_user):
settings_store.update(db, {"default_permissions": {"chat.create": False}})
assert client.post("/api/chats").status_code == 403
assert client.post("/api/chats/start", data={"content": "hi"}).status_code == 403
assert db.scalar(select(Chat)) is None
@@ -108,19 +108,21 @@ def test_folder_routes_are_refused_without_permission(client: TestClient, db, pl
assert client.post("/api/folders", data={"name": "Nope"}).status_code == 403
def test_changing_sampling_is_refused_without_permission(client: TestClient, db, plain_user):
def test_changing_sampling_is_refused_without_permission(
client: TestClient, db, plain_user, make_chat
):
_model(db, "test-model")
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat(email="sam@shire.test")
response = client.patch(f"/api/chats/{chat_id}", data={"temperature": "0.9"})
assert response.status_code == 403
def test_sampling_is_allowed_once_a_group_grants_it(client: TestClient, db, plain_user):
def test_sampling_is_allowed_once_a_group_grants_it(client: TestClient, db, plain_user, make_chat):
_model(db, "test-model")
db.add(Group(name="Tuners", permissions_json={"chat.params": True}, users=[plain_user]))
db.commit()
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat(email="sam@shire.test")
assert client.patch(f"/api/chats/{chat_id}", data={"temperature": "0.9"}).status_code == 204
chat = db.get(Chat, chat_id)
@@ -134,10 +136,10 @@ def test_sampling_is_allowed_once_a_group_grants_it(client: TestClient, db, plai
)
def test_out_of_range_parameters_are_dropped_not_clamped(
client: TestClient, db, registered, field, value
):
, make_chat):
"""Silently changing what someone typed is worse than ignoring it."""
_model(db, "test-model")
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
client.patch(f"/api/chats/{chat_id}", data={field: value})
chat = db.get(Chat, chat_id)
@@ -145,9 +147,9 @@ def test_out_of_range_parameters_are_dropped_not_clamped(
assert field not in (chat.params_json or {})
def test_an_empty_parameter_clears_it(client: TestClient, db, registered):
def test_an_empty_parameter_clears_it(client: TestClient, db, registered, make_chat):
_model(db, "test-model")
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
client.patch(f"/api/chats/{chat_id}", data={"temperature": "0.7"})
client.patch(f"/api/chats/{chat_id}", data={"temperature": ""})
@@ -187,12 +189,14 @@ def test_disabled_models_are_hidden_from_everyone(db, registered):
assert permissions.models_visible_to(db, admin_user) == []
def test_switching_to_an_inaccessible_model_is_refused(client: TestClient, db, plain_user):
def test_switching_to_an_inaccessible_model_is_refused(
client: TestClient, db, plain_user, make_chat
):
"""The picker is not the security boundary; a crafted request must fail."""
_model(db, "open-model", public=True)
_model(db, "secret-model", public=False)
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat(email="sam@shire.test")
response = client.patch(f"/api/chats/{chat_id}", data={"model_id": "secret-model"})
assert response.status_code == 403
@@ -201,17 +205,21 @@ def test_switching_to_an_inaccessible_model_is_refused(client: TestClient, db, p
assert chat.model_id == "open-model"
def test_model_select_permission_is_required_to_switch(client: TestClient, db, plain_user):
def test_model_select_permission_is_required_to_switch(
client: TestClient, db, plain_user, make_chat
):
_model(db, "a-model", public=True)
_model(db, "b-model", public=True)
settings_store.update(db, {"default_permissions": {"chat.model_select": False}})
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat(email="sam@shire.test")
assert client.patch(f"/api/chats/{chat_id}", data={"model_id": "b-model"}).status_code == 403
# --- Ordering and defaults ---------------------------------------------------
def test_pinned_models_sort_first(db, registered):
def test_pinning_does_not_reorder_the_picker(db, registered):
"""Pinning is a sidebar shortcut. A picker whose order silently differs from
the admin screen is just confusing."""
connection = _connection(db)
db.add_all(
[
@@ -222,8 +230,8 @@ def test_pinned_models_sort_first(db, registered):
db.commit()
admin_user = db.scalar(select(User).where(User.role == "admin"))
assert [m.model_id for m in chat_service.available_models(db, admin_user)] == [
"favourite",
"ordinary",
"favourite",
]
@@ -254,7 +262,7 @@ def test_instance_default_model_is_used_for_new_chats(client: TestClient, db, re
db.commit()
settings_store.update(db, {"default_model": "chosen"})
client.post("/api/chats")
client.post("/api/chats/start", data={"content": "hi"})
assert db.scalar(select(Chat)).model_id == "chosen"
@@ -270,7 +278,7 @@ def test_a_users_own_default_beats_the_instance_default(client: TestClient, db,
settings_store.update(db, {"default_model": "instance-pick"})
client.post("/api/preferences/default-model", data={"model_id": "my-pick"})
client.post("/api/chats")
client.post("/api/chats/start", data={"content": "hi"})
assert db.scalar(select(Chat)).model_id == "my-pick"
@@ -346,7 +354,7 @@ def test_deactivating_a_user_revokes_their_sessions(client: TestClient, db, regi
assert other.get("/chat", follow_redirects=False).status_code == 303
def test_a_pinned_model_appears_once_in_the_picker(client: TestClient, db, registered):
def test_a_pinned_model_appears_once_in_the_picker(client: TestClient, db, registered, make_chat):
"""Two options with the same value, both selected, is not a picker."""
connection = _connection(db)
db.add_all(
@@ -357,7 +365,115 @@ def test_a_pinned_model_appears_once_in_the_picker(client: TestClient, db, regis
)
db.commit()
chat_id = client.post("/api/chats").headers["HX-Redirect"].rsplit("/", 1)[1]
chat_id = make_chat()
page = client.get(f"/chat/{chat_id}").text
assert page.count('<option value="favourite"') == 1
assert page.count('<option value="ordinary"') == 1
# --- System prompt layering --------------------------------------------------
def test_system_prompt_falls_back_to_the_instance(db, user_id):
connection = _connection(db)
db.add(Model(connection_id=connection.id, model_id="m"))
db.commit()
settings_store.update(db, {"system_prompt": "You are terse."})
chat = Chat(user_id=user_id, model_id="m", connection_id=connection.id)
db.add(chat)
db.commit()
assert chat_service.effective_system_prompt(db, chat) == "You are terse."
def test_a_models_prompt_beats_the_instance(db, user_id):
connection = _connection(db)
db.add(Model(connection_id=connection.id, model_id="m", system_prompt="You are a poet."))
db.commit()
settings_store.update(db, {"system_prompt": "You are terse."})
chat = Chat(user_id=user_id, model_id="m", connection_id=connection.id)
db.add(chat)
db.commit()
assert chat_service.effective_system_prompt(db, chat) == "You are a poet."
def test_a_chats_prompt_beats_everything(db, user_id):
connection = _connection(db)
db.add(Model(connection_id=connection.id, model_id="m", system_prompt="You are a poet."))
db.commit()
settings_store.update(db, {"system_prompt": "You are terse."})
chat = Chat(
user_id=user_id, model_id="m", connection_id=connection.id,
system_prompt="You are a dwarf.",
)
db.add(chat)
db.commit()
assert chat_service.effective_system_prompt(db, chat) == "You are a dwarf."
def test_layers_replace_rather_than_stack(db, user_id):
"""Concatenating them reads well in a settings screen and badly in practice:
two layers that disagree give the model contradictory instructions."""
connection = _connection(db)
db.add(Model(connection_id=connection.id, model_id="m", system_prompt="MODEL"))
db.commit()
settings_store.update(db, {"system_prompt": "INSTANCE"})
chat = Chat(user_id=user_id, model_id="m", connection_id=connection.id)
db.add(chat)
db.commit()
assert "INSTANCE" not in chat_service.effective_system_prompt(db, chat)
def test_no_prompt_anywhere_sends_no_system_message(db, user_id):
connection = _connection(db)
db.add(Model(connection_id=connection.id, model_id="m"))
db.commit()
chat = Chat(user_id=user_id, model_id="m", connection_id=connection.id)
db.add(chat)
db.commit()
assert chat_service.build_request(db, chat)["messages"] == []
# --- Admin bulk actions ------------------------------------------------------
def test_bulk_disable_works(client: TestClient, db, registered):
"""Regression: /admin/models/{model_id} was registered first, so "bulk" was
parsed as a model id and every bulk action 404'd."""
connection = _connection(db)
db.add_all(
[
Model(connection_id=connection.id, model_id="a"),
Model(connection_id=connection.id, model_id="b"),
]
)
db.commit()
ids = [m.id for m in db.scalars(select(Model))]
response = client.post(
"/admin/models/bulk", data={"action": "disable", "model_ids": ids},
follow_redirects=False,
)
assert response.status_code == 303
assert all(not m.enabled for m in db.scalars(select(Model)))
def test_bulk_restrict_then_publish(client: TestClient, db, registered):
connection = _connection(db)
db.add(Model(connection_id=connection.id, model_id="a"))
db.commit()
model = db.scalar(select(Model))
client.post("/admin/models/bulk", data={"action": "private", "model_ids": [model.id]})
db.refresh(model)
assert model.public is False
client.post("/admin/models/bulk", data={"action": "public", "model_ids": [model.id]})
db.refresh(model)
assert model.public is True
def test_bulk_with_nothing_selected_is_harmless(client: TestClient, db, registered):
assert client.post(
"/admin/models/bulk", data={"action": "disable"}, follow_redirects=False
).status_code == 303