5e75948069
The last unbuilt capability, and built the way CLAUDE.md said it had to be: a
ToolDef reaching resolve_tools plus a permission and a capability flag, not a new
code path. The only genuinely new UI is one branch in the transcript.
services/images/ is three modules. comfy.py speaks HTTP -- submit, poll /history,
fetch the PNG, /free, and an /object_info discovery for the admin page only.
Polled and not socketed, because holding a connection open for the length of a
generation is the live-connection state the whole ssh.py design forbids, and the
thing being waited for takes tens of seconds anyway. The base URL is exempt from
the SSRF guard by construction, exactly as Connection.base_url and the audio
endpoints are -- said out loud in the docstring, because a default of
127.0.0.1:8188 is precisely the shape that guard exists to refuse and therefore
reads as a hole rather than a decision.
workflow.py fills a template, and the one thing that matters is that it walks the
parsed JSON rather than the text of it. A value that is exactly "{{steps}}"
becomes the number 20; ComfyUI validates types and refuses the string. A
placeholder inside a longer string is still text, which is what makes
"{{prompt}}, masterpiece" work -- and text substitution would additionally mean a
prompt containing a quotation mark produced a document that no longer parses, on
the one input guaranteed to hold arbitrary text. Which node holds the prompt is
the administrator's statement rather than a guess from node types: sniffing for
the first CLIPTextEncode works on the shipped workflow and on nothing else, and
swaps positive for negative the first time somebody reorders them. seed has no
fixed default, because one would make every unspecified generation identical and
make the retry loop redraw the same rejected picture four times.
tool.py is one call, one finished image. Returning every attempt to the
conversation would cost a round each, make the ceiling advisory rather than
enforced, and walk the reader past every reject -- so the reviewer lives inside
the tool and is asked about *bytes*: an attempt about to be discarded should not
leave an Attachment behind, so it sees a downscaled preview built in memory and
only the kept image is written. Anything that goes wrong in review is a keep;
losing a picture because a judging request timed out would be the check
destroying the thing it was checking. The last attempt is kept whatever the
verdict, so a request always produces something. Rejects are recorded, not
stored.
Preserve VRAM unloads the chat's own connection and nothing else, because the
memory being freed belongs to one machine: local llama-swap answers GET /unload,
and a box on the network has no reason to be unloaded when ComfyUI wants memory
here. The swap goes round the review rather than round the tool, which costs two
model loads per retry -- so the two settings are independent and the page warns
when both are on. Nothing loads the LLM back: the reply's next request does, and
that step exists in the description and not in the code, so the code says so.
Two rules elsewhere had to be drawn for the first time. message_payload sends
images only on user turns -- no assistant message had ever carried one, and the
moment one does the multimodal list form on an assistant turn is rejected by
OpenAI and most local runners, breaking every later turn in the chat. And
files.store gained keep_original, because _process_image turns anything without
alpha into JPEG q85 at 1400px: right for a phone photo, a visible loss on the one
output this feature exists to produce.
/image sends the ordinary message with force_tool, which becomes tool_choice for
the first round only -- left in place the reply would draw a picture, be asked
again, and draw another. FORCEABLE_TOOLS is an allow list because the name is
read off a form.
ToolContext gained chat_id, and that fixed a tool nobody had ever successfully
run: _run_scratch_write read context.chat_id on a dataclass with no such field,
so every call raised AttributeError, swallowed by run_tool's blanket except into
"the scratch_write tool failed" -- indistinguishable from a model calling it
wrongly. The test that existed asserted the family and the risk, which are
properties of the declaration rather than of the code.
Verified against the real ComfyUI 0.27.0 on this machine rather than against
documentation: every endpoint shape here was read off it, a generation ran end to
end through the client, the reviewer was shown a matching and a mismatched prompt
and answered KEEP and RETRY correctly, and the unload hook fired for the local
llama-swap and not for the remote box.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
215 lines
7.8 KiB
Python
215 lines
7.8 KiB
Python
"""Application factory, lifespan and error handling."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from collections.abc import AsyncIterator
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, Request, status
|
|
from fastapi.responses import JSONResponse, Response
|
|
from fastapi.staticfiles import StaticFiles
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from lembas import __version__
|
|
from lembas.api import (
|
|
admin,
|
|
admin_agents,
|
|
admin_audio,
|
|
admin_images,
|
|
admin_models,
|
|
admin_prompts,
|
|
admin_search,
|
|
admin_suggestions,
|
|
admin_tools,
|
|
admin_users,
|
|
agents,
|
|
audio,
|
|
auth,
|
|
canvas,
|
|
chats,
|
|
files,
|
|
folders,
|
|
library,
|
|
pages,
|
|
preferences,
|
|
terminal,
|
|
)
|
|
from lembas.api.deps import RedirectToLogin, is_htmx, login_redirect
|
|
from lembas.config import settings
|
|
from lembas.db.session import init_db
|
|
from lembas.web.templating import STATIC_DIR, render
|
|
|
|
log = logging.getLogger("lembas")
|
|
|
|
|
|
def configure_logging() -> None:
|
|
logging.basicConfig(
|
|
level=settings.log_level.upper(),
|
|
format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
|
|
datefmt="%H:%M:%S",
|
|
)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
configure_logging()
|
|
settings.ensure_dirs()
|
|
init_db()
|
|
|
|
if settings.secret_key_is_ephemeral:
|
|
log.warning(
|
|
"No LEMBAS_SECRET_KEY set, so a temporary one was generated. Every "
|
|
"restart will sign all users out and make stored API keys "
|
|
"unreadable. Generate a permanent key with:\n"
|
|
' python -c "import secrets; print(secrets.token_urlsafe(48))"'
|
|
)
|
|
|
|
# Files chosen in a composer that was never sent would otherwise sit on
|
|
# disk forever. Cheap, and startup is the natural moment for it.
|
|
try:
|
|
from lembas.db.session import session_scope
|
|
from lembas.services.chat import sweep_temporary
|
|
from lembas.services.files import sweep_orphans
|
|
from lembas.services.library.documents import sweep_unfiled
|
|
from lembas.services.suggestions import seed_defaults as seed_suggestions
|
|
|
|
with session_scope() as db:
|
|
sweep_orphans(db)
|
|
# Documents that predate knowledge bases have nowhere to live until
|
|
# this runs; see services/library/documents.py.
|
|
sweep_unfiled(db)
|
|
# Temporary chats older than a day. Startup only, like the sweeps
|
|
# above it -- see services/chat.py:sweep_temporary.
|
|
sweep_temporary(db)
|
|
# Three starting points on the empty screen, written once ever.
|
|
seed_suggestions(db)
|
|
except Exception: # noqa: BLE001 - housekeeping must never block startup
|
|
log.exception("orphaned upload sweep failed")
|
|
|
|
# Background jobs that were still running when we last stopped keep running
|
|
# on their own hosts; pick their watchers back up so the model is still
|
|
# woken when they finish. Best-effort, and inside the loop so its tasks land
|
|
# in this event loop.
|
|
try:
|
|
from lembas.services.agent.jobs import rehydrate as rehydrate_jobs
|
|
|
|
rehydrate_jobs()
|
|
except Exception: # noqa: BLE001 - a job that cannot be rehydrated is not fatal
|
|
log.exception("could not rehydrate background jobs")
|
|
|
|
log.info("LLeMbas %s starting on http://%s:%s", __version__, settings.host, settings.port)
|
|
log.info("data directory: %s", settings.data_dir.resolve())
|
|
yield
|
|
|
|
# Replies still being written are cancelled and persisted with whatever
|
|
# they have, rather than left as permanently unfinished rows.
|
|
from lembas.services.agent.jobs import shutdown as stop_jobs
|
|
from lembas.services.agent.terminal import shutdown as stop_terminals
|
|
from lembas.services.generation import shutdown as stop_generations
|
|
|
|
await stop_generations()
|
|
# Open shells have nothing to persist: whatever was running on the far side
|
|
# is cut off mid-command. Every deploy does this, and the panel is told why
|
|
# rather than left to guess -- see deploy/README.md.
|
|
await stop_terminals()
|
|
# Background jobs are the exception: cancelling a watcher does NOT stop the
|
|
# detached remote job, which keeps running and is rehydrated on the next
|
|
# start. Only the watching stops here.
|
|
await stop_jobs()
|
|
log.info("LLeMbas stopped")
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
app = FastAPI(
|
|
title="LLeMbas",
|
|
version=__version__,
|
|
lifespan=lifespan,
|
|
# The API is an implementation detail of the UI, not a product surface.
|
|
docs_url="/api/docs" if settings.log_level == "debug" else None,
|
|
redoc_url=None,
|
|
)
|
|
|
|
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
|
|
|
app.include_router(pages.router)
|
|
app.include_router(auth.router)
|
|
app.include_router(preferences.router)
|
|
app.include_router(chats.router)
|
|
app.include_router(canvas.router)
|
|
app.include_router(terminal.router)
|
|
app.include_router(audio.router)
|
|
app.include_router(files.router)
|
|
app.include_router(folders.router)
|
|
app.include_router(library.router)
|
|
app.include_router(agents.router)
|
|
app.include_router(admin.router)
|
|
app.include_router(admin_users.router)
|
|
app.include_router(admin_models.router)
|
|
app.include_router(admin_audio.router)
|
|
app.include_router(admin_search.router)
|
|
app.include_router(admin_images.router)
|
|
app.include_router(admin_prompts.router)
|
|
app.include_router(admin_suggestions.router)
|
|
app.include_router(admin_tools.router)
|
|
app.include_router(admin_agents.router)
|
|
|
|
register_error_handlers(app)
|
|
return app
|
|
|
|
|
|
def register_error_handlers(app: FastAPI) -> None:
|
|
@app.exception_handler(RedirectToLogin)
|
|
async def _not_signed_in(request: Request, exc: RedirectToLogin) -> Response:
|
|
# An htmx request must not swap a login page into a fragment of the
|
|
# chat UI, so tell the browser to navigate instead.
|
|
if is_htmx(request):
|
|
response = Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
response.headers["HX-Redirect"] = "/auth/login"
|
|
return response
|
|
return login_redirect(exc.next_url)
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def _http_error(request: Request, exc: StarletteHTTPException) -> Response:
|
|
# JSON callers and htmx fragments want the bare status; humans loading a
|
|
# page want a themed page they can navigate away from.
|
|
wants_page = "text/html" in request.headers.get("accept", "") and not is_htmx(request)
|
|
if not wants_page:
|
|
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
|
|
|
|
return render(
|
|
request,
|
|
"error.html",
|
|
{
|
|
"status_code": exc.status_code,
|
|
"detail": exc.detail,
|
|
"flavour": ERROR_FLAVOUR.get(exc.status_code, ERROR_FLAVOUR[500]),
|
|
},
|
|
status_code=exc.status_code,
|
|
)
|
|
|
|
@app.exception_handler(Exception)
|
|
async def _unhandled(request: Request, exc: Exception) -> Response:
|
|
log.exception("unhandled error at %s", request.url.path)
|
|
if is_htmx(request) or "text/html" not in request.headers.get("accept", ""):
|
|
return JSONResponse({"detail": "Internal server error"}, status_code=500)
|
|
return render(
|
|
request,
|
|
"error.html",
|
|
{"status_code": 500, "detail": "Something went wrong.",
|
|
"flavour": ERROR_FLAVOUR[500]},
|
|
status_code=500,
|
|
)
|
|
|
|
|
|
# Flavour lives in error pages, empty states and theme names -- never in the
|
|
# functional UI. See CLAUDE.md.
|
|
ERROR_FLAVOUR = {
|
|
403: "Speak, friend, and enter. This door is not yours to open.",
|
|
404: "Not all those who wander are lost. This page, however, is.",
|
|
500: "The Road goes ever on, but this stretch of it has washed out.",
|
|
}
|
|
|
|
|
|
app = create_app()
|