""" title: Theme Designer Pro description: Instance-wide theme designer for Open WebUI. Replaces the built-in dark, light, OLED, and her modes with fully custom themes for all users. Registers an interactive UI at /api/v1/theme-designer and persists themes server-side, publishing them through the Shared Assets Protocol so every user sees the admin's theme from the first paint. author: @G30 author_url: https://openwebui.com/u/g30 funding_url: https://buymeacoffee.com/iamg30 version: 1.8.5 license: MIT required_open_webui_version: 0.11.0 """ import hashlib import json as _json import logging import os import re as _re import socket import asyncio from pathlib import Path from typing import Any, Literal from pydantic import BaseModel, Field VERSION = "1.8.5" ROUTE_PATH = "/api/v1/theme-designer" CSS_FILE_NAME = "open_theme_designer.css" log = logging.getLogger(__name__) import asyncio import logging import uuid from typing import Any, Optional from open_webui.utils.json_codec import JSONCodec ASSET_KEY = "theme-designer-pro" # fixed, used for asset_register too # =========================================================================== # Live reload broadcast # --------------------------------------------------------------------------- # Each load publishes over Redis; a peer whose cached code differs from the # database re-executes it. register(app) is yours and must be idempotent; gate # each producer on reload_active(app). # =========================================================================== RELOAD_STATE_ATTR = "_owui_live_reload" # {key: {active, exec_id, listener}} RELOAD_EXEC_ID = uuid.uuid4().hex # new on every exec of this source # Open WebUI executes each function as module "function_". RELOAD_FUNCTION_ID = __name__.removeprefix("function_") reload_log = logging.getLogger("owui-live-reload") # asyncio only keeps weak references to tasks. reload_tasks: set = set() def reload_state(app: Any) -> dict: registry = getattr(app.state, RELOAD_STATE_ATTR, None) if not isinstance(registry, dict): registry = {} app.state.__setattr__(RELOAD_STATE_ATTR, registry) return registry.setdefault(ASSET_KEY, {}) def reload_active(app: Any) -> bool: return bool(reload_state(app).get("active")) def reload_channel() -> str: from open_webui.env import REDIS_KEY_PREFIX return f"{REDIS_KEY_PREFIX}:live-reload:{ASSET_KEY}" def reload_mark_loaded(app: Any) -> None: register(app) state = reload_state(app) state["active"] = True state["exec_id"] = RELOAD_EXEC_ID async def reload_publish(app: Any, active: bool) -> None: redis = getattr(app.state, "redis", None) if redis is None: return try: await redis.publish(reload_channel(), JSONCodec.dumps({"active": active})) except Exception as e: reload_log.warning("[%s] publish failed: %s", ASSET_KEY, type(e).__name__) async def reload_ensure_listener(app: Any) -> None: state = reload_state(app) if state.get("listener") is not None: return redis = getattr(app.state, "redis", None) if redis is None: return from types import SimpleNamespace from open_webui.models.functions import Functions from open_webui.utils.plugin import ( get_function_module_from_cache, get_functions_cache, ) # Mark before awaiting so a concurrent event() can't double-subscribe. state["listener"] = True try: pubsub = redis.pubsub() await pubsub.subscribe(reload_channel()) except Exception as e: state["listener"] = None reload_log.warning("[%s] subscribe failed: %s", ASSET_KEY, type(e).__name__) return async def listen(): try: async for message in pubsub.listen(): if message.get("type") != "message": continue if not JSONCodec.loads(message["data"])["active"]: state["active"] = False continue was_active = state.get("active") # Enable broadcasts arrive before is_active commits; bootstrap trusts this flag. state["active"] = True context = SimpleNamespace(app=app) if not was_active: # Force a fresh exec so its bootstrap registers again. get_functions_cache(context).pop(RELOAD_FUNCTION_ID, None) try: function_module, _, _ = await get_function_module_from_cache( context, RELOAD_FUNCTION_ID ) # Peers never see a valves save; re-read them like Open WebUI's dispatch does. if hasattr(function_module, "Valves"): valves = await Functions.get_function_valves_by_id( RELOAD_FUNCTION_ID ) function_module.valves = function_module.Valves( **(valves or {}) ) except Exception as e: reload_log.warning( "[%s] reload from db failed: %s", ASSET_KEY, type(e).__name__ ) except Exception as e: reload_log.warning("[%s] listener stopped: %s", ASSET_KEY, type(e).__name__) state["listener"] = asyncio.create_task(listen()) def reload_bootstrap() -> None: try: loop = asyncio.get_running_loop() except RuntimeError: return async def bootstrap(): try: from open_webui.main import app from open_webui.models.functions import Functions own = await Functions.get_function_by_id(RELOAD_FUNCTION_ID) # Loading a disabled function (e.g. for its valves) must not switch it on. if own is None or not (own.is_active or reload_active(app)): return reload_mark_loaded(app) await reload_ensure_listener(app) await reload_publish(app, True) except Exception as e: reload_log.warning("[%s] bootstrap failed: %s", ASSET_KEY, type(e).__name__) task = loop.create_task(bootstrap()) reload_tasks.add(task) task.add_done_callback(reload_tasks.discard) async def reload_on_event( app: Any, event: Optional[dict], event_name: Optional[str] ) -> None: await reload_ensure_listener(app) state = reload_state(app) is_own = ((event or {}).get("subject") or {}).get("id") == RELOAD_FUNCTION_ID if is_own and event_name == "function.disable_started": state["active"] = False await reload_publish(app, False) return if is_own and event_name == "function.valves_updated": await reload_publish(app, True) current = state.get("active") and state.get("exec_id") == RELOAD_EXEC_ID if current and event_name != "system.startup.completed": return reload_mark_loaded(app) await reload_publish(app, True) # =========================== end live reload block ========================= import hashlib from pathlib import Path from typing import Any # =========================================================================== # Shared static-asset registry # --- KEEP BYTE-IDENTICAL IN EVERY PLUGIN THAT USES IT ---------------------- # --------------------------------------------------------------------------- # Each plugin publishes a fragment into one app.state registry and the route # composes them per request, so load order is irrelevant. Per-process: each # container serves what it has loaded. # # Contract: # * ASSET_REGISTRY_ATTR, ASSET_ROUTE_ATTR, the entry shape and the paths are # the interop surface. The route owner's copy serves everyone. # * `key` must be a module-level constant, or a re-exec adds a second entry. # * Lower `order` composes first (default 0). Never encode priority in the key. # * Producers run on the event loop for every request, 304s included: return # a prebuilt string, no I/O, no locks. # * Return "" to withdraw. A deleted plugin never sees its own deletion, so # disable it first. # * Inline fragments only: """ def __init__(self): self.valves = self.Valves() Event.instance = self reload_bootstrap() def _valves_snapshot(self): """A hashable, order-stable snapshot of every valve value. Used to detect that ANY valve changed — the existing per-valve flags only cover the three that alter a live SSE broadcast, but nearly every valve changes the composed loader.js (it embeds the whole config), so a peer worker has to re-read on any of them. """ v = self.valves data = v.model_dump() if hasattr(v, "model_dump") else v.dict() return tuple(sorted(data.items())) # -- URL validation ------------------------------------------------------- def _get_route_base(self) -> str: """Return the validated designer URL, auto-correcting if needed.""" route = self.valves.designer_url.rstrip("/") # Sanitize: only allow alphanumeric, hyphens, underscores, slashes, and dots route = _re.sub(r'[^a-zA-Z0-9/_.-]', '', route) if not route.startswith("/api/v1/"): corrected = "/api/v1" + (route if route.startswith("/") else "/" + route) log.warning( "[Theme Pro] designer_url '%s' is outside /api/v1/ — " "auto-correcting to '%s' (SPA catch-all intercepts non-API routes)", route, corrected, ) return corrected return route # -- bootloader management ----------------------------------------------- def _strip_bootloader(self, content: str) -> str: """Remove ALL existing bootloader instances from content string. Uses a while loop (not if) so that accumulated duplicates — e.g. from previous bugs or interrupted writes — are fully stripped before re-injection. """ start_marker = "" end_marker = "" while start_marker in content: start_idx = content.find(start_marker) end_idx = content.find(end_marker, start_idx) if end_idx == -1: break end_idx += len(end_marker) if end_idx < len(content) and content[end_idx] == "\n": end_idx += 1 content = content[:start_idx] + content[end_idx:] return content @staticmethod def _strip_all_theme_blocks(content: str) -> str: """Strip all server theme CSS and state JSON blocks from HTML content.""" markers = [ (''), (''), ] for start_marker, end_marker in markers: while start_marker in content: start = content.find(start_marker) end = content.find(end_marker, start) if end == -1: break end += len(end_marker) if end < len(content) and content[end] == "\n": end += 1 content = content[:start] + content[end:] return content # Cached result of _find_index_file() — index.html path never changes at runtime _cached_index_path = None def _find_index_file(self): """Find the frontend index.html served by SPAStaticFiles.""" if Event._cached_index_path is not None: return Event._cached_index_path try: from open_webui.env import FRONTEND_BUILD_DIR idx = Path(FRONTEND_BUILD_DIR) / "index.html" if idx.exists(): Event._cached_index_path = str(idx) return Event._cached_index_path except ImportError: pass # Fallback: guess common paths fallbacks = [ "/app/backend/open_webui/frontend/index.html", "/app/build/index.html", "../build/index.html", "./build/index.html", ] for path in fallbacks: if os.path.exists(path): Event._cached_index_path = path return Event._cached_index_path return None # File-based lock to serialize all index.html read-modify-write operations # across processes/workers. threading.Lock only protects within a single process, # but Open WebUI fires event() from multiple concurrent contexts during startup. _index_lock_path = None # Set lazily on first use @classmethod def _get_index_lock(cls): """Return a context manager that acquires an exclusive file lock.""" import fcntl from contextlib import contextmanager @contextmanager def _flock(): if cls._index_lock_path is None: try: from open_webui.env import DATA_DIR cls._index_lock_path = Path(DATA_DIR) / "theme" / ".index.lock" except ImportError: cls._index_lock_path = Path("/tmp/.owui_index.lock") cls._index_lock_path.parent.mkdir(parents=True, exist_ok=True) fd = open(cls._index_lock_path, "w") try: fcntl.flock(fd, fcntl.LOCK_EX) yield finally: fcntl.flock(fd, fcntl.LOCK_UN) fd.close() return _flock() @staticmethod def _atomic_write(path, content): """Atomically write content to path via tempfile + os.replace.""" import tempfile as _tmpf _fd, _tmp = _tmpf.mkstemp(dir=os.path.dirname(path), suffix='.tmp') try: with os.fdopen(_fd, 'w', encoding='utf-8') as f: f.write(content) os.replace(_tmp, path) except BaseException: try: os.unlink(_tmp) except OSError: pass raise # -- shared static-asset fragments --------------------------------------- # Marker pairs wrapping this plugin's block inside each composed asset, so # asset_compose can strip a previous build's block before re-appending. LOADER_BLOCK_START = "// owui-theme-designer-pro:start" LOADER_BLOCK_END = "// owui-theme-designer-pro:end" CSS_BLOCK_START = "/* owui-theme-designer-pro:start */" CSS_BLOCK_END = "/* owui-theme-designer-pro:end */" # Fixed literal, never derived from a build/function id — the shared-asset # contract requires a stable key, because a key that changes per re-exec # registers a SECOND entry and the output is emitted twice. ASSET_KEY = "theme-designer-pro" # asset_compose sorts fragments by (order, key); higher composes last. On # custom.css that is the CSS cascade between plugins, and this plugin's # custom-CSS section is documented as last = highest priority (Section 13), # so it claims a high order explicitly rather than relying on where # "theme-designer-pro" happens to fall alphabetically. On loader.js the # same value makes this bootloader the outermost wrapper. ASSET_ORDER = 100 @staticmethod def _strip_canvas_scripts(state_str: str) -> str: """Drop only the canvasScript bodies from a delivered state JSON string. Measured on the largest Canvas FX script in the presets repo across four modes, the scripts are 93% of the inlined state (129 KB of 139 KB) and would make the loader fragment ~205 KB. asset_compose rebuilds and md5-hashes the entire composed body on EVERY request — the ETag is compared only after the producer has already run, so a 304 revalidation costs almost exactly as much server CPU as a 200 (measured: 3.87 ms vs 4.08 ms per request). Inlining the scripts would therefore charge every page load of every user for a background animation that nobody can perceive starting one round trip later. Nothing flash-sensitive is lost. enforceTheme() reads CSS, not state, and that CSS arrives via the render-blocking /static/custom.css. _cssSections stays inlined (9 KB) because the auth page assembles its CSS from it before the fetch lands. initCanvas() simply finds no script on its first pass and starts the canvas when /state.json arrives. """ try: data = _json.loads(state_str) if not isinstance(data, dict): return state_str stripped = False for config in data.values(): # _cssSections is a sibling of the mode dicts and has no # canvasScript, so it falls through untouched. if isinstance(config, dict) and config.get("canvasScript"): config.pop("canvasScript", None) stripped = True if not stripped: return state_str return _json.dumps(data, separators=(",", ":")) except Exception: return state_str # Unparseable state is served as-is by design _bootloader_body_cache = None @classmethod def _bootloader_body(cls) -> str: """BOOTLOADER_SCRIPT with its HTML comment + \s*$", "", cls.BOOTLOADER_SCRIPT.strip(), flags=_re.DOTALL, ) return cls._bootloader_body_cache def _loader_fragment(self, active: bool) -> str: """Producer for the /static/loader.js fragment. Runs inside the request handler on every page load, so the whole result is memoised and the steady state is a tuple compare. The two stat()s behind _get_state_delivery are the only syscalls; its ETag stands in for the state and sections mtimes plus the valves that affect delivery. Stays published while the function is disabled, with __THEME_ACTIVE__ false: the bootloader strips the theme from a fresh load but keeps the SSE connection, which is how a later re-enable reaches open tabs. The CSS fragment is what goes empty on disable. """ delivery = self._get_state_delivery() if active else None cache_key = ( active, self._get_route_base(), self.valves.enable_canvas_api_access, delivery[1] if delivery else None, # state delivery ETag ) cached = Event._loader_fragment_cache if cached and cached[0] == cache_key: return cached[1] js = self._bootloader_body().replace( "__THEME_ROUTE__", cache_key[1] ).replace( "__CANVAS_API_ACCESS__", "true" if self.valves.enable_canvas_api_access else "false", ).replace( "__THEME_ACTIVE__", "true" if active else "false", ) # State inlined as a JS string literal, minus the canvas scripts. Was a # """ # Same substitutions as _loader_fragment, minus the embedded state: # the designer page manages its own state directly (the bootloader's # fetch/state path is gated on !window.__THEME_DESIGNER__), so the # placeholder resolves to null rather than shipping a second copy. route_base = self._get_route_base() bootloader_js = self._bootloader_body().replace( "__THEME_ROUTE__", route_base ).replace( "__CANVAS_API_ACCESS__", "true" if self.valves.enable_canvas_api_access else "false", ).replace( "__THEME_ACTIVE__", "true", ).replace( "__EMBEDDED_STATE__", "null", ) valve_config = { "enableCanvasFx": self.valves.enable_canvas_fx, "enableCanvasApiAccess": self.valves.enable_canvas_api_access, "enableUrlImport": self.valves.enable_url_import, "allowedImportDomains": [ d.strip() for d in self.valves.allowed_import_domains.split(",") if d.strip() ], "enableCustomCss": self.valves.enable_custom_css, "enableAuthPageTheming": self.valves.enable_auth_page_theming, "enableGradientBuilder": self.valves.enable_gradient_builder, "enableCommunityThemes": self.valves.enable_community_themes, "draftModeDefault": self.valves.draft_mode_default, "autoSync": self.valves.auto_sync, "sidebarTransparency": self.valves.sidebar_transparency, "overlayTransparency": self.valves.overlay_transparency, } safe_config = _json.dumps(valve_config).replace("' f"window.__THEME_PRO_CONFIG__={safe_config};" f"window.__THEME_PRO_SAVED_STATE__={safe_saved_state};" "" ) # --- Generate templated HTML fragments --- def _metadata_grid(prefix, fields): """Generate a metadata-grid with the given ID prefix.""" html = '
\n' for fid, label, placeholder, full_width in fields: style = ' style="grid-column: 1 / -1;"' if full_width else '' html += f' \n' html += '
' return html # Shared field definitions (fid_suffix, label, placeholder, full_width) _shared_meta = [ ('desc-input', 'Description', 'A short description', False), ('author-input', 'Author', 'Your name', False), ('version-input', 'Theme Version', '1.0.0', False), ('target-input', 'Target WebUI Version', '0.9.0', False), ('repo-input', 'Repository URL', 'https://github.com/...', False), ('update-input', 'Theme Update URL', 'https://...', True), ] save_meta = _metadata_grid('theme', [ ('name-input', 'Name', 'My Custom Theme', False), ] + _shared_meta) rename_meta = _metadata_grid('rename', [ ('input', 'Name', 'Theme Name', False), ] + _shared_meta) # Sync option blocks _sync_opts = [ ('palette', 'OKLCH Palette', 'L, C, H base color values'), ('overrides', 'Variable Overrides', 'Manual 50-950 ramp steps & locks'), ('css', 'Custom CSS Snippet', 'All raw styles from Custom CSS tab'), ('canvas', 'Canvas FX Script', 'Background animation code & state'), ('gradient', 'Gradient Background', 'Color stops, direction, type & animation'), ('auth', 'Auth Page Visibility', "'Show on Auth Pages' toggles for all tabs"), ] sync_html = '\n\n'.join( f'
\n' f' \n' f' \n' f' \n' f'
\n' f' ' for key, label, desc in _sync_opts ) # JSON editor modals def _json_modal(modal_id, lang_label, textarea_id, readonly, badge_id, collapse_id, close_id, close_tooltip, buttons=None): ro = ' readonly' if readonly else '' html = ( f' ' return html json_modals = '\n\n'.join([ _json_modal('json-view-modal', 'json', 'json-view-textarea', True, 'json-valid-badge', 'json-collapse-btn', 'json-close-btn', 'Close JSON Viewer'), _json_modal('snapshot-json-edit-modal', 'json \u2014 Manual Snapshot Editor', 'snapshot-json-edit-textarea', False, 'snapshot-json-valid-badge', 'snapshot-json-collapse-btn', 'snapshot-json-cancel-btn', 'Close without saving', [('snapshot-json-discard-btn', 'Cancel', 'btn'), ('snapshot-json-save-btn', 'Save Changes', 'btn btn-primary')]), _json_modal('save-json-edit-modal', 'json \u2014 New Theme Editor', 'save-json-edit-textarea', False, 'save-json-valid-badge', 'save-json-collapse-btn', 'save-json-cancel-btn', 'Close without saving', [('save-json-discard-btn', 'Cancel', 'btn'), ('save-json-save-btn', 'Save as New Theme', 'btn btn-primary')]), ]) final_html = ( html_content.replace("{VERSION}", VERSION) .replace("{BOOTLOADER_SRC}", bootloader_js) .replace("{ROUTE_BASE}", route_base) .replace("{SAVE_METADATA_GRID}", save_meta) .replace("{RENAME_METADATA_GRID}", rename_meta) .replace("{SYNC_OPTIONS}", sync_html) .replace("{JSON_EDITOR_MODALS}", json_modals) .replace("", config_tag + "") .strip() ) return final_html # -- entry point --------------------------------------------------------- _published = False # Set once the shared-asset fragments are published in this process # Delivery caches for /theme.css and /state.json: (cache_key, body, etag). # Keyed on source-file mtimes + valve settings, so saves and valve changes # invalidate naturally; per-process (each worker warms its own copy). _css_delivery_cache = None _state_delivery_cache = None _safe_css_cache = None # (cache_key, css) for the first-paint-safe subset _loader_fragment_cache = None # (cache_key, fragment) for the composed loader.js block _reenabling = False # Set by function.enable_started; triggers SSE broadcast on next inject _routes_registered_url = None # Route base the routes were registered under _last_designer_url = None # Track URL changes to re-register routes _last_enable_canvas_fx = None # Track Canvas FX valve to broadcast changes _last_sidebar_transparency = None # Track sidebar transparency valve to broadcast changes _last_overlay_transparency = None # Track overlay transparency valve to broadcast changes # Cross-worker valve convergence (multi-container / Redis only). instance = None # Live instance the producers and peer valve sync read _last_valves_snapshot = None # All valve values at the last event(), to detect ANY change _sse_clients: set = ( set() ) # Active SSE connections — aliased to app.state in _register_route() # Per-worker ceiling on concurrent SSE connections. The endpoint is # unauthenticated, so this bounds worst-case memory/FD usage; over-cap # clients degrade gracefully to reconnect-later + refetch-on-focus. _SSE_MAX_CLIENTS = 8192 # Tags this process's own Redis messages so its subscriber skips them. The # PID alone repeats across containers, where the server is often PID 1. _WORKER_ID = f"{socket.gethostname()}:{os.getpid()}" @staticmethod def _strip_canvas_from_state(state_str: str) -> str: """Strip canvasEnabled/canvasScript/canvasShowAuth from state JSON. Used to enforce the Enable Canvas FX valve at the delivery layer without modifying the saved state on disk (preserves user presets). """ try: data = _json.loads(state_str) for mode in ("dark", "oled", "light", "her"): if isinstance(data.get(mode), dict): data[mode]["canvasEnabled"] = False data[mode].pop("canvasScript", None) data[mode].pop("canvasShowAuth", None) return _json.dumps(data, separators=(",", ":")) except Exception: return state_str @classmethod def _apply_sidebar_transparency(cls, css: str, mode: str) -> str: """Post-process flat CSS for the sidebar transparency valve. Composition of the per-rule rewrite (safe to run on individual sections) and the appended mobile-upgrade block (must be added exactly once, at the end of the delivered CSS). """ css = cls._rewrite_sidebar_fx(css, mode) if mode == "transparent": css += cls._sidebar_mobile_css() return css @staticmethod def _rewrite_sidebar_fx(css: str, mode: str) -> str: """Rewrite opaque /*[FX]*/ sidebar rules for the transparency valve. mode='translucent': tinted glass (semi-transparent bg + backdrop-blur) mode='transparent': fully see-through (transparent bg, no blur) Only affects sidebar rules marked with /*[FX]*/ (canvas/gradient blocks). Plain-mode sidebar rules (no marker) are left untouched. Operates on individual rules, so it can be applied to the flat CSS or to the structural/gradient sections independently. """ if mode == 'translucent': blur_val = 'blur(20px) saturate(1.3)' else: blur_val = 'none' # Replace structural opaque sidebar (marked with /*[FX]*/): var-based bg # Pattern groups: (1: prefix) (2: var ref) (3: !important;) — closing } matched but not captured if mode == 'translucent': css = _re.sub( r'(#sidebar\s*\{\s*/\*\[FX\]\*/\s*background-color:\s*)(var\(--[^)]+\))(\s*!important\s*;)\s*\}', rf'\1color-mix(in srgb, \2 20%, transparent)\3 backdrop-filter: {blur_val} !important; -webkit-backdrop-filter: {blur_val} !important; }}', css, ) else: css = _re.sub( r'(#sidebar\s*\{\s*/\*\[FX\]\*/\s*background-color:\s*)var\(--[^)]+\)(\s*!important\s*;)\s*\}', rf'\1transparent\2 backdrop-filter: {blur_val} !important; -webkit-backdrop-filter: {blur_val} !important; }}', css, ) # Replace gradient sidebar (marked with /*[FX]*/): rgba-based bg + existing blur if mode == 'translucent': css = _re.sub( r'(#sidebar\s*\{\s*/\*\[FX\]\*/[^}]*background-color:\s*)rgba\(([^,]+,[^,]+,[^,]+),\s*[\d.]+\)(\s*!important\s*;[^}]*backdrop-filter:\s*)blur\([^)]+\)', rf'\1rgba(\2, 0.25)\3{blur_val}', css, ) else: css = _re.sub( r'(#sidebar\s*\{\s*/\*\[FX\]\*/[^}]*background-color:\s*)rgba\([^)]+\)(\s*!important\s*;[^}]*backdrop-filter:\s*)blur\([^)]+\)', rf'\1transparent\2{blur_val}', css, ) # Remove the revert-layer rule (marked with /*[FX]*/) css = _re.sub( r'[^\n]*#sidebar[^{]*\{\s*/\*\[FX\]\*/\s*background-color:\s*revert-layer\s*;?\s*\}[^\n]*\n?', '', css, ) return css @staticmethod def _sidebar_mobile_css() -> str: """Mobile override: auto-upgrade transparent sidebar → translucent. Uses #sidebar#sidebar for specificity to override the transparent rules. Appended once at the end of the delivered CSS (the 'extra' section when assembling from structured sections). """ return ( "\n/* Mobile: auto-upgrade transparent sidebar to translucent */\n" "@media (max-width: 768px) {\n" " .dark #sidebar#sidebar,\n" ' [data-theme="dark"] #sidebar#sidebar,\n' ' [data-theme="oled-dark"] #sidebar#sidebar {\n' " background-color: color-mix(in srgb, var(--color-gray-950) 20%, transparent) !important;\n" " backdrop-filter: blur(20px) saturate(1.3) !important;\n" " -webkit-backdrop-filter: blur(20px) saturate(1.3) !important;\n" " }\n" ' :root:not(.dark):not([data-theme="dark"]):not([data-theme="oled-dark"]) #sidebar#sidebar {\n' " background-color: color-mix(in srgb, var(--color-gray-50) 20%, transparent) !important;\n" " backdrop-filter: blur(20px) saturate(1.3) !important;\n" " -webkit-backdrop-filter: blur(20px) saturate(1.3) !important;\n" " }\n" "}\n" ) @classmethod def _apply_overlay_transparency(cls, css: str) -> str: """Append translucent glass CSS for portaled overlay UI elements.""" return css + cls._overlay_css() @staticmethod def _overlay_css() -> str: """Return the translucent glass CSS block for portaled overlay UI. Targets settings modal, dropdown menus, user menus, integration menus, and other UI elements portaled outside .app directly on . Uses descendant selectors to handle varying portal DOM depths. Appended at the end of the delivered CSS (the 'extra' section when assembling from structured sections). """ blur = 'blur(20px) saturate(1.3)' # Selector fragment: portal wrappers (direct children of body that aren't part of the app/theme system) pex = ':not(.app):not(#theme-designer-container):not([id^="owui-"]):not(#svelte):not(script):not(style)' # Selector fragment: background-bearing elements inside portals (exclude interactive widgets + app internals) iex = ':not(button):not(a):not(input):not(select):not(label):not(span):not(svg):not(img):not(.app *):not(#theme-designer-container *)' def _where(util): toks = [f'div[class^="{util}"]', f'div[class*=" {util}"]', f'div[class^="dark:{util}"]', f'div[class*=" dark:{util}"]'] return ':where(' + ', '.join(t + iex for t in toks) + ')' wgray = _where('bg-gray-') wwhite = _where('bg-white') def _decl(color_var): return ( f' background-color: color-mix(in srgb, var({color_var}) 25%, transparent) !important;\n' f' backdrop-filter: {blur} !important;\n' f' -webkit-backdrop-filter: {blur} !important;\n' ) rules = [ ([f'.dark body > div{pex} {wgray}', f'[data-theme="dark"] body > div{pex} {wgray}', f'[data-theme="oled-dark"] body > div{pex} {wgray}'], '--color-gray-950'), ([f':root:not(.dark):not([data-theme="dark"]):not([data-theme="oled-dark"]):not([data-theme="her"]) body > div{pex} {wwhite}', f':root:not(.dark):not([data-theme="dark"]):not([data-theme="oled-dark"]):not([data-theme="her"]) body > div{pex} {wgray}'], '--color-gray-50'), ([f'.her body > div{pex} {wwhite}', f'[data-theme="her"] body > div{pex} {wwhite}', f'.her body > div{pex} {wgray}', f'[data-theme="her"] body > div{pex} {wgray}'], '--color-gray-50'), ] css = '\n/* --- Overlay Translucency (valve-injected) --- */\n' for sels, color_var in rules: css += ',\n'.join(sels) + ' {\n' + _decl(color_var) + '}\n' # System mode media queries for scheme, color_var in [('dark', '--color-gray-950'), ('light', '--color-gray-50')]: media_sels = [f' [data-theme="system"] body > div{pex} {wgray}'] if scheme == 'light': media_sels.insert(0, f' [data-theme="system"] body > div{pex} {wwhite}') css += f'@media (prefers-color-scheme: {scheme}) {{\n' css += ',\n'.join(media_sels) + ' {\n' + _decl(color_var) + ' }\n}\n' return css def _postprocess_css(self, css): """Apply valve-based CSS post-processing (sidebar + overlay transparency).""" if self.valves.sidebar_transparency != "opaque": css = self._apply_sidebar_transparency(css, self.valves.sidebar_transparency) if self.valves.overlay_transparency != "opaque": css = self._apply_overlay_transparency(css) return css def _postprocess_sections(self, sections: dict) -> dict: """Per-section mirror of _postprocess_css. The sidebar valve rewrites /*[FX]*/ rules, which live only in the structural and gradient sections. Valve-APPENDED rules (mobile sidebar upgrade, overlay glass) go into a synthetic 'extra' section so consumers assembling from sections deliver the same CSS as /theme.css. 'extra' is never auth-gated by the bootloader. """ out = dict(sections) extra = "" sidebar_mode = self.valves.sidebar_transparency if sidebar_mode != "opaque": out["structural"] = self._rewrite_sidebar_fx(out["structural"], sidebar_mode) out["gradient"] = self._rewrite_sidebar_fx(out["gradient"], sidebar_mode) if sidebar_mode == "transparent": extra += self._sidebar_mobile_css() if self.valves.overlay_transparency != "opaque": extra += self._overlay_css() out["extra"] = extra return out def _state_with_sections(self, state: str) -> str: """Merge valve-postprocessed CSS sections into a state JSON string. Injected at delivery time under the reserved '_cssSections' key so the bootloader can assemble auth-page CSS from structured sections instead of regex-slicing the flat blob. No-op when the sections file is missing (legacy flat-CSS saves — bootloader falls back to marker regexes) or the state isn't parseable JSON (served as-is by design). """ sections = self._load_sections() if not sections: return state try: data = _json.loads(state) if not isinstance(data, dict): return state except Exception: return state data["_cssSections"] = self._postprocess_sections(sections) return _json.dumps(data, separators=(",", ":")) def _postprocess_state(self, state): """Apply valve-based state post-processing (strip canvas if disabled).""" if state and not self.valves.enable_canvas_fx: state = self._strip_canvas_from_state(state) return state @classmethod def _redis_publish(cls, msg: str): """Publish a message to the Redis theme_pro_sse channel (best-effort). The blocking publish is dispatched to the default thread-pool executor when an event loop is running — a stalled Redis connection must never freeze the server's event loop (broadcasts fire from async handlers). """ if not os.environ.get("REDIS_URL", ""): return try: loop = asyncio.get_running_loop() except RuntimeError: loop = None if loop is not None: loop.run_in_executor(None, cls._redis_publish_sync, msg) else: cls._redis_publish_sync(msg) @classmethod def _redis_publish_sync(cls, msg: str): """Blocking Redis publish — call via _redis_publish, not directly.""" redis_url = os.environ.get("REDIS_URL", "") if not redis_url: return try: import redis as _sync_redis import inspect as _insp _extra = {} try: if 'maint_notifications' in _insp.signature(_sync_redis.Redis.from_url).parameters: _extra['maint_notifications'] = False except Exception: pass # Bounded timeouts: even off-loop, a dead route shouldn't pin a # thread-pool worker for minutes waiting on TCP defaults. r = _sync_redis.Redis.from_url( redis_url, socket_connect_timeout=2, socket_timeout=2, **_extra, ) r.publish("theme_pro_sse", f"wid:{cls._WORKER_ID}\n{msg}") r.close() except Exception: pass # Redis unavailable — local broadcast still runs below @classmethod def _broadcast_update(cls, etags: dict | None = None, local_only: bool = False): """Push a theme-update notification to all connected SSE clients. The payload carries a version token — clients refetch /theme.css and /state.json, which apply valve post-processing at delivery time. This keeps SSE frames tiny instead of shipping the full CSS + state (including the entire canvas script) to every client on every debounced save. When etags (from _prime_delivery_caches) are provided they ride along, letting clients that already applied that exact version skip the refetch entirely. local_only skips the Redis re-publish: set when this broadcast is itself the result of receiving a peer's message, so it reaches this worker's own clients without echoing back onto the channel. """ import time data = {"v": int(time.time() * 1000)} if etags: if etags.get("cssTag"): data["cssTag"] = etags["cssTag"] if etags.get("stateTag"): data["stateTag"] = etags["stateTag"] payload = _json.dumps(data, separators=(",", ":")) msg = f"event: theme-update\ndata: {payload}\n\n" if not local_only: cls._redis_publish(msg) for q in list(cls._sse_clients): try: q.put_nowait(msg) except asyncio.QueueFull: pass # Drop if client is backed up @classmethod def _broadcast_disable(cls, reason="disabled"): """Push a theme-disable event to all SSE clients (strip theme + reload). reason distinguishes a function toggle ("disabled") from a Global Reset ("reset"). Clients strip the theme identically in both cases, but the designer's save-hold must only latch on a real disable: after a reset the function is still running and saves must keep working — latching would hold every save while no theme-update can ever arrive to release them, deadlocking the designer until a page reload. """ msg = f'event: theme-disable\ndata: {{"reason":"{reason}"}}\n\n' cls._redis_publish(msg) for q in list(cls._sse_clients): try: q.put_nowait(msg) except asyncio.QueueFull: pass # --- Cross-worker valve convergence ------------------------------------- # An admin changes a valve on ONE worker; Open WebUI reloads the function # there, but every other worker keeps its cached instance with the old # values until its own next dispatched event. All valves alter rendered # output (the loader.js fragment embeds the whole config), so peers can # serve a stale theme for that window. The worker that saw the change tells # the others to re-read from the DB. Redis-only: a single-worker install # already holds the fresh valves, so _redis_publish is a no-op there. # # Framed as an SSE comment (":") so a peer still on an older build, whose # subscriber forwards raw channel traffic straight to browsers, delivers an # ignored keep-alive rather than a malformed event. Our own subscriber # intercepts it before any client sees it. _CTRL_PREFIX = ":owui-theme-ctrl " @classmethod def _broadcast_valve_sync(cls): """Signal peer workers that a valve changed and they should re-read it.""" cls._redis_publish(f"{cls._CTRL_PREFIX}valvesync\n\n") @staticmethod async def _read_valves_from_db(inst, function_id): """Read + validate this function's stored valves; None on any failure. Fail-safe by construction: a missing Open WebUI API, an unreadable row, or data that no longer validates all resolve to None, and the caller then leaves the current valves untouched — behaviour identical to pre-1.7.9, where the worker converges on its own next event. No stored valves means the defaults, as in Open WebUI's own dispatch. """ try: from open_webui.models.functions import Functions stored = await Functions.get_function_valves_by_id(function_id) or {} except Exception: return None if not isinstance(stored, dict): return None try: return inst.Valves(**stored) except Exception: return None @classmethod async def _handle_peer_valve_sync(cls, app): """Apply a peer's valve change to this worker's live instance. Also runs after live_reload executes this code on a worker that no event reaches, which is how that worker gets its valves and routes. Cache priming runs off-loop; the app-state mutations (route re-registration, fragment republish) run on-loop, the same order event() uses, so they interleave cooperatively with event() instead of racing it in a thread. """ inst = cls.instance if inst is None or (app is not None and not reload_active(app)): return new_valves = await cls._read_valves_from_db(inst, RELOAD_FUNCTION_ID) if new_valves is None: return inst.valves = new_valves snap = inst._valves_snapshot() if snap == cls._last_valves_snapshot: return # already holding this value — nothing to converge cls._last_valves_snapshot = snap if app is not None: route = inst._get_route_base() if route != cls._routes_registered_url: inst._register_route(app) cls._routes_registered_url = route inst._publish_fragments(app) etags = await asyncio.to_thread(inst._prime_delivery_caches) # local_only: this refetch nudge is the downstream of a peer's message; # echoing it back to Redis would ripple across the cluster. cls._broadcast_update(etags, local_only=True) log.info( "[Theme Pro] Applied peer valve change — refreshed valves, re-primed, notified local clients" ) @classmethod async def _shutdown_cleanup(cls, app): """Cancel background tasks and end SSE streams before the loop closes. Called from event() on system.shutdown.* (primary path — Open WebUI publishes those from its lifespan exit while the event loop is still fully alive) and from the legacy router.on_shutdown hook on old stacks where that still fires. Idempotent via app.state._theme_shutting_down. That flag also gates the subscriber/heartbeat creation paths: shutdown events are dispatched as fire-and-forget tasks, so a straggler event() can run mid-teardown — if it respawned the Redis subscriber, the new task would miss the runner's cancellation sweep and be destroyed pending at loop close ("Task was destroyed but it is pending!", "RuntimeError: no running event loop", un-awaited redis disconnect coroutines in the GC phase of interpreter shutdown). """ app.state._theme_shutting_down = True for attr in ("_theme_redis_task", "_theme_sse_heartbeat"): task = getattr(app.state, attr, None) if task is not None: task.cancel() try: await task except BaseException: pass # CancelledError (expected) or teardown noise setattr(app.state, attr, None) # Wake every SSE stream with a None sentinel so the generators # return. This lets uvicorn's graceful wait for in-flight responses # finish instead of stalling on open EventSource connections until # the container runtime SIGKILLs the process (~10s restart penalty). for q in list(cls._sse_clients): try: q.put_nowait(None) except asyncio.QueueFull: try: q.get_nowait() # Drop one queued frame to make room q.put_nowait(None) except (asyncio.QueueEmpty, asyncio.QueueFull): pass def _ensure_redis_subscriber(self, app): """Start the Redis pub/sub subscriber for multi-worker SSE broadcasting. Called from event() and register() (async context) rather than _register_route (sync) to avoid 'Task was destroyed' errors from transient startup event loops. The _sub_alive guard ensures the task is only created once, or recreated if the previous one died or was started by an older exec of this code. """ redis_url = os.environ.get("REDIS_URL", "") _existing_task = getattr(app.state, "_theme_redis_task", None) _sub_alive = _existing_task is not None and not _existing_task.done() # A subscriber started by an older exec of this code would hand peer # valve syncs to that exec's dead class, so a new exec replaces it. if _sub_alive and getattr(app.state, "_theme_redis_exec", None) != RELOAD_EXEC_ID: _existing_task.cancel() _sub_alive = False # Never (re)spawn once shutdown cleanup ran: shutdown events are # dispatched fire-and-forget, so this code can execute mid-teardown # after the old subscriber was cancelled (_sub_alive False again) — # a respawned task would be orphaned at loop close. _shutting_down = getattr(app.state, "_theme_shutting_down", False) if redis_url and not _sub_alive and not _shutting_down: try: import redis.asyncio as aioredis import inspect as _insp # Detect if redis-py supports maint_notifications (v7+) _redis_extra = {} try: if 'maint_notifications' in _insp.signature(aioredis.from_url).parameters: _redis_extra['maint_notifications'] = False else: import logging as _logging _logging.getLogger('redis.connection').setLevel(_logging.WARNING) except Exception: pass async def _redis_subscriber(): """Listen on Redis channel and forward messages to local SSE clients. Reconnects automatically on timeout or connection loss.""" while True: r = None pubsub = None # Set when the loop/interpreter is dying: skip every # remaining await (logging included) so finalization # stays silent instead of raising into the GC. _teardown = False try: r = aioredis.from_url( redis_url, socket_timeout=None, socket_connect_timeout=10, **_redis_extra, ) pubsub = r.pubsub() await pubsub.subscribe("theme_pro_sse") log.info("[Theme Pro] Redis subscriber connected on channel 'theme_pro_sse'") async for message in pubsub.listen(): if message["type"] != "message": continue raw = message["data"] if isinstance(raw, bytes): raw = raw.decode("utf-8") if raw.startswith("wid:"): newline = raw.index("\n") sender_id = raw[4:newline] if sender_id == Event._WORKER_ID: continue raw = raw[newline + 1:] # Internal control messages never reach browsers. if raw.startswith(Event._CTRL_PREFIX): if raw[len(Event._CTRL_PREFIX):].strip() == "valvesync": try: await Event._handle_peer_valve_sync(app) except Exception: log.warning( "[Theme Pro] Peer valve sync failed", exc_info=True, ) continue for q in list(Event._sse_clients): try: q.put_nowait(raw) except asyncio.QueueFull: pass except asyncio.CancelledError: break except GeneratorExit: # GC is finalizing this coroutine after the loop # already closed (shutdown cleanup never ran — # e.g. hard kill). Any await here raises straight # into the finalizer; bail out silently. _teardown = True raise except Exception as exc: # During finalization redis-py can convert the # thrown GeneratorExit into an ordinary # ConnectionError, landing here with no loop to # sleep on. Only log + retry on a live loop. try: asyncio.get_running_loop() except RuntimeError: _teardown = True return log.warning("[Theme Pro] Redis subscriber lost connection: %s — reconnecting in 5s", exc) await asyncio.sleep(5) finally: # Close connections to prevent FD/connection leaks on # reconnect. redis-py >= 5 renamed close() to aclose() # and deprecated close() — feature-detect to stay quiet # on new versions and compatible with old ones. # BaseException: a re-delivered CancelledError during # shutdown must not skip closing the second connection. if not _teardown: if pubsub: try: await (pubsub.aclose() if hasattr(pubsub, "aclose") else pubsub.close()) except BaseException: pass if r: try: await (r.aclose() if hasattr(r, "aclose") else r.close()) except BaseException: pass app.state._theme_redis_task = asyncio.get_running_loop().create_task(_redis_subscriber()) app.state._theme_redis_exec = RELOAD_EXEC_ID except Exception as exc: log.warning("[Theme Pro] Could not start Redis subscriber: %s", exc) async def event( self, event: dict, __event_name__: str = None, __id__: str = None, __app__=None, **kwargs, ) -> None: # --- Server shutdown cleanup --- # Open WebUI publishes system.shutdown.* from its lifespan exit while # the event loop is still running — the only reliable shutdown hook # (router.on_shutdown never fires on lifespan-based apps). Cancel the # Redis subscriber + SSE heartbeat and end SSE streams NOW; once the # loop closes, an un-cancelled subscriber surfaces at interpreter # exit as "Task was destroyed but it is pending!" / "RuntimeError: # no running event loop" GC noise. Runs even when the function is # disabled: a subscriber started before a disable is still alive. if __event_name__ in ( "system.shutdown.started", "system.shutdown.completed", ): if __app__ is not None and not getattr( __app__.state, "_theme_shutting_down", False ): log.info( "[Theme Pro] Server shutdown — cancelling background tasks and closing SSE streams" ) await Event._shutdown_cleanup(__app__) return # No injection/broadcast work during shutdown if __app__ is None: return # On/off, code saves and valve saves reach every worker through # live_reload, which also flips reload_active() for the producers and # route handlers. await reload_on_event(__app__, event, __event_name__) is_own = ((event or {}).get("subject") or {}).get("id") == RELOAD_FUNCTION_ID # --- Pre-disable cleanup --- # When the admin toggles this function OFF, Open WebUI dispatches # 'function.disable_started' synchronously BEFORE committing # is_active=False (Open WebUI v0.11.0+; earlier builds never # dispatch pre-toggle lifecycle events). # # live_reload has already switched the function off on every worker, # so the next request composes a custom.css without our block and a # loader.js with __THEME_ACTIVE__=false. The loader fragment stays # published deliberately: an inactive bootloader still holds its SSE # connection, which is how the theme-update broadcast on re-enable # reaches all connected clients. What is left is to broadcast # theme-disable, which strips the theme from all open tabs. if is_own and __event_name__ == "function.disable_started": log.info( "[Theme Pro] Function is being disabled — CSS fragment withdrawn, SSE kept alive" ) Event._broadcast_disable() Event._published = False log.info( "[Theme Pro] Cleanup complete — CSS withdrawn, bootloader set inactive, clients notified" ) return # Nothing else to do on this event # --- Pre-enable re-injection --- # When the admin toggles this function back ON, Open WebUI dispatches # 'function.enable_started' synchronously BEFORE committing # is_active=True (the not-yet-active function is included via # extra_function_ids). Ensure _published is False so the main logic # below republishes the fragments and rebroadcasts to open tabs # immediately. if is_own and __event_name__ == "function.enable_started": log.info("[Theme Pro] Function is being re-enabled — triggering re-injection") Event._published = False # Forces the republish + broadcast below Event._reenabling = True # Triggers broadcast to connected clients if not reload_active(__app__): return url_changed = ( Event._last_designer_url is not None and Event._last_designer_url != self.valves.designer_url ) # Register routes on first call or when the designer URL valve changes. # Guarded because _register_route rewrites app.routes; the fragment # publish below is cheap enough to run unguarded. _current_route = self._get_route_base() if ( Event._routes_registered_url is None or _current_route != Event._routes_registered_url ): self._register_route(__app__) Event._routes_registered_url = _current_route # A URL change rewrites __THEME_ROUTE__ inside the loader fragment. # The producer picks that up on its own at the next compose, but # clearing the flag also rebroadcasts so already-loaded tabs move # their SSE connection to the new route instead of retrying a 404. if url_changed: Event._published = False self._ensure_redis_subscriber(__app__) canvas_valve_changed = ( Event._last_enable_canvas_fx is not None and Event._last_enable_canvas_fx != self.valves.enable_canvas_fx ) sidebar_valve_changed = ( Event._last_sidebar_transparency is not None and Event._last_sidebar_transparency != self.valves.sidebar_transparency ) overlay_valve_changed = ( Event._last_overlay_transparency is not None and Event._last_overlay_transparency != self.valves.overlay_transparency ) # Any valve change (not just the three that drive a live broadcast) tells # peer workers to re-read from the DB — they hold a cached instance that # Open WebUI only reloads on the worker where the change was made. First # event of the process is skipped (snapshot is None): startup is not a # change, and peers load their own valves on their own startup. _valves_now = self._valves_snapshot() if ( Event._last_valves_snapshot is not None and _valves_now != Event._last_valves_snapshot ): Event._broadcast_valve_sync() # One-shot: remove blocks an older, index.html-writing build left behind. # Threaded — the flock can wait on another process and must not stall # the loop. Self-guarded, so this is a no-op after the first call. if not Event._legacy_index_cleaned: await asyncio.to_thread(self._clean_legacy_index_injection) # Capture whether fragments have been published in this process yet # (first event after startup, a disable, or a class reload). Used below # to trigger an SSE broadcast so connected clients receive the theme # immediately without needing a page refresh. _was_not_published = not Event._published # Publish unconditionally. This replaced a read-modify-write of # index.html under a cross-process flock, which had to be guarded on # "did anything actually change?"; re-pointing the two fragments is two # dict writes plus a route scan, so the guard is not worth its own bugs. # Re-pointing on every event is also what makes a hot reload converge: # the registry ends up holding the NEW instance's producer. # No valve branches either — the producers read self.valves at compose # time, so a valve change is already reflected on the next request. _published_ok = ( self._publish_fragments(__app__) if __app__ is not None else False ) if _published_ok: # Broadcast theme state to connected clients when: # - First publish cycle after disable/startup (_was_not_published) # - Function was just re-enabled (_reenabling from function.enable_started) # - A valve changed (admin toggled a setting) _reenabling = Event._reenabling Event._reenabling = False if _was_not_published or _reenabling or canvas_valve_changed or sidebar_valve_changed or overlay_valve_changed: # Token + ETag broadcast — clients refetch /theme.css + /state.json # (valve post-processing applies at delivery), unless the tags show # they already hold this exact version. Priming runs off-loop. _etags = await asyncio.to_thread(self._prime_delivery_caches) Event._broadcast_update(_etags) _reasons = [] if _was_not_published: _reasons.append("first publish cycle") if _reenabling: _reasons.append("function re-enabled") if canvas_valve_changed: _reasons.append(f"Canvas FX → {self.valves.enable_canvas_fx}") if sidebar_valve_changed: _reasons.append(f"sidebar → {self.valves.sidebar_transparency}") if overlay_valve_changed: _reasons.append(f"overlay → {self.valves.overlay_transparency}") log.info("[Theme Pro] Valve change (%s) — pushed to SSE clients", ", ".join(_reasons)) if _was_not_published: log.info( "[Theme Pro] Published loader.js + custom.css fragments to the shared static-asset registry" ) Event._published = True elif __app__ is not None: # Only latch on success — a transient failure leaves the flag unset # so the next event retries instead of silently serving an unthemed # instance until something else happens to republish. log.warning( "[Theme Pro] Fragment publish failed — will retry on next event" ) # Always track the current valve state for next comparison Event._last_designer_url = self.valves.designer_url Event._last_enable_canvas_fx = self.valves.enable_canvas_fx Event._last_sidebar_transparency = self.valves.sidebar_transparency Event._last_overlay_transparency = self.valves.overlay_transparency Event._last_valves_snapshot = _valves_now def register(app: Any) -> None: inst = Event.instance inst._publish_fragments(app) # live_reload can execute this code on a worker that no event reaches, so # load its valves, routes and Redis subscriber the way a peer valve sync # does. Runs as a task: the valves are read from the database. async def load(): inst._ensure_redis_subscriber(app) await Event._handle_peer_valve_sync(app) task = asyncio.get_running_loop().create_task(load()) reload_tasks.add(task) task.add_done_callback(reload_tasks.discard)