"""Chat creation, messaging and the streaming reply endpoint.""" from __future__ import annotations import asyncio import json import logging import time from collections.abc import AsyncIterator from datetime import UTC, datetime from types import SimpleNamespace from fastapi import APIRouter, Depends, Form, HTTPException, Request, status from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse from sqlalchemy import and_, func, or_, select from sqlalchemy.orm import Session as DBSession from lembas.api.deps import Db, RequiredUser, require_permission from lembas.db.models import ( KIND_AGENT, KIND_CHAT, KIND_MESSAGES, KINDS, ROLE_ASSISTANT, ROLE_USER, Chat, Folder, Message, Model, User, ) from lembas.db.session import session_scope from lembas.security import permissions from lembas.services import audio as audio_service from lembas.services import chat as chat_service from lembas.services import compaction as compaction_service from lembas.services import files as files_service from lembas.services import generation as generation_service from lembas.services import interaction, settings_store, sse from lembas.services import metrics as metrics_service from lembas.services import prompts as prompts_service from lembas.services import reports as reports_service from lembas.services import steps as steps_service from lembas.services import tokens as tokens_service from lembas.services import tools as tools_service from lembas.services.agent import draft as draft_service from lembas.services.agent import policy as agent_policy from lembas.services.agent import terminal as terminal_service from lembas.services.markdown import escape_text, render_markdown from lembas.web.templating import render, templates log = logging.getLogger(__name__) router = APIRouter(prefix="/api/chats", tags=["chats"]) # Seconds of silence before a comment frame is sent to hold the connection open. # Well under nginx's 60s default; see services/sse.py:KEEPALIVE. KEEPALIVE_AFTER = 15.0 # How often the metrics chips are re-sent when nothing else has changed. The # reply's version does not move while a tool runs on the far machine, but its # clock does, so without this the counts and tokens/second stand still for most # of a long agent reply's wall time. A second is slow enough to be free and fast # enough that the numbers read as live. METRICS_INTERVAL = 1.0 # How many prompts may wait behind a reply at once. The terminal panel's Auto # send is what this exists for: a `for` loop in a shell can produce commands # faster than any model answers them, and a bound with a sentence attached is # better than four hundred rows nobody meant to write. MAX_QUEUED = 10 # Which tools a request may compel the model to call. An allow list rather than # a passthrough: this becomes `tool_choice`, and a name read straight off a form # would let anyone who can send a message decide what the model must do next. # Being on this list is not permission to *use* the tool -- `resolve_tools` still # decides that, and forcing one that was never offered simply does nothing. FORCEABLE_TOOLS = frozenset({"image_generate"}) # How many things one chat may have switched off. There are a dozen families and # sixty skills at most, so this is not a limit anybody reaches by hand -- it is # there so a crafted POST cannot grow the column without bound. MAX_SCOPE_KEYS = 200 def _owned_chat(db: DBSession, chat_id: str, user_id: str) -> Chat: chat = db.get(Chat, chat_id) # 404 rather than 403 for someone else's chat: whether a given id exists is # not information this endpoint should hand out. if chat is None or chat.user_id != user_id: raise HTTPException(status.HTTP_404_NOT_FOUND, "That chat no longer exists.") return chat def _adopt_draft(db: DBSession, user: User, draft_id: str, chat: Chat) -> None: """Hand the new-chat screen's shell and open files to the chat it became. Between `_new_chat` and the first message deliberately: the chat has an id by here, and `generation.ensure` below has not yet started a reply that would read `chat.canvas_json`. The shell is only adopted when it is a shell on the same target. `_new_chat` settles `project_dir` last -- an empty one falls back to the connection's own login directory -- so the comparison is against the chat as resolved, never against what the form said. On a mismatch the session is left alone rather than transplanted onto a chat that says it runs somewhere else; it belongs to whatever draft it was opened under and is reaped on idle. """ if not draft_id or not draft_service.is_draft(draft_id): return draft = draft_service.get(draft_id, user.id) if draft is None: return matches = ( chat.kind == KIND_AGENT and draft.profile_id == (chat.ssh_profile_id or "") and draft.project_dir == (chat.project_dir or "") ) if not matches: return session = terminal_service.peek(draft_id) if session is not None: terminal_service.rekey(draft_id, chat.id) # Only what a chat can actually reopen. A tab whose source needs a row it # never had is dropped rather than carried across to fail on first click. tabs = dict(draft.canvas_json or {}) kept = [ tab for tab in tabs.get("tabs") or [] if not draft_service.refuses(str(tab.get("key", "")).split(":", 1)[0]) ] if kept: chat.canvas_json = {**tabs, "tabs": kept} db.commit() draft_service.forget(draft_id) def _new_chat( db: DBSession, user: User, *, folder_id: str = "", model_id: str = "", temporary: bool = False, kind: str = KIND_CHAT, ssh_profile_id: str = "", project_dir: str = "", agent_mode: str = "", reasoning_effort: str = "", ) -> Chat: """Create a chat row, resolving which model it should use. An agent chat's connection is settled here and never again. That is the lock: the harness, the tools offered and the approval loop all differ, so a conversation whose earlier turns ran somewhere else is not one conversation. The mode is *not* part of that lock and is accepted here so it can be chosen before the first word. Without it, reaching Plan mode meant starting a chat in Manual, sending something to make the chat exist, and only then being offered the control -- by which point the model had already answered under the wrong rules. The reasoning effort is accepted for the same reason, and wins over the model's default: an explicit choice beats an inherited one. A folder's own defaults fill in anything the request left empty, and nothing it filled in. That order is the point: the folder says what this piece of work usually needs, and the screen in front of somebody says what they want this time. The folder's system prompt is deliberately not among them -- it is read at request time so that editing the folder later reaches the chats already in it. """ folder = db.get(Folder, folder_id) if folder_id else None if folder is not None and folder.user_id != user.id: folder = None if folder is not None: model_id = model_id or folder.model_id kind = kind or folder.kind if kind == KIND_AGENT: ssh_profile_id = ssh_profile_id or folder.ssh_profile_id project_dir = project_dir or folder.project_dir agent_mode = agent_mode or folder.agent_mode chosen = None if model_id: match = next( (m for m in chat_service.available_models(db, user) if m.model_id == model_id), None ) if match is not None: chosen = (match.model_id, match.connection_id) if chosen is None: chosen = chat_service.default_model(db, user) # `Model.params_json` has said "default sampling params applied to new chats # using this model" since it was added and has been applied nowhere. It is # empty on every existing row, so honouring it now changes nothing until an # administrator sets something -- and it is what makes a per-model default # reasoning effort possible without a second column meaning the same thing. defaults: dict = {} if chosen is not None: model = db.scalar( select(Model).where( Model.model_id == chosen[0], Model.connection_id == chosen[1] ) ) if model is not None: defaults = dict(model.params_json or {}) profile = _agent_target(db, user, kind, ssh_profile_id) chat = Chat( user_id=user.id, folder_id=folder_id or None, model_id=chosen[0] if chosen else "", connection_id=chosen[1] if chosen else None, temporary=temporary, kind=KIND_AGENT if profile is not None else KIND_CHAT, ssh_profile_id=profile.id if profile is not None else None, project_dir=(project_dir.strip() or profile.default_dir) if profile is not None else "", params_json=defaults, ) # Ignored rather than refused when it is not a mode, matching how every # other bad value here collapses: somebody who mistypes should get a chat # under the safest rules, not an error page holding their message hostage. # Left alone entirely on a plain chat, where it means nothing. if profile is not None and agent_mode.strip() in agent_policy.MODES: chat.agent_mode = agent_mode.strip() # After the model's defaults, so choosing one on the new-chat screen wins # over the administrator's. # # `"off"` is a sentinel, and it has to be: `reasoning_effort` arrives as # `Form("")`, so an absent field and an empty one are indistinguishable -- # the FastAPI trap this codebase has already been bitten by once. With # `value=""` on the off option, the reader would pick "off", the value would # fall out of EFFORTS, the model's default seeded above would stay, and they # would silently get "high". The picker shows what will be sent, so the two # have to agree. wanted_effort = reasoning_effort.strip().lower() if wanted_effort == "off": chat.params_json = {k: v for k, v in chat.params_json.items() if k != "reasoning_effort"} elif wanted_effort in chat_service.EFFORTS: chat.params_json = {**chat.params_json, "reasoning_effort": wanted_effort} db.add(chat) db.commit() return chat @router.post("/start", dependencies=[Depends(require_permission("chat.create"))]) async def start_chat( db: Db, user: RequiredUser, content: str = Form(""), file_ids: list[str] = Form(default=[]), folder_id: str = Form(""), model_id: str = Form(""), temporary: bool = Form(False), kind: str = Form(KIND_CHAT), ssh_profile_id: str = Form(""), project_dir: str = Form(""), agent_mode: str = Form(""), reasoning_effort: str = Form(""), draft_id: str = Form(""), ) -> Response: """Create a chat from its first message. Chats are made here rather than by a "New chat" button so that an opened- and-abandoned chat never exists: the row appears only once there is something in it. The reply then streams the same way as any other, because /chat/{id} renders the unfinished assistant message with its sse-connect. """ content = content.strip() if not content and not file_ids: return Response(status_code=status.HTTP_204_NO_CONTENT) chat = _new_chat( db, user, folder_id=folder_id, model_id=model_id, temporary=temporary, kind=kind, ssh_profile_id=ssh_profile_id, project_dir=project_dir, agent_mode=agent_mode, reasoning_effort=reasoning_effort, ) _adopt_draft(db, user, draft_id, chat) user_message = chat_service.create_message(db, chat, ROLE_USER, content) if file_ids: files_service.claim(db, ids=file_ids, user_id=user.id, message_id=user_message.id) assistant = chat_service.create_message( db, chat, ROLE_ASSISTANT, "", complete_=False, model_id=chat.model_id ) generation_service.ensure(chat.id, assistant.id) response = Response(status_code=status.HTTP_204_NO_CONTENT) response.headers["HX-Redirect"] = f"/chat/{chat.id}" return response def _agent_target(db: DBSession, user: User, kind: str, profile_id: str): """The connection an agent chat is being pointed at, or None. Every "no" collapses to None and the chat is an ordinary one: not asked for, no permission, the feature off, or a profile that is not this person's. Refusing outright would be worse -- somebody whose permission was withdrawn between opening the composer and sending would lose the message. """ from lembas.db.models import SshProfile from lembas.security import permissions if kind != KIND_AGENT or not profile_id: return None if not permissions.has(db, user, "tools.agent"): return None if not settings_store.agents(db).get("enabled"): return None profile = db.get(SshProfile, profile_id) # Ownership re-checked rather than trusted from the form: an id in a POST is # not an authorisation, and these are credentials to somebody's machine. if profile is None or profile.owner_id != user.id or not profile.enabled: return None return profile # There is deliberately no route that creates an empty chat. Starting one is # navigation to /chat (optionally ?model=...), and the row is written by # /start when the first message is actually sent. @router.get("/{chat_id}/inspect") async def inspect_chat(request: Request, db: Db, user: RequiredUser, chat_id: str) -> Response: """What this chat would send upstream right now. Owner-checked *and* admin-checked, not admin alone. `permissions.resolve` giving an admin everything is about configuration, which they can grant themselves anyway; reading someone's conversation is a different act, which is why `sharing.visible_to` has no admin branch either. An inspector that could dump any user's transcript would be that branch under another name. Rebuilt, not recorded. Recording every request would store a copy of the whole conversation against every message, which grows quadratically with chat length -- and the thing an administrator actually wants to see is what the current configuration produces. The panel says so in as many words. """ chat = _owned_chat(db, chat_id, user.id) if not user.is_admin: raise HTTPException( status.HTTP_403_FORBIDDEN, "The inspector is restricted to administrators." ) offered = tools_service.enabled_tools(db, chat, user) payload = chat_service.build_request(db, chat, tools=offered, user=user) last = db.scalar( select(Message) .where(Message.chat_id == chat.id, Message.role == ROLE_ASSISTANT) .order_by(Message.created_at.desc()) ) messages = payload.get("messages") or [] system = messages[0]["content"] if messages and messages[0].get("role") == "system" else "" return render( request, "chat/_inspector_body.html", { "chat": chat, "system": system, "request_json": _pretty(_redact(payload)), "row": last, "metrics": metrics_service.from_message(last.usage_json if last else None), "tool_names": [ (t.get("function") or {}).get("name", "") for t in offered ], "model": chat_service.model_for(db, chat), }, ) @router.get("/{chat_id}/usage") async def chat_usage(request: Request, db: Db, user: RequiredUser, chat_id: str) -> Response: """What this conversation has cost, and how full the window is. Owner-checked and nothing else: it is your own chat's totals. Unlike the inspector next door there is no admin branch, because there is no reason for one -- the numbers describe a conversation, and reading somebody's conversation is exactly what `sharing` has no admin branch for either. Summed from what each reply recorded rather than recomputed: an endpoint that reported no usage contributed an estimate at the time, and re-deriving it now with a different estimator would make the totals move under a chat that had not changed. """ chat = _owned_chat(db, chat_id, user.id) replies = list( db.scalars( select(Message) .where(Message.chat_id == chat.id, Message.role == ROLE_ASSISTANT) .order_by(Message.created_at) ) ) totals = {"prompt": 0, "completion": 0, "total": 0} estimated = False for reply in replies: usage = metrics_service.from_message(reply.usage_json) totals["prompt"] += usage.prompt_tokens totals["completion"] += usage.completion_tokens totals["total"] += usage.total_tokens estimated = estimated or usage.estimated last = replies[-1] if replies else None return render( request, "chat/_usage.html", { "chat": chat, "totals": totals, "estimated": estimated, "replies": len(replies), "metrics": metrics_service.from_message(last.usage_json if last else None), "model": chat_service.model_for(db, chat), }, ) # Roughly what a downscaled phone photo comes to as base64. The exact figure # does not matter; putting megabytes of it into the DOM does. _REDACTED_URI = "data:…base64 image omitted…" MAX_INSPECT_CHARS = 40_000 def _redact(payload: dict) -> dict: """Replace image data URIs before dumping. Nothing else is hidden -- fidelity is the whole point of the panel, and API keys never appear because `build_request` returns a body, not headers. """ messages = [] for message in payload.get("messages") or []: content = message.get("content") if isinstance(content, list): parts = [] for part in content: if isinstance(part, dict) and part.get("type") == "image_url": parts.append({"type": "image_url", "image_url": {"url": _REDACTED_URI}}) else: parts.append(part) message = {**message, "content": parts} messages.append(message) return {**payload, "messages": messages} def _pretty(payload: dict) -> str: text = json.dumps(payload, indent=2, ensure_ascii=False, default=str) if len(text) > MAX_INSPECT_CHARS: return text[:MAX_INSPECT_CHARS] + "\n… truncated" return text @router.post("/{chat_id}/compact") async def compact_chat(request: Request, db: Db, user: RequiredUser, chat_id: str) -> Response: """Summarise the earlier turns and stop sending them. No permission of its own: compaction changes only what one chat sends upstream, and gating it would mean answering "why can this user not tidy their own conversation". """ chat = _owned_chat(db, chat_id, user.id) unfinished = db.scalar( select(Message).where(Message.chat_id == chat.id, Message.complete.is_(False)) ) if unfinished is not None: # Summarising a transcript that is still being written races # build_request. Queuing it is a state machine nobody asked for. raise HTTPException( status.HTTP_409_CONFLICT, "Wait for the current reply to finish, then compact." ) template = prompts_service.resolve(db, "task.compact") if not template.strip(): raise HTTPException( status.HTTP_409_CONFLICT, "Compaction is turned off: its prompt is empty under Admin → Prompts.", ) upto = compaction_service.last_complete(db, chat) if upto is None: raise HTTPException( status.HTTP_409_CONFLICT, "There is nothing here to summarise yet." ) endpoint, model_id = chat_service.resolve_endpoint(db, chat) transcript = compaction_service.transcript(db, chat, upto=upto) previous = compaction_service.previous_summary_block(chat) summary = await chat_service.summarise_for_compaction( endpoint, model_id, transcript=transcript, previous_summary=previous, template=template, ) if not summary: raise HTTPException( status.HTTP_409_CONFLICT, "The model returned no summary, so nothing changed." ) compaction_service.apply(chat, summary=summary, upto=upto) db.commit() log.info("chat %s compacted through %s", chat.id, upto.id) return templates.TemplateResponse( request, "chat/_thread.html", {"request": request, **_thread_context(db, chat, user)} ) @router.post("/{chat_id}/index") async def reindex_chat(db: Db, user: RequiredUser, chat_id: str) -> Response: """Walk the project directory again, now. The listing is cached for five minutes and only ever built when a reply starts, so a tree that has just changed under somebody's hands -- a checkout, a build, anything done in the terminal panel rather than through `file_write` -- stays wrong until the next reply after the TTL lapses. This is the "look again" that was missing. Read-only, and therefore outside `agent/policy.py` for the reason the directory browser is: it is LLeMbas acting on a person's instruction, not a model choosing to look, and a listing that asked permission would be useless. The gate is ownership of the connection, checked here rather than trusted from the chat. """ from lembas.db.models import SshProfile from lembas.services.agent import index as index_service from lembas.services.agent import ssh as ssh_service chat = _owned_chat(db, chat_id, user.id) if chat.kind != KIND_AGENT or not chat.ssh_profile_id: raise HTTPException(status.HTTP_409_CONFLICT, "This chat has no project directory.") if not permissions.has(db, user, "tools.agent"): raise HTTPException(status.HTTP_403_FORBIDDEN, "You may not use agent connections.") profile = db.get(SshProfile, chat.ssh_profile_id) if profile is None or profile.owner_id != user.id or not profile.enabled: raise HTTPException(status.HTTP_404_NOT_FOUND, "That connection is not available.") if not profile.host_key: raise HTTPException( status.HTTP_409_CONFLICT, "This connection's host key has not been accepted yet.", ) project_dir = chat.project_dir or profile.default_dir or "" try: found = await index_service.ensure( ssh_service.SshExecutor(ssh_service.spec_from(profile), project_dir), profile.id, project_dir, refresh=True, ) except Exception as exc: # noqa: BLE001 - surfaced to the reader, not swallowed log.warning("could not index %s for chat %s: %s", project_dir, chat.id, exc) raise HTTPException( status.HTTP_502_BAD_GATEWAY, "Could not read the project directory." ) from exc listed = len(found.paths) return JSONResponse( { "ok": True, "files": found.total, "listed": listed, "truncated": found.truncated, "message": ( f"{found.total} files under {project_dir or '~'}" + (f", {listed} listed." if listed != found.total else ".") ), } ) @router.post("/{chat_id}/bases") async def attach_base( request: Request, db: Db, user: RequiredUser, chat_id: str, base_id: str = Form("") ) -> Response: """Scope this chat to a knowledge base, from the `@` menu. A base is a *reference*, not an attachment: `Chat.knowledge_bases` already narrows `knowledge_search`, and the harness already names the attached bases so the model can tell "there is nothing about this" from "I can only see this folder". Copying a folder of documents into the window instead would cost the context on every request forever to answer one question. Additive, and idempotent -- choosing the same base twice is not an error. Removing one is a checkbox in the chat's settings, where the whole set is visible at once. """ from lembas.db.models import KnowledgeBase from lembas.services.library import documents as documents_service chat = _owned_chat(db, chat_id, user.id) if not permissions.has(db, user, "library.use"): raise HTTPException(status.HTTP_403_FORBIDDEN, "You may not use the library.") base = db.scalar( documents_service.visible_bases(db, user).where(KnowledgeBase.id == base_id) ) if base is None: raise HTTPException(status.HTTP_404_NOT_FOUND, "That knowledge base is not available.") if base.id not in {b.id for b in chat.knowledge_bases}: chat.knowledge_bases = [*chat.knowledge_bases, base] db.commit() return templates.TemplateResponse( request, "chat/_base_chip.html", {"request": request, "base": base} ) @router.post("/{chat_id}/scope") async def set_scope( db: Db, user: RequiredUser, chat_id: str, kind: str = Form(""), name: str = Form(""), on: bool = Form(False), ) -> Response: """Turn one thing this chat may use on or off. **Narrowing only.** Nothing here widens anything. `resolve_tools` applies this *after* the model's capabilities, the reader's permissions and the instance configuration, so a crafted POST turning something on reaches a tool those gates have already removed -- there is a test for exactly that. On is stored by **removing** the key rather than by writing True, so absent stays the single representation of "on" and the column cannot grow a row per family per chat. Bounded, so a crafted request cannot grow it either. JSON reassignment rather than mutation: a plain dict assignment into a JSON column is not detected. """ chat = _owned_chat(db, chat_id, user.id) bucket = {"family": "families", "skill": "skills"}.get(kind.strip()) wanted = name.strip()[:64] if bucket is None or not wanted: raise HTTPException(status.HTTP_400_BAD_REQUEST, "Say what to turn on or off.") scope = dict(chat.scope_json or {}) entries = dict(scope.get(bucket) or {}) if on: entries.pop(wanted, None) else: if len(entries) >= MAX_SCOPE_KEYS: raise HTTPException(status.HTTP_409_CONFLICT, "Too many things switched off.") entries[wanted] = False if entries: scope[bucket] = entries else: scope.pop(bucket, None) chat.scope_json = scope db.commit() return Response(status_code=status.HTTP_204_NO_CONTENT) @router.post("/{chat_id}/keep") async def keep_chat(db: Db, user: RequiredUser, chat_id: str) -> Response: """Stop a temporary chat being temporary. A conversation that turns out to matter has to have a way out; without one, the sweep destroys it a day later with no recourse, and people discover that exactly once. """ chat = _owned_chat(db, chat_id, user.id) chat.temporary = False db.commit() response = Response(status_code=status.HTTP_204_NO_CONTENT) # The sidebar has to gain a row and the topbar has to lose a badge; a full # refresh is one line against a handful of out-of-band fragments. response.headers["HX-Refresh"] = "true" return response @router.get("/unread") async def unread_poll(db: Db, user: RequiredUser) -> Response: """Dots for the sidebar, and a toast for anything newly arrived. Polled rather than pushed: a browser sitting on a different chat has no open connection to the one that finished, and a second always-on channel per tab is a lot of machinery for a green dot. Returns out-of-band spans so only the dots change -- re-rendering the whole sidebar would reset the folder open/closed state on every tick. """ chats = list( db.scalars( select(Chat).where( Chat.user_id == user.id, Chat.archived.is_(False), # A temporary chat has no sidebar row, so a dot has nowhere to # land and the toast would name a chat nobody can navigate to. Chat.temporary.is_(False), # And neither has a conversation belonging to a section rather # than to the tree. Those get one dot per *section*, below -- # forty task chats must not mean forty out-of-band spans aimed # at elements that are not on the page. htmx says nothing at all # when an OOB target is missing, so this would be silent waste. Chat.kind.in_(KINDS), ) ) ) fresh = [c for c in chats if c.unread and not c.unread_notified] for chat in fresh: chat.unread_notified = True if fresh: db.commit() markup = "".join( f'' for c in chats ) # One dot for the whole Reports section, carried by this poll rather than by # a second timer of its own. Sent on every tick including empty, because it # has to be able to clear: a dot that survived reading the last report would # be news that cannot be dismissed. if permissions.has(db, user, "reports.use"): waiting = reports_service.unread_count(db, user) markup += ( '' ) # The Messages conversation, read from the row rather than created: this # runs every ten seconds on every open page, and `for_user` would write one # for every account that has never opened the section. conversation = db.scalars( select(Chat).where(Chat.user_id == user.id, Chat.kind == KIND_MESSAGES) ).first() markup += ( '' ) response = HTMLResponse(markup) if fresh: # HX-Trigger carries the toast; ui.js listens for it. response.headers["HX-Trigger"] = json.dumps( {"lembas:unread": {"titles": [c.title for c in fresh]}} ) return response @router.get("/{chat_id}/tail") async def thread_tail(db: Db, user: RequiredUser, chat_id: str, after: str = "") -> Response: """Turns this page has not got yet, appended to the transcript it is showing. A reply can begin without a request from the browser: `jobs.wake` writes a completion turn and calls `generation.ensure` when a background job finishes on an idle chat. There is no channel to tell the page about it. The only stream here is per-message and it is opened by the `sse-connect` on an incomplete assistant bubble -- a bubble this page does not have, because the reply that created it started somewhere else. `_queue_frames` proves the swap works, but it can only ride a stream that is already open. So the page asks. Polled for the same reason `/unread` is: a second always-on connection per tab is a great deal of machinery for something that happens a few times a day. The cursor comes from the browser -- see `app.js`, which reads the last bubble in `#thread`, the honest answer to what this page already holds. """ chat = _owned_chat(db, chat_id, user.id) # Somebody is looking at this chat, which is what `unread` means the absence # of. `_persist` marks a reply unread whenever `generation.followers == 0`, # and that is true of a job-woken reply even with the reader watching it -- # so today the toast announces a chat that is already on screen. This is # `pages.chat_detail` said again for as long as the page stays open rather # than once when it loads, and it is cleared whether or not anything arrived: # the claim being made is that somebody is here. # # Not airtight, and not pretending to be: the sidebar polls on 10s and this # on 5s, so this usually wins, but a badly timed tick can still raise one # toast for the chat in front of you. if chat.unread or chat.unread_notified: chat.unread = False chat.unread_notified = False db.commit() # No cursor, a cursor from another chat, or one naming a row a rewind has # since deleted. Answering with the transcript would append a second copy of # every bubble the page still holds, and a page whose history was rewritten # underneath it is one only a reload can reconcile -- which is not this # route's decision to make, with a half-typed message possibly in the box. cut = db.get(Message, after) if after else None if cut is None or cut.chat_id != chat.id: return Response(status_code=status.HTTP_204_NO_CONTENT) # The cut is read from the row rather than taken as a timestamp on the wire, # which is what makes `_inject`'s restamp harmless: if the page's last bubble # was the assistant placeholder and the placeholder moved, the cut moves with # it. Compared in SQL and never in Python, for the reason `compaction.moment` # exists -- a row read back from SQLite is naive and one still in the session # is aware, and `>` between them raises. # # The id clause is not decoration. Under a bare `>` a row sharing the cut's # microsecond is skipped forever; with it, at most the one sorting lower is. fresh = list( db.scalars( select(Message) .where( Message.chat_id == chat.id, or_( Message.created_at > cut.created_at, and_(Message.created_at == cut.created_at, Message.id > cut.id), ), ) .order_by(Message.created_at, Message.id) ) ) if not fresh: # 204 and not an empty 200: htmx does not swap on a 204, where an empty # body would still fire a swap and a settle on every open page every # five seconds. return Response(status_code=status.HTTP_204_NO_CONTENT) # Queued turns come too, unfiltered. A completion waiting behind a running # reply is exactly what the reader wants to watch arrive, and its bubble can # never carry `sse-connect` -- `_message.html` requires the assistant role # for that. When the running reply ends, `_queue_frames` deletes the stale # node out of band and re-renders it in place, so arriving early costs # nothing. # # No `just_finished`: that flag is what read-aloud-automatically keys off, # and a bubble the page merely missed must not start talking. return HTMLResponse("".join(_render_bubble(db, chat, user, row) for row in fresh)) @router.post("/{chat_id}/messages") async def post_message( request: Request, db: Db, user: RequiredUser, chat_id: str, content: str = Form(""), file_ids: list[str] = Form(default=[]), force_tool: str = Form(""), ) -> Response: """Persist the user's turn and hand back the pair of bubbles. The assistant bubble comes back empty, carrying the sse-connect attribute that opens the stream below. Splitting it this way means the POST returns immediately and the slow part is a separate, resumable connection. `force_tool` is `/image` and nothing else. It is checked against a fixed list rather than passed through: this ends up in `tool_choice`, and a name taken from a form would let anybody who can send a message pick which tool the model is compelled to call. Whether that tool is *offered* is still decided by `resolve_tools`, so this can only ever narrow to something the chat was already allowed. """ chat = _owned_chat(db, chat_id, user.id) content = content.strip() # "Here, look at this" with no words is a legitimate turn, so an empty # message is only empty when it carries nothing at all. if not content and not file_ids: return Response(status_code=status.HTTP_204_NO_CONTENT) forced = force_tool.strip() if force_tool.strip() in FORCEABLE_TOOLS else "" return _send(request, db, chat, user, content, file_ids=file_ids, force_tool=forced) def _reply_in_flight(db: DBSession, chat: Chat) -> bool: """Whether this chat already has a reply being written. The row is the authority, not the registry: a restart leaves an incomplete assistant message behind with no `Generation` anywhere, and that row is what starts the reply again on the next page load. The registry is consulted too, for the sliver in which a generation is still running and its row has already been written -- `_persist` sets `complete` before `_run` sets `done`. """ unfinished = db.scalar( select(Message).where(Message.chat_id == chat.id, Message.complete.is_(False)) ) return unfinished is not None or generation_service.running_for(chat.id) is not None def _note_rewind(chat: Chat) -> None: """Record that an agent chat's transcript went back and the machine did not. Deliberately no attempt to undo anything out there. The project directory is somebody's real working tree, and deleting their work to match a rewound transcript would be far worse than the inconsistency. So the model is told instead -- see the `tool.agent_rewound` fragment -- and can look rather than assume. """ if chat.kind == KIND_AGENT: chat.rewound_at = datetime.now(UTC) def _send( request: Request, db: Db, chat: Chat, user: User, content: str, *, file_ids: list[str] | None = None, force_tool: str = "", ) -> Response: """Write a turn, start the reply, and hand back the pair of bubbles. Shared by the composer and by anything else that puts words into a conversation on somebody's behalf -- carrying out a plan, for one. One path rather than two, so a second way of sending cannot drift from the first. If a reply is already being written, the turn is *queued* instead: written, shown, and not sent. Starting a second reply here is what used to happen, and it produced two generations answering the same chat from two different prefixes of it, with Stop pointing at whichever bubble came first in the document. """ if queued := _reply_in_flight(db, chat): waiting = db.scalar( select(func.count()) .select_from(Message) .where(Message.chat_id == chat.id, Message.queued.is_(True)) ) if waiting >= MAX_QUEUED: raise HTTPException( status.HTTP_409_CONFLICT, f"There are already {MAX_QUEUED} messages waiting to be sent.", ) user_message = chat_service.create_message(db, chat, ROLE_USER, content, queued=queued) if file_ids: files_service.claim(db, ids=file_ids, user_id=user.id, message_id=user_message.id) db.refresh(user_message) if queued: # One bubble and no assistant placeholder. The streaming shell is the # only thing that starts a generation, so a placeholder here would be a # second concurrent reply -- exactly what the queue exists to prevent. if (live := generation_service.running_for(chat.id)) is not None: # So a reply between two rounds of tool calls notices it, and so # anybody following sees the status change. live.touch() return templates.TemplateResponse( request, "chat/_message.html", { "request": request, "message": user_message, "chat": chat, "user": user, "models_by_id": { m.model_id: m for m in chat_service.available_models(db, user) }, **audio_service.template_flags(db, user), }, ) assistant_message = chat_service.create_message( db, chat, ROLE_ASSISTANT, "", complete_=False, model_id=chat.model_id ) generation_service.ensure(chat.id, assistant_message.id, force_tool=force_tool) # `user` is required by the shared message template, which renders both # roles; without it the user bubble's initial blows up. return templates.TemplateResponse( request, "chat/_turn.html", { "request": request, "user_message": user_message, "assistant_message": assistant_message, "chat": chat, "user": user, "models_by_id": { m.model_id: m for m in chat_service.available_models(db, user) }, **audio_service.template_flags(db, user), }, ) @router.get("/{chat_id}/messages/{message_id}/stream") async def stream_message( db: Db, user: RequiredUser, chat_id: str, message_id: str, ) -> Response: """Stream the assistant's reply as server-sent events. Emits `token` events carrying escaped text, then a single `done` event carrying the finished bubble rendered from Markdown, then `close`. """ chat = _owned_chat(db, chat_id, user.id) message = db.get(Message, message_id) if message is None or message.chat_id != chat.id: raise HTTPException(status.HTTP_404_NOT_FOUND, "That message no longer exists.") return StreamingResponse( _follow(chat.id, message.id), media_type="text/event-stream", headers={ "Cache-Control": "no-cache, no-transform", "Connection": "keep-alive", # nginx buffers proxied responses by default, which turns a stream # into one delivery at the end. This is the documented opt-out. "X-Accel-Buffering": "no", }, ) def _step_html(message_id: str, step) -> str: """One closed step of a running reply. `SimpleNamespace` for the message, as `_canvas_tabs` already does for the chat: the partial wants an id to build its element ids from and nothing else, and there is no `Message` in scope here -- the row is not written until the reply ends. `reasoning_ms` is only known then too, so a live step says "Thought" and the stored one says how long for. """ return templates.get_template("chat/_step.html").render( {"step": step, "message": SimpleNamespace(id=message_id, reasoning_ms=0)} ) def _think_label(generation, thinking_tail: str) -> str: """How long this round has been thinking, and roughly how much. This round's, not the reply's, so the live block means the same thing as the closed blocks above it and does not change meaning the moment it settles. The reply's total is already under the bubble, in the metrics chips. The producer owns the number. Computing it here from a start time would keep the clock running after the model had stopped thinking and moved on to a tool, which is a timer rather than a measurement. """ return steps_service.thinking_label( ms=generation.round_thinking_ms, tokens=tokens_service.estimate(thinking_tail), live=True, ) def _ask_html(chat_id: str, pending) -> str: """The card asking the reader something, or nothing at all. Returns "" when there is nothing pending, and the frame is sent unconditionally, because this is one of the few blocks that has to be able to *clear* itself: the card must vanish the moment it is answered. `reasoning`, `render` and `steps` are the opposite -- guarded by truthiness so a frame can never blank them. """ if pending is None: return "" return templates.get_template("chat/_interaction.html").render( # The sentinel the "Something else" row submits, passed in rather than # written into the template, so the value the card sends and the value # this module looks for cannot drift apart. {"ask": pending, "chat_id": chat_id, "other_value": interaction.OTHER} ) def _canvas_tabs(chat_id: str, state: dict) -> str: """The canvas tab strip, as an out-of-band swap. Out of band because it belongs to a panel, not to the bubble the stream is writing into -- the same move the `done` frame already makes for the chat title. Only the strip: pushing the file's contents on every version bump would be a lot of bytes for nothing, and would overwrite a textarea somebody is typing in. The active tab's body fetches itself once instead. """ return templates.get_template("chat/_canvas_tabs.html").render( { "chat": SimpleNamespace(id=chat_id), "tabs": state.get("tabs") or [], "active": state.get("active") or "", "oob": True, } ) async def _follow(chat_id: str, message_id: str) -> AsyncIterator[str]: """Stream a generation that is running independently of this request. This connection only *watches*. Closing it -- navigating away, opening another chat -- leaves the reply being written, and reconnecting replays the whole state immediately rather than starting over. Every frame carries the complete block each time rather than a delta, which is what makes reattaching mid-reply work at all: a follower arriving late has no earlier fragments to append to. The split is along **closed versus open**, not along kind. `steps` carries every step that has finished and moves only when a round ends; `reasoning` and `render` carry the step still being written and move at streaming speed. That is what makes this affordable: the old `tools` frame re-rendered every tool call in the reply twelve times a second, against an output budget of a megabyte, so a long agent reply spent most of its wall time re-rendering its own transcript. `rendered` below is a render cache and not a wire protocol -- it starts empty for every follower, so one attaching mid-reply still receives the whole prefix in its first frame. The order within one pass is load-bearing: `steps` before `reasoning` and `render`, because `steps` carries the containers those two are swapped into. htmx re-registers `sse-swap` on content it swaps in, which is the same property the approval card's buttons already rely on. """ generation = generation_service.ensure(chat_id, message_id) generation.followers += 1 seen = -1 last_frame = time.monotonic() last_metrics = 0.0 # The HTML of every step already rendered, and how many *marks* that covers. # Two counters and not one: a mark can produce up to three steps -- thinking, # prose, tools -- so the length of the list is not an index into the marks. rendered: list[str] = [] marks_done = 0 try: while True: if generation.version != seen: seen = generation.version if len(generation.steps) > marks_done: for step in steps_service.closed_from(generation, since=marks_done): rendered.append(_step_html(message_id, step)) marks_done = len(generation.steps) yield sse.event("steps", "".join(rendered)) # Sent every pass, empty included. That is what clears the tail # when a round closes and its contents become a step above -- # and it is safe precisely because these carry the open tail # only. The version that carried the whole reply had to be # guarded, or a frame could wipe the answer. thinking_tail, text_tail = steps_service.tail(generation) yield sse.event("reasoning", escape_text(thinking_tail)) yield sse.event("think", escape_text(_think_label(generation, thinking_tail))) yield sse.event("render", render_markdown(text_tail) if text_tail else "") if generation.canvas.get("tabs"): # Guarded on truthiness, which puts this in the # reasoning/tools/render group and not the # metrics/status/ask one. Those three are sent even when # empty *because* each has to be able to clear itself; this # one must never be able to, since an empty canvas frame # would close every tab somebody had open. The card that # could be pressed twice, with the sign reversed. # # The whole strip each time, not a delta, so a follower # attaching mid-reply gets every tab the reply has touched # rather than the ones that happened to arrive after it. yield sse.event("canvas", _canvas_tabs(chat_id, generation.canvas)) yield sse.event("metrics", _metrics_html(generation)) yield sse.event("status", escape_text(generation.status)) yield sse.event("ask", _ask_html(chat_id, generation.pending)) last_frame = last_metrics = time.monotonic() # On a clock as well as on a change, because the version does not # move while a tool runs -- there is no `touch()` inside # `_run_calls` -- and a five-minute build on the far side is exactly # when somebody looks at these numbers to see whether anything is # happening. The elapsed clock is advancing throughout, so tok/s has # to be allowed to fall; frozen chips beside a spinner read as a # hang. One small swap a second, and only while the reply is live. elif time.monotonic() - last_metrics > METRICS_INTERVAL: yield sse.event("metrics", _metrics_html(generation)) last_frame = last_metrics = time.monotonic() if generation.done: break # A reasoning model can think for a minute or more without emitting # anything, and an idle connection is what a proxy closes. The # comment frame keeps it open and is ignored by the browser. if time.monotonic() - last_frame > KEEPALIVE_AFTER: yield sse.KEEPALIVE last_frame = time.monotonic() # Polling rather than per-follower wakeups: the producer already # works in RENDER_INTERVAL steps, so a short sleep is simpler and # cannot drop a notification. await asyncio.sleep(generation_service.RENDER_INTERVAL * 0.8) finally: generation.followers = max(0, generation.followers - 1) # The producer commits the message before marking itself done, so by here # the row is authoritative and the final bubble can be rendered from it. with session_scope() as db: message = db.get(Message, message_id) chat = db.get(Chat, chat_id) if message is None or chat is None: yield sse.event("close", "") return owner = db.get(User, chat.user_id) final_html = templates.get_template("chat/_message.html").render( { "message": message, "chat": chat, # Passed even though an assistant bubble never reads it: the # template shares both roles, and a missing `user` would only # blow up on whichever branch is not being exercised here. "user": owner, "models_by_id": { m.model_id: m for m in chat_service.available_models(db, None) }, # This frame replaces the whole bubble, so it has to carry the # speaker button's conditions too -- and the owner's, not the # follower's: there is no request here to ask who is watching. **audio_service.template_flags(db, owner), # The one render that means "this reply just landed", which is # what read-aloud-automatically keys off. A page load must not # set it or reopening a chat would start talking. "just_finished": True, } ) title_html = templates.get_template("chat/_title_oob.html").render({"chat": chat}) # What the queue did while this reply was running. There is no push # channel that outlives one message's stream, and this is the last frame # that reaches the browser -- so it carries the rest out of band, the # way the chat title already does. moved_html, queue_html = _queue_frames(db, chat, owner, generation) yield sse.event("done", moved_html + final_html + queue_html + title_html) yield sse.event("close", "") def _render_bubble(db: DBSession, chat: Chat, owner: User | None, message: Message) -> str: """One finished bubble, rendered the way the `done` frame renders its own.""" return templates.get_template("chat/_message.html").render( { "message": message, "chat": chat, "user": owner, "models_by_id": {m.model_id: m for m in chat_service.available_models(db, None)}, **audio_service.template_flags(db, owner), } ) def _queue_frames( db: DBSession, chat: Chat, owner: User | None, generation ) -> tuple[str, str]: """The bubbles the queue produced during this reply, as out-of-band HTML. Two pieces, because they swap differently. Anything taken *into* this reply mid-round now sorts before it, so it is rendered ahead of the finished bubble in the same `outerHTML` swap and its stale node is deleted out of band -- one frame, and the DOM ends up in the order the database is in. Anything drained *after* the reply is a new pair appended to the thread. """ moved: list[str] = [] out_of_band: list[str] = [] for injected_id in generation.injected_ids: row = db.get(Message, injected_id) if row is None: continue moved.append(_render_bubble(db, chat, owner, row)) # Removed where it was; it is about to reappear above the reply. out_of_band.append(f'') if generation.drained: fresh = list( db.scalars( select(Message) .where(Message.chat_id == chat.id, Message.complete.is_(False)) .order_by(Message.created_at) ) ) for assistant in fresh: # The user turn that was waiting has just lost its Send now and # Discard, so it is re-rendered in place. delivered = db.scalars( select(Message) .where( Message.chat_id == chat.id, Message.role == ROLE_USER, Message.created_at <= assistant.created_at, ) .order_by(Message.created_at.desc()) .limit(1) ).first() if delivered is not None: out_of_band.append( f'