feat(webui): support custom background images (#6674)
This commit is contained in:
1 parent
92d23d2d2b
commit
e91906bc3a
29 files changed
+1259
-3
No files matched your search
@@ -0,0 +1,85 @@
|
||||
"""Instance-wide, sanitized WebUI background image."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import TypeGuard, cast
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
MAX_PIXELS = 32_000_000
|
||||
MAX_BYTES = 6 * 1024 * 1024
|
||||
FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG", "image/webp": "WEBP"}
|
||||
|
||||
|
||||
def save_background(directory: Path, source: Path | bytes, mime: str) -> None:
|
||||
"""Decode and re-encode a bounded static raster before atomic replacement."""
|
||||
if mime not in FORMATS or (source.stat().st_size if isinstance(source, Path) else len(source)) > MAX_BYTES:
|
||||
raise ValueError("Unsupported or oversized background")
|
||||
image_source = source if isinstance(source, Path) else io.BytesIO(source)
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(image_source) as image:
|
||||
if (image.format != FORMATS[mime] or image.width * image.height > MAX_PIXELS
|
||||
or getattr(image, "n_frames", 1) != 1):
|
||||
raise ValueError("Invalid background image")
|
||||
image.load()
|
||||
image = ImageOps.exif_transpose(image)
|
||||
clean = image.convert("RGBA" if "A" in image.getbands() or "transparency" in image.info else "RGB")
|
||||
out = io.BytesIO()
|
||||
clean.save(out, format="PNG")
|
||||
except (UnidentifiedImageError, OSError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
|
||||
raise ValueError("Invalid background image") from exc
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
fd, name = tempfile.mkstemp(prefix=".background-", dir=directory)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as file:
|
||||
file.write(out.getvalue())
|
||||
os.replace(name, directory / "background.png")
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _valid_blur(blur: object) -> TypeGuard[int]:
|
||||
return type(blur) is int and 0 <= blur <= 20
|
||||
|
||||
|
||||
def _valid_veil(veil: object) -> TypeGuard[int]:
|
||||
return type(veil) is int and 0 <= veil <= 100
|
||||
|
||||
|
||||
def load_background_style(directory: Path) -> dict[str, int]:
|
||||
"""Read current or legacy instance style, defaulting invalid fields."""
|
||||
default = {"blur": 5, "veil": 88}
|
||||
try:
|
||||
value = json.loads((directory / "background-style").read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, UnicodeDecodeError, ValueError):
|
||||
return default
|
||||
if not isinstance(value, dict):
|
||||
return default
|
||||
style = cast(dict[str, object], value)
|
||||
blur, veil = style.get("blur"), style.get("veil")
|
||||
return {
|
||||
"blur": blur if _valid_blur(blur) else default["blur"],
|
||||
"veil": veil if _valid_veil(veil) else default["veil"],
|
||||
}
|
||||
|
||||
|
||||
def save_background_style(directory: Path, blur: object, veil: object) -> None:
|
||||
"""Validate both values before atomically replacing the instance setting."""
|
||||
if not _valid_blur(blur) or not _valid_veil(veil):
|
||||
raise ValueError("Invalid background style")
|
||||
data = json.dumps({"blur": blur, "veil": veil}, separators=(",", ":")).encode("ascii")
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
fd, name = tempfile.mkstemp(prefix=".background-style-", dir=directory)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as file:
|
||||
file.write(data)
|
||||
os.replace(name, directory / "background-style")
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
@@ -18,6 +18,7 @@ from nanobot.channels.websocket.attachment_policy import validate_attachment_bat
|
||||
from nanobot.channels.websocket.attachment_store import AttachmentUploadError
|
||||
from nanobot.command.application import builtin_command_starts_agent_turn
|
||||
from nanobot.command.builtin import USER_SHELL_COMMAND
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.runtime_context import (
|
||||
RUNTIME_CONTEXT_INPUT_META,
|
||||
WEBUI_QUOTE_METADATA,
|
||||
@@ -36,6 +37,7 @@ from nanobot.session.webui_turns import (
|
||||
websocket_turn_id,
|
||||
websocket_turn_wall_started_at,
|
||||
)
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
from nanobot.utils.helpers import safe_filename
|
||||
from nanobot.utils.prompt_templates import render_template
|
||||
from nanobot.webui.attachments import inspect_local_attachment
|
||||
@@ -159,6 +161,8 @@ class WebUICommandRouter:
|
||||
] = {}
|
||||
self.request_operations: dict[str, WebUIRequestOperation] = {}
|
||||
self.request_locks: dict[ServerConnection, asyncio.Lock] = {}
|
||||
self._background_lock = asyncio.Lock()
|
||||
self._background_references: set[tuple[str, str]] = set()
|
||||
self._accepted_messages: dict[tuple[str, str], float] = {}
|
||||
self._message_locks: dict[tuple[str, str], tuple[asyncio.Lock, int]] = {}
|
||||
|
||||
@@ -755,6 +759,8 @@ class WebUICommandRouter:
|
||||
)
|
||||
for path in local_paths
|
||||
]
|
||||
if any((upload_owner, ref) in self._background_references for ref in references):
|
||||
raise AttachmentUploadError("Attachment is being used for a background")
|
||||
uploaded = self._uploads.store.inspect(references, owner=upload_owner) if references else []
|
||||
validate_attachment_batch(
|
||||
[item["mime"] for item in local] + [item.mime for item in uploaded],
|
||||
@@ -1157,6 +1163,55 @@ class WebUICommandRouter:
|
||||
try:
|
||||
lock = self.request_locks.setdefault(connection, asyncio.Lock())
|
||||
async with lock:
|
||||
if action in {"background.update", "background.delete", "background.style"}:
|
||||
from nanobot.webui.background import (
|
||||
MAX_BYTES,
|
||||
save_background,
|
||||
save_background_style,
|
||||
)
|
||||
|
||||
async def mutate_background() -> WebUIRequestResult:
|
||||
try:
|
||||
with self._http_router.bus.admission.activity():
|
||||
directory = self._http_router.settings.config.path.parent / "webui"
|
||||
if action == "background.delete":
|
||||
await asyncio.to_thread((directory / "background.png").unlink, missing_ok=True)
|
||||
elif action == "background.style":
|
||||
try:
|
||||
await asyncio.to_thread(save_background_style, directory, payload.get("blur"), payload.get("veil"))
|
||||
except ValueError as exc:
|
||||
return WebUIRequestResult(status=400, message=str(exc))
|
||||
else:
|
||||
reference = payload.get("reference")
|
||||
if not isinstance(reference, str):
|
||||
return WebUIRequestResult(status=400, message="Invalid attachment reference")
|
||||
owner = self._uploads.owner(connection)
|
||||
try:
|
||||
entry = self._uploads.store.inspect([reference], owner=owner)[0]
|
||||
# Snapshot a bounded staged file before yielding so disconnect cleanup
|
||||
# never unlinks an open source handle on Windows.
|
||||
with entry.path.open("rb") as source:
|
||||
data = source.read(MAX_BYTES + 1)
|
||||
key = (owner, reference)
|
||||
self._background_references.add(key)
|
||||
try:
|
||||
await asyncio.to_thread(save_background, directory, data, entry.mime)
|
||||
finally:
|
||||
self._background_references.discard(key)
|
||||
self._uploads.store.discard([reference], owner=owner)
|
||||
except (AttachmentUploadError, ValueError) as exc:
|
||||
return WebUIRequestResult(status=400, message=str(exc))
|
||||
return WebUIRequestResult(result={"ok": True})
|
||||
except RuntimeMaintenanceError:
|
||||
return WebUIRequestResult(status=503, message="Gateway update is being verified. Retry shortly.")
|
||||
except Exception:
|
||||
# shield_and_drain gives cancellation precedence; retain an
|
||||
# observable failure even when its caller was cancelled.
|
||||
logger.exception("Background mutation '{}' failed", action)
|
||||
raise
|
||||
|
||||
async with self._background_lock:
|
||||
return await shield_and_drain(mutate_background())
|
||||
response = await self._http_router.dispatch_webui_mutation(
|
||||
connection,
|
||||
action,
|
||||
|
||||
@@ -621,6 +621,26 @@ class GatewayHTTPHandler:
|
||||
request: WsRequest,
|
||||
got: str,
|
||||
) -> Any | None:
|
||||
if got == "/api/settings/background-style":
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
from nanobot.webui.background import load_background_style
|
||||
|
||||
directory = self.settings.config.path.parent / "webui"
|
||||
return _http_json_response(
|
||||
load_background_style(directory), extra_headers=_NO_STORE_HEADERS,
|
||||
)
|
||||
if got == "/api/settings/background":
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
path = self.settings.config.path.parent / "webui" / "background.png"
|
||||
try:
|
||||
body = path.read_bytes()
|
||||
except FileNotFoundError:
|
||||
return _http_error(404, "Background not found")
|
||||
return _http_response(body, content_type="image/png", extra_headers=[
|
||||
("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff"),
|
||||
])
|
||||
if got == "/api/remote-instances" or got.startswith("/api/remote-instances/"):
|
||||
return await self._dispatch_remote_instances(connection, request, got)
|
||||
if self.config.token_issue_path:
|
||||
|
||||
Reference in new issue
Block a user