diff --git a/docs/CURRENT_SYSTEM.md b/docs/CURRENT_SYSTEM.md index ba4d297..c0622a6 100644 --- a/docs/CURRENT_SYSTEM.md +++ b/docs/CURRENT_SYSTEM.md @@ -128,3 +128,13 @@ Original-JavaScript read-only über Unraids persistente Container-Vorlage eingeb OpenWebUI mit gleichem Image neu erstellt. Athena/SoulX nicht neu gestartet. Installation, Sicherung, Prüfgrenzen und Rückbau: [Reasoning Effort Selector](../integrations/openwebui-reasoning-selector/README.md). + +### Weitere OpenWebUI-Community-Plugins (7. Oktober 2026) + +Inline Visualizer samt `visualize`-Skill, Token Usage Display, Markdown +Normalizer, Word-/Excel-Export und Download Code Blocks importiert und +serverseitig synthetisch geprüft. Sub Agent nicht installiert. Nach ausdrücklicher +Zustimmung sind die fünf Funktionen global aktiviert und Same-Origin für +den Visualizer im Benutzerprofil freigegeben. Browserprüfung noch offen. +Quellen, Versionen, Backup und Einschränkungen: +[integrations/openwebui-community-plugins](../integrations/openwebui-community-plugins/README.md). diff --git a/integrations/openwebui-community-plugins/LICENSE-Classic298 b/integrations/openwebui-community-plugins/LICENSE-Classic298 new file mode 100644 index 0000000..e55cbe3 --- /dev/null +++ b/integrations/openwebui-community-plugins/LICENSE-Classic298 @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2026, Classic298 + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/integrations/openwebui-community-plugins/LICENSE-Fu-Jie b/integrations/openwebui-community-plugins/LICENSE-Fu-Jie new file mode 100644 index 0000000..3a5ba00 --- /dev/null +++ b/integrations/openwebui-community-plugins/LICENSE-Fu-Jie @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2024 Awesome OpenWebUI Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/integrations/openwebui-community-plugins/LICENSE-SmetDenis b/integrations/openwebui-community-plugins/LICENSE-SmetDenis new file mode 100644 index 0000000..17063bd --- /dev/null +++ b/integrations/openwebui-community-plugins/LICENSE-SmetDenis @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Denis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/integrations/openwebui-community-plugins/README.md b/integrations/openwebui-community-plugins/README.md new file mode 100644 index 0000000..61e44b0 --- /dev/null +++ b/integrations/openwebui-community-plugins/README.md @@ -0,0 +1,79 @@ +# OpenWebUI Community-Erweiterungen + +Stand: 7. Oktober 2026. Sechs unveränderte Original-Erweiterungen importiert; +Sub Agent ausdrücklich ausgeschlossen. Quellen, feste Git-Revisionen und +SHA-256 stehen in `manifest.json`. Download Code Blocks stammt aus dem +öffentlichen Community-Post; dessen heruntergeladener Python-Inhalt ist per +Prüfsumme festgehalten. Lizenzen der Repositories liegen daneben; Download +Code Blocks erklärt MIT im eigenen Header. + +| ID | Version | Typ | +| --- | --- | --- | +| inline_visualizer | 2.2.3 | Werkzeug | +| token_usage_display | 2.6.0 | Filter | +| markdown_normalizer | 1.2.9 | Filter | +| export_to_word | 0.5.3 | Aktion | +| export_to_excel | 0.3.11 | Aktion | +| download_code_blocks | 1.1.0 | Aktion | + +## Installation und Zustand + +Installation erfolgte über die OpenWebUI-API im bestehenden Unraid-Dienst. +Keine Containerneustarts und keine Frontend-Patches. Nach ausdrücklicher +Zustimmung des Nutzers wurden alle fünf Funktionen global aktiviert und +`iframeSandboxAllowSameOrigin` im bestehenden Admin-Benutzerprofil gesetzt. +Der Zustand wird per API zurückgelesen. Das Visualizer-Werkzeug ist in +Workspace → Tools verfügbar; der zugehörige Original-Skill `visualize` +liegt in der nativen OpenWebUI-Skillverwaltung. Für die beiden Freigaben +wurde `activate.py` getrennt von der Installation ausgeführt. Die erste +automatische Freigabeprüfung hatte diese Schritte bis zur ausdrücklichen +Zustimmung blockiert. Browserdarstellung noch nicht Ende zu Ende geprüft. + +Tokenfilter: Kostenanzeige und externe models.dev-Abfragen ausgeschaltet. +Kontext-Prozentanzeige ebenfalls ausgeschaltet, bis die realen Athena- +Profilgrößen verlässlich zugeordnet werden; keine geratenen Modellgrößen. +Tokenzahlen und Dauer bleiben verfügbar. API-Zahlen werden bevorzugt, +Schätzungen können verwendet werden, wenn keine Zahlen vorliegen. + +## Reproduktion, Abhängigkeiten, Sicherung + +`install.py` ist der dokumentierte Importweg für einen vorhandenen +OpenWebUI-Dienst (nicht der native Athena-Installer). Im OpenWebUI-Python +mit dessen Backend im PYTHONPATH starten. Der Helfer verwendet einen +kurzlebigen, nicht ausgegebenen Admin-Token, sichert zuerst die SQLite-DB, +importiert über die API und überschreibt keine vorhandenen IDs. +Die Pfade beziehen sich ausdrücklich auf den aktuellen OpenWebUI-Container. +Für OpenWebUI an anderer Stelle müssen DB-Pfad und API-Adresse angepasst +werden; für einen nativen Athena-Deck-Dienst wird kein Plugin benötigt. + +OpenWebUI-Datenpartition inklusive webui.db, Plugins, Skills und +Plugin-Backups sichern. Private DB-Sicherungen gehören nicht in Git. +Vorimport-Sicherung: `/app/backend/data/plugin-backups/20261006T223416Z/webui.db`. + +Word benötigt python-docx, Pygments, latex2mathml, mathml2omml; letztere +fehlten vorher und wurden beim API-Import durch OpenWebUIs vorgesehenen +Requirements-Mechanismus installiert. Excel braucht pandas und xlsxwriter; +beides war im vorhandenen Image verfügbar. Bei Neuaufbau importiert +OpenWebUI die Word-Abhängigkeiten; Excel-Abhängigkeiten im Zielimage prüfen. +Visualizer/Word verwenden für bestimmte Browserfunktionen öffentliche +CDN-Bibliotheken. Kein eigener Source-Patch und kein zusätzlicher Container. + +## Prüfung und Bedienung + +`verify.py`: alle sechs Module geladen und Prüfsummen geprüft. Synthetische +Token-Statistik, Markdown-Ausgangsfilter, echte DOCX- und XLSX-Erzeugung, +Codeblock-Dateinamen und Visualizer-Werkzeugaufruf bestanden. Keine echten +Chats gelesen, keine LLM-Inferenz. Browserdownload und interaktive +Darstellung sind damit noch nicht Ende zu Ende geprüft. + +Funktionen: Administration → Funktionen. Aktionsknöpfe werden nach +Zuordnung unter Antworten angeboten. Filter wirken nach Zuordnung an +Modelle oder global. Visualizer pro Chat unter Werkzeuge wählen; mit dem +bestehenden Tool-Search kann das Modell das lokale Werkzeug entdecken. +Vor einer Visualisierung den Skill `visualize` laden. + +Rückfall: betroffene Funktionen deaktivieren oder Zuordnung entfernen, +Werkzeug/Skill bei Bedarf deaktivieren. Ganze DB nur bei gestopptem Dienst +und bewusstem Rücksetzen wiederherstellen, da sonst neuere Chats verloren +gehen würden. Bestehende Thinking-, Audio- und Tool-Search-Erweiterungen +wurden nicht geändert. diff --git a/integrations/openwebui-community-plugins/activate.py b/integrations/openwebui-community-plugins/activate.py new file mode 100644 index 0000000..8ef6691 --- /dev/null +++ b/integrations/openwebui-community-plugins/activate.py @@ -0,0 +1,23 @@ +"""Explicitly authorized global activation and visualizer browser preference.""" +import json,sqlite3,urllib.request +from datetime import timedelta +from open_webui.utils.auth import create_token +c=sqlite3.connect("/app/backend/data/webui.db") +uid=c.execute("select id from user where role='admin' limit 1").fetchone()[0] +token=create_token({"id":uid},timedelta(minutes=5)) +def api(path,data=None): + req=urllib.request.Request("http://127.0.0.1:8080/api/v1/"+path,data=None if data is None else json.dumps(data).encode(),headers={"Authorization":"Bearer "+token,"Content-Type":"application/json"}) + with urllib.request.urlopen(req,timeout=60) as r:return json.load(r) +ids=('token_usage_display','markdown_normalizer','export_to_word','export_to_excel','download_code_blocks') +for ident in ids: + row=next(x for x in api('functions/') if x['id']==ident) + if not row.get('is_active'):api('functions/id/'+ident+'/toggle',{}) + if not row.get('is_global'):api('functions/id/'+ident+'/toggle/global',{}) +settings=api('users/user/settings') or {} +settings.setdefault('ui',{})['iframeSandboxAllowSameOrigin']=True +api('users/user/settings/update',settings) +assert api('users/user/settings')['ui']['iframeSandboxAllowSameOrigin'] is True +for row in api('functions/'): + if row['id'] in ids: + assert row['is_active'] and row['is_global'];print(row['id'],'active/global') +print('Visualizer same-origin preference verified') diff --git a/integrations/openwebui-community-plugins/download_code_blocks.py b/integrations/openwebui-community-plugins/download_code_blocks.py new file mode 100644 index 0000000..a1b1312 --- /dev/null +++ b/integrations/openwebui-community-plugins/download_code_blocks.py @@ -0,0 +1,918 @@ +""" +title: Download Code Blocks +author: silentoplayz +author_url: https://github.com/silentoplayz +funding_url: https://github.com/sponsors/silentoplayz +version: 1.1.0 +license: MIT +description: Extracts fenced code blocks from any assistant response and downloads them as properly named files. Features a confirmation modal with syntax-highlighted previews, line numbers, and editable filenames. Supports 170+ languages. +required_open_webui_version: 0.4.0 +""" + +import html as html_lib +import re +from pydantic import BaseModel, Field + +try: + from pygments import highlight as _pygments_highlight + from pygments.lexers import get_lexer_by_name, ClassNotFound as _LexerNotFound + from pygments.formatters import HtmlFormatter as _HtmlFormatter + + _HAS_PYGMENTS = True +except ImportError: + _HAS_PYGMENTS = False + + +class Action: + # SVG download icon (Lucide arrow-down-to-line) + icon_url = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 17V3'/%3E%3Cpath d='m6 11 6 6 6-6'/%3E%3Cpath d='M19 21H5'/%3E%3C/svg%3E" + + class Valves(BaseModel): + priority: int = Field( + default=0, description="Priority level for the action button ordering." + ) + default_filename: str = Field( + default="code", + description="Base filename used when a code block has no language specified.", + ) + auto_download: bool = Field( + default=False, + description="When enabled, downloads all code blocks immediately without confirmation prompts.", + ) + + class UserValves(BaseModel): + default_filename: str = Field( + default="code", + description="Base filename used when a code block has no language specified.", + ) + auto_download: bool = Field( + default=False, + description="When enabled, downloads all code blocks immediately without confirmation prompts.", + ) + + def __init__(self): + self.valves = self.Valves() + + # Mapping of language identifiers to file extensions + LANG_EXTENSION_MAP = { + # Web + "html": "html", + "htm": "html", + "css": "css", + "scss": "scss", + "sass": "sass", + "less": "less", + "javascript": "js", + "js": "js", + "jsx": "jsx", + "typescript": "ts", + "ts": "ts", + "tsx": "tsx", + "svelte": "svelte", + "vue": "vue", + "astro": "astro", + # Python + "python": "py", + "py": "py", + "python3": "py", + "pyw": "pyw", + # Systems + "c": "c", + "cpp": "cpp", + "c++": "cpp", + "cxx": "cpp", + "h": "h", + "hpp": "hpp", + "rust": "rs", + "rs": "rs", + "go": "go", + "golang": "go", + "zig": "zig", + # JVM + "java": "java", + "kotlin": "kt", + "kt": "kt", + "scala": "scala", + "groovy": "groovy", + # .NET + "csharp": "cs", + "cs": "cs", + "c#": "cs", + "fsharp": "fs", + "fs": "fs", + "f#": "fs", + "vb": "vb", + "vbnet": "vb", + # Shell + "bash": "sh", + "sh": "sh", + "shell": "sh", + "zsh": "zsh", + "fish": "fish", + "powershell": "ps1", + "ps1": "ps1", + "pwsh": "ps1", + "bat": "bat", + "batch": "bat", + "cmd": "cmd", + # Data / Config + "json": "json", + "jsonc": "jsonc", + "json5": "json5", + "yaml": "yaml", + "yml": "yaml", + "toml": "toml", + "ini": "ini", + "cfg": "cfg", + "xml": "xml", + "csv": "csv", + "tsv": "tsv", + "env": "env", + "dotenv": "env", + "properties": "properties", + # Markup / Docs + "markdown": "md", + "md": "md", + "rst": "rst", + "restructuredtext": "rst", + "tex": "tex", + "latex": "tex", + "txt": "txt", + "text": "txt", + "plaintext": "txt", + # Ruby + "ruby": "rb", + "rb": "rb", + # PHP + "php": "php", + # Swift / Objective-C + "swift": "swift", + "objectivec": "m", + "objc": "m", + # Functional + "haskell": "hs", + "hs": "hs", + "elixir": "ex", + "ex": "ex", + "erlang": "erl", + "erl": "erl", + "clojure": "clj", + "clj": "clj", + "ocaml": "ml", + "ml": "ml", + "lisp": "lisp", + "scheme": "scm", + "racket": "rkt", + # Scripting + "lua": "lua", + "perl": "pl", + "pl": "pl", + "r": "r", + "julia": "jl", + "jl": "jl", + "dart": "dart", + "nim": "nim", + "v": "v", + "vlang": "v", + # Database + "sql": "sql", + "mysql": "sql", + "postgresql": "sql", + "postgres": "sql", + "sqlite": "sql", + "plsql": "sql", + "graphql": "graphql", + "gql": "graphql", + # DevOps / IaC + "dockerfile": "Dockerfile", + "docker": "Dockerfile", + "terraform": "tf", + "tf": "tf", + "hcl": "tf", + "nginx": "conf", + "apache": "conf", + # Build tools + "makefile": "Makefile", + "make": "Makefile", + "cmake": "cmake", + "gradle": "gradle", + # Other + "diff": "diff", + "patch": "patch", + "asm": "asm", + "assembly": "asm", + "nasm": "asm", + "wasm": "wasm", + "proto": "proto", + "protobuf": "proto", + "solidity": "sol", + "sol": "sol", + "cuda": "cu", + "glsl": "glsl", + "hlsl": "hlsl", + "wgsl": "wgsl", + "regex": "txt", + "mermaid": "mmd", + } + + # MIME type mapping for common extensions + MIME_TYPE_MAP = { + "html": "text/html", + "css": "text/css", + "js": "text/javascript", + "jsx": "text/javascript", + "ts": "text/typescript", + "tsx": "text/typescript", + "json": "application/json", + "xml": "application/xml", + "svg": "image/svg+xml", + "md": "text/markdown", + "py": "text/x-python", + "sh": "text/x-shellscript", + "sql": "application/sql", + "yaml": "text/yaml", + "csv": "text/csv", + } + + # Maximum number of lines to show in the code preview + MAX_PREVIEW_LINES = 200 + + def _get_extension(self, lang: str) -> str: + """Resolve a language identifier to a file extension.""" + if not lang: + return "txt" + return self.LANG_EXTENSION_MAP.get(lang.lower().strip(), lang.lower().strip()) + + def _get_mime_type(self, ext: str) -> str: + """Get the MIME type for a file extension.""" + return self.MIME_TYPE_MAP.get(ext, "text/plain") + + def _extract_code_blocks(self, content: str) -> list[dict]: + """ + Extract all fenced code blocks from markdown content. + Returns a list of dicts with 'lang', 'code', and 'filename' keys. + """ + # Match ```lang ... ``` blocks, including optional filename hints + pattern = r"```(\w*)\s*\n(.*?)```" + matches = re.findall(pattern, content, re.DOTALL) + + blocks = [] + lang_counters: dict[str, int] = {} + + for lang, code in matches: + lang = lang.strip() if lang else "" + code = code.rstrip("\n") + + if not code.strip(): + continue + + ext = self._get_extension(lang) + base = self.valves.default_filename + + # Use the language as a more descriptive base if available + if lang: + base = lang.lower() + + # Always number files: python_1.py, python_2.py, etc. + lang_counters[ext] = lang_counters.get(ext, 0) + 1 + count = lang_counters[ext] + + filename = f"{base}_{count}.{ext}" + + # Handle special filenames (Dockerfile, Makefile, etc.) + if ext in ("Dockerfile", "Makefile"): + filename = f"{ext}_{count}" + + blocks.append( + { + "lang": lang or "text", + "code": code, + "filename": filename, + "extension": ext, + } + ) + + return blocks + + def _build_code_preview(self, block: dict, index: int, total: int) -> str: + """ + Build an HTML-formatted code preview for the confirmation modal. + + Uses raw HTML that visually matches Open WebUI's native CodeBlock + component: OLED black background, language header bar, and CSS- + powered line numbers. html.escape() prevents code content from + being rendered by the marked parser. A scrollable container + handles long code. + """ + lang = block["lang"] + code = block["code"] + lines = code.split("\n") + total_lines = len(lines) + + # Truncate extremely long blocks to limit WebSocket payload size + if total_lines > self.MAX_PREVIEW_LINES: + preview_lines = lines[: self.MAX_PREVIEW_LINES] + remaining = total_lines - self.MAX_PREVIEW_LINES + truncation_html = ( + f'
' + f"\u2026 {remaining} more line{'s' if remaining != 1 else ''} " + f"(truncated for preview)
" + ) + else: + preview_lines = lines + truncation_html = "" + + escaped_lang = html_lib.escape(lang) + line_label = f"{total_lines} line{'s' if total_lines != 1 else ''}" + + return ( + f'

' + f"Code block {index} of {total} · " + f"{line_label}

" + # + # Code block container + f'
' + # + # ── Header bar (matches CodeBlock.svelte sticky header) ── + f'
' + f'{escaped_lang}' + f"
" + # + # ── Scrollable code area ── + f'
' + f'
'
+            f"{self._build_numbered_code(preview_lines, lang)}"
+            f"
" + # + # Truncation notice (if applicable) + f"{truncation_html}" + f"
" + ) + + def _highlight_code(self, code: str, lang: str) -> str | None: + """ + Syntax-highlight code using Pygments with github-dark inline styles. + + Returns the highlighted HTML string, or None if Pygments is + unavailable or the language is not recognized. Uses + ``noclasses=True`` so all colors are inlined as ``style`` + attributes, which survive DOMPurify sanitization. + """ + if not _HAS_PYGMENTS: + return None + + try: + lexer = get_lexer_by_name(lang) + except _LexerNotFound: + return None + + # github-dark matches Open WebUI's highlight.js theme + for style in ("github-dark", "monokai"): + try: + formatter = _HtmlFormatter( + noclasses=True, + style=style, + nowrap=True, + ) + return _pygments_highlight(code, lexer, formatter) + except Exception: + continue + + return None + + def _build_numbered_code(self, lines: list[str], lang: str = "") -> str: + """ + Build HTML for code lines with inline line numbers and optional + syntax highlighting. + + If Pygments is available the code is highlighted first, then + split by newlines so each line can be prefixed with a dimmed, + right-aligned line number ````. + """ + # Attempt syntax highlighting + preview_code = "\n".join(lines) + highlighted = self._highlight_code(preview_code, lang) + + if highlighted is not None: + h_lines = highlighted.rstrip("\n").split("\n") + else: + h_lines = None + + gutter_width = len(str(len(lines))) + parts = [] + for i in range(len(lines)): + # Use highlighted line if available, otherwise escape + if h_lines is not None and i < len(h_lines): + content = h_lines[i] if h_lines[i] else " " + else: + content = html_lib.escape(lines[i]) if lines[i] else " " + + num_str = str(i + 1).rjust(gutter_width) + parts.append( + f'{num_str}{content}' + ) + return "\n".join(parts) + + def _build_single_download_js(self, code: str, filename: str, ext: str) -> str: + """Build JavaScript to download a single file.""" + mime = self._get_mime_type(ext) + escaped_code = ( + code.replace("\\", "\\\\").replace("`", "\\`").replace("${", "\\${") + ) + return f""" + (function() {{ + const content = `{escaped_code}`; + const blob = new Blob([content], {{ type: '{mime}' }}); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = '{filename}'; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }})(); + """ + + def _build_batch_download_js(self, blocks: list[dict]) -> str: + """ + Build JavaScript that downloads multiple files via the browser. + Uses a staggered approach to avoid popup blockers. + """ + file_defs = [] + for block in blocks: + mime = self._get_mime_type(block["extension"]) + escaped_code = ( + block["code"] + .replace("\\", "\\\\") + .replace("`", "\\`") + .replace("${", "\\${") + ) + file_defs.append( + f'{{ filename: "{block["filename"]}", content: `{escaped_code}`, mime: "{mime}" }}' + ) + + files_array = ",\n ".join(file_defs) + + return f""" + (function() {{ + const files = [ + {files_array} + ]; + + function downloadFile(file) {{ + const blob = new Blob([file.content], {{ type: file.mime }}); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = file.filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }} + + // Stagger downloads to avoid browser throttling + files.forEach(function(file, index) {{ + setTimeout(function() {{ + downloadFile(file); + }}, index * 350); + }}); + }})(); + """ + + async def _confirm_and_download( + self, + blocks: list[dict], + __event_emitter__, + __event_call__, + ) -> None: + """ + Interactive download flow with navigation between code blocks. + + For **multiple blocks**, shows a custom modal (via ``execute`` + event) with ◀ Prev / Skip ▶ / ✓ Save buttons so the user can + freely navigate between code blocks, review the syntax- + highlighted preview, rename each file, and choose which to save. + + For a **single block**, uses the simpler built-in ``input`` + modal since there is nothing to navigate. + """ + total = len(blocks) + saved_count = 0 + saved_files = [] + + if total == 1: + # ── Single block — use the simpler built-in input modal ── + block = blocks[0] + preview = self._build_code_preview(block, 1, 1) + + response = await __event_call__( + { + "type": "input", + "data": { + "title": "Save Code Block", + "message": preview, + "placeholder": "Enter filename...", + "value": block["filename"], + }, + } + ) + + if response is not False and response is not None: + filename = str(response).strip() or block["filename"] + if not filename: + filename = block["filename"] + if "." in filename: + ext = filename.rsplit(".", 1)[-1] + else: + ext = block["extension"] + filename = f"{filename}.{ext}" + + js_code = self._build_single_download_js(block["code"], filename, ext) + await __event_emitter__({"type": "execute", "data": {"code": js_code}}) + saved_count = 1 + saved_files.append(filename) + else: + # ── Multiple blocks — custom navigator modal ───────────── + # Pre-render all code previews for instant navigation + previews = [ + self._build_code_preview(block, i + 1, total) + for i, block in enumerate(blocks) + ] + + current = 0 + while 0 <= current < total: + block = blocks[current] + + js_code = self._build_navigator_js( + preview_html=previews[current], + filename=block["filename"], + current=current + 1, + total=total, + ) + + result = await __event_call__( + {"type": "execute", "data": {"code": js_code}} + ) + + # Determine the user's action + if isinstance(result, dict): + user_action = result.get("action", "done") + else: + user_action = "done" + + if user_action == "save": + filename = ( + str(result.get("filename", "")).strip() or block["filename"] + ) + if "." in filename: + ext = filename.rsplit(".", 1)[-1] + else: + ext = block["extension"] + filename = f"{filename}.{ext}" + + dl_js = self._build_single_download_js(block["code"], filename, ext) + await __event_emitter__( + {"type": "execute", "data": {"code": dl_js}} + ) + + saved_count += 1 + saved_files.append(filename) + + await __event_emitter__( + { + "type": "status", + "data": { + "description": f"Saved {filename}", + "done": False, + }, + } + ) + current += 1 + + elif user_action == "skip": + current += 1 + + elif user_action == "prev": + current = max(0, current - 1) + + else: # "done" or unknown + break + + # ── Final status ───────────────────────────────────────────── + if saved_count == 0: + description = "No code blocks were saved." + else: + noun = "file" if saved_count == 1 else "files" + file_list = ", ".join(saved_files) + description = f"Saved {saved_count} {noun}: {file_list}" + + await __event_emitter__( + { + "type": "status", + "data": {"description": description, "done": True}, + } + ) + + def _build_navigator_js( + self, + preview_html: str, + filename: str, + current: int, + total: int, + ) -> str: + """ + Build JavaScript that creates a custom modal with navigation + buttons (◀ Prev / Skip ▶ / ✓ Save). + + The JS returns a Promise that resolves when the user clicks a + button. The resolved value is an object like + ``{ action: 'save', filename: '...' }``. The ``execute`` event + awaits this Promise and passes the result back to Python via + the socket.io acknowledgment callback. + """ + import json + + preview_json = json.dumps(preview_html) + filename_json = json.dumps(filename) + + return f""" +return new Promise(function(resolve) {{ + var previewHtml = {preview_json}; + var defaultFilename = {filename_json}; + var current = {current}; + var total = {total}; + + /* ── Overlay ─────────────────────────────────────────────── */ + var overlay = document.createElement('div'); + overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);z-index:99999999;display:flex;justify-content:center;align-items:center;opacity:0;transition:opacity 0.1s ease;'; + + /* ── Modal ───────────────────────────────────────────────── */ + var modal = document.createElement('div'); + modal.style.cssText = 'background:rgba(3,7,18,0.95);border-radius:2rem;max-width:32rem;width:calc(100% - 2rem);max-height:90dvh;display:flex;flex-direction:column;box-shadow:0 25px 50px rgba(0,0,0,0.5);border:1px solid rgb(17,24,39);transform:scale(0.985);opacity:0;transition:transform 0.1s ease,opacity 0.1s ease;'; + modal.addEventListener('mousedown', function(e) {{ e.stopPropagation(); }}); + overlay.addEventListener('mousedown', function() {{ finish('done'); }}); + + /* ── Title ───────────────────────────────────────────────── */ + var titleEl = document.createElement('div'); + titleEl.style.cssText = 'padding:1.5rem 1.75rem 0;font-size:1.125rem;font-weight:500;color:#e5e7eb;'; + titleEl.textContent = 'Save Code Block (' + current + '/' + total + ')'; + + /* ── Code preview ────────────────────────────────────────── */ + var content = document.createElement('div'); + content.style.cssText = 'padding:0.75rem 1.75rem 0;overflow-y:auto;flex:1 1 auto;min-height:0;font-size:0.875rem;color:#9ca3af;'; + content.innerHTML = previewHtml; + + /* ── Filename input ──────────────────────────────────────── */ + var inputWrap = document.createElement('div'); + inputWrap.style.cssText = 'padding:0 1.75rem;'; + var input = document.createElement('input'); + input.type = 'text'; + input.value = defaultFilename; + input.placeholder = 'Enter filename...'; + input.style.cssText = 'width:100%;box-sizing:border-box;margin-top:0.75rem;border-radius:0.75rem;padding:0.625rem 1rem;font-size:0.875rem;color:#d1d5db;background:rgb(17,24,39);border:none;outline:none;'; + inputWrap.appendChild(input); + + /* ── Buttons ─────────────────────────────────────────────── */ + var btnRow = document.createElement('div'); + btnRow.style.cssText = 'display:flex;gap:0.375rem;padding:1.5rem 1.75rem;'; + + function makeBtn(text, bg, fg) {{ + var b = document.createElement('button'); + b.textContent = text; + b.style.cssText = 'padding:0.5rem 0;border-radius:1.5rem;border:none;cursor:pointer;font-size:0.875rem;font-weight:500;transition:opacity 0.15s;flex:1;background:' + bg + ';color:' + fg + ';'; + b.addEventListener('mouseenter', function() {{ b.style.opacity = '0.85'; }}); + b.addEventListener('mouseleave', function() {{ b.style.opacity = '1'; }}); + return b; + }} + + var prevBtn = makeBtn('\\u25C0 Prev', 'rgb(31,41,55)', '#9ca3af'); + if (current <= 1) {{ + prevBtn.disabled = true; + prevBtn.style.opacity = '0.3'; + prevBtn.style.cursor = 'default'; + }} + prevBtn.addEventListener('click', function() {{ if (current > 1) finish('prev'); }}); + + var skipBtn = makeBtn('Skip \\u25B6', 'rgb(31,41,55)', '#9ca3af'); + skipBtn.addEventListener('click', function() {{ finish('skip'); }}); + + var saveBtn = makeBtn('\\u2713 Save', 'rgb(243,244,246)', 'rgb(31,41,55)'); + saveBtn.style.fontWeight = '600'; + saveBtn.addEventListener('click', function() {{ finish('save'); }}); + + btnRow.append(prevBtn, skipBtn, saveBtn); + modal.append(titleEl, content, inputWrap, btnRow); + overlay.appendChild(modal); + + /* ── Lock body scroll ────────────────────────────────────── */ + var prevOverflow = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + document.body.appendChild(overlay); + + /* ── Animate in ──────────────────────────────────────────── */ + requestAnimationFrame(function() {{ + overlay.style.opacity = '1'; + modal.style.transform = 'scale(1)'; + modal.style.opacity = '1'; + input.focus(); + input.select(); + }}); + + /* ── Keyboard shortcuts ──────────────────────────────────── */ + function handleKey(e) {{ + if (e.key === 'Escape') {{ finish('done'); }} + else if (e.key === 'Enter') {{ e.preventDefault(); finish('save'); }} + }} + document.addEventListener('keydown', handleKey, true); + + /* ── Cleanup and resolve ─────────────────────────────────── */ + var resolved = false; + function finish(action) {{ + if (resolved) return; + resolved = true; + document.removeEventListener('keydown', handleKey, true); + document.body.style.overflow = prevOverflow || ''; + overlay.style.opacity = '0'; + modal.style.transform = 'scale(0.985)'; + modal.style.opacity = '0'; + setTimeout(function() {{ + try {{ document.body.removeChild(overlay); }} catch(e) {{}} + resolve({{ action: action, filename: input.value.trim() || defaultFilename }}); + }}, 120); + }} +}}); +""" + + return indices + + async def _auto_download( + self, + blocks: list[dict], + __event_emitter__, + ) -> None: + """Download all code blocks immediately without confirmation.""" + count = len(blocks) + file_list = ", ".join(b["filename"] for b in blocks) + noun = "file" if count == 1 else "files" + + await __event_emitter__( + { + "type": "status", + "data": { + "description": f"Found {count} code {noun}. Downloading: {file_list}", + "done": False, + }, + } + ) + + js_code = self._build_batch_download_js(blocks) + + await __event_emitter__( + { + "type": "execute", + "data": {"code": js_code}, + } + ) + + await __event_emitter__( + { + "type": "status", + "data": { + "description": f"Downloaded {count} {noun}: {file_list}", + "done": True, + }, + } + ) + + async def action( + self, + body: dict, + __user__=None, + __event_emitter__=None, + __event_call__=None, + ) -> None: + """Extract code blocks from the assistant's response and download them.""" + + # Resolve effective settings: user valves override admin valves + user_valves = ( + __user__.get("valves") if __user__ and isinstance(__user__, dict) else None + ) + + auto_download = ( + user_valves.auto_download if user_valves else self.valves.auto_download + ) + default_filename = ( + user_valves.default_filename + if user_valves + else self.valves.default_filename + ) + + # Temporarily apply the resolved filename for extraction + original_filename = self.valves.default_filename + self.valves.default_filename = default_filename + + if __event_emitter__: + await __event_emitter__( + { + "type": "status", + "data": { + "description": "Scanning for code blocks...", + "done": False, + }, + } + ) + + # Get the messages from the body + messages = body.get("messages", []) + + if not messages: + self.valves.default_filename = original_filename + if __event_emitter__: + await __event_emitter__( + { + "type": "status", + "data": { + "description": "No messages found.", + "done": True, + }, + } + ) + return + + # Find the target assistant message. + # The action button is attached to a specific message — `body["id"]` + # corresponds to the message_id. Walk backwards to find the matching + # assistant message. + target_message_id = body.get("id") + target_content = None + + for msg in reversed(messages): + if msg.get("role") == "assistant": + # If we can match by id, do so; otherwise take the last assistant msg + if target_message_id and msg.get("id") == target_message_id: + target_content = msg.get("content", "") + break + elif not target_content: + target_content = msg.get("content", "") + + if not target_content: + self.valves.default_filename = original_filename + if __event_emitter__: + await __event_emitter__( + { + "type": "status", + "data": { + "description": "No assistant response found.", + "done": True, + }, + } + ) + return + + # Extract code blocks + blocks = self._extract_code_blocks(target_content) + + # Restore the original valve value + self.valves.default_filename = original_filename + + if not blocks: + if __event_emitter__: + await __event_emitter__( + { + "type": "status", + "data": { + "description": "No code blocks found in the response.", + "done": True, + }, + } + ) + return + + # Dispatch to the appropriate mode + if auto_download: + await self._auto_download(blocks, __event_emitter__) + else: + if not __event_call__: + # Fallback: if __event_call__ isn't available, use auto download + await self._auto_download(blocks, __event_emitter__) + else: + await self._confirm_and_download( + blocks, __event_emitter__, __event_call__ + ) diff --git a/integrations/openwebui-community-plugins/export_to_excel.py b/integrations/openwebui-community-plugins/export_to_excel.py new file mode 100644 index 0000000..d2e59a1 --- /dev/null +++ b/integrations/openwebui-community-plugins/export_to_excel.py @@ -0,0 +1,1552 @@ +""" +title: Export to Excel +author: Fu-Jie +author_url: https://github.com/Fu-Jie/openwebui-extensions +funding_url: https://github.com/open-webui +version: 0.3.11 +required_open_webui_version: 0.10.2 +openwebui_id: 244b8f9d-7459-47d6-84d3-c7ae8e3ec710 +icon_url: data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxwYXRoIGQ9Ik0xNSAySDZhMiAyIDAgMCAwLTIgMnYxNmEyIDIgMCAwIDAgMiAyaDEyYTIgMiAwIDAgMCAyLTJWN1oiLz48cGF0aCBkPSJNMTQgMnY0YTIgMiAwIDAgMCAyIDJoNCIvPjxwYXRoIGQ9Ik04IDEzaDIiLz48cGF0aCBkPSJNMTQgMTNoMiIvPjxwYXRoIGQ9Ik04IDE3aDIiLz48cGF0aCBkPSJNMTQgMTdoMiIvPjwvc3ZnPg== +description: Extracts tables from chat messages and exports them to Excel (.xlsx) files with smart formatting. +""" + +import os +import pandas as pd +import re +import base64 +from fastapi import FastAPI, HTTPException +from typing import Optional, Callable, Awaitable, Any, List, Dict +import datetime +import asyncio +from inspect import iscoroutinefunction +from open_webui.models.chats import Chats +from open_webui.models.chat_messages import ChatMessages +from open_webui.models.users import Users +from open_webui.utils.chat import generate_chat_completion +from open_webui.utils.misc import convert_output_to_messages +from pydantic import BaseModel, Field +from typing import Literal + +# ── OpenWebUI version detection for async DB compatibility ────────── +try: + from open_webui.env import VERSION as _owui_version +except ImportError: + _owui_version = "0.0.0" + + +def _owui_version_ge(threshold: str) -> bool: + try: + v = [int(x) for x in _owui_version.split(".")[:3]] + t = [int(x) for x in threshold.split(".")[:3]] + return v >= t + except (ValueError, TypeError): + return False + + +async def _call_db(method, *args, **kwargs): + if iscoroutinefunction(method): + return await method(*args, **kwargs) + res = method(*args, **kwargs) + if asyncio.iscoroutine(res): + return await res + return res + + +app = FastAPI() + + +class Action: + class Valves(BaseModel): + TITLE_SOURCE: Literal["chat_title", "ai_generated", "markdown_title"] = Field( + default="chat_title", + description="Title Source: 'chat_title' (Chat Title), 'ai_generated' (AI Generated), 'markdown_title' (Markdown Title)", + ) + SHOW_STATUS: bool = Field( + default=True, + description="Whether to show operation status updates.", + ) + EXPORT_SCOPE: Literal["last_message", "all_messages"] = Field( + default="last_message", + description="Export Scope: 'last_message' (Last Message Only), 'all_messages' (All Messages)", + ) + MODEL_ID: str = Field( + default="", + description="Model ID for AI title generation. Leave empty to use the current chat model.", + ) + SHOW_DEBUG_LOG: bool = Field( + default=False, + description="Whether to print debug logs in the browser console.", + ) + ROW_HEIGHT: int = Field( + default=0, + description="Fixed row height in points for data rows. 0 = auto-adjust based on content. Set e.g. 20 for compact single-line rows.", + ) + COLUMN_WIDTH: int = Field( + default=0, + description="Fixed column width in characters for all data columns. 0 = auto-adjust based on content. Set e.g. 15 for uniform compact columns.", + ) + + def __init__(self): + self.valves = self.Valves() + + async def _emit_status( + self, + emitter: Optional[Callable[[Any], Awaitable[None]]], + description: str, + done: bool = False, + ): + """Emits a status update event.""" + if self.valves.SHOW_STATUS and emitter: + await emitter( + {"type": "status", "data": {"description": description, "done": done}} + ) + + async def _emit_notification( + self, + emitter: Optional[Callable[[Any], Awaitable[None]]], + content: str, + ntype: str = "info", + ): + """Emits a notification event (info, success, warning, error).""" + if emitter: + await emitter( + {"type": "notification", "data": {"type": ntype, "content": content}} + ) + + async def _emit_debug_log(self, emitter, title: str, data: dict): + """Print structured debug logs in the browser console""" + if not self.valves.SHOW_DEBUG_LOG or not emitter: + return + + try: + import json + + js_code = f""" + (async function() {{ + console.group("🛠️ {title}"); + console.log({json.dumps(data, ensure_ascii=False)}); + console.groupEnd(); + }})(); + """ + + await emitter({"type": "execute", "data": {"code": js_code}}) + except Exception as e: + print(f"Error emitting debug log: {e}") + + async def action( + self, + body: dict, + __user__=None, + __event_emitter__=None, + __event_call__: Optional[Callable[[Any], Awaitable[None]]] = None, + __request__: Optional[Any] = None, + ): + print(f"action:{__name__}") + if isinstance(__user__, (list, tuple)): + user_language = ( + __user__[0].get("language", "en-US") if __user__ else "en-US" + ) + user_name = __user__[0].get("name", "User") if __user__[0] else "User" + user_id = ( + __user__[0]["id"] + if __user__ and "id" in __user__[0] + else "unknown_user" + ) + elif isinstance(__user__, dict): + user_language = __user__.get("language", "en-US") + user_name = __user__.get("name", "User") + user_id = __user__.get("id", "unknown_user") + + if __event_emitter__: + await __event_emitter__( + { + "type": "status", + "data": {"description": "Saving to file...", "done": False}, + } + ) + + try: + messages = body.get("messages", []) + if not messages: + raise HTTPException(status_code=400, detail="No messages found.") + + # Determine messages to process based on scope + target_messages = [] + if self.valves.EXPORT_SCOPE == "all_messages": + target_messages = messages + else: + target_messages = [messages[-1]] + + chat_ctx = self._get_chat_context(body, None) + chat_id = chat_ctx["chat_id"] + + # OWUI 0.10+ stores replies as structured `output` and leaves the flat + # `content` empty; recover each target message's text so table + # extraction and title generation see it. + if chat_id: + for msg in target_messages: + existing = msg.get("content") + if not (isinstance(existing, str) and existing.strip()): + recovered = await self._fetch_message_output_text( + chat_id, str(msg.get("id") or "") + ) + if recovered: + msg["content"] = recovered + + all_tables = [] + all_sheet_names = [] + + # Process messages + for msg_index, msg in enumerate(target_messages): + content = msg.get("content", "") + tables = self.extract_tables_from_message(content) + + if not tables: + continue + + # Generate sheet names for this message's tables + # If multiple messages, we need to ensure uniqueness across the whole workbook + # We'll generate base names here and deduplicate later if needed, + # or better: generate unique names on the fly. + + # Extract headers for this message + headers = [] + lines = content.split("\n") + for i, line in enumerate(lines): + if re.match(r"^#{1,6}\s+", line): + headers.append( + { + "text": re.sub(r"^#{1,6}\s+", "", line).strip(), + "line_num": i, + } + ) + + for table_index, table in enumerate(tables): + sheet_name = "" + + # 1. Try Markdown Header (closest above) + table_start_line = table["start_line"] - 1 + closest_header_text = None + candidate_headers = [ + h for h in headers if h["line_num"] < table_start_line + ] + if candidate_headers: + closest_header = max( + candidate_headers, key=lambda x: x["line_num"] + ) + closest_header_text = closest_header["text"] + + if closest_header_text: + sheet_name = self.clean_sheet_name(closest_header_text) + + # 2. AI Generated (Only if explicitly enabled and we have a request object) + # Note: Generating titles for EVERY table in all messages might be too slow/expensive. + # We'll skip this for 'all_messages' scope to avoid timeout, unless it's just one message. + if ( + not sheet_name + and self.valves.TITLE_SOURCE == "ai_generated" + and len(target_messages) == 1 + ): + # Logic for AI generation (simplified for now, reusing existing flow if possible) + pass + + # 3. Fallback: Message Index + if not sheet_name: + if len(target_messages) > 1: + # Use global message index (from original list if possible, but here we iterate target_messages) + # Let's use the loop index. + # If multiple tables in one message: "Msg 1 - Table 1" + if len(tables) > 1: + sheet_name = f"Msg{msg_index+1}-Tab{table_index+1}" + else: + sheet_name = f"Msg{msg_index+1}" + else: + # Single message (last_message scope) + if len(tables) > 1: + sheet_name = f"Table {table_index+1}" + else: + sheet_name = "Sheet1" + + all_tables.append(table) + all_sheet_names.append(sheet_name) + + if not all_tables: + raise HTTPException( + status_code=400, detail="No tables found in the selected scope." + ) + + # Deduplicate sheet names + final_sheet_names = [] + seen_names = {} + for name in all_sheet_names: + base_name = name + counter = 1 + while name in seen_names: + name = f"{base_name} ({counter})" + counter += 1 + seen_names[name] = True + final_sheet_names.append(name) + + # Notify user about the number of tables found + table_count = len(all_tables) + if self.valves.EXPORT_SCOPE == "all_messages": + await self._emit_notification( + __event_emitter__, + f"Found {table_count} table(s) in all messages.", + "info", + ) + # Wait a moment for user to see the notification before download dialog + await asyncio.sleep(1.5) + # Generate Workbook Title (Filename) + # Use the title of the chat, or the first header of the first message with tables + title = "" + chat_title = "" + if chat_id: + chat_title = await self.fetch_chat_title(chat_id, user_id) + + if ( + self.valves.TITLE_SOURCE == "chat_title" + or not self.valves.TITLE_SOURCE + ): + title = chat_title + elif self.valves.TITLE_SOURCE == "ai_generated": + # Use AI to generate a title based on message content + if target_messages and __request__: + # Get content from the first message with tables + content_for_title = "" + for msg in target_messages: + msg_content = msg.get("content", "") + if msg_content: + content_for_title = msg_content + break + if content_for_title: + title = await self.generate_title_using_ai( + body, + content_for_title, + user_id, + __request__, + __event_emitter__, + ) + elif self.valves.TITLE_SOURCE == "markdown_title": + # Try to find first header in the first message that has content + for msg in target_messages: + extracted = self.extract_title(msg.get("content", "")) + if extracted: + title = extracted + break + + # Fallback for filename + if not title: + if chat_title: + title = chat_title + else: + # Try extracting from content again if not already tried + if self.valves.TITLE_SOURCE != "markdown_title": + for msg in target_messages: + extracted = self.extract_title(msg.get("content", "")) + if extracted: + title = extracted + break + + current_datetime = datetime.datetime.now() + formatted_date = current_datetime.strftime("%Y%m%d") + + if not title: + workbook_name = f"{user_name}_{formatted_date}" + else: + workbook_name = self.clean_filename(title) + + filename = f"{workbook_name}.xlsx" + excel_file_path = os.path.join( + "app", "backend", "data", "temp", filename + ) + + os.makedirs(os.path.dirname(excel_file_path), exist_ok=True) + + # Save tables to Excel + self.save_tables_to_excel_enhanced( + all_tables, excel_file_path, final_sheet_names + ) + + # Trigger file download + if __event_call__: + with open(excel_file_path, "rb") as file: + file_content = file.read() + base64_blob = base64.b64encode(file_content).decode("utf-8") + + await __event_call__( + { + "type": "execute", + "data": { + "code": f""" + try {{ + const base64Data = "{base64_blob}"; + const binaryData = atob(base64Data); + const arrayBuffer = new Uint8Array(binaryData.length); + for (let i = 0; i < binaryData.length; i++) {{ + arrayBuffer[i] = binaryData.charCodeAt(i); + }} + const blob = new Blob([arrayBuffer], {{ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }}); + const filename = "{filename}"; + + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.style.display = "none"; + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + URL.revokeObjectURL(url); + document.body.removeChild(a); + }} catch (error) {{ + console.error('Error triggering download:', error); + }} + """ + }, + } + ) + await __event_emitter__( + { + "type": "status", + "data": {"description": "File saved", "done": True}, + } + ) + + # Clean up temp file + if os.path.exists(excel_file_path): + os.remove(excel_file_path) + + return {"message": "Download triggered"} + + except HTTPException as e: + print(f"Error processing tables: {str(e.detail)}") + await __event_emitter__( + { + "type": "status", + "data": { + "description": f"Error saving file: {e.detail}", + "done": True, + }, + } + ) + await self._emit_notification( + __event_emitter__, "No tables found to export!", "error" + ) + raise e + except Exception as e: + print(f"Error processing tables: {str(e)}") + await __event_emitter__( + { + "type": "status", + "data": { + "description": f"Error saving file: {str(e)}", + "done": True, + }, + } + ) + await self._emit_notification( + __event_emitter__, "No tables found to export!", "error" + ) + + async def generate_title_using_ai( + self, + body: dict, + content: str, + user_id: str, + request: Any, + event_emitter: Callable = None, + ) -> str: + if not request: + return "" + + try: + user_obj = await _call_db(Users.get_user_by_id, user_id) + # Use configured MODEL_ID or fallback to current chat model + model = ( + self.valves.MODEL_ID.strip() + if self.valves.MODEL_ID + else body.get("model") + ) + + payload = { + "model": model, + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant. Generate a short, concise filename (max 10 words) for an Excel export based on the following content. Do not use quotes or file extensions. Avoid special characters that are invalid in filenames. Only output the filename.", + }, + {"role": "user", "content": content[:2000]}, # Limit content length + ], + "stream": False, + } + + # Define the generation task + async def generate_task(): + return await generate_chat_completion(request, payload, user_obj) + + # Define the notification task + async def notification_task(): + # Send initial notification immediately + if event_emitter: + await self._emit_notification( + event_emitter, + "AI is generating a filename for your Excel file...", + "info", + ) + + # Subsequent notifications every 5 seconds + while True: + await asyncio.sleep(5) + if event_emitter: + await self._emit_notification( + event_emitter, + "Still generating filename, please be patient...", + "info", + ) + + # Run tasks concurrently + gen_future = asyncio.ensure_future(generate_task()) + notify_future = asyncio.ensure_future(notification_task()) + + done, pending = await asyncio.wait( + [gen_future, notify_future], return_when=asyncio.FIRST_COMPLETED + ) + + # Cancel notification task if generation is done + if not notify_future.done(): + notify_future.cancel() + + # Get result + if gen_future in done: + response = gen_future.result() + if response and "choices" in response: + return response["choices"][0]["message"]["content"].strip() + else: + # Should not happen if return_when=FIRST_COMPLETED and we cancel notify + await gen_future + response = gen_future.result() + if response and "choices" in response: + return response["choices"][0]["message"]["content"].strip() + + except Exception as e: + print(f"Error generating title: {e}") + if event_emitter: + await self._emit_notification( + event_emitter, + f"AI title generation failed, using default title. Error: {str(e)}", + "warning", + ) + + return "" + + def extract_title(self, content: str) -> str: + """Extract title from Markdown h1/h2 only""" + lines = content.split("\n") + for line in lines: + # Match h1-h2 headings only + match = re.match(r"^#{1,2}\s+(.+)$", line.strip()) + if match: + return match.group(1).strip() + return "" + + def _get_user_context(self, __user__: Optional[Dict[str, Any]]) -> Dict[str, str]: + """Safely extracts user context information.""" + if isinstance(__user__, (list, tuple)): + user_data = __user__[0] if __user__ else {} + elif isinstance(__user__, dict): + user_data = __user__ + else: + user_data = {} + + return { + "user_id": user_data.get("id", "unknown_user"), + "user_name": user_data.get("name", "User"), + "user_language": user_data.get("language", "en-US"), + } + + def _get_chat_context( + self, body: dict, __metadata__: Optional[dict] = None + ) -> Dict[str, str]: + """ + Unified extraction of chat context information (chat_id, message_id). + Prioritizes extraction from body, then metadata. + """ + chat_id = "" + message_id = "" + + # 1. Try to get from body + if isinstance(body, dict): + chat_id = body.get("chat_id", "") + message_id = body.get("id", "") # message_id is usually 'id' in body + + # Check body.metadata as fallback + if not chat_id or not message_id: + body_metadata = body.get("metadata", {}) + if isinstance(body_metadata, dict): + if not chat_id: + chat_id = body_metadata.get("chat_id", "") + if not message_id: + message_id = body_metadata.get("message_id", "") + + # 2. Try to get from __metadata__ (as supplement) + if __metadata__ and isinstance(__metadata__, dict): + if not chat_id: + chat_id = __metadata__.get("chat_id", "") + if not message_id: + message_id = __metadata__.get("message_id", "") + + return { + "chat_id": str(chat_id).strip(), + "message_id": str(message_id).strip(), + } + + async def fetch_chat_title(self, chat_id: str, user_id: str = "") -> str: + """Fetch chat title from database by chat_id""" + if not chat_id: + return "" + + try: + chat = None + if user_id: + chat = await _call_db( + Chats.get_chat_by_id_and_user_id, id=chat_id, user_id=user_id + ) + if not chat: + chat = await _call_db(Chats.get_chat_by_id, chat_id) + except Exception as exc: + print(f"Failed to load chat {chat_id}: {exc}") + return "" + + if not chat: + return "" + + data = getattr(chat, "chat", {}) or {} + title = data.get("title") or getattr(chat, "title", "") + return title.strip() if isinstance(title, str) else "" + + def _extract_text_from_output(self, output: Any) -> str: + """Rebuild assistant text from structured ``output`` via OWUI's + ``convert_output_to_messages`` (reasoning excluded); "" if none.""" + if not isinstance(output, list) or not output: + return "" + reconstructed = convert_output_to_messages(output) + assistant_texts = [ + msg["content"] + for msg in reconstructed + if isinstance(msg, dict) + and msg.get("role") == "assistant" + and isinstance(msg.get("content"), str) + and msg["content"].strip() + ] + return "\n".join(assistant_texts) + + async def _fetch_message_output_text(self, chat_id: str, message_id: str) -> str: + """Assistant text for a message via OWUI's ChatMessages store: its structured + ``output`` reconstructed by convert_output_to_messages. "" if not found.""" + if not chat_id or not message_id: + return "" + message = await _call_db( + ChatMessages.get_message_by_id, f"{chat_id}-{message_id}" + ) + return self._extract_text_from_output(message.output) if message else "" + + def extract_tables_from_message(self, message: str) -> List[Dict]: + """ + Extract Markdown tables and their positions from message text + Returns structure: [{ + "data": table data, + "start_line": start line number, + "end_line": end line number + }] + """ + table_row_pattern = r"^\s*\|.*\|.*\s*$" + rows = message.split("\n") + tables = [] + current_table = [] + start_line = None + current_line = 0 + + for row in rows: + current_line += 1 + if re.search(table_row_pattern, row): + if start_line is None: + start_line = current_line # Record table start line + + # Process table row + cells = [cell.strip() for cell in row.strip().strip("|").split("|")] + + # Skip separator row + is_separator_row = all(re.fullmatch(r"[:\-]+", cell) for cell in cells) + if not is_separator_row: + current_table.append(cells) + elif current_table: + # Table ends + tables.append( + { + "data": current_table, + "start_line": start_line, + "end_line": current_line - 1, + } + ) + current_table = [] + start_line = None + + # Process the last table + if current_table: + tables.append( + { + "data": current_table, + "start_line": start_line, + "end_line": current_line, + } + ) + + return tables + + def generate_names_from_content(self, content: str, tables: List[Dict]) -> tuple: + """ + Generate workbook name and sheet names based on content + - Ignore non-empty paragraphs, only use markdown headers (h1-h6). + - Single table: Use the closest header as workbook and sheet name. + - Multiple tables: Use the first header in the document as workbook name, and closest header for each table as sheet name. + - Default naming: + - Workbook: Handled in main flow (user_yyyymmdd.xlsx). + - Sheet: Sheet1, Sheet2, ... + """ + lines = content.split("\n") + workbook_name = "" + sheet_names = [] + all_headers = [] + + # 1. Find all h1-h6 headers and their positions + for i, line in enumerate(lines): + if re.match(r"^#{1,6}\s+", line): + all_headers.append( + {"text": re.sub(r"^#{1,6}\s+", "", line).strip(), "line_num": i} + ) + + # 2. Generate sheet name for each table + for i, table in enumerate(tables): + table_start_line = table["start_line"] - 1 # Convert to 0-based index + closest_header_text = None + + # Find closest header above current table + candidate_headers = [ + h for h in all_headers if h["line_num"] < table_start_line + ] + if candidate_headers: + # Find the header with the largest line number among candidates + closest_header = max(candidate_headers, key=lambda x: x["line_num"]) + closest_header_text = closest_header["text"] + + if closest_header_text: + # Clean and add found header + sheet_names.append(self.clean_sheet_name(closest_header_text)) + else: + # If no header found, use default name "Sheet{i+1}" + sheet_names.append(f"Sheet{i+1}") + + # 3. Determine workbook name based on table count + if len(tables) == 1: + # Single table: Use its sheet name as workbook name (if not default "Sheet1") + if sheet_names[0] != "Sheet1": + workbook_name = sheet_names[0] + elif len(tables) > 1: + # Multiple tables: Use the first header in the document as workbook name + if all_headers: + # Find header with smallest line number + first_header = min(all_headers, key=lambda x: x["line_num"]) + workbook_name = first_header["text"] + + # 4. Clean workbook name (if empty, main flow will use default name) + workbook_name = self.clean_filename(workbook_name) if workbook_name else "" + + return workbook_name, sheet_names + + def clean_filename(self, name: str) -> str: + """Clean illegal characters and clamp length for filesystem safety.""" + if not isinstance(name, str): + return "" + cleaned = re.sub(r'[\\/*?:"<>|]', "", name) + cleaned = re.sub(r"\s+", " ", cleaned).strip().strip(".") + return cleaned[:50].strip() + + def clean_sheet_name(self, name: str) -> str: + """Clean sheet name (limit 31 chars, remove illegal chars)""" + name = re.sub(r"[\\/*?[\]:]", "", name).strip() + return name[:31] if len(name) > 31 else name + + # ======================== Enhanced Formatting ======================== + + def calculate_text_width(self, text: str) -> float: + """ + Calculate text display width, considering CJK characters + CJK characters count as 2 units, others as 1 unit + """ + if not text: + return 0 + + width = 0 + for char in str(text): + # Check if CJK character + if "\u4e00" <= char <= "\u9fff" or "\u3000" <= char <= "\u303f": + width += 2 + else: + width += 1 + + return width + + def calculate_text_height(self, text: str, max_width: int = 50) -> int: + """ + Calculate required lines for text display + Based on newlines and text length + """ + if not text: + return 1 + + text = str(text) + # Calculate lines from newlines + explicit_lines = text.count("\n") + 1 + + # Calculate extra lines from wrapping + text_width = self.calculate_text_width(text.replace("\n", "")) + wrapped_lines = max( + 1, int(text_width / max_width) + (1 if text_width % max_width > 0 else 0) + ) + + return max(explicit_lines, wrapped_lines) + + def get_column_letter(self, col_index: int) -> str: + """ + Convert column index to Excel column letter (A, B, C, ..., AA, AB, ...) + """ + result = "" + while col_index >= 0: + result = chr(65 + col_index % 26) + result + col_index = col_index // 26 - 1 + return result + + def determine_content_type(self, header: str, values: list) -> str: + """ + Intelligently determine data type based on header and content + Returns: 'number', 'date', 'sequence', 'text' + """ + header_lower = str(header).lower().strip() + + # Check header keywords + number_keywords = [ + "quantity", + "amount", + "price", + "cost", + "revenue", + "expense", + "total", + "subtotal", + "percentage", + "%", + "ratio", + "rate", + "value", + "score", + "points", + ] + date_keywords = ["date", "time", "year", "month", "moment"] + sequence_keywords = [ + "no", + "no.", + "id", + "index", + "rank", + "order", + "sequence", + "code", + ] + + # Check header + for keyword in number_keywords: + if keyword in header_lower: + return "number" + + for keyword in date_keywords: + if keyword in header_lower: + return "date" + + for keyword in sequence_keywords: + if keyword in header_lower: + return "sequence" + + # Check data content + if not values: + return "text" + + sample_values = [ + str(v).strip() for v in values[:10] if str(v).strip() + ] # Use first 10 non-empty values as sample + if not sample_values: + return "text" + + numeric_count = 0 + date_count = 0 + sequence_count = 0 + + for value in sample_values: + # Check if number + try: + float(value.replace(",", "").replace("%", "")) + numeric_count += 1 + continue + except ValueError: + pass + + # Check if date format + date_patterns = [ + r"\d{4}[-/]\d{1,2}[-/]\d{1,2}", + r"\d{1,2}[-/]\d{1,2}[-/]\d{4}", + r"\d{4}\d{2}\d{2}", + ] + for pattern in date_patterns: + if re.match(pattern, value): + date_count += 1 + break + + # Check if sequence format + if ( + re.match(r"^\d+$", value) and len(value) <= 4 + ): # Pure digits and <= 4 chars, likely sequence + sequence_count += 1 + + total_count = len(sample_values) + + # Determine type based on ratio + if numeric_count / total_count >= 0.7: + return "number" + elif date_count / total_count >= 0.7: + return "date" + elif sequence_count / total_count >= 0.8 and sequence_count > 2: + return "sequence" + else: + return "text" + + def save_tables_to_excel_enhanced( + self, tables: List[Dict], file_path: str, sheet_names: List[str] + ): + """ + Enhanced Excel saving function with standard formatting + """ + try: + with pd.ExcelWriter(file_path, engine="xlsxwriter") as writer: + workbook = writer.book + + # OpenWebUI-style theme colors + HEADER_BG = "#1f2937" # Dark gray (matches OpenWebUI sidebar) + HEADER_FG = "#ffffff" # White text + ROW_ODD_BG = "#ffffff" # White for odd rows + ROW_EVEN_BG = "#f3f4f6" # Light gray for even rows (zebra striping) + BORDER_COLOR = "#e5e7eb" # Light border + + # Define header style - Center aligned + header_format = workbook.add_format( + { + "bold": True, + "font_size": 11, + "font_name": "Arial", + "font_color": HEADER_FG, + "bg_color": HEADER_BG, + "border": 1, + "border_color": BORDER_COLOR, + "align": "center", + "valign": "vcenter", + "text_wrap": True, + } + ) + + # Text cell style - Left aligned (odd rows) + text_format = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_ODD_BG, + "align": "left", + "valign": "vcenter", + "text_wrap": True, + } + ) + + # Text cell style - Left aligned (even rows - zebra) + text_format_alt = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_EVEN_BG, + "align": "left", + "valign": "vcenter", + "text_wrap": True, + } + ) + + # Number cell style - Right aligned + number_format = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_ODD_BG, + "align": "right", + "valign": "vcenter", + } + ) + + number_format_alt = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_EVEN_BG, + "align": "right", + "valign": "vcenter", + } + ) + + # Integer format - Right aligned + integer_format = workbook.add_format( + { + "num_format": "0", + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_ODD_BG, + "align": "right", + "valign": "vcenter", + } + ) + + integer_format_alt = workbook.add_format( + { + "num_format": "0", + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_EVEN_BG, + "align": "right", + "valign": "vcenter", + } + ) + + # Decimal format - Right aligned + decimal_format = workbook.add_format( + { + "num_format": "0.00", + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_ODD_BG, + "align": "right", + "valign": "vcenter", + } + ) + + decimal_format_alt = workbook.add_format( + { + "num_format": "0.00", + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_EVEN_BG, + "align": "right", + "valign": "vcenter", + } + ) + + # Date format - Center aligned + date_format = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_ODD_BG, + "align": "center", + "valign": "vcenter", + "text_wrap": True, + } + ) + + date_format_alt = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_EVEN_BG, + "align": "center", + "valign": "vcenter", + "text_wrap": True, + } + ) + + # Sequence format - Center aligned + sequence_format = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_ODD_BG, + "align": "center", + "valign": "vcenter", + } + ) + + sequence_format_alt = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_EVEN_BG, + "align": "center", + "valign": "vcenter", + } + ) + + # Bold cell style (for full cell bolding) + text_bold_format = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_ODD_BG, + "align": "left", + "valign": "vcenter", + "text_wrap": True, + "bold": True, + } + ) + + text_bold_format_alt = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_EVEN_BG, + "align": "left", + "valign": "vcenter", + "text_wrap": True, + "bold": True, + } + ) + + # Italic cell style (for full cell italics) + text_italic_format = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_ODD_BG, + "align": "left", + "valign": "vcenter", + "text_wrap": True, + "italic": True, + } + ) + + text_italic_format_alt = workbook.add_format( + { + "font_name": "Arial", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": ROW_EVEN_BG, + "align": "left", + "valign": "vcenter", + "text_wrap": True, + "italic": True, + } + ) + + # Code cell style (for inline code with highlight background) + CODE_BG = "#f0f0f0" # Light gray background for code + text_code_format = workbook.add_format( + { + "font_name": "Consolas", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": CODE_BG, + "align": "left", + "valign": "vcenter", + "text_wrap": True, + } + ) + + text_code_format_alt = workbook.add_format( + { + "font_name": "Consolas", + "font_size": 10, + "border": 1, + "border_color": BORDER_COLOR, + "bg_color": CODE_BG, + "align": "left", + "valign": "vcenter", + "text_wrap": True, + } + ) + + for i, table in enumerate(tables): + try: + table_data = table["data"] + if not table_data or len(table_data) < 1: + print(f"Skipping empty table at index {i}") + continue + + print(f"Processing table {i+1} with {len(table_data)} rows") + + # Get sheet name + sheet_name = ( + sheet_names[i] if i < len(sheet_names) else f"Sheet{i+1}" + ) + + # Create DataFrame + headers = [ + str(cell).strip() + for cell in table_data[0] + if str(cell).strip() + ] + if not headers: + print(f"Warning: No valid headers found for table {i+1}") + headers = [f"Col{j+1}" for j in range(len(table_data[0]))] + + data_rows = [] + if len(table_data) > 1: + max_cols = len(headers) + for row in table_data[1:]: + processed_row = [] + for j in range(max_cols): + if j < len(row): + processed_row.append(str(row[j])) + else: + processed_row.append("") + data_rows.append(processed_row) + df = pd.DataFrame(data_rows, columns=headers) + else: + df = pd.DataFrame(columns=headers) + + print(f"DataFrame created with columns: {list(df.columns)}") + + # Smart data type conversion using pandas infer_objects + for col in df.columns: + # Try numeric conversion first + try: + df[col] = pd.to_numeric(df[col]) + except (ValueError, TypeError): + # Try datetime conversion + try: + df[col] = pd.to_datetime(df[col], errors="raise") + except (ValueError, TypeError): + # Keep as string, use infer_objects for optimization + df[col] = df[col].infer_objects() + + # Write data first (without header) + df.to_excel( + writer, + sheet_name=sheet_name, + index=False, + header=False, + startrow=1, + ) + worksheet = writer.sheets[sheet_name] + + # Apply enhanced formatting with zebra striping + formats = { + "header": header_format, + "text": [text_format, text_format_alt], + "number": [number_format, number_format_alt], + "integer": [integer_format, integer_format_alt], + "decimal": [decimal_format, decimal_format_alt], + "date": [date_format, date_format_alt], + "sequence": [sequence_format, sequence_format_alt], + "bold": [text_bold_format, text_bold_format_alt], + "italic": [text_italic_format, text_italic_format_alt], + "code": [text_code_format, text_code_format_alt], + } + self.apply_enhanced_formatting( + worksheet, + df, + headers, + workbook, + formats, + row_height=self.valves.ROW_HEIGHT, + column_width=self.valves.COLUMN_WIDTH, + ) + + except Exception as e: + print(f"Error processing table {i+1}: {str(e)}") + continue + + except Exception as e: + print(f"Error saving Excel file: {str(e)}") + raise + + def apply_enhanced_formatting( + self, + worksheet, + df, + headers, + workbook, + formats, + row_height: int = 0, + column_width: int = 0, + ): + """ + Apply enhanced formatting with zebra striping + - Header: Center aligned (dark background) + - Number: Right aligned + - Text: Left aligned + - Date: Center aligned + - Sequence: Center aligned + - Zebra striping: alternating row colors + - Supports full cell Markdown bold (**text**) and italic (*text*) + - row_height: Fixed row height in points. 0 = auto-adjust based on content. + - column_width: Fixed column width in characters. 0 = auto-adjust based on content. + """ + try: + # Extract format from formats dict + header_format = formats["header"] + + # 1. Write headers (Center aligned) + print(f"Writing headers with enhanced alignment: {headers}") + for col_idx, header in enumerate(headers): + if header and str(header).strip(): + worksheet.write(0, col_idx, str(header).strip(), header_format) + else: + default_header = f"Col{col_idx+1}" + worksheet.write(0, col_idx, default_header, header_format) + + # 2. Analyze column types + column_types = {} + for col_idx, column in enumerate(headers): + if col_idx < len(df.columns): + column_values = df.iloc[:, col_idx].tolist() + column_types[col_idx] = self.determine_content_type( + column, column_values + ) + print( + f"Column '{column}' determined as type: {column_types[col_idx]}" + ) + else: + column_types[col_idx] = "text" + + # 3. Write and format data with zebra striping + for row_idx, row in df.iterrows(): + # Determine if odd or even row (0-indexed, so row 0 is odd visually as row 1) + is_alt_row = ( + row_idx % 2 == 1 + ) # Even index = odd visual row, use alt format + + for col_idx, value in enumerate(row): + content_type = column_types.get(col_idx, "text") + + # Select format based on content type and zebra striping + fmt_idx = 1 if is_alt_row else 0 + + if content_type == "number": + # Number - Right aligned + if pd.api.types.is_numeric_dtype(df.iloc[:, col_idx]): + if pd.api.types.is_integer_dtype(df.iloc[:, col_idx]): + current_format = formats["integer"][fmt_idx] + else: + try: + numeric_value = float(value) + if numeric_value.is_integer(): + current_format = formats["integer"][fmt_idx] + value = int(numeric_value) + else: + current_format = formats["decimal"][fmt_idx] + except (ValueError, TypeError): + current_format = formats["decimal"][fmt_idx] + else: + current_format = formats["number"][fmt_idx] + + elif content_type == "date": + # Date - Center aligned + current_format = formats["date"][fmt_idx] + + elif content_type == "sequence": + # Sequence - Center aligned + current_format = formats["sequence"][fmt_idx] + + else: + # Text - Left aligned + current_format = formats["text"][fmt_idx] + + if content_type == "text" and isinstance(value, str): + # Check for full cell bold (**text**) + match_bold = re.fullmatch(r"\*\*(.+)\*\*", value.strip()) + # Check for full cell italic (*text*) + match_italic = re.fullmatch(r"\*(.+)\*", value.strip()) + # Check for full cell code (`text`) + match_code = re.fullmatch(r"`(.+)`", value.strip()) + + if match_bold: + # Extract content and apply bold format + clean_value = match_bold.group(1) + worksheet.write( + row_idx + 1, + col_idx, + clean_value, + formats["bold"][fmt_idx], + ) + elif match_italic: + # Extract content and apply italic format + clean_value = match_italic.group(1) + worksheet.write( + row_idx + 1, + col_idx, + clean_value, + formats["italic"][fmt_idx], + ) + elif match_code: + # Extract content and apply code format (highlighted) + clean_value = match_code.group(1) + worksheet.write( + row_idx + 1, + col_idx, + clean_value, + formats["code"][fmt_idx], + ) + else: + # Remove partial markdown formatting symbols (can't render partial formatting in Excel) + # Remove bold markers **text** -> text + clean_value = re.sub(r"\*\*(.+?)\*\*", r"\1", value) + # Remove italic markers *text* -> text (but not inside **) + clean_value = re.sub( + r"(? text + clean_value = re.sub(r"`(.+?)`", r"\1", clean_value) + worksheet.write( + row_idx + 1, col_idx, clean_value, current_format + ) + else: + worksheet.write(row_idx + 1, col_idx, value, current_format) + + # 4. Column width + if column_width > 0: + # Fixed column width mode + for col_idx in range(len(headers)): + col_letter = self.get_column_letter(col_idx) + worksheet.set_column(f"{col_letter}:{col_letter}", column_width) + else: + # Auto-adjust column width based on content + for col_idx, column in enumerate(headers): + col_letter = self.get_column_letter(col_idx) + + # Calculate header width + header_width = self.calculate_text_width(str(column)) + + # Calculate max data width + max_data_width = 0 + if not df.empty and col_idx < len(df.columns): + for value in df.iloc[:, col_idx]: + value_width = self.calculate_text_width(str(value)) + max_data_width = max(max_data_width, value_width) + + # Base width + base_width = max(header_width, max_data_width) + + # Adjust width based on type + content_type = column_types.get(col_idx, "text") + if content_type == "sequence": + optimal_width = max(8, min(15, base_width + 2)) + elif content_type == "number": + optimal_width = max(12, min(25, base_width + 3)) + elif content_type == "date": + optimal_width = max(15, min(20, base_width + 2)) + else: + if base_width <= 10: + optimal_width = base_width + 3 + elif base_width <= 20: + optimal_width = base_width + 4 + else: + optimal_width = base_width + 5 + optimal_width = max(10, min(60, optimal_width)) + + worksheet.set_column(f"{col_letter}:{col_letter}", optimal_width) + + # 5. Row height + worksheet.set_row(0, 35) + + if row_height > 0: + # Fixed row height mode + for row_idx in range(len(df)): + worksheet.set_row(row_idx + 1, row_height) + else: + # Auto-adjust row height based on content + for row_idx, row in df.iterrows(): + max_row_height = 20 + + for col_idx, value in enumerate(row): + if col_idx < len(headers): + col_width = min( + 60, + max( + 10, + self.calculate_text_width(str(headers[col_idx])) + + 5, + ), + ) + else: + col_width = 15 + + cell_lines = self.calculate_text_height(str(value), col_width) + cell_height = cell_lines * 20 + + max_row_height = max(max_row_height, cell_height) + + final_height = min(120, max_row_height) + worksheet.set_row(row_idx + 1, final_height) + + print(f"Successfully applied enhanced formatting") + + except Exception as e: + print(f"Warning: Failed to apply enhanced formatting: {str(e)}") + self.apply_basic_formatting_fallback(worksheet, df) + + def apply_basic_formatting_fallback(self, worksheet, df): + """ + Basic formatting fallback + """ + try: + for i, column in enumerate(df.columns): + column_width = ( + max( + len(str(column)), + (df[column].astype(str).map(len).max() if not df.empty else 0), + ) + + 2 + ) + + col_letter = self.get_column_letter(i) + worksheet.set_column( + f"{col_letter}:{col_letter}", min(60, max(10, column_width)) + ) + + except Exception as e: + print(f"Error in basic formatting: {str(e)}") + + except Exception as e: + print(f"Error in basic formatting: {str(e)}") diff --git a/integrations/openwebui-community-plugins/export_to_word.py b/integrations/openwebui-community-plugins/export_to_word.py new file mode 100644 index 0000000..1eb4b98 --- /dev/null +++ b/integrations/openwebui-community-plugins/export_to_word.py @@ -0,0 +1,3436 @@ +""" +title: Export to Word Enhanced +author: Fu-Jie +author_url: https://github.com/Fu-Jie/openwebui-extensions +funding_url: https://github.com/open-webui +version: 0.5.3 +required_open_webui_version: 0.10.2 +openwebui_id: fca6a315-2a45-42cc-8c96-55cbc85f87f2 +icon_url: data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNiAyMmEyIDIgMCAwIDEtMi0yVjRhMiAyIDAgMCAxIDItMmg4YTIuNCAyLjQgMCAwIDEgMS43MDQuNzA2bDMuNTg4IDMuNTg4QTIuNCAyLjQgMCAwIDEgMjAgOHYxMmEyIDIgMCAwIDEtMiAyeiIgLz4KICA8cGF0aCBkPSJNMTQgMnY1YTEgMSAwIDAgMCAxIDFoNSIgLz4KICA8cGF0aCBkPSJNMTAgOUg4IiAvPgogIDxwYXRoIGQ9Ik0xNiAxM0g4IiAvPgogIDxwYXRoIGQ9Ik0xNiAxN0g4IiAvPgo8L3N2Zz4K +requirements: python-docx, Pygments, latex2mathml, mathml2omml +description: Export current conversation from Markdown to Word (.docx) with Mermaid diagrams rendered client-side (Mermaid.js, SVG+PNG), LaTeX math, real hyperlinks, improved tables, syntax highlighting, and blockquote support. +notes: Added i18n support, configurable fonts/colors, and parallel PNG rendering optimization. +""" + +from __future__ import annotations + +import re +import base64 +import datetime +import time +import io +import asyncio +from inspect import iscoroutinefunction +import logging +import hashlib +import struct +import zlib +import binascii +from pathlib import Path +from dataclasses import dataclass +from typing import Optional, Callable, Awaitable, Any, List, Tuple, Dict, cast +from urllib.parse import quote +from docx import Document +from docx.shared import Pt, Inches, RGBColor, Cm +from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING +from docx.enum.table import WD_TABLE_ALIGNMENT +from docx.enum.style import WD_STYLE_TYPE +from docx.opc.constants import RELATIONSHIP_TYPE as RT +from docx.oxml import parse_xml +from docx.oxml.ns import qn, nsmap +from docx.oxml import OxmlElement +from open_webui.models.chats import Chats +from open_webui.models.chat_messages import ChatMessages +from open_webui.models.users import Users +from open_webui.storage.provider import Storage +from open_webui.retrieval.web.utils import get_ssrf_safe_session, validate_url +from open_webui.utils.chat import generate_chat_completion + +# OWUI 0.10+ stores replies as structured `output`; rebuilds text (reasoning excluded). Requires >= 0.10.2. +from open_webui.utils.misc import convert_output_to_messages +from pydantic import BaseModel, Field + +# Files are used to embed internal /api/v1/files//content images. +try: + from open_webui.models.files import Files # type: ignore +except Exception: # pragma: no cover - depends on host Open WebUI runtime + Files = None + +# Pygments for syntax highlighting +try: + from pygments import lex + from pygments.lexers import get_lexer_by_name, TextLexer + from pygments.token import Token + + PYGMENTS_AVAILABLE = True +except ImportError: + PYGMENTS_AVAILABLE = False + +try: + from latex2mathml.converter import convert as latex_to_mathml + import mathml2omml + + LATEX_MATH_AVAILABLE = True +except Exception: + LATEX_MATH_AVAILABLE = False + + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", +) +logger = logging.getLogger(__name__) + +# ── OpenWebUI version detection for async DB compatibility ────────── +try: + from open_webui.env import VERSION as _owui_version +except ImportError: + _owui_version = "0.0.0" + + +def _owui_version_ge(threshold: str) -> bool: + try: + v = [int(x) for x in _owui_version.split(".")[:3]] + t = [int(x) for x in threshold.split(".")[:3]] + return v >= t + except (ValueError, TypeError): + return False + + +async def _call_db(method, *args, **kwargs): + if iscoroutinefunction(method): + return await method(*args, **kwargs) + res = method(*args, **kwargs) + if asyncio.iscoroutine(res): + return await res + return res + + +_AUTO_URL_RE = re.compile(r"(?:https?://|www\.)[^\s<>()]+") +_DATA_IMAGE_URL_RE = re.compile( + r"^data:(?Pimage/[a-z0-9.+-]+)\s*;\s*base64\s*,\s*(?P.*)$", + re.IGNORECASE | re.DOTALL, +) +_OWUI_API_FILE_ID_RE = re.compile( + r"/api/v1/files/(?P[A-Za-z0-9-]+)(?:/content)?(?:[/?#]|$)", + re.IGNORECASE, +) +_CURRENCY_NUMBER_RE = re.compile(r"^\d[\d,]*(?:\.\d+)?$") + +_TRANSPARENT_1PX_PNG = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABDQottAAAAABJRU5ErkJggg==" +) + +_ASVG_NS = "http://schemas.microsoft.com/office/drawing/2016/SVG/main" +nsmap.setdefault("asvg", _ASVG_NS) + +_ALL_DETAILS_RE = re.compile( + r"]*>.*?", re.IGNORECASE | re.DOTALL +) +_THINK_RE = re.compile(r"]*>.*?", re.IGNORECASE | re.DOTALL) +_ANALYSIS_RE = re.compile( + r"]*>.*?", re.IGNORECASE | re.DOTALL +) +# Markdown reference-definition lines (`[label]: target`) render invisibly, so they +# must be stripped from the export. Same pattern OpenWebUI uses in removeFormattings() +# — src/lib/utils/index.ts: `/^\[[^\]]+\]:\s*.*$/gm`. +_MD_REFERENCE_DEF_RE = re.compile(r"^\[[^\]]+\]:\s*.*$\n?", re.MULTILINE) +# Markdown image URL: ![alt](url ...) with optional <...> wrapping — captures the URL. +_MD_IMAGE_URL_RE = re.compile(r"!\[[^\]]*\]\(\s*\s]+)") + + +@dataclass(frozen=True) +class _CitationRef: + idx: int + anchor: str + title: str + url: Optional[str] + source_id: str + + +class Action: + # Internationalization message dictionaries + _I18N_MESSAGES: Dict[str, Dict[str, str]] = { + "en": { + "converting": "Converting to Word document...", + "exported": "Word document exported", + "success": "Successfully exported to {filename}", + "error_no_content": "No content found to export!", + "error_export": "Error exporting Word document: {error}", + "export_failed": "Export failed: {error}", + "figure_prefix": "Figure", + "references": "References", + }, + "zh": { + "converting": "正在转换为 Word 文档...", + "exported": "Word 文档导出完成", + "success": "成功导出至 {filename}", + "error_no_content": "没有找到可导出的内容!", + "error_export": "导出 Word 文档时出错: {error}", + "export_failed": "导出失败: {error}", + "figure_prefix": "图", + "references": "参考文献", + }, + } + + class Valves(BaseModel): + TITLE_SOURCE: str = Field( + default="chat_title", + description="Title Source: 'chat_title' (Chat Title), 'ai_generated' (AI Generated), 'markdown_title' (Markdown Title)", + ) + SHOW_STATUS: bool = Field( + default=True, + description="Whether to show operation status updates.", + ) + SHOW_DEBUG_LOG: bool = Field( + default=False, + description="Whether to print debug logs in the browser console.", + ) + + MAX_EMBED_IMAGE_MB: int = Field( + default=20, + description="Maximum image size to embed into DOCX (MB). Applies to data URLs and /api/v1/files//content images.", + ) + EMBED_EXTERNAL_IMAGES: bool = Field( + default=False, + description="Download and embed images from external http(s) URLs, capped by MAX_EMBED_IMAGE_MB. Unfetchable images show a placeholder instead.", + ) + + # Font configuration + FONT_LATIN: str = Field( + default="Times New Roman", + description="Font for Latin characters (e.g., 'Times New Roman', 'Calibri', 'Arial')", + ) + FONT_ASIAN: str = Field( + default="SimSun", + description="Font for Asian characters (e.g., 'SimSun', 'Microsoft YaHei', 'PingFang SC')", + ) + FONT_CODE: str = Field( + default="Consolas", + description="Font for code blocks and inline code (e.g., 'Consolas', 'Courier New', 'Monaco')", + ) + FONT_H1_LATIN: str = Field( + default="Aptos Display", + description="Font for Heading 1 Latin characters (e.g., 'Aptos Display', 'Calibri Light'). Empty uses FONT_LATIN.", + ) + FONT_H1_ASIAN: str = Field( + default="SimHei", + description="Font for Heading 1 Asian characters (e.g., 'SimHei', 'Microsoft YaHei'). Empty uses FONT_ASIAN.", + ) + FONT_H2_LATIN: str = Field( + default="Calibri Light", + description="Font for Heading 2 Latin characters (e.g., 'Aptos Display', 'Calibri Light'). Empty uses FONT_LATIN.", + ) + FONT_H2_ASIAN: str = Field( + default="SimHei", + description="Font for Heading 2 Asian characters (e.g., 'SimHei', 'Microsoft YaHei'). Empty uses FONT_ASIAN.", + ) + + # Title alignment + TITLE_ALIGNMENT: str = Field( + default="center", + description="Title alignment: 'left', 'center', or 'right'", + ) + + # Table styling + TABLE_HEADER_COLOR: str = Field( + default="F2F2F2", + description="Table header background color (hex, without #)", + ) + TABLE_ZEBRA_COLOR: str = Field( + default="FBFBFB", + description="Table zebra stripe background color for alternate rows (hex, without #)", + ) + + MERMAID_JS_URL: str = Field( + default="https://cdn.jsdelivr.net/npm/mermaid@11.12.2/dist/mermaid.min.js", + description="Mermaid JS CDN URL", + ) + MERMAID_JSZIP_URL: str = Field( + default="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js", + description="JSZip CDN URL (DOCX manipulation)", + ) + MERMAID_PNG_SCALE: float = Field( + default=3.0, + description="PNG render resolution multiplier (higher = clearer, larger file)", + ) + MERMAID_DISPLAY_SCALE: float = Field( + default=1.0, + description="Diagram width relative to available page width (<=1 recommended)", + ) + MERMAID_OPTIMIZE_LAYOUT: bool = Field( + default=False, + description="Optimize Mermaid layout: convert LR to TD for graph/flowchart", + ) + MERMAID_BACKGROUND: str = Field( + default="", + description="Mermaid background color. Empty = transparent (recommended for Word dark mode). Used only for optional PNG fill.", + ) + + MERMAID_CAPTIONS_ENABLE: bool = Field( + default=True, + description="Add figure captions under Mermaid images/charts", + ) + MERMAID_CAPTION_STYLE: str = Field( + default="Caption", + description="Paragraph style name for Mermaid captions (uses 'Caption' if available, otherwise creates a safe custom style)", + ) + MERMAID_CAPTION_PREFIX: str = Field( + default="", + description="Caption prefix label (e.g., 'Figure' or '图'). Empty = auto-detect based on user language.", + ) + + MATH_ENABLE: bool = Field( + default=True, + description="Enable LaTeX math block conversion (\\[...\\] and $$...$$) into Word equations", + ) + MATH_INLINE_DOLLAR_ENABLE: bool = Field( + default=True, + description="Enable inline $...$ math conversion into Word equations (conservative parsing to reduce false positives)", + ) + + # Language configuration + UI_LANGUAGE: str = Field( + default="en", + description="UI language for export messages. Options: 'en' (English), 'zh' (Chinese)", + ) + + class UserValves(BaseModel): + TITLE_SOURCE: Optional[str] = Field( + default=None, + description="Title Source: 'chat_title' (Chat Title), 'ai_generated' (AI Generated), 'markdown_title' (Markdown Title)", + ) + UI_LANGUAGE: Optional[str] = Field( + default=None, + description="UI language for export messages. Options: 'en' (English), 'zh' (Chinese)", + ) + FONT_LATIN: Optional[str] = Field( + default=None, + description="Font for Latin characters (e.g., 'Times New Roman', 'Calibri', 'Arial')", + ) + FONT_ASIAN: Optional[str] = Field( + default=None, + description="Font for Asian characters (e.g., 'SimSun', 'Microsoft YaHei', 'PingFang SC')", + ) + FONT_CODE: Optional[str] = Field( + default=None, + description="Font for code blocks and inline code (e.g., 'Consolas', 'Courier New', 'Monaco')", + ) + FONT_H1_LATIN: Optional[str] = Field( + default=None, + description="Font for Heading 1 Latin characters (e.g., 'Aptos Display', 'Calibri Light'). Empty uses FONT_LATIN.", + ) + FONT_H1_ASIAN: Optional[str] = Field( + default=None, + description="Font for Heading 1 Asian characters (e.g., 'SimHei', 'Microsoft YaHei'). Empty uses FONT_ASIAN.", + ) + FONT_H2_LATIN: Optional[str] = Field( + default=None, + description="Font for Heading 2 Latin characters (e.g., 'Aptos Display', 'Calibri Light'). Empty uses FONT_LATIN.", + ) + FONT_H2_ASIAN: Optional[str] = Field( + default=None, + description="Font for Heading 2 Asian characters (e.g., 'SimHei', 'Microsoft YaHei'). Empty uses FONT_ASIAN.", + ) + TABLE_HEADER_COLOR: Optional[str] = Field( + default=None, + description="Table header background color (hex, without #)", + ) + TABLE_ZEBRA_COLOR: Optional[str] = Field( + default=None, + description="Table zebra stripe background color for alternate rows (hex, without #)", + ) + MERMAID_PNG_SCALE: Optional[float] = Field( + default=None, + description="PNG render resolution multiplier (higher = clearer, larger file)", + ) + MERMAID_DISPLAY_SCALE: Optional[float] = Field( + default=None, + description="Diagram width relative to available page width (<=1 recommended)", + ) + MERMAID_OPTIMIZE_LAYOUT: Optional[bool] = Field( + default=None, + description="Optimize Mermaid layout: convert LR to TD for graph/flowchart", + ) + MERMAID_BACKGROUND: Optional[str] = Field( + default=None, + description="Mermaid background color. Empty = transparent (recommended for Word dark mode). Used only for optional PNG fill.", + ) + MERMAID_CAPTIONS_ENABLE: Optional[bool] = Field( + default=None, + description="Add figure captions under Mermaid images/charts", + ) + MATH_ENABLE: Optional[bool] = Field( + default=None, + description="Enable LaTeX math block conversion (\\\\[...\\\\] and $$...$$) into Word equations", + ) + MATH_INLINE_DOLLAR_ENABLE: Optional[bool] = Field( + default=None, + description="Enable inline $...$ math conversion into Word equations (conservative parsing to reduce false positives)", + ) + + def __init__(self): + self.valves = self.Valves() + self._mermaid_figure_counter: int = 0 + self._mermaid_placeholder_counter: int = 0 + self._caption_style_name: Optional[str] = None + self._citation_anchor_by_index: Dict[int, str] = {} + self._citation_refs: List[_CitationRef] = [] + self._bookmark_id_counter: int = 1 + self._active_doc: Optional[Document] = None + self._user_lang: str = "en" # Will be set per-request + self._prefetched_files: dict = ( + {} + ) # file_id -> FileModel, pre-fetched async before sync doc build + self._prefetched_external_images: dict = {} # url -> bytes, pre-fetched async + + def _get_lang_key(self, user_language: str) -> str: + """Convert user language code to i18n key (e.g., 'zh-CN' -> 'zh', 'en-US' -> 'en').""" + lang = (user_language or "en").lower().split("-")[0] + return lang if lang in self._I18N_MESSAGES else "en" + + def _get_msg(self, key: str, **kwargs) -> str: + """Get internationalized message by key with optional formatting.""" + messages = self._I18N_MESSAGES.get(self._user_lang, self._I18N_MESSAGES["en"]) + msg = messages.get(key, self._I18N_MESSAGES["en"].get(key, key)) + if kwargs: + try: + return msg.format(**kwargs) + except KeyError: + return msg + return msg + + def _get_user_context(self, __user__: Optional[Dict[str, Any]]) -> Dict[str, str]: + """Safely extracts user context information.""" + if isinstance(__user__, (list, tuple)): + user_data = __user__[0] if __user__ else {} + elif isinstance(__user__, dict): + user_data = __user__ + else: + user_data = {} + + return { + "user_id": user_data.get("id", "unknown_user"), + "user_name": user_data.get("name", "User"), + "user_language": user_data.get("language", "en-US"), + } + + def _get_chat_context( + self, body: dict, __metadata__: Optional[dict] = None + ) -> Dict[str, str]: + """ + Unified extraction of chat context information (chat_id, message_id). + Prioritizes extraction from body, then metadata. + """ + chat_id = "" + message_id = "" + + # 1. Try to get from body + if isinstance(body, dict): + chat_id = body.get("chat_id", "") + message_id = body.get("id", "") # message_id is usually 'id' in body + + # Check body.metadata as fallback + if not chat_id or not message_id: + body_metadata = body.get("metadata", {}) + if isinstance(body_metadata, dict): + if not chat_id: + chat_id = body_metadata.get("chat_id", "") + if not message_id: + message_id = body_metadata.get("message_id", "") + + # 2. Try to get from __metadata__ (as supplement) + if __metadata__ and isinstance(__metadata__, dict): + if not chat_id: + chat_id = __metadata__.get("chat_id", "") + if not message_id: + message_id = __metadata__.get("message_id", "") + + return { + "chat_id": str(chat_id).strip(), + "message_id": str(message_id).strip(), + } + + async def _emit_status( + self, + emitter: Optional[Callable[[Any], Awaitable[None]]], + description: str, + done: bool = False, + ): + """Emits a status update event.""" + if self.valves.SHOW_STATUS and emitter: + await emitter( + {"type": "status", "data": {"description": description, "done": done}} + ) + + async def _emit_notification( + self, + emitter: Optional[Callable[[Any], Awaitable[None]]], + content: str, + ntype: str = "info", + ): + """Emits a notification event (info, success, warning, error).""" + if emitter: + await emitter( + {"type": "notification", "data": {"type": ntype, "content": content}} + ) + + async def _emit_debug_log(self, emitter, title: str, data: dict): + """Print structured debug logs in the browser console""" + if not self.valves.SHOW_DEBUG_LOG or not emitter: + return + + try: + import json + + js_code = f""" + (async function() {{ + console.group("🛠️ {title}"); + console.log({json.dumps(data, ensure_ascii=False)}); + console.groupEnd(); + }})(); + """ + + await emitter({"type": "execute", "data": {"code": js_code}}) + except Exception as e: + print(f"Error emitting debug log: {e}") + + async def action( + self, + body: dict, + __user__=None, + __event_emitter__=None, + __event_call__: Optional[Callable[[Any], Awaitable[None]]] = None, + __metadata__: Optional[dict] = None, + __request__: Optional[Any] = None, + ): + logger.info(f"action:{__name__}") + + # Parse user info + user_name = "User" + user_id = "unknown_user" + if isinstance(__user__, (list, tuple)): + user_name = __user__[0].get("name", "User") if __user__[0] else "User" + user_id = ( + __user__[0]["id"] + if __user__ and "id" in __user__[0] + else "unknown_user" + ) + elif isinstance(__user__, dict): + user_name = __user__.get("name", "User") + user_id = __user__.get("id", "unknown_user") + + # Apply UserValves if present + if __user__: + # Robustly parse UserValves whether it's a dict or Pydantic model + raw_valves = __user__.get("valves", {}) + if isinstance(raw_valves, self.UserValves): + user_valves = raw_valves + elif isinstance(raw_valves, dict): + user_valves = self.UserValves(**raw_valves) + else: + user_valves = None + + if user_valves: + for key, value in user_valves.model_dump(exclude_unset=True).items(): + # Only override if the value is not None (and explicitly set) + if hasattr(self.valves, key) and value is not None: + setattr(self.valves, key, value) + + # Get user language from Valves configuration + self._user_lang = self._get_lang_key(self.valves.UI_LANGUAGE) + + if __event_emitter__: + last_assistant_message = body["messages"][-1] + + await __event_emitter__( + { + "type": "status", + "data": { + "description": self._get_msg("converting"), + "done": False, + }, + } + ) + + try: + chat_ctx = self._get_chat_context(body, __metadata__) + chat_id = chat_ctx["chat_id"] + + message_content = last_assistant_message.get("content") + if isinstance(message_content, str): + if __event_emitter__ and self.valves.SHOW_DEBUG_LOG: + debug_data = {} + for name, regex in [ + ("Details Block", _ALL_DETAILS_RE), + ("Think Block", _THINK_RE), + ("Analysis Block", _ANALYSIS_RE), + ]: + matches = regex.findall(message_content) + if matches: + debug_data[name] = [ + (m[:200] + "...") if len(m) > 200 else m + for m in matches + ] + if debug_data: + await self._emit_debug_log( + __event_emitter__, + "Context Stripping Analysis", + debug_data, + ) + + # Log font configuration + await self._emit_debug_log( + __event_emitter__, + "Font Configuration", + { + "Latin Font": self.valves.FONT_LATIN, + "Asian Font": self.valves.FONT_ASIAN, + "Code Font": self.valves.FONT_CODE, + }, + ) + + message_content = self._strip_reasoning_blocks(message_content) + + # 0.10+ leaves flat `content` empty (text is in `output`, not + # forwarded here); recover it from the DB. + if not message_content or ( + isinstance(message_content, str) and not message_content.strip() + ): + output_text = await self._fetch_message_output_text( + chat_id, chat_ctx["message_id"] + ) + if output_text: + message_content = self._strip_reasoning_blocks(output_text) + + if isinstance(message_content, str): + message_content = self._strip_reference_definitions(message_content) + + if not message_content or not message_content.strip(): + await self._emit_notification( + __event_emitter__, self._get_msg("error_no_content"), "error" + ) + return + + # Generate filename + title = "" + + # Fetch chat_title directly via chat_id as it's usually missing in body + chat_title = "" + if chat_id: + chat_title = await self.fetch_chat_title(chat_id, user_id) + + if ( + self.valves.TITLE_SOURCE.strip() == "chat_title" + or not self.valves.TITLE_SOURCE.strip() + ): + title = chat_title + elif self.valves.TITLE_SOURCE.strip() == "markdown_title": + title = self.extract_title(message_content) + elif self.valves.TITLE_SOURCE.strip() == "ai_generated": + title = await self.generate_title_using_ai( + body, message_content, user_id, __request__ + ) + + # Fallback logic + if not title: + if self.valves.TITLE_SOURCE.strip() != "chat_title" and chat_title: + title = chat_title + elif self.valves.TITLE_SOURCE.strip() != "markdown_title": + extracted = self.extract_title(message_content) + if extracted: + title = extracted + + current_datetime = datetime.datetime.now() + formatted_date = current_datetime.strftime("%Y%m%d") + + cleaned_title = self.clean_filename(title) if title else "" + if cleaned_title: + filename = f"{cleaned_title}.docx" + else: + clean_user = self.clean_filename(user_name) + filename = f"{clean_user}_{formatted_date}.docx" + + # Escape filename for JS string + js_filename = filename.replace("\\", "\\\\").replace('"', '\\"') + + top_heading = "" + if chat_title: + top_heading = chat_title + elif title: + top_heading = title + + # Create Word document; if no h1 exists, inject chat title as h1 + has_h1 = bool(re.search(r"^#\s+.+$", message_content, re.MULTILINE)) + + # Heading level normalization (Relative Algorithm) + if not has_h1: + # Find the minimum heading level in the content + heading_levels = [ + len(m.group(1)) + for m in re.finditer(r"^(#+)\s+.+$", message_content, re.MULTILINE) + ] + if heading_levels: + min_level = min(heading_levels) + if min_level > 1: + shift = min_level - 1 + # Perform promotion: replace ^### with ^##, etc. + def _promote(m): + current_level = len(m.group(1)) + new_level = max(1, current_level - shift) + return "#" * new_level + m.group(2) + + message_content = re.sub( + r"^(#+)(\s+.+)$", _promote, message_content, flags=re.MULTILINE + ) + # After promotion, we now have H1 + has_h1 = True + await self._emit_debug_log( + __event_emitter__, + "Relative Heading Algorithm", + f"Normalized headings by shifting -{shift} levels.", + ) + sources = ( + last_assistant_message.get("sources") or body.get("sources") or [] + ) + doc = await self.markdown_to_docx( + message_content, + top_heading=top_heading, + + sources=sources, + event_emitter=__event_emitter__, + user_name=user_name, + title=title, + ) + + # Save to memory + doc_buffer = io.BytesIO() + doc.save(doc_buffer) + doc_buffer.seek(0) + file_content = doc_buffer.read() + base64_blob = base64.b64encode(file_content).decode("utf-8") + + # Trigger file download + if __event_call__: + await __event_call__( + { + "type": "execute", + "data": { + "code": f""" + (async function() {{ + const base64Data = "{base64_blob}"; + const filename = "{js_filename}"; + const mermaidUrl = "{self.valves.MERMAID_JS_URL}"; + const jszipUrl = "{self.valves.MERMAID_JSZIP_URL}"; + const pngScale = {float(self.valves.MERMAID_PNG_SCALE)}; + const displayScale = {float(self.valves.MERMAID_DISPLAY_SCALE)}; + const bgRaw = "{(self.valves.MERMAID_BACKGROUND or '').strip()}"; + const bg = (bgRaw || "").trim(); + const bgFill = (bg && bg.toLowerCase() !== "transparent") ? bg : ""; + const themeBackground = bgFill || "transparent"; + + function downloadBlob(blob, filename) {{ + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.style.display = "none"; + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + URL.revokeObjectURL(url); + document.body.removeChild(a); + }} + + async function loadScript(url, globalName) {{ + if (globalName && window[globalName]) return; + await new Promise((resolve, reject) => {{ + const script = document.createElement("script"); + script.src = url; + script.onload = resolve; + script.onerror = reject; + document.head.appendChild(script); + }}); + }} + + function decodeBase64ToUint8Array(b64) {{ + const binary = atob(b64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; + }} + + function parseViewBox(vb) {{ + if (!vb) return null; + const parts = vb.trim().split(/\\s+/).map(Number); + if (parts.length !== 4 || parts.some((n) => !isFinite(n))) return null; + return {{ minX: parts[0], minY: parts[1], width: parts[2], height: parts[3] }}; + }} + + function normalizeSvgForWord(svgText) {{ + const parser = new DOMParser(); + const doc = parser.parseFromString(svgText, "image/svg+xml"); + const svgEl = doc.documentElement; + if (!svgEl || svgEl.tagName.toLowerCase() !== "svg") return svgText; + + // Pad viewBox a little to reduce clipping in Word. + const vb0 = parseViewBox(svgEl.getAttribute("viewBox")); + if (vb0 && vb0.width > 0 && vb0.height > 0) {{ + const minDim = Math.min(vb0.width, vb0.height); + let pad = Math.max(8.0, minDim * 0.02); + pad = Math.min(pad, 24.0); + const vb = {{ + minX: vb0.minX - pad, + minY: vb0.minY - pad, + width: vb0.width + 2 * pad, + height: vb0.height + 2 * pad, + }}; + svgEl.setAttribute("viewBox", `${{vb.minX}} ${{vb.minY}} ${{vb.width}} ${{vb.height}}`); + }} + + const vb = parseViewBox(svgEl.getAttribute("viewBox")); + const widthAttr = (svgEl.getAttribute("width") || "").trim(); + const heightAttr = (svgEl.getAttribute("height") || "").trim(); + const widthPct = widthAttr.endsWith("%"); + const heightPct = heightAttr.endsWith("%"); + if (vb && vb.width > 0 && vb.height > 0 && (!widthAttr || !heightAttr || widthPct || heightPct)) {{ + svgEl.setAttribute("width", `${{vb.width}}`); + svgEl.setAttribute("height", `${{vb.height}}`); + }} + + svgEl.removeAttribute("style"); + svgEl.setAttribute("preserveAspectRatio", "xMidYMid meet"); + svgEl.setAttribute("overflow", "visible"); + + const removeNode = (n) => {{ + try {{ n && n.parentNode && n.parentNode.removeChild(n); }} catch (_e) {{}} + }}; + + // Remove Mermaid/OWUI background rectangles to avoid \"white box\" rendering in Word dark mode. + svgEl + .querySelectorAll('rect[data-owui-bg=\"1\"], rect.background, rect[class~=\"background\"], rect#background') + .forEach(removeNode); + try {{ + const isWhiteish = (fill) => {{ + const f = (fill || "").trim().toLowerCase(); + return ( + f === "white" || + f === "#fff" || + f === "#ffffff" || + f === "rgb(255,255,255)" || + f === "rgb(255, 255, 255)" + ); + }}; + const nearly = (a, b) => Math.abs(a - b) <= 1e-3; + const rectMatches = (r, box) => {{ + if (!box) return false; + const x = parseFloat(r.getAttribute("x") || "0"); + const y = parseFloat(r.getAttribute("y") || "0"); + const w = parseFloat(r.getAttribute("width") || ""); + const h = parseFloat(r.getAttribute("height") || ""); + if (!isFinite(x) || !isFinite(y) || !isFinite(w) || !isFinite(h)) return false; + return ( + nearly(x, box.minX) && + nearly(y, box.minY) && + nearly(w, box.width) && + nearly(h, box.height) + ); + }}; + const vbNow = parseViewBox(svgEl.getAttribute("viewBox")); + svgEl.querySelectorAll("rect[fill]").forEach((r) => {{ + const fill = r.getAttribute("fill"); + if (!isWhiteish(fill)) return; + if (rectMatches(r, vb0) || rectMatches(r, vbNow)) removeNode(r); + }}); + }} catch (_e) {{}} + try {{ + const vbCanvas = parseViewBox(svgEl.getAttribute(\"viewBox\")) || vb0 || vb; + if (vbCanvas) {{ + const existing = svgEl.querySelector('rect[data-owui-canvas=\"1\"]'); + const rect = existing || doc.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\"); + rect.setAttribute(\"data-owui-canvas\", \"1\"); + rect.setAttribute(\"x\", `${{vbCanvas.minX}}`); + rect.setAttribute(\"y\", `${{vbCanvas.minY}}`); + rect.setAttribute(\"width\", `${{vbCanvas.width}}`); + rect.setAttribute(\"height\", `${{vbCanvas.height}}`); + rect.setAttribute(\"fill\", \"#FFFFFF\"); + // Word quirk: without a full-canvas rect with *non-zero* opacity, Word will often + // only offer \"Convert to Shape\" when clicking on an actual stroke/fill (not empty space). + // We keep this rect nearly transparent and non-interactive. + rect.setAttribute(\"fill-opacity\", \"0.001\"); + rect.setAttribute(\"stroke\", \"none\"); + rect.setAttribute(\"stroke-opacity\", \"0\"); + rect.setAttribute(\"pointer-events\", \"none\"); + if (!existing) {{ + const first = svgEl.firstChild; + svgEl.insertBefore(rect, first); + }} + }} + }} catch (_e) {{}} + + return new XMLSerializer().serializeToString(svgEl); + }} + + function getMaxWidthEmu(xmlDoc) {{ + try {{ + const sects = xmlDoc.getElementsByTagName("w:sectPr"); + const sect = sects && sects.length ? sects[sects.length - 1] : null; + if (!sect) return 5486400; // 6 in + const pgSz = sect.getElementsByTagName("w:pgSz")[0]; + const pgMar = sect.getElementsByTagName("w:pgMar")[0]; + if (!pgSz || !pgMar) return 5486400; + const pageW = parseInt(pgSz.getAttribute("w:w") || "", 10); + const left = parseInt(pgMar.getAttribute("w:left") || "", 10); + const right = parseInt(pgMar.getAttribute("w:right") || "", 10); + if (!isFinite(pageW) || !isFinite(left) || !isFinite(right)) return 5486400; + const twips = Math.max(1, pageW - left - right); + return Math.round(twips * 635); // 1 twip = 635 EMU + }} catch (_e) {{ + return 5486400; + }} + }} + + function getChildByTag(parent, tag) {{ + const nodes = parent.getElementsByTagName(tag); + return nodes && nodes.length ? nodes[0] : null; + }} + + try {{ + await loadScript(jszipUrl, "JSZip"); + await loadScript(mermaidUrl, "mermaid"); + + // Mermaid init: disable htmlLabels to keep SVG Word-friendly; PNG fallback still included. + try {{ + window.mermaid.initialize({{ + startOnLoad: false, + theme: "default", + themeVariables: {{ + background: themeBackground, + fontFamily: "Calibri, Segoe UI, Arial, sans-serif", + fontSize: "10pt", + }}, + themeCSS: ".slice {{ font-size: 10pt !important; }}\\n.legend text {{ font-size: 10pt !important; }}\\n.pieTitleText {{ font-size: 10pt !important; }}", + fontFamily: "Calibri, Segoe UI, Arial, sans-serif", + securityLevel: "strict", + htmlLabels: false, + flowchart: {{ htmlLabels: false }}, + }}); + }} catch (_e) {{ + // Ignore and proceed with defaults. + }} + + const bytes = decodeBase64ToUint8Array(base64Data); + const zip = new window.JSZip(); + await zip.loadAsync(bytes); + + const docXml = await zip.file("word/document.xml").async("string"); + const relsXml = await zip.file("word/_rels/document.xml.rels").async("string"); + const parser = new DOMParser(); + const xmlDoc = parser.parseFromString(docXml, "application/xml"); + const relsDoc = parser.parseFromString(relsXml, "application/xml"); + + // Build rId -> target path mapping + const rels = relsDoc.getElementsByTagName("Relationship"); + const rIdToTarget = {{}}; + for (let i = 0; i < rels.length; i++) {{ + const rel = rels[i]; + const id = rel.getAttribute("Id"); + const target = rel.getAttribute("Target"); + if (id && target) rIdToTarget[id] = target; + }} + + const maxWidthEmu = getMaxWidthEmu(xmlDoc); + const maxWidthEmuScaled = Math.max(1, Math.round(maxWidthEmu * Math.min(1.0, Math.max(0.1, displayScale || 1.0)))); + + const drawings = xmlDoc.getElementsByTagName("w:drawing"); + const placeholders = []; + + for (let i = 0; i < drawings.length; i++) {{ + const drawing = drawings[i]; + const docPr = getChildByTag(drawing, "wp:docPr"); + if (!docPr) continue; + const descr = docPr.getAttribute("descr") || ""; + if (!descr.startsWith("MERMAID_SRC:")) continue; + const encoded = descr.substring("MERMAID_SRC:".length); + const code = decodeURIComponent(encoded); + + const blip = getChildByTag(drawing, "a:blip"); + const ridPng = blip ? blip.getAttribute("r:embed") : null; + const svgBlip = getChildByTag(drawing, "asvg:svgBlip"); + const ridSvg = svgBlip ? svgBlip.getAttribute("r:embed") : null; + + const container = getChildByTag(drawing, "wp:inline") || getChildByTag(drawing, "wp:anchor"); + const extent = container ? getChildByTag(container, "wp:extent") : null; + + const xfrm = getChildByTag(drawing, "a:xfrm"); + const xfrmExt = xfrm ? getChildByTag(xfrm, "a:ext") : null; + + placeholders.push({{ code, ridPng, ridSvg, extent, xfrmExt, svgBlip }}); + }} + + if (!placeholders.length) {{ + const blob = new Blob([bytes], {{ type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }}); + downloadBlob(blob, filename); + return; + }} + + // Phase 1: Render all Mermaid diagrams sequentially (mermaid needs DOM) + const renderResults = []; + for (let i = 0; i < placeholders.length; i++) {{ + const item = placeholders[i]; + try {{ + const id = "owui-mermaid-" + i; + const rendered = await window.mermaid.render(id, item.code); + let svgText = rendered && rendered.svg ? rendered.svg : rendered; + if (!svgText || typeof svgText !== "string") throw new Error("Mermaid returned empty SVG"); + + svgText = normalizeSvgForWord(svgText); + const hasForeignObject = / 0 && vb.height > 0 ? (vb.width / vb.height) : (4/3); + + const widthEmu = maxWidthEmuScaled; + const heightEmu = Math.max(1, Math.round(widthEmu / ratio)); + + renderResults.push({{ item, svgText, widthEmu, heightEmu, success: true }}); + }} catch (err) {{ + console.error("Mermaid render failed for block", i, err); + renderResults.push({{ item, svgText: null, widthEmu: 0, heightEmu: 0, success: false }}); + }} + }} + + // Phase 2: Convert SVG to PNG in parallel for performance + async function svgToPng(svgText, targetWidthPx, targetHeightPx) {{ + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + const scale = Math.max(1.0, pngScale || 1.0); + canvas.width = Math.round(targetWidthPx * scale); + canvas.height = Math.round(targetHeightPx * scale); + ctx.setTransform(1, 0, 0, 1, 0, 0); + if (bgFill) {{ + ctx.fillStyle = bgFill; + ctx.fillRect(0, 0, canvas.width, canvas.height); + }} + ctx.scale(scale, scale); + + const img = new Image(); + await new Promise((resolve, reject) => {{ + img.onload = resolve; + img.onerror = reject; + img.src = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgText))); + }}); + + ctx.drawImage(img, 0, 0, targetWidthPx, targetHeightPx); + const pngDataUrl = canvas.toDataURL("image/png"); + return pngDataUrl.split(",")[1]; + }} + + // Create PNG conversion promises for parallel execution + const pngPromises = renderResults.map(async (result, i) => {{ + if (!result.success || !result.svgText) return null; + const {{ item, widthEmu, heightEmu }} = result; + if (!item.ridPng || !rIdToTarget[item.ridPng]) return null; + + const targetWidthPx = Math.max(1, Math.round(widthEmu / 9525)); + const targetHeightPx = Math.max(1, Math.round(heightEmu / 9525)); + + try {{ + const pngBase64 = await svgToPng(result.svgText, targetWidthPx, targetHeightPx); + return {{ index: i, pngBase64, path: "word/" + rIdToTarget[item.ridPng] }}; + }} catch (err) {{ + console.error("PNG conversion failed for block", i, err); + return null; + }} + }}); + + // Wait for all PNG conversions to complete + const pngResults = await Promise.all(pngPromises); + + // Phase 3: Update ZIP with all results + for (let i = 0; i < renderResults.length; i++) {{ + const result = renderResults[i]; + if (!result.success) continue; + + const {{ item, svgText, widthEmu, heightEmu }} = result; + + // Update extent in XML + if (item.extent) {{ + item.extent.setAttribute("cx", `${{widthEmu}}`); + item.extent.setAttribute("cy", `${{heightEmu}}`); + }} + if (item.xfrmExt) {{ + item.xfrmExt.setAttribute("cx", `${{widthEmu}}`); + item.xfrmExt.setAttribute("cy", `${{heightEmu}}`); + }} + + // Write SVG part + if (item.ridSvg && rIdToTarget[item.ridSvg]) {{ + zip.file("word/" + rIdToTarget[item.ridSvg], svgText); + }} + }} + + // Write PNG files from parallel results + for (const pngResult of pngResults) {{ + if (pngResult && pngResult.pngBase64) {{ + zip.file(pngResult.path, pngResult.pngBase64, {{ base64: true }}); + }} + }} + + const newDocXml = new XMLSerializer().serializeToString(xmlDoc); + zip.file("word/document.xml", newDocXml); + + const finalBlob = await zip.generateAsync({{ + type: "blob", + compression: "DEFLATE", + compressionOptions: {{ level: 6 }}, + }}); + downloadBlob(finalBlob, filename); + }} catch (error) {{ + console.error("Export pipeline failed:", error); + const bytes = decodeBase64ToUint8Array(base64Data); + const blob = new Blob([bytes], {{ type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }}); + downloadBlob(blob, filename); + }} + }})(); + """ + }, + } + ) + + await __event_emitter__( + { + "type": "status", + "data": { + "description": self._get_msg("exported"), + "done": True, + }, + } + ) + + await self._emit_notification( + __event_emitter__, + self._get_msg("success", filename=filename), + "success", + ) + + return {"message": "Download triggered"} + + except Exception as e: + logger.exception(f"Error exporting to Word: {str(e)}") + await __event_emitter__( + { + "type": "status", + "data": { + "description": self._get_msg("export_failed", error=str(e)), + "done": True, + }, + } + ) + await self._emit_notification( + __event_emitter__, + self._get_msg("error_export", error=str(e)), + "error", + ) + + async def generate_title_using_ai( + self, body: dict, content: str, user_id: str, request: Any + ) -> str: + if not request: + return "" + + try: + user_obj = await _call_db(Users.get_user_by_id, user_id) + model = body.get("model") + + payload = { + "model": model, + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant. Generate a short, concise title (max 10 words) for the following text. Do not use quotes. Only output the title.", + }, + {"role": "user", "content": content[:2000]}, # Limit content length + ], + "stream": False, + } + + response = await generate_chat_completion(request, payload, user_obj) + if response and "choices" in response: + return response["choices"][0]["message"]["content"].strip() + except Exception as e: + logger.error(f"Error generating title: {e}") + + return "" + + def extract_title(self, content: str) -> str: + """Extract title from Markdown h1/h2 only""" + lines = content.split("\n") + for line in lines: + # Match h1-h2 headings only + match = re.match(r"^#{1,2}\s+(.+)$", line.strip()) + if match: + return match.group(1).strip() + return "" + + def extract_chat_title(self, body: dict) -> str: + """Extract chat title from common payload fields.""" + if not isinstance(body, dict): + return "" + + candidates = [] + + for key in ("chat", "conversation"): + if isinstance(body.get(key), dict): + candidates.append(body.get(key, {}).get("title", "")) + + for key in ("title", "chat_title"): + value = body.get(key) + if isinstance(value, str): + candidates.append(value) + + for candidate in candidates: + if candidate and isinstance(candidate, str): + return candidate.strip() + return "" + + def extract_chat_id(self, body: dict, metadata: Optional[dict]) -> str: + """Extract chat_id from body or metadata""" + if isinstance(body, dict): + chat_id = body.get("chat_id") or body.get("id") + if isinstance(chat_id, str) and chat_id.strip(): + return chat_id.strip() + + for key in ("chat", "conversation"): + nested = body.get(key) + if isinstance(nested, dict): + nested_id = nested.get("id") or nested.get("chat_id") + if isinstance(nested_id, str) and nested_id.strip(): + return nested_id.strip() + if isinstance(metadata, dict): + chat_id = metadata.get("chat_id") + if isinstance(chat_id, str) and chat_id.strip(): + return chat_id.strip() + return "" + + async def fetch_chat_title(self, chat_id: str, user_id: str = "") -> str: + """Fetch chat title from database by chat_id""" + if not chat_id: + return "" + + try: + chat = None + if user_id: + chat = await _call_db( + Chats.get_chat_by_id_and_user_id, id=chat_id, user_id=user_id + ) + if not chat: + chat = await _call_db(Chats.get_chat_by_id, chat_id) + except Exception as exc: + logger.warning(f"Failed to load chat {chat_id}: {exc}") + return "" + + if not chat: + return "" + + data = getattr(chat, "chat", {}) or {} + title = data.get("title") or getattr(chat, "title", "") + return title.strip() if isinstance(title, str) else "" + + def _extract_text_from_output(self, output: Any) -> str: + """Rebuild assistant text from structured ``output`` via OWUI's + ``convert_output_to_messages`` (reasoning excluded); "" if none.""" + if not isinstance(output, list) or not output: + return "" + + reconstructed = convert_output_to_messages(output) + assistant_texts = [ + msg["content"] + for msg in reconstructed + if isinstance(msg, dict) + and msg.get("role") == "assistant" + and isinstance(msg.get("content"), str) + and msg["content"].strip() + ] + return "\n".join(assistant_texts) + + async def _fetch_message_output_text(self, chat_id: str, message_id: str) -> str: + """Assistant text for a message via OWUI's ChatMessages store: its structured + ``output`` reconstructed by convert_output_to_messages. "" if not found.""" + if not chat_id or not message_id: + return "" + message = await _call_db( + ChatMessages.get_message_by_id, f"{chat_id}-{message_id}" + ) + return self._extract_text_from_output(message.output) if message else "" + + def clean_filename(self, name: str) -> str: + """Clean illegal characters from filename and strip emoji.""" + if not isinstance(name, str): + return "" + + without_emoji = self._remove_emojis(name) + cleaned = re.sub(r'[\\/*?:"<>|]', "", without_emoji) + cleaned = re.sub(r"\s+", " ", cleaned).strip().strip(".") + return cleaned[:50].strip() + + def _max_embed_image_bytes(self) -> int: + mb = getattr(self.valves, "MAX_EMBED_IMAGE_MB", 20) + try: + mb_i = int(mb) + except Exception: + mb_i = 20 + mb_i = max(1, mb_i) + return mb_i * 1024 * 1024 + + def _extract_owui_api_file_id(self, url: str) -> Optional[str]: + if not isinstance(url, str) or not url: + return None + m = _OWUI_API_FILE_ID_RE.search(url) + if not m: + return None + fid = (m.group("id") or "").strip() + return fid or None + + def _read_file_bytes_limited(self, path: Path, max_bytes: int) -> Optional[bytes]: + try: + if not path.exists(): + return None + try: + size = path.stat().st_size + if size > max_bytes: + return None + except Exception: + pass + with path.open("rb") as f: + data = f.read(max_bytes + 1) + if len(data) > max_bytes: + return None + return data + except Exception: + return None + + def _decode_base64_limited(self, b64: str, max_bytes: int) -> Optional[bytes]: + if not isinstance(b64, str): + return None + s = re.sub(r"\s+", "", b64.strip()) + if not s: + return None + + # Rough pre-check: base64 expands by ~4/3. Avoid decoding clearly oversized payloads. + est = (len(s) * 3) // 4 + if est > max_bytes: + return None + + pad = (-len(s)) % 4 + if pad: + s = s + ("=" * pad) + try: + out = base64.b64decode(s, validate=False) + except (binascii.Error, ValueError): + return None + if len(out) > max_bytes: + return None + return out + + def _image_bytes_from_data_url(self, url: str, max_bytes: int) -> Optional[bytes]: + if not isinstance(url, str): + return None + m = _DATA_IMAGE_URL_RE.match(url.strip()) + if not m: + return None + b64 = m.group("b64") or "" + return self._decode_base64_limited(b64, max_bytes) + + def _image_bytes_from_owui_file_id( + self, file_id: str, max_bytes: int + ) -> Optional[bytes]: + if not file_id: + return None + + if Files is None: + logger.error( + "Files model is not available (import failed). Cannot retrieve file content." + ) + return None + + # Use pre-fetched file object (populated async before document build) + file_obj = self._prefetched_files.get(file_id) + if file_obj is None: + logger.warning(f"File {file_id} not found in prefetch cache.") + return None + + # 1. Try data field (DB stored) + data_field = getattr(file_obj, "data", None) + if isinstance(data_field, dict): + blob_value = data_field.get("bytes") + if isinstance(blob_value, (bytes, bytearray)): + raw = bytes(blob_value) + return raw if len(raw) <= max_bytes else None + for key in ("b64", "base64", "data"): + inline = data_field.get(key) + if isinstance(inline, str) and inline.strip(): + return self._decode_base64_limited(inline, max_bytes) + + # 2. Storage-backed content: OWUI's Storage provider resolves file.path + # (local / S3 / GCS / Azure, using OWUI's configured storage) to a local path. + path = getattr(file_obj, "path", None) + if isinstance(path, str) and path.strip(): + try: + local_path = Storage.get_file(path) + except Exception as exc: + logger.warning(f"Storage.get_file failed for {file_id} ({path}): {exc}") + else: + raw = self._read_file_bytes_limited(Path(local_path), max_bytes) + if raw is not None: + return raw + + logger.warning(f"File {file_id} found but no content accessible via Storage.") + return None + + async def _fetch_external_image(self, url: str) -> Optional[bytes]: + """Download an external image URL to bytes (gated by EMBED_EXTERNAL_IMAGES). + + SSRF protection is OpenWebUI's: validate_url() pre-flight + a + get_ssrf_safe_session() whose resolver re-validates the resolved IP at + connect time (defeats DNS rebinding). Enforces MAX_EMBED_IMAGE_MB and an + image/* content type. Returns None (-> placeholder) on any failure. + """ + max_bytes = self._max_embed_image_bytes() + try: + validate_url(url) + except Exception as exc: + logger.warning(f"External image blocked by validate_url: {url} ({exc})") + return None + try: + async with get_ssrf_safe_session() as session: + async with session.get(url) as resp: + if not (200 <= resp.status < 300): + logger.warning(f"External image HTTP {resp.status}: {url}") + return None + ctype = ( + (resp.headers.get("Content-Type") or "") + .split(";")[0] + .strip() + .lower() + ) + if ctype and not ctype.startswith("image/"): + logger.warning( + f"External URL is not an image (Content-Type={ctype}): {url}" + ) + return None + buf = bytearray() + async for chunk in resp.content.iter_chunked(65536): + buf += chunk + if len(buf) > max_bytes: + logger.warning( + f"External image exceeds {max_bytes} bytes: {url}" + ) + return None + return bytes(buf) + except Exception as exc: + logger.warning(f"Failed to fetch external image {url}: {exc}") + return None + + def _add_image_placeholder(self, paragraph, alt: str, reason: str): + label = (alt or "").strip() or "image" + msg = f"[{label} not embedded: {reason}]" + self._add_text_run(paragraph, msg, bold=False, italic=False, strike=False) + + def _try_embed_image( + self, paragraph, image_bytes: bytes + ) -> Tuple[bool, Optional[str]]: + if not image_bytes: + return False, "empty image bytes" + try: + run = paragraph.add_run() + width = None + if self._active_doc is not None: + try: + width = self._available_block_width(self._active_doc) + except Exception: + width = None + run.add_picture(cast(Any, io.BytesIO(image_bytes)), width=width) + return True, None + except Exception as e: + return False, str(e) + + def _embed_markdown_image(self, paragraph, alt: str, url: str): + max_bytes = self._max_embed_image_bytes() + u = (url or "").strip() + if not u: + self._add_image_placeholder(paragraph, alt, "missing URL") + return + + image_bytes: Optional[bytes] = None + if u.lower().startswith("data:"): + image_bytes = self._image_bytes_from_data_url(u, max_bytes) + if image_bytes is None: + self._add_image_placeholder( + paragraph, + alt, + f"invalid data URL or exceeds {self.valves.MAX_EMBED_IMAGE_MB}MB", + ) + return + else: + file_id = self._extract_owui_api_file_id(u) + if not file_id: + # External image: embed prefetched bytes when the opt-in valve is on, + # otherwise leave a placeholder. + image_bytes = ( + self._prefetched_external_images.get(u) + if self.valves.EMBED_EXTERNAL_IMAGES + else None + ) + if image_bytes is None: + self._add_image_placeholder(paragraph, alt, "external URL") + return + else: + image_bytes = self._image_bytes_from_owui_file_id(file_id, max_bytes) + if image_bytes is None: + self._add_image_placeholder( + paragraph, alt, f"file unavailable ({file_id})" + ) + return + + success, error_msg = self._try_embed_image(paragraph, image_bytes) + if not success: + self._add_image_placeholder( + paragraph, alt, f"unsupported image type: {error_msg}" + ) + + async def markdown_to_docx( + self, + markdown_text: str, + top_heading: str = "", + + sources: Optional[List[dict]] = None, + event_emitter: Optional[Callable] = None, + user_name: str = "", + title: str = "", + ) -> Document: + """ + Convert Markdown text to Word document + Supports: headings, paragraphs, bold, italic, code blocks, lists, tables, links + Additionally: Mermaid fenced blocks (```mermaid) rendered client-side via Mermaid.js (SVG+PNG), + LaTeX math to Word equations, and OpenWebUI citations to References. + """ + doc = Document() + self._sanitize_metadata(doc, author=user_name, title=title) + self._active_doc = doc + try: + self._mermaid_figure_counter = 0 + self._mermaid_placeholder_counter = 0 + self._caption_style_name = None + self._citation_anchor_by_index = {} + self._citation_refs = self._build_citation_refs(sources or []) + self._bookmark_id_counter = 1 + for ref in self._citation_refs: + self._citation_anchor_by_index[ref.idx] = ref.anchor + + # Pre-fetch all OWUI file objects referenced in this markdown (needed for sync image embedding) + if Files is not None: + file_ids = list(set(_OWUI_API_FILE_ID_RE.findall(markdown_text))) + self._prefetched_files = {} + for fid in file_ids: + try: + fobj = await _call_db(Files.get_file_by_id, fid) + if fobj: + self._prefetched_files[fid] = fobj + except Exception as e: + logger.warning(f"Failed to prefetch file {fid}: {e}") + + # Pre-fetch external images (opt-in) so the sync doc build can embed them. + self._prefetched_external_images = {} + if self.valves.EMBED_EXTERNAL_IMAGES: + ext_urls = { + u + for u in ( + m.group(1).strip() + for m in _MD_IMAGE_URL_RE.finditer(markdown_text) + ) + if u.lower().startswith(("http://", "https://")) + and not self._extract_owui_api_file_id(u) + } + urls = list(ext_urls) + results = await asyncio.gather( + *(self._fetch_external_image(u) for u in urls) + ) + self._prefetched_external_images = { + u: d for u, d in zip(urls, results) if d + } + + # Set default fonts + self.set_document_default_font(doc) + + # Inject Document Title (Style Level 0) + if top_heading: + # Remove emojis from title for a professional look + clean_title = self._remove_emojis(top_heading) + # Use Title style (level 0) for the main document title + self.add_heading(doc, clean_title, 0) + + lines = markdown_text.split("\n") + i = 0 + in_code_block = False + code_block_content = [] + code_block_info_raw = "" + code_block_lang = "" + code_block_attrs: List[str] = [] + in_math_block = False + math_block_delim = "" + math_block_lines: List[str] = [] + in_list = False + list_items = [] + list_type = None # 'ordered' or 'unordered' + + total_lines = len(lines) + last_update_time = time.time() + + while i < len(lines): + # Update status every 2 seconds + if event_emitter and time.time() - last_update_time > 2.0: + progress = int((i / total_lines) * 100) + await event_emitter( + { + "type": "status", + "data": { + "description": f"{self._get_msg('converting')} ({progress}%)", + "done": False, + }, + } + ) + last_update_time = time.time() + + line = lines[i] + + # Handle display math blocks (\[...\] or $$...$$) + if not in_code_block and self.valves.MATH_ENABLE: + single_line = self._extract_single_line_math(line) + if single_line is not None: + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + self._add_display_equation(doc, single_line) + i += 1 + continue + + if not in_math_block: + stripped = line.strip() + if stripped in (r"\[", "$$"): + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + in_math_block = True + math_block_delim = stripped + math_block_lines = [] + i += 1 + continue + else: + stripped = line.strip() + close = r"\]" if math_block_delim == r"\[" else "$$" + if stripped == close: + in_math_block = False + latex = "\n".join(math_block_lines).strip() + self._add_display_equation(doc, latex) + math_block_delim = "" + math_block_lines = [] + i += 1 + continue + math_block_lines.append(line) + i += 1 + continue + + # Handle code blocks + if line.strip().startswith("```"): + if not in_code_block: + # Process pending list first + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + + in_code_block = True + code_block_info_raw = line.strip()[3:].strip() + code_block_lang, code_block_attrs = self._parse_fence_info( + code_block_info_raw + ) + code_block_content = [] + else: + # End code block + in_code_block = False + code_text = "\n".join(code_block_content) + if code_block_lang.lower() == "mermaid": + self._insert_mermaid_placeholder(doc, code_text) + else: + self.add_code_block(doc, code_text, code_block_lang) + code_block_content = [] + code_block_info_raw = "" + code_block_lang = "" + code_block_attrs = [] + i += 1 + continue + + if in_code_block: + code_block_content.append(line) + i += 1 + continue + + # Handle tables + if line.strip().startswith("|") and line.strip().endswith("|"): + # Process pending list first + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + + table_lines = [] + while i < len(lines) and lines[i].strip().startswith("|"): + table_lines.append(lines[i]) + i += 1 + self.add_table(doc, table_lines) + continue + + # Handle headings + header_match = re.match(r"^(#{1,6})\s+(.+)$", line.strip()) + if header_match: + # Process pending list first + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + + level = len(header_match.group(1)) + text = header_match.group(2) + self.add_heading(doc, text, level) + i += 1 + continue + + # Handle unordered lists + unordered_match = re.match(r"^(\s*)[-*+]\s+(.+)$", line) + if unordered_match: + if not in_list or list_type != "unordered": + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = True + list_type = "unordered" + indent = len(unordered_match.group(1)) // 2 + list_items.append((indent, unordered_match.group(2))) + i += 1 + continue + + # Handle ordered lists + ordered_match = re.match(r"^(\s*)\d+[.)]\s+(.+)$", line) + if ordered_match: + if not in_list or list_type != "ordered": + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = True + list_type = "ordered" + indent = len(ordered_match.group(1)) // 2 + list_items.append((indent, ordered_match.group(2))) + i += 1 + continue + + # Handle blockquotes + if line.strip().startswith(">"): + # Process pending list first + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + + # Collect consecutive quote lines + blockquote_lines = [] + while i < len(lines) and lines[i].strip().startswith(">"): + # Remove leading > and optional space + quote_line = re.sub(r"^>\s?", "", lines[i]) + blockquote_lines.append(quote_line) + i += 1 + self.add_blockquote(doc, "\n".join(blockquote_lines)) + continue + + # Handle horizontal rules + if re.match(r"^[-*_]{3,}$", line.strip()): + # Process pending list first + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + + self.add_horizontal_rule(doc) + i += 1 + continue + + # Handle empty lines + if not line.strip(): + # End list + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + i += 1 + continue + + # Handle normal paragraphs + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + list_items = [] + in_list = False + + self.add_paragraph(doc, line) + i += 1 + + # Process remaining list + if in_list and list_items: + self.add_list_to_doc(doc, list_items, list_type) + + # If math block wasn't closed, render it as plain text for robustness. + if in_math_block and math_block_lines: + self.add_paragraph(doc, r"\[") + for l in math_block_lines: + self.add_paragraph(doc, l) + self.add_paragraph(doc, r"\]") + + if self._citation_refs: + self._add_references_section(doc) + + return doc + finally: + self._active_doc = None + + def _extract_single_line_math(self, line: str) -> Optional[str]: + s = line.strip() + # \[ ... \] + m = re.match(r"^\\\[(.*)\\\]$", s) + if m: + return m.group(1).strip() + # $$ ... $$ + m = re.match(r"^\$\$(.*)\$\$$", s) + if m: + return m.group(1).strip() + return None + + def _strip_reference_definitions(self, text: str) -> str: + """Remove markdown reference-definition lines (``[label]: target``), which + render invisibly and would otherwise appear as literal text in the export. + Matches OpenWebUI's own removeFormattings pattern.""" + if not text: + return text + return _MD_REFERENCE_DEF_RE.sub("", text) + + def _strip_reasoning_blocks(self, text: str) -> str: + """ + Strip model reasoning blocks from assistant Markdown before export. + + OpenWebUI can include reasoning as interleaved
...
+ (and sometimes / blocks). These should never be exported into DOCX. + """ + if not text: + return text + + cur = text + for _ in range(10): + prev = cur + cur = _ALL_DETAILS_RE.sub("", cur) + cur = _THINK_RE.sub("", cur) + cur = _ANALYSIS_RE.sub("", cur) + if cur == prev: + break + + # Clean up excessive blank lines left by removals. + cur = re.sub(r"\n{4,}", "\n\n\n", cur) + return cur + + def _add_display_equation(self, doc: Document, latex: str): + latex = (latex or "").strip() + if not latex: + return + + if not LATEX_MATH_AVAILABLE: + self.add_code_block(doc, latex, "latex") + return + + try: + mathml = latex_to_mathml(latex) + omml = mathml2omml.convert(mathml) + para = doc.add_paragraph() + para.alignment = WD_ALIGN_PARAGRAPH.CENTER + cast(Any, para)._p.append(self._wrap_omml_for_word(omml)) + except Exception as exc: + logger.warning(f"Math conversion failed; falling back to text: {exc}") + self.add_code_block(doc, latex, "latex") + + def _wrap_omml_for_word(self, omml: str): + m_ns = "http://schemas.openxmlformats.org/officeDocument/2006/math" + w_ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" + # Keep the OMML payload as-is, but ensure it has the math namespace declared. + xml = f'{omml}' + return parse_xml(xml) + + # (Math warning paragraphs removed) + + def _build_citation_refs(self, sources: List[dict]) -> List[_CitationRef]: + citation_idx_map: Dict[str, int] = {} + refs_by_idx: Dict[int, _CitationRef] = {} + + for source in sources or []: + if not isinstance(source, dict): + continue + + documents = source.get("document") or [] + metadatas = source.get("metadata") or [] + src_info = source.get("source") or {} + + src_name = src_info.get("name") if isinstance(src_info, dict) else None + src_id_default = src_info.get("id") if isinstance(src_info, dict) else None + src_urls = src_info.get("urls") if isinstance(src_info, dict) else None + + if not isinstance(documents, list): + documents = [] + if not isinstance(metadatas, list): + metadatas = [] + + for idx_doc, _doc_text in enumerate(documents): + meta = metadatas[idx_doc] if idx_doc < len(metadatas) else {} + if not isinstance(meta, dict): + meta = {} + + source_id = meta.get("source") or src_id_default or "N/A" + source_id_str = str(source_id) + + if source_id_str not in citation_idx_map: + citation_idx_map[source_id_str] = len(citation_idx_map) + 1 + idx = citation_idx_map[source_id_str] + + if idx in refs_by_idx: + continue + + url: Optional[str] = None + if isinstance(source_id, str) and re.match(r"^https?://", source_id): + url = source_id + elif isinstance(meta.get("url"), str) and re.match( + r"^https?://", meta["url"] + ): + url = meta["url"] + elif isinstance(src_urls, list) and src_urls: + if isinstance(src_urls[0], str) and re.match( + r"^https?://", src_urls[0] + ): + url = src_urls[0] + + title = ( + (meta.get("title") if isinstance(meta.get("title"), str) else None) + or (meta.get("name") if isinstance(meta.get("name"), str) else None) + or ( + src_name + if isinstance(src_name, str) and src_name.strip() + else None + ) + or (url if url else None) + or source_id_str + ) + + anchor = f"OWUIRef{idx}" + refs_by_idx[idx] = _CitationRef( + idx=idx, + anchor=anchor, + title=title, + url=url, + source_id=source_id_str, + ) + + return [refs_by_idx[i] for i in sorted(refs_by_idx.keys())] + + def _add_bookmark(self, paragraph, name: str): + bookmark_id = self._bookmark_id_counter + self._bookmark_id_counter += 1 + + start = OxmlElement("w:bookmarkStart") + start.set(qn("w:id"), str(bookmark_id)) + start.set(qn("w:name"), name) + + end = OxmlElement("w:bookmarkEnd") + end.set(qn("w:id"), str(bookmark_id)) + + p = cast(Any, paragraph)._p + p.insert(0, start) + p.append(end) + + def _add_internal_hyperlink(self, paragraph, display_text: str, anchor: str): + hyperlink = OxmlElement("w:hyperlink") + hyperlink.set(qn("w:anchor"), anchor) + + new_run = OxmlElement("w:r") + rPr = OxmlElement("w:rPr") + rStyle = OxmlElement("w:rStyle") + rStyle.set(qn("w:val"), "Hyperlink") + rPr.append(rStyle) + + new_run.append(rPr) + t = OxmlElement("w:t") + t.text = display_text + new_run.append(t) + + hyperlink.append(new_run) + cast(Any, paragraph)._p.append(hyperlink) + + def _add_references_section(self, doc: Document): + self.add_heading(doc, self._get_msg("references"), 2) + + for ref in self._citation_refs: + para = doc.add_paragraph(style="List Number") + self._add_bookmark(para, ref.anchor) + # Include URL as an external link when available. + if ref.url: + self._add_hyperlink(para, ref.title, ref.url, display_text=ref.title) + else: + self._add_text_run( + para, ref.title, bold=False, italic=False, strike=False + ) + + def _parse_fence_info(self, info_raw: str) -> Tuple[str, List[str]]: + parts = [p for p in (info_raw or "").split() if p.strip()] + if not parts: + return "", [] + return parts[0], parts[1:] + + def _normalize_mermaid_text(self, source: str) -> str: + text = (source or "").replace("\r\n", "\n").replace("\r", "\n").strip() + return text + "\n" + + def _prepare_mermaid_for_js(self, source: str) -> str: + """ + Prepare Mermaid source for client-side rendering: + - strip title directives (caption already carries it), + """ + text = self._strip_mermaid_title_for_render(source) + return text + + def _png_with_text_chunk(self, png_bytes: bytes, keyword: str, value: str) -> bytes: + """ + Ensure placeholder PNGs stay distinct in the DOCX package: + python-docx may deduplicate identical image bytes into one media part. + We insert a small tEXt chunk so each placeholder is unique, without changing + dimensions or requiring external imaging libraries. + """ + if not png_bytes.startswith(b"\x89PNG\r\n\x1a\n"): + return png_bytes + + keyword_b = (keyword or "owui").encode("latin-1", errors="ignore")[:79] + keyword_b = keyword_b.replace(b"\x00", b"") or b"owui" + value_b = (value or "").encode("latin-1", errors="ignore") + data = keyword_b + b"\x00" + value_b + chunk_type = b"tEXt" + crc = zlib.crc32(chunk_type + data) & 0xFFFFFFFF + chunk = ( + struct.pack("!I", len(data)) + chunk_type + data + struct.pack("!I", crc) + ) + + out = bytearray() + out.extend(png_bytes[:8]) + offset = 8 + inserted = False + while offset + 8 <= len(png_bytes): + length = struct.unpack("!I", png_bytes[offset : offset + 4])[0] + ctype = png_bytes[offset + 4 : offset + 8] + chunk_total = 12 + length + if offset + chunk_total > len(png_bytes): + break + if ctype == b"IEND" and not inserted: + out.extend(chunk) + inserted = True + out.extend(png_bytes[offset : offset + chunk_total]) + offset += chunk_total + if ctype == b"IEND": + break + if not inserted: + return png_bytes + return bytes(out) + + def _make_mermaid_placeholder_png(self, seed: str) -> bytes: + return self._png_with_text_chunk(_TRANSPARENT_1PX_PNG, "owui", seed) + + def _dummy_mermaid_svg_bytes(self) -> bytes: + return ( + '' + ).encode("utf-8") + + def _insert_mermaid_placeholder(self, doc: Document, mermaid_source: str): + caption_title: Optional[str] = ( + self._extract_mermaid_title(mermaid_source) + if self.valves.MERMAID_CAPTIONS_ENABLE + else None + ) + + source_for_render = mermaid_source + if self.valves.MERMAID_OPTIMIZE_LAYOUT: + source_for_render = re.sub( + r"^(graph|flowchart)\s+LR\b", + r"\1 TD", + source_for_render, + flags=re.MULTILINE | re.IGNORECASE, + ) + source_for_render = self._prepare_mermaid_for_js(source_for_render) + + self._mermaid_placeholder_counter += 1 + seed = hashlib.sha256( + f"{self._mermaid_placeholder_counter}\n{source_for_render}".encode( + "utf-8", errors="replace" + ) + ).hexdigest()[:16] + png_bytes = self._make_mermaid_placeholder_png(seed) + + try: + shape = doc.add_picture(cast(Any, io.BytesIO(png_bytes))) + except Exception as e: + logger.warning(f"Failed to add Mermaid placeholder image: {e}") + self.add_paragraph(doc, f"[Mermaid placeholder failed: {e}]") + return + try: + doc.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER + except Exception: + pass + + # Attach a dummy SVG part so we can later overwrite it client-side (SVG+PNG). + self._attach_svg_blip(doc, shape, self._dummy_mermaid_svg_bytes()) + + try: + encoded = quote(source_for_render) + inline = shape._inline + docPr = inline.docPr + docPr.set("descr", f"MERMAID_SRC:{encoded}") + docPr.set("title", "Mermaid Diagram Placeholder") + except Exception as exc: + logger.warning(f"Failed to annotate Mermaid placeholder: {exc}") + + self._add_mermaid_caption(doc, caption_title) + + def _extract_mermaid_title(self, source: str) -> Optional[str]: + lines = self._normalize_mermaid_text(source).split("\n") + header_found = False + for raw in lines: + line = raw.strip() + if not line: + continue + if line.startswith("%%{") and line.endswith("}%%"): + continue + if line.startswith("%%"): + continue + # diagram header line + if not header_found: + header_found = True + # Mermaid beta/diagram headers can embed a title on the header line, e.g.: + # - radar-beta title Foo + # - xychart-beta title: "Foo" + mt = re.match( + r"^(?P
\S.*?)(?:\s+title\s*:?\s+)(?P.+)$", + line, + re.IGNORECASE, + ) + if mt: + title = (mt.group("title") or "").strip().strip('"').strip("'") + if title: + return title + continue + + # title "Foo" / title Foo + m = re.match(r'^title\s*:?\s+"(.+)"\s*$', line, re.IGNORECASE) + if m: + return m.group(1).strip() + m = re.match(r"^title\s*:?\s+(.+)$", line, re.IGNORECASE) + if m: + return m.group(1).strip().strip('"').strip("'") + return None + + def _strip_mermaid_title_for_render(self, source: str) -> str: + """ + Removes Mermaid title directives from the source before rendering. + Captions already carry the title. + """ + lines = self._normalize_mermaid_text(source).split("\n") + out: List[str] = [] + header_found = False + title_stripped = False + meaningful_after_header = False + + for raw in lines: + line = raw.rstrip("\n") + stripped = line.strip() + + if not stripped: + out.append(line) + continue + + if stripped.startswith("%%{") and stripped.endswith("}%%"): + out.append(line) + continue + if stripped.startswith("%%"): + out.append(line) + continue + + if not header_found: + header_found = True + # Some Mermaid diagram headers can embed a title on the header line, e.g.: + # - radar-beta title Foo + # - xychart-beta title: "Foo" + mt = re.match( + r"^(?P<header>\S.*?)(?:\s+title\s*:?\s+)(?P<title>.+)$", + stripped, + re.IGNORECASE, + ) + if mt: + cleaned = (mt.group("header") or "").strip() + out.append(cleaned if cleaned else stripped) + title_stripped = True + continue + out.append(line) + continue + + if not title_stripped and not meaningful_after_header: + # Strip a standalone title directive line early in the diagram. + if re.match(r'^title\s*:?\s+(".+"|.+)$', stripped, re.IGNORECASE): + title_stripped = True + continue + + # Consider this a meaningful content line after header. + meaningful_after_header = True + out.append(line) + + return "\n".join(out).strip() + "\n" + + def _ensure_caption_style(self, doc: Document) -> str: + if self._caption_style_name is not None: + return self._caption_style_name + + style_name = (self.valves.MERMAID_CAPTION_STYLE or "").strip() + if style_name == "": + # Empty means: do not apply a caption style. + self._caption_style_name = "" + return "" + + # Prefer existing style if present. + try: + _ = doc.styles[style_name] + self._caption_style_name = style_name + return style_name + except KeyError: + pass + + # If user requested "Caption" but it's missing, create a safe custom style name. + if style_name.lower() == "caption": + style_name = "OWUI Caption" + + try: + _ = doc.styles[style_name] + self._caption_style_name = style_name + return style_name + except KeyError: + pass + + try: + style = doc.styles.add_style(style_name, WD_STYLE_TYPE.PARAGRAPH) + style.font.name = "Calibri" + style.font.size = Pt(9) + style.font.color.rgb = RGBColor(80, 80, 80) + style.paragraph_format.space_before = Pt(2) + style.paragraph_format.space_after = Pt(8) + self._caption_style_name = style_name + return style_name + except Exception: + self._caption_style_name = "Normal" + return "Normal" + + def _add_mermaid_caption(self, doc: Document, title: Optional[str]): + if not self.valves.MERMAID_CAPTIONS_ENABLE: + return + + # Use configured prefix, or auto-detect from user language + prefix = (self.valves.MERMAID_CAPTION_PREFIX or "").strip() + if prefix == "": + prefix = self._get_msg("figure_prefix") + + if prefix == "" and not title: + return + + self._mermaid_figure_counter += 1 + if prefix == "": + caption = title or "" + else: + base = f"{prefix} {self._mermaid_figure_counter}" + caption = f"{base}: {title}" if title else base + if caption == "": + return + + para = doc.add_paragraph() + style_name = self._ensure_caption_style(doc) + if style_name: + para.style = style_name + para.alignment = WD_ALIGN_PARAGRAPH.CENTER + self.add_formatted_text(para, caption) + + def _available_block_width(self, doc: Document): + section = doc.sections[0] + return section.page_width - section.left_margin - section.right_margin + + def _attach_svg_blip(self, doc: Document, inline_shape: Any, svg_bytes: bytes): + if not svg_bytes: + return + + try: + pkg = doc.part.package + partname = pkg.next_partname("/word/media/image%d.svg") + from docx.opc.part import Part + + svg_part = Part(partname, "image/svg+xml", svg_bytes) + rid_svg = doc.part.relate_to(svg_part, RT.IMAGE) + + inline = inline_shape._inline + blips = inline.xpath(".//a:blip") + if not blips: + return + blip = blips[0] + + existing = blip.xpath(".//asvg:svgBlip") + if existing: + existing[0].set(qn("r:embed"), rid_svg) + return + + extLst = OxmlElement("a:extLst") + ext = OxmlElement("a:ext") + ext.set("uri", "{96DAC541-7B7A-43D3-8B79-37D633B846F1}") + + svgBlip = OxmlElement("asvg:svgBlip") + svgBlip.set(qn("r:embed"), rid_svg) + ext.append(svgBlip) + extLst.append(ext) + blip.append(extLst) + except Exception as exc: + logger.warning(f"Failed to attach SVG blip; keeping PNG fallback: {exc}") + + # (Mermaid warning paragraphs removed) + + def set_document_default_font(self, doc: Document): + """Set document default font using configured fonts.""" + style = doc.styles["Normal"] + font = style.font + font.name = self.valves.FONT_LATIN + font.size = Pt(11) + + # Ensure rPr element exists + rPr = style._element.get_or_add_rPr() + rFonts = rPr.get_or_add_rFonts() + + # Set Latin and Asian fonts explicitly + rFonts.set(qn("w:ascii"), self.valves.FONT_LATIN) + rFonts.set(qn("w:hAnsi"), self.valves.FONT_LATIN) + rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN) + + # CRITICAL: Clear theme fonts to prevent Word from overriding with defaults (like SimSun) + rFonts.set(qn("w:asciiTheme"), "") + rFonts.set(qn("w:hAnsiTheme"), "") + rFonts.set(qn("w:eastAsiaTheme"), "") + rFonts.set(qn("w:cstheme"), "") + + # Set language to zh-CN to prevent MS Gothic fallback (Japanese font) + # Even for English interface, we want to prioritize Chinese glyphs over Japanese for CJK + lang = rPr.find(qn("w:lang")) + if lang is None: + lang = OxmlElement("w:lang") + rPr.append(lang) + lang.set(qn("w:val"), "en-US") + lang.set(qn("w:eastAsia"), "zh-CN") + + logger.info( + f"[Font Config] Latin: {self.valves.FONT_LATIN}, Asian: {self.valves.FONT_ASIAN}" + ) + + # Set paragraph format + paragraph_format = style.paragraph_format + paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE + paragraph_format.space_after = Pt(6) + + # Configure Title style (used for document title) + # Standard format: 22pt (二号), bold, centered, 24pt space after + if "Title" in doc.styles: + title_style = doc.styles["Title"] + title_font = title_style.font + title_font.name = self.valves.FONT_LATIN + title_font.size = Pt(22) # 二号字体 + title_font.bold = True + title_font.color.rgb = RGBColor(0, 0, 0) + + # Set paragraph format: alignment based on configuration + title_pf = title_style.paragraph_format + alignment_map = { + "left": WD_ALIGN_PARAGRAPH.LEFT, + "center": WD_ALIGN_PARAGRAPH.CENTER, + "right": WD_ALIGN_PARAGRAPH.RIGHT, + } + title_pf.alignment = alignment_map.get( + self.valves.TITLE_ALIGNMENT.lower(), WD_ALIGN_PARAGRAPH.CENTER + ) + title_pf.space_before = Pt(0) + title_pf.space_after = Pt(24) + + # Explicitly disable underline and borders for Title style + title_font.underline = False + title_p_el = title_style._element.get_or_add_pPr() + title_pbdr = title_p_el.find(qn("w:pBdr")) + if title_pbdr is not None: + title_p_el.remove(title_pbdr) + + t_rPr = title_style._element.get_or_add_rPr() + t_rFonts = t_rPr.get_or_add_rFonts() + t_rFonts.set(qn("w:ascii"), self.valves.FONT_LATIN) + t_rFonts.set(qn("w:hAnsi"), self.valves.FONT_LATIN) + t_rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN) + + # Clear theme fonts for Title + t_rFonts.set(qn("w:asciiTheme"), "") + t_rFonts.set(qn("w:hAnsiTheme"), "") + t_rFonts.set(qn("w:eastAsiaTheme"), "") + + t_lang = t_rPr.find(qn("w:lang")) + if t_lang is None: + t_lang = OxmlElement("w:lang") + t_rPr.append(t_lang) + t_lang.set(qn("w:val"), "en-US") + t_lang.set(qn("w:eastAsia"), "zh-CN") + + # Standard heading sizes based on Chinese document standards: + # Heading 1: 16pt (三号), bold, space before 24pt, space after 12pt + # Heading 2: 15pt (小三), bold, space before 18pt, space after 6pt + # Heading 3: 14pt (四号), bold, space before 12pt, space after 6pt + # Heading 4-9: 12pt (小四), bold, gradually reduced spacing + heading_formats = { + 1: {"size": 16, "space_before": 24, "space_after": 12}, + 2: {"size": 15, "space_before": 18, "space_after": 6}, + 3: {"size": 14, "space_before": 12, "space_after": 6}, + 4: {"size": 12, "space_before": 12, "space_after": 6}, + 5: {"size": 12, "space_before": 6, "space_after": 6}, + 6: {"size": 11, "space_before": 6, "space_after": 3}, + 7: {"size": 11, "space_before": 6, "space_after": 3}, + 8: {"size": 10.5, "space_before": 6, "space_after": 3}, + 9: {"size": 10.5, "space_before": 6, "space_after": 3}, + } + + # Apply font and formatting settings to Heading 1-9 + for i in range(1, 10): + style_id = f"Heading {i}" + if style_id in doc.styles: + heading_style = doc.styles[style_id] + heading_font = heading_style.font + heading_font.color.rgb = RGBColor(0, 0, 0) + + # Determine fonts to use (fallback to document defaults) + if i == 1: + target_latin = ( + self.valves.FONT_H1_LATIN.strip() or self.valves.FONT_LATIN + ) + target_asian = ( + self.valves.FONT_H1_ASIAN.strip() or self.valves.FONT_ASIAN + ) + elif i == 2: + target_latin = ( + self.valves.FONT_H2_LATIN.strip() or self.valves.FONT_LATIN + ) + target_asian = ( + self.valves.FONT_H2_ASIAN.strip() or self.valves.FONT_ASIAN + ) + else: + target_latin = self.valves.FONT_LATIN + target_asian = self.valves.FONT_ASIAN + + heading_font.name = target_latin + + # Apply standard formatting (size, bold, spacing) + fmt = heading_formats.get( + i, {"size": 11, "space_before": 6, "space_after": 3} + ) + heading_font.size = Pt(fmt["size"]) + heading_font.bold = True + + heading_pf = heading_style.paragraph_format + heading_pf.space_before = Pt(fmt["space_before"]) + heading_pf.space_after = Pt(fmt["space_after"]) + + # Explicitly disable underline and borders for Heading style + heading_font.underline = False + h_p_el = heading_style._element.get_or_add_pPr() + h_pbdr = h_p_el.find(qn("w:pBdr")) + if h_pbdr is not None: + h_p_el.remove(h_pbdr) + + # Ensure rPr exists + h_rPr = heading_style._element.get_or_add_rPr() + h_rFonts = h_rPr.get_or_add_rFonts() + + # Set Latin and Asian fonts explicitly in XML + h_rFonts.set(qn("w:ascii"), target_latin) + h_rFonts.set(qn("w:hAnsi"), target_latin) + h_rFonts.set(qn("w:eastAsia"), target_asian) + + # Clear theme fonts for Headings + h_rFonts.set(qn("w:asciiTheme"), "") + h_rFonts.set(qn("w:hAnsiTheme"), "") + h_rFonts.set(qn("w:eastAsiaTheme"), "") + + # Set language to zh-CN + h_lang = h_rPr.find(qn("w:lang")) + if h_lang is None: + h_lang = OxmlElement("w:lang") + h_rPr.append(h_lang) + h_lang.set(qn("w:val"), "en-US") + h_lang.set(qn("w:eastAsia"), "zh-CN") + + def _remove_emojis(self, text: str) -> str: + """Remove emojis from text based on unicode ranges.""" + if not isinstance(text, str): + return "" + + def _is_emoji_codepoint(codepoint: int) -> bool: + # Common emoji ranges + flag regional indicators. + return ( + 0x1F000 <= codepoint <= 0x1FAFF + or 0x1F1E6 <= codepoint <= 0x1F1FF + or 0x2600 <= codepoint <= 0x26FF + or 0x2700 <= codepoint <= 0x27BF + or 0x2300 <= codepoint <= 0x23FF + or 0x2B00 <= codepoint <= 0x2BFF + ) + + def _is_emoji_modifier(codepoint: int) -> bool: + # VS15/VS16, ZWJ, keycap, skin tones, and tag characters used in some emoji sequences. + return ( + codepoint in (0x200D, 0xFE0E, 0xFE0F, 0x20E3) + or 0x1F3FB <= codepoint <= 0x1F3FF + or 0xE0020 <= codepoint <= 0xE007F + ) + + return "".join( + ch + for ch in text + if not (_is_emoji_codepoint(ord(ch)) or _is_emoji_modifier(ord(ch))) + ) + + def add_heading(self, doc: Document, text: str, level: int): + """Add heading""" + # Word heading levels start from 0, Markdown from 1 + heading_level = min(level, 9) # Word supports up to Heading 9 + heading = doc.add_heading(level=heading_level) + + # Parse and add formatted text + self.add_formatted_text(heading, text) + + def add_paragraph(self, doc: Document, text: str): + """Add paragraph with inline formatting support""" + paragraph = doc.add_paragraph() + self.add_formatted_text(paragraph, text) + + def add_formatted_text(self, paragraph, text: str): + """ + Parse Markdown inline formatting and add to paragraph. + Supports: bold, italic, inline code, links, strikethrough, auto-link URLs, + and inline LaTeX math \\(...\\) when MATH_ENABLE is on. + """ + self._add_inline_segments( + paragraph, text or "", bold=False, italic=False, strike=False + ) + + def _add_text_run(self, paragraph, s: str, bold: bool, italic: bool, strike: bool): + if not s: + return + run = paragraph.add_run(s) + if bold: + run.bold = True + if italic: + run.italic = True + if strike: + run.font.strike = True + + # Explicitly set East Asian font at Run level for heading paragraphs. + # Style-level fonts alone are unreliable for headings because Word's theme + # font inheritance (w:eastAsiaTheme) on the run's rPr can override style-level + # rFonts. Setting it here ensures SimHei (or the configured heading font) wins + # regardless of the document template or theme settings. + style_name = getattr(getattr(paragraph, "style", None), "name", "") or "" + if style_name.startswith("Heading"): + # Extract heading level number from style name (e.g., "Heading 1" → 1) + parts = style_name.split() + heading_level = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else 0 + if heading_level == 1: + target_asian = ( + self.valves.FONT_H1_ASIAN.strip() or self.valves.FONT_ASIAN + ) + elif heading_level == 2: + target_asian = ( + self.valves.FONT_H2_ASIAN.strip() or self.valves.FONT_ASIAN + ) + else: + target_asian = self.valves.FONT_ASIAN + + rPr = run._element.get_or_add_rPr() + rFonts = rPr.get_or_add_rFonts() + rFonts.set(qn("w:eastAsia"), target_asian) + # Clear theme font to prevent Word from overriding our explicit font choice + rFonts.set(qn("w:eastAsiaTheme"), "") + + def _add_inline_code(self, paragraph, s: str): + if s == "": + return + + def _add_code_run(chunk: str): + if not chunk: + return + run = paragraph.add_run(chunk) + run.font.name = self.valves.FONT_CODE + run._element.rPr.rFonts.set(qn("w:eastAsia"), self.valves.FONT_CODE) + run.font.size = Pt(10) + shading = OxmlElement("w:shd") + shading.set(qn("w:fill"), "E8E8E8") + run._element.rPr.append(shading) + + i = 0 + for m in _AUTO_URL_RE.finditer(s): + start, end = m.span() + if start > i: + _add_code_run(s[i:start]) + + raw = m.group(0) + trimmed = raw + while trimmed and trimmed[-1] in ".,;:!?)]}": + trimmed = trimmed[:-1] + suffix = raw[len(trimmed) :] + + normalized = self._normalize_url(trimmed) + if normalized: + self._add_hyperlink_code( + paragraph, display_text=trimmed, url=normalized + ) + else: + _add_code_run(raw) + + if suffix: + _add_code_run(suffix) + + i = end + + if i < len(s): + _add_code_run(s[i:]) + + def _add_hyperlink_code(self, paragraph, display_text: str, url: str): + u = self._normalize_url(url) + if not u: + self._add_inline_code(paragraph, display_text) + return + + part = getattr(paragraph, "part", None) + if part is None or not hasattr(part, "relate_to"): + self._add_inline_code(paragraph, display_text) + return + + r_id = part.relate_to(u, RT.HYPERLINK, is_external=True) + + hyperlink = OxmlElement("w:hyperlink") + hyperlink.set(qn("r:id"), r_id) + + new_run = OxmlElement("w:r") + rPr = OxmlElement("w:rPr") + + rFonts = OxmlElement("w:rFonts") + rFonts.set(qn("w:ascii"), self.valves.FONT_CODE) + rFonts.set(qn("w:hAnsi"), self.valves.FONT_CODE) + rFonts.set(qn("w:eastAsia"), self.valves.FONT_CODE) + rPr.append(rFonts) + + sz = OxmlElement("w:sz") + sz.set(qn("w:val"), "20") # 10pt + rPr.append(sz) + sz_cs = OxmlElement("w:szCs") + sz_cs.set(qn("w:val"), "20") + rPr.append(sz_cs) + + shading = OxmlElement("w:shd") + shading.set(qn("w:fill"), "E8E8E8") + rPr.append(shading) + + new_run.append(rPr) + + t = OxmlElement("w:t") + t.text = display_text + new_run.append(t) + + hyperlink.append(new_run) + cast(Any, paragraph)._p.append(hyperlink) + + def _add_inline_segments( + self, paragraph, text: str, bold: bool, italic: bool, strike: bool + ): + i = 0 + n = len(text) + + def next_special(start: int) -> int: + candidates = [] + for ch in ("`", "!", "[", "*", "_", "~", "$", "\\"): + idx = text.find(ch, start) + if idx != -1: + candidates.append(idx) + idx = text.find(r"\(", start) + if idx != -1: + candidates.append(idx) + idx = text.find("http://", start) + if idx != -1: + candidates.append(idx) + idx = text.find("https://", start) + if idx != -1: + candidates.append(idx) + idx = text.find("www.", start) + if idx != -1: + candidates.append(idx) + return min(candidates) if candidates else n + + while i < n: + # Markdown image: ![alt](url) + if text.startswith("![", i): + close = text.find("]", i + 2) + if close != -1 and close + 1 < n and text[close + 1] == "(": + close_paren = text.find(")", close + 2) + if close_paren != -1: + alt = text[i + 2 : close] + url = text[close + 2 : close_paren].strip() + # Allow angle-bracket wrapped URLs: ![](</api/...>) + if url.startswith("<") and url.endswith(">") and len(url) >= 2: + url = url[1:-1].strip() + self._embed_markdown_image(paragraph, alt=alt, url=url) + i = close_paren + 1 + continue + + if text[i] == "`": + j = text.find("`", i + 1) + if j != -1: + self._add_inline_code(paragraph, text[i + 1 : j]) + i = j + 1 + continue + + if text.startswith(r"\(", i): + j = text.find(r"\)", i + 2) + if j != -1: + self._add_inline_equation( + paragraph, + text[i + 2 : j], + bold=bold, + italic=italic, + strike=strike, + ) + i = j + 2 + continue + + # Handle backslash escapes + if text[i] == "\\": + if i + 1 < n: + ch = text[i + 1] + # Standard Markdown escapes + $ for math + if ch in "\\`*_{}[]()#+-.!|$": + self._add_text_run(paragraph, ch, bold, italic, strike) + i += 2 + continue + # Keep other backslashes literal + self._add_text_run(paragraph, "\\", bold, italic, strike) + i += 1 + continue + + # Handle long run of underscores (fill-in-the-blank) + if text[i] == "_": + run_len = 0 + while i + run_len < n and text[i + run_len] == "_": + run_len += 1 + if run_len >= 4: + self._add_text_run( + paragraph, text[i : i + run_len], bold, italic, strike + ) + i += run_len + continue + + # Handle long run of asterisks (separator/mask) + if text[i] == "*": + run_len = 0 + while i + run_len < n and text[i + run_len] == "*": + run_len += 1 + if run_len >= 4: + self._add_text_run( + paragraph, text[i : i + run_len], bold, italic, strike + ) + i += run_len + continue + + # Handle long run of tildes (separator) + if text[i] == "~": + run_len = 0 + while i + run_len < n and text[i + run_len] == "~": + run_len += 1 + if run_len >= 4: + self._add_text_run( + paragraph, text[i : i + run_len], bold, italic, strike + ) + i += run_len + continue + + # Inline $...$ math (conservative parsing) + if ( + text[i] == "$" + and self.valves.MATH_ENABLE + and self.valves.MATH_INLINE_DOLLAR_ENABLE + ): + # Avoid treating $$ as inline math here (block math uses $$ on its own line). + if text.startswith("$$", i): + self._add_text_run(paragraph, "$", bold, italic, strike) + i += 1 + continue + + # Markdown-ish heuristics to reduce false positives: + # - Do not allow whitespace right after opening or right before closing + # - Avoid cases like "USD$5" where opening is attached to an alnum + if i + 1 >= n or text[i + 1].isspace(): + self._add_text_run(paragraph, "$", bold, italic, strike) + i += 1 + continue + if i > 0 and text[i - 1].isalnum(): + self._add_text_run(paragraph, "$", bold, italic, strike) + i += 1 + continue + + j = i + 1 + while True: + j = text.find("$", j) + if j == -1: + break + # Skip escaped dollars inside: "\$" + if j > 0 and text[j - 1] == "\\": + j += 1 + continue + break + + if j != -1: + inner = text[i + 1 : j] + if ( + inner + and "\n" not in inner + and not inner[0].isspace() + and not inner[-1].isspace() + ): + # Treat "$5" as currency more often than math. + if _CURRENCY_NUMBER_RE.match(inner) and ( + i == 0 or text[i - 1].isspace() + ): + self._add_text_run(paragraph, "$", bold, italic, strike) + i += 1 + continue + # Disallow digit immediately following the closing $ (common in prices like "$5.00" already handled above). + if j + 1 < n and text[j + 1].isdigit(): + self._add_text_run(paragraph, "$", bold, italic, strike) + i += 1 + continue + self._add_inline_equation( + paragraph, inner, bold=bold, italic=italic, strike=strike + ) + i = j + 1 + continue + + self._add_text_run(paragraph, "$", bold, italic, strike) + i += 1 + continue + + if text.startswith("~~", i): + j = text.find("~~", i + 2) + if j != -1: + self._add_inline_segments( + paragraph, + text[i + 2 : j], + bold=bold, + italic=italic, + strike=True, + ) + i = j + 2 + continue + + if text.startswith("**", i): + j = text.find("**", i + 2) + if j != -1: + self._add_inline_segments( + paragraph, + text[i + 2 : j], + bold=True, + italic=italic, + strike=strike, + ) + i = j + 2 + continue + + if text.startswith("__", i): + j = text.find("__", i + 2) + if j != -1: + self._add_inline_segments( + paragraph, + text[i + 2 : j], + bold=True, + italic=italic, + strike=strike, + ) + i = j + 2 + continue + + if text[i] == "*" and (i + 1 >= n or text[i + 1] != "*"): + j = text.find("*", i + 1) + if j != -1: + self._add_inline_segments( + paragraph, + text[i + 1 : j], + bold=bold, + italic=True, + strike=strike, + ) + i = j + 1 + continue + + if text[i] == "_" and (i + 1 >= n or text[i + 1] != "_"): + j = text.find("_", i + 1) + if j != -1: + self._add_inline_segments( + paragraph, + text[i + 1 : j], + bold=bold, + italic=True, + strike=strike, + ) + i = j + 1 + continue + + if text[i] == "[": + close = text.find("]", i + 1) + if close != -1 and close + 1 < n and text[close + 1] == "(": + close_paren = text.find(")", close + 2) + if close_paren != -1: + label = text[i + 1 : close] + url = text[close + 2 : close_paren] + self._add_hyperlink(paragraph, label, url) + i = close_paren + 1 + continue + # Citation marker like [12] -> internal link to References. + if close != -1: + inner = text[i + 1 : close].strip() + if inner.isdigit(): + idx = int(inner) + anchor = self._citation_anchor_by_index.get(idx) + if anchor: + self._add_internal_hyperlink(paragraph, f"[{idx}]", anchor) + i = close + 1 + continue + + m = _AUTO_URL_RE.match(text, i) + if m: + raw = m.group(0) + trimmed = raw + while trimmed and trimmed[-1] in ".,;:!?)]}": + trimmed = trimmed[:-1] + suffix = raw[len(trimmed) :] + + normalized = self._normalize_url(trimmed) + if normalized: + # Display the original (trimmed) text; use normalized URL as the target. + self._add_hyperlink( + paragraph, trimmed, normalized, display_text=trimmed + ) + else: + self._add_text_run(paragraph, raw, bold, italic, strike) + i += len(raw) + continue + + if suffix: + self._add_text_run(paragraph, suffix, bold, italic, strike) + i += len(raw) + continue + + j = next_special(i) + if j == i: + # Unmatched special character; treat literally to avoid infinite loops. + self._add_text_run(paragraph, text[i], bold, italic, strike) + i += 1 + else: + self._add_text_run(paragraph, text[i:j], bold, italic, strike) + i = j + + def _normalize_url(self, url: str) -> str: + u = (url or "").strip() + if u.lower().startswith("www."): + u = "https://" + u + + # Trim common trailing punctuation that often follows URLs in prose. + while u and u[-1] in ".,;:!?)]}": + u = u[:-1] + return u + + def _add_hyperlink( + self, paragraph, text: str, url: str, display_text: Optional[str] = None + ): + u = self._normalize_url(url) + if not u: + run = paragraph.add_run(display_text or text) + # Set East Asian font to prevent MS Gothic fallback + rPr = run._element.get_or_add_rPr() + rFonts = rPr.get_or_add_rFonts() + rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN) + return + + part = getattr(paragraph, "part", None) + if part is None or not hasattr(part, "relate_to"): + # Fallback if relationship API isn't available. + run = paragraph.add_run(display_text or text) + run.font.color.rgb = RGBColor(0, 0, 255) + run.font.underline = True + # Set East Asian font to prevent MS Gothic fallback + rPr = run._element.get_or_add_rPr() + rFonts = rPr.get_or_add_rFonts() + rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN) + return + + r_id = part.relate_to(u, RT.HYPERLINK, is_external=True) + + hyperlink = OxmlElement("w:hyperlink") + hyperlink.set(qn("r:id"), r_id) + + new_run = OxmlElement("w:r") + rPr = OxmlElement("w:rPr") + rStyle = OxmlElement("w:rStyle") + rStyle.set(qn("w:val"), "Hyperlink") + rPr.append(rStyle) + + # Set East Asian font to prevent MS Gothic fallback + rFonts = OxmlElement("w:rFonts") + rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN) + rPr.append(rFonts) + + color = OxmlElement("w:color") + color.set(qn("w:val"), "0000FF") + rPr.append(color) + + u_el = OxmlElement("w:u") + u_el.set(qn("w:val"), "single") + rPr.append(u_el) + + new_run.append(rPr) + + t = OxmlElement("w:t") + t.text = display_text or text + new_run.append(t) + + hyperlink.append(new_run) + cast(Any, paragraph)._p.append(hyperlink) + + def _add_inline_equation( + self, + paragraph, + latex: str, + bold: bool = False, + italic: bool = False, + strike: bool = False, + ): + latex = (latex or "").strip() + if not latex: + return + + if not self.valves.MATH_ENABLE or not LATEX_MATH_AVAILABLE: + self._add_text_run( + paragraph, f"\\({latex}\\)", bold=bold, italic=italic, strike=strike + ) + return + + try: + mathml = latex_to_mathml(latex) + omml = mathml2omml.convert(mathml) + o_math = self._omml_oMath_element(omml) + run = paragraph.add_run() + run.bold = bold + run.italic = italic + run.font.strike = strike + cast(Any, run)._r.append(o_math) + except Exception as exc: + logger.warning(f"Inline math conversion failed; keeping literal: {exc}") + self._add_text_run( + paragraph, f"\\({latex}\\)", bold=bold, italic=italic, strike=strike + ) + + def _omml_oMath_element(self, omml: str): + # Ensure the OMML element declares the math namespace so parse_xml works. + m_ns = "http://schemas.openxmlformats.org/officeDocument/2006/math" + s = (omml or "").strip() + if s.startswith("<m:oMath>") and s.endswith("</m:oMath>"): + inner = s[len("<m:oMath>") : -len("</m:oMath>")] + s = f'<m:oMath xmlns:m="{m_ns}">{inner}</m:oMath>' + elif s.startswith("<m:oMath") and "xmlns:m=" not in s.split(">", 1)[0]: + s = s.replace("<m:oMath", f'<m:oMath xmlns:m="{m_ns}"', 1) + return parse_xml(s) + + def add_code_block(self, doc: Document, code: str, language: str = ""): + """Add code block with syntax highlighting""" + # Token color mapping (based on common IDE themes) + TOKEN_COLORS = { + Token.Keyword: RGBColor(0, 92, 197), # macOS blue - keywords + Token.Keyword.Constant: RGBColor(0, 92, 197), + Token.Keyword.Declaration: RGBColor(0, 92, 197), + Token.Keyword.Namespace: RGBColor(0, 92, 197), + Token.Keyword.Type: RGBColor(0, 92, 197), + Token.Name.Function: RGBColor(0, 0, 0), # Functions stay black + Token.Name.Class: RGBColor(38, 82, 120), # Deep cyan-blue - classes + Token.Name.Decorator: RGBColor(170, 51, 0), # Warm orange - decorators + Token.Name.Builtin: RGBColor(0, 110, 71), # Deep green - builtins + Token.String: RGBColor(196, 26, 22), # Red - strings + Token.String.Doc: RGBColor(109, 120, 133), # Gray - docstrings + Token.Comment: RGBColor(109, 120, 133), # Gray - comments + Token.Comment.Single: RGBColor(109, 120, 133), + Token.Comment.Multiline: RGBColor(109, 120, 133), + Token.Number: RGBColor(28, 0, 207), # Indigo - numbers + Token.Number.Integer: RGBColor(28, 0, 207), + Token.Number.Float: RGBColor(28, 0, 207), + Token.Operator: RGBColor(90, 99, 120), # Gray-blue - operators + Token.Punctuation: RGBColor(0, 0, 0), # Black - punctuation + } + + def get_token_color(token_type): + """Recursively find token color""" + while token_type: + if token_type in TOKEN_COLORS: + return TOKEN_COLORS[token_type] + token_type = token_type.parent + return None + + # Add language label if available + if language: + lang_para = doc.add_paragraph() + lang_para.paragraph_format.space_before = Pt(6) + lang_para.paragraph_format.space_after = Pt(0) + lang_para.paragraph_format.left_indent = Cm(0.5) + lang_run = lang_para.add_run(language.upper()) + lang_run.font.name = self.valves.FONT_CODE + lang_run.font.size = Pt(8) + lang_run.font.color.rgb = RGBColor(100, 100, 100) + lang_run.font.bold = True + + # Add code block paragraph + paragraph = doc.add_paragraph() + paragraph.paragraph_format.left_indent = Cm(0.5) + paragraph.paragraph_format.space_before = Pt(3) if language else Pt(6) + paragraph.paragraph_format.space_after = Pt(6) + + # Add light gray background + shading = OxmlElement("w:shd") + shading.set(qn("w:fill"), "F7F7F7") + paragraph._element.pPr.append(shading) + + # Try to use Pygments for syntax highlighting + if PYGMENTS_AVAILABLE and language: + try: + lexer = get_lexer_by_name(language, stripall=False) + except Exception: + lexer = TextLexer() + + tokens = list(lex(code, lexer)) + + for token_type, token_value in tokens: + if not token_value: + continue + run = paragraph.add_run(token_value) + run.font.name = self.valves.FONT_CODE + run._element.rPr.rFonts.set(qn("w:eastAsia"), self.valves.FONT_CODE) + run.font.size = Pt(10) + + # Apply color + color = get_token_color(token_type) + if color: + run.font.color.rgb = color + + # Bold keywords + if token_type in Token.Keyword: + run.font.bold = True + else: + # No syntax highlighting, plain text display + run = paragraph.add_run(code) + run.font.name = self.valves.FONT_CODE + run._element.rPr.rFonts.set(qn("w:eastAsia"), self.valves.FONT_CODE) + run.font.size = Pt(10) + + def add_table(self, doc: Document, table_lines: List[str]): + """Add Markdown table with sane Word sizing/spacing, alignment, and hyperlinks/math support in cells.""" + if len(table_lines) < 2: + return + + def _validate_hex(c: str, default: str) -> str: + c = c.strip().lstrip("#") + if re.fullmatch(r"[0-9A-Fa-f]{6}", c): + return c + return default + + header_fill = _validate_hex(self.valves.TABLE_HEADER_COLOR, "F2F2F2") + zebra_fill = _validate_hex(self.valves.TABLE_ZEBRA_COLOR, "FBFBFB") + + def _split_row(line: str) -> List[str]: + # Keep empty cells, trim surrounding pipes. + raw = line.strip().strip("|") + return [c.strip() for c in raw.split("|")] + + def _is_separator_row(cells: List[str]) -> bool: + # Markdown separator: --- / :--- / ---: / :---: + if not cells: + return False + ok = 0 + for c in cells: + c = c.strip() + if re.fullmatch(r":?-{3,}:?", c): + ok += 1 + return ok == len(cells) + + def _col_align(cell: str) -> WD_ALIGN_PARAGRAPH: + s = (cell or "").strip() + if s.startswith(":") and s.endswith(":"): + return WD_ALIGN_PARAGRAPH.CENTER + if s.endswith(":"): + return WD_ALIGN_PARAGRAPH.RIGHT + return WD_ALIGN_PARAGRAPH.LEFT + + def _set_cell_shading(cell, fill: str): + tc_pr = cell._element.get_or_add_tcPr() + shd = OxmlElement("w:shd") + shd.set(qn("w:fill"), fill) + tc_pr.append(shd) + + raw_rows = [_split_row(l) for l in table_lines if l.strip().startswith("|")] + if not raw_rows: + return + + sep_idx = 1 if len(raw_rows) > 1 and _is_separator_row(raw_rows[1]) else -1 + header = raw_rows[0] + body = raw_rows[sep_idx + 1 :] if sep_idx >= 0 else raw_rows[1:] + + num_cols = max(len(header), *(len(r) for r in body)) if body else len(header) + header = header + [""] * (num_cols - len(header)) + body = [r + [""] * (num_cols - len(r)) for r in body] + + aligns = [ + _col_align(c) for c in (raw_rows[1] if sep_idx == 1 else [""] * num_cols) + ] + + table = doc.add_table(rows=1 + len(body), cols=num_cols) + table.style = "Table Grid" + table.alignment = WD_TABLE_ALIGNMENT.LEFT + cast(Any, table).autofit = False + + # Cell margins (twips): smaller padding for compact tables. + self._set_table_cell_margins(table, top=60, bottom=60, left=90, right=90) + + # Column widths: proportional to content, bounded, then normalized to page width. + available_width = int(self._available_block_width(doc)) + min_col = max(int(Inches(0.55)), available_width // max(1, num_cols * 3)) + + def _plain_len(s: str) -> int: + t = re.sub(r"`([^`]+)`", r"\1", s or "") + t = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1", t) + t = re.sub(r"\s+", " ", t).strip() + return len(t) + + weights: List[int] = [] + for ci in range(num_cols): + max_len = _plain_len(header[ci]) + for r in body: + max_len = max(max_len, _plain_len(r[ci])) + weights.append(max(1, min(max_len, 40))) + + sum_w = sum(weights) or 1 + widths = [max(min_col, int(available_width * w / sum_w)) for w in weights] + total = sum(widths) + if total > available_width: + even = max(1, available_width // max(1, num_cols)) + widths = [even] * num_cols + total = sum(widths) + if total < available_width: + rem = available_width - total + order = sorted(range(num_cols), key=lambda i: weights[i], reverse=True) + oi = 0 + while rem > 0 and order: + widths[order[oi % len(order)]] += 1 + rem -= 1 + oi += 1 + + for ci, w in enumerate(widths): + table.columns[ci].width = w + for row in table.rows: + row.cells[ci].width = w + + def _format_cell_paragraph(para, align: WD_ALIGN_PARAGRAPH): + para.alignment = align + pf = para.paragraph_format + pf.space_before = Pt(0) + pf.space_after = Pt(0) + pf.line_spacing_rule = WD_LINE_SPACING.SINGLE + + def _fill_cell(cell, text: str, align: WD_ALIGN_PARAGRAPH, bold: bool = False): + cell.text = "" + parts = [ + p for p in re.split(r"(?:<br\s*/?>|\n)", text or "") if p is not None + ] + if not parts: + parts = [""] + for pi, part in enumerate(parts): + para = cell.paragraphs[0] if pi == 0 else cell.add_paragraph() + _format_cell_paragraph(para, align) + self.add_formatted_text(para, part) + for run in para.runs: + run.font.size = Pt(9) + if bold: + run.bold = True + + # Header row + header_row = table.rows[0] + self._set_table_header_row_repeat(header_row) + for ci in range(num_cols): + cell = header_row.cells[ci] + _set_cell_shading(cell, header_fill) + _fill_cell( + cell, + header[ci], + aligns[ci] if ci < len(aligns) else WD_ALIGN_PARAGRAPH.LEFT, + bold=True, + ) + + # Body rows + for ri, row_data in enumerate(body, start=1): + row = table.rows[ri] + for ci in range(num_cols): + cell = row.cells[ci] + if (ri % 2) == 0: + _set_cell_shading(cell, zebra_fill) + _fill_cell( + cell, + row_data[ci], + aligns[ci] if ci < len(aligns) else WD_ALIGN_PARAGRAPH.LEFT, + ) + + def _set_table_cell_margins( + self, table, top: int, bottom: int, left: int, right: int + ): + tbl_pr = cast(Any, table)._tbl.tblPr + tbl_cell_mar = OxmlElement("w:tblCellMar") + for tag, val in ( + ("top", top), + ("bottom", bottom), + ("left", left), + ("right", right), + ): + el = OxmlElement(f"w:{tag}") + el.set(qn("w:w"), str(int(val))) + el.set(qn("w:type"), "dxa") + tbl_cell_mar.append(el) + tbl_pr.append(tbl_cell_mar) + + def _set_table_header_row_repeat(self, row): + tr_pr = row._tr.get_or_add_trPr() + tbl_header = OxmlElement("w:tblHeader") + tbl_header.set(qn("w:val"), "true") + tr_pr.append(tbl_header) + + def add_list_to_doc( + self, doc: Document, items: List[Tuple[int, str]], list_type: str + ): + """Add list""" + for indent, text in items: + paragraph = doc.add_paragraph() + + if list_type == "unordered": + # Unordered list with bullets + paragraph.style = "List Bullet" + else: + # Ordered list with numbers + paragraph.style = "List Number" + + # Set indent + paragraph.paragraph_format.left_indent = Cm(0.5 * (indent + 1)) + + # Add formatted text + self.add_formatted_text(paragraph, text) + + def add_horizontal_rule(self, doc: Document): + """Add horizontal rule""" + paragraph = doc.add_paragraph() + paragraph.paragraph_format.space_before = Pt(12) + paragraph.paragraph_format.space_after = Pt(12) + + # Add bottom border as horizontal rule + pPr = paragraph._element.get_or_add_pPr() + pBdr = OxmlElement("w:pBdr") + bottom = OxmlElement("w:bottom") + bottom.set(qn("w:val"), "single") + bottom.set(qn("w:sz"), "6") + bottom.set(qn("w:space"), "1") + bottom.set(qn("w:color"), "auto") + pBdr.append(bottom) + pPr.append(pBdr) + + def add_blockquote(self, doc: Document, text: str): + """Add blockquote with left border and gray background""" + for line in text.split("\n"): + paragraph = doc.add_paragraph() + paragraph.paragraph_format.left_indent = Cm(1.0) + paragraph.paragraph_format.space_before = Pt(3) + paragraph.paragraph_format.space_after = Pt(3) + + # Add left border + pPr = paragraph._element.get_or_add_pPr() + pBdr = OxmlElement("w:pBdr") + left = OxmlElement("w:left") + left.set(qn("w:val"), "single") + left.set(qn("w:sz"), "24") # Border thickness + left.set(qn("w:space"), "4") # Space between border and text + left.set(qn("w:color"), "CCCCCC") # Gray border + pBdr.append(left) + pPr.append(pBdr) + + # Add light gray background + shading = OxmlElement("w:shd") + shading.set(qn("w:fill"), "F9F9F9") + pPr.append(shading) + + # Add formatted text + self.add_formatted_text(paragraph, line) + + # Set font to italic gray + for run in paragraph.runs: + run.font.color.rgb = RGBColor(85, 85, 85) # Dark gray text + run.italic = True + + def _sanitize_metadata(self, doc: Document, author: str = "", title: str = ""): + """Removes library fingerprints and sets professional defaults.""" + p = doc.core_properties + p.author = author # Set your preferred author name + p.comments = "" # Clears any default library comments + p.title = title # Initialise as empty; logic fills this later + p.keywords = "" + p.subject = "" + p.last_modified_by = author + + try: + from docx.opc.constants import CONTENT_TYPE as CT + + # Setting these to an empty string or a custom value + # obscures the default 'python-docx' signature. + p.category = "" + p.content_status = "" + except Exception: + pass diff --git a/integrations/openwebui-community-plugins/inline_visualizer.py b/integrations/openwebui-community-plugins/inline_visualizer.py new file mode 100644 index 0000000..22304d5 --- /dev/null +++ b/integrations/openwebui-community-plugins/inline_visualizer.py @@ -0,0 +1,4171 @@ +""" +title: Inline Visualizer +author: Classic298 +author_url: https://github.com/Classic298 +funding_url: https://github.com/Classic298 +version: 2.2.3 +required_open_webui_version: 0.10.2 +description: Renders interactive HTML/SVG visualizations inline in chat. Requires "iframe Sandbox Allow Same Origin" to be enabled in Open WebUI Settings -> Interface. For design instructions, the model should call view_skill("visualize"). +""" + +import re +import asyncio +from typing import Literal + +# Build marker embedded into the rendered iframe so the running +# version can be verified at runtime (search DevTools for +# `data-iv-build` on <html>). Keep in sync with the frontmatter version. +_IV_BUILD = "2.2.3" + +from fastapi.responses import HTMLResponse +from pydantic import BaseModel, Field + +# --------------------------------------------------------------------------- +# Injected CSS — Theme variables (light default, dark via data-theme) +# --------------------------------------------------------------------------- + +THEME_CSS = """ +:root { + --color-text-primary: #1F2937; + --color-text-secondary: #6B7280; + --color-text-tertiary: #9CA3AF; + --color-text-info: #2563EB; + --color-text-success: #059669; + --color-text-warning: #D97706; + --color-text-danger: #DC2626; + --color-bg-primary: #FFFFFF; + --color-bg-secondary: #F9FAFB; + --color-bg-tertiary: #F3F4F6; + --color-border-tertiary: rgba(0,0,0,0.15); + --color-border-secondary: rgba(0,0,0,0.3); + --color-border-primary: rgba(0,0,0,0.4); + --font-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; + --font-mono: 'SF Mono', Menlo, Consolas, monospace; + --radius-md: 8px; + --radius-lg: 12px; + --radius-xl: 16px; + /* --- Color ramp variables (light) --- */ + --ramp-purple-fill:#EEEDFE; --ramp-purple-stroke:#534AB7; --ramp-purple-th:#3C3489; --ramp-purple-ts:#534AB7; + --ramp-teal-fill:#E1F5EE; --ramp-teal-stroke:#0F6E56; --ramp-teal-th:#085041; --ramp-teal-ts:#0F6E56; + --ramp-coral-fill:#FAECE7; --ramp-coral-stroke:#993C1D; --ramp-coral-th:#712B13; --ramp-coral-ts:#993C1D; + --ramp-pink-fill:#FBEAF0; --ramp-pink-stroke:#993556; --ramp-pink-th:#72243E; --ramp-pink-ts:#993556; + --ramp-gray-fill:#F1EFE8; --ramp-gray-stroke:#5F5E5A; --ramp-gray-th:#444441; --ramp-gray-ts:#5F5E5A; + --ramp-blue-fill:#E6F1FB; --ramp-blue-stroke:#185FA5; --ramp-blue-th:#0C447C; --ramp-blue-ts:#185FA5; + --ramp-green-fill:#EAF3DE; --ramp-green-stroke:#3B6D11; --ramp-green-th:#27500A; --ramp-green-ts:#3B6D11; + --ramp-amber-fill:#FAEEDA; --ramp-amber-stroke:#854F0B; --ramp-amber-th:#633806; --ramp-amber-ts:#854F0B; + --ramp-red-fill:#FCEBEB; --ramp-red-stroke:#A32D2D; --ramp-red-th:#791F1F; --ramp-red-ts:#A32D2D; + /* --- Common aliases (catch hallucinated variable names) --- */ + /* Text */ + --fg: var(--color-text-primary); + --text: var(--color-text-primary); + --foreground: var(--color-text-primary); + --text-primary: var(--color-text-primary); + --text-color: var(--color-text-primary); + --color-text: var(--color-text-primary); + --color-foreground: var(--color-text-primary); + --body-color: var(--color-text-primary); + --muted: var(--color-text-secondary); + --muted-foreground: var(--color-text-secondary); + --text-muted: var(--color-text-secondary); + --text-secondary: var(--color-text-secondary); + --secondary: var(--color-text-secondary); + --subtle: var(--color-text-tertiary); + --text-tertiary: var(--color-text-tertiary); + /* Backgrounds */ + --bg: var(--color-bg-primary); + --background: var(--color-bg-primary); + --bg-primary: var(--color-bg-primary); + --body-bg: var(--color-bg-primary); + --color-bg: var(--color-bg-primary); + --surface: var(--color-bg-secondary); + --surface-1: var(--color-bg-secondary); + --surface-2: var(--color-bg-tertiary); + --card: var(--color-bg-secondary); + --card-bg: var(--color-bg-secondary); + --card-foreground: var(--color-text-primary); + --card-background: var(--color-bg-secondary); + --popover: var(--color-bg-secondary); + --popover-foreground: var(--color-text-primary); + --hover: rgba(0,0,0,0.04); + /* Borders */ + --border: var(--color-border-tertiary); + --border-color: var(--color-border-tertiary); + --divider: var(--color-border-tertiary); + --separator: var(--color-border-tertiary); + --input: var(--color-border-tertiary); + --ring: var(--color-border-secondary); + /* Accent / Primary (AI uses --accent as brand color, not surface) */ + --primary: #6c2eb9; + --primary-foreground: #ffffff; + --accent: #6c2eb9; + --accent-foreground: #ffffff; + /* Themed select chevron (light) — used by the pre-styled <select> */ + --select-arrow: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'><path d='M3 4.5l3 3 3-3' fill='none' stroke='%236B7280' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/></svg>"); +} +:root[data-theme="dark"] { + --color-text-primary: #E5E7EB; + --color-text-secondary: #9CA3AF; + --color-text-tertiary: #6B7280; + --color-text-info: #60A5FA; + --color-text-success: #34D399; + --color-text-warning: #FBBF24; + --color-text-danger: #F87171; + --color-bg-primary: #1A1A1A; + --color-bg-secondary: #262626; + --color-bg-tertiary: #111111; + --color-border-tertiary: rgba(255,255,255,0.15); + --color-border-secondary: rgba(255,255,255,0.3); + --color-border-primary: rgba(255,255,255,0.4); + --ramp-purple-fill:#3C3489; --ramp-purple-stroke:#AFA9EC; --ramp-purple-th:#CECBF6; --ramp-purple-ts:#AFA9EC; + --ramp-teal-fill:#085041; --ramp-teal-stroke:#5DCAA5; --ramp-teal-th:#9FE1CB; --ramp-teal-ts:#5DCAA5; + --ramp-coral-fill:#712B13; --ramp-coral-stroke:#F0997B; --ramp-coral-th:#F5C4B3; --ramp-coral-ts:#F0997B; + --ramp-pink-fill:#72243E; --ramp-pink-stroke:#ED93B1; --ramp-pink-th:#F4C0D1; --ramp-pink-ts:#ED93B1; + --ramp-gray-fill:#444441; --ramp-gray-stroke:#B4B2A9; --ramp-gray-th:#D3D1C7; --ramp-gray-ts:#B4B2A9; + --ramp-blue-fill:#0C447C; --ramp-blue-stroke:#85B7EB; --ramp-blue-th:#B5D4F4; --ramp-blue-ts:#85B7EB; + --ramp-green-fill:#27500A; --ramp-green-stroke:#97C459; --ramp-green-th:#C0DD97; --ramp-green-ts:#97C459; + --ramp-amber-fill:#633806; --ramp-amber-stroke:#EF9F27; --ramp-amber-th:#FAC775; --ramp-amber-ts:#EF9F27; + --ramp-red-fill:#791F1F; --ramp-red-stroke:#F09595; --ramp-red-th:#F7C1C1; --ramp-red-ts:#F09595; + /* --- Common aliases (dark overrides) --- */ + --text: var(--color-text-primary); + --foreground: var(--color-text-primary); + --text-primary: var(--color-text-primary); + --text-color: var(--color-text-primary); + --color-text: var(--color-text-primary); + --body-color: var(--color-text-primary); + --muted: var(--color-text-secondary); + --muted-foreground: var(--color-text-secondary); + --text-muted: var(--color-text-secondary); + --text-secondary: var(--color-text-secondary); + --secondary: var(--color-text-secondary); + --subtle: var(--color-text-tertiary); + --text-tertiary: var(--color-text-tertiary); + --bg: var(--color-bg-primary); + --background: var(--color-bg-primary); + --bg-primary: var(--color-bg-primary); + --body-bg: var(--color-bg-primary); + --color-bg: var(--color-bg-primary); + --surface: var(--color-bg-secondary); + --surface-1: var(--color-bg-secondary); + --surface-2: var(--color-bg-tertiary); + --card: var(--color-bg-secondary); + --card-bg: var(--color-bg-secondary); + --card-foreground: var(--color-text-primary); + --card-background: var(--color-bg-secondary); + --popover: var(--color-bg-secondary); + --popover-foreground: var(--color-text-primary); + --hover: rgba(255,255,255,0.06); + --border: var(--color-border-tertiary); + --border-color: var(--color-border-tertiary); + --divider: var(--color-border-tertiary); + --separator: var(--color-border-tertiary); + --input: var(--color-border-tertiary); + --ring: var(--color-border-secondary); + --primary: #a78bfa; + --primary-foreground: #1A1A1A; + --accent: #a78bfa; + --accent-foreground: #ffffff; + --select-arrow: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'><path d='M3 4.5l3 3 3-3' fill='none' stroke='%239CA3AF' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/></svg>"); +} + +/* --- Named accent palette --- + * Apply data-accent="<name>" on <html> for global, on any element + * for local override. The variants reuse the existing color-ramp + * stroke colors so charts and forms share visual vocabulary + * (teal here = teal in a chart). Each variant works in both + * light and dark themes — --accent picks up the ramp's per-theme + * stroke automatically; --accent-foreground flips dark in dark + * mode so text stays legible on pastel accents. + */ +[data-accent="purple"] { --accent: var(--ramp-purple-stroke); --accent-foreground: #ffffff; } +[data-accent="teal"] { --accent: var(--ramp-teal-stroke); --accent-foreground: #ffffff; } +[data-accent="coral"] { --accent: var(--ramp-coral-stroke); --accent-foreground: #ffffff; } +[data-accent="pink"] { --accent: var(--ramp-pink-stroke); --accent-foreground: #ffffff; } +[data-accent="gray"] { --accent: var(--ramp-gray-stroke); --accent-foreground: #ffffff; } +[data-accent="blue"] { --accent: var(--ramp-blue-stroke); --accent-foreground: #ffffff; } +[data-accent="green"] { --accent: var(--ramp-green-stroke); --accent-foreground: #ffffff; } +[data-accent="amber"] { --accent: var(--ramp-amber-stroke); --accent-foreground: #ffffff; } +[data-accent="red"] { --accent: var(--ramp-red-stroke); --accent-foreground: #ffffff; } + +[data-theme="dark"] [data-accent], +[data-theme="dark"][data-accent] { + --accent-foreground: #1A1A1A; +} +""" + +# --------------------------------------------------------------------------- +# Injected CSS — SVG utility classes + color ramp selectors +# --------------------------------------------------------------------------- + +SVG_CLASSES = """ +/* --- Text --- */ +.t { font: 400 14px/1.4 var(--font-sans); fill: var(--color-text-primary); } +.ts { font: 400 12px/1.4 var(--font-sans); fill: var(--color-text-secondary); } +.th { font: 500 14px/1.4 var(--font-sans); fill: var(--color-text-primary); } + +/* --- Shapes --- */ +.box { fill: var(--color-bg-secondary); stroke: var(--color-border-tertiary); stroke-width: 0.5; } +.node { cursor: pointer; } +.node:hover { opacity: 0.85; } +.arr { stroke: var(--color-border-secondary); stroke-width: 1.5; fill: none; } +.leader { stroke: var(--color-text-tertiary); stroke-width: 0.5; stroke-dasharray: 3 2; fill: none; } + +/* --- Color ramp selectors (fill/stroke adapt via CSS vars) --- */ +/* color: on the group resolves currentColor marks to the series color. + path/polygon get the saturated stroke stop (pale fill stops sit behind + label text and are indistinguishable side by side in a pie); classed + or explicitly-filled marks keep their own styling. */ +.c-purple>rect,.c-purple>circle,.c-purple>ellipse{fill:var(--ramp-purple-fill);stroke:var(--ramp-purple-stroke);stroke-width:.5} +g.c-purple{color:var(--ramp-purple-stroke)} .c-purple>path:not([class]):not([fill]),.c-purple>polygon:not([class]):not([fill]){fill:var(--ramp-purple-stroke)} +.c-purple>.th{fill:var(--ramp-purple-th)!important} .c-purple>.ts{fill:var(--ramp-purple-ts)!important} +.c-teal>rect,.c-teal>circle,.c-teal>ellipse{fill:var(--ramp-teal-fill);stroke:var(--ramp-teal-stroke);stroke-width:.5} +g.c-teal{color:var(--ramp-teal-stroke)} .c-teal>path:not([class]):not([fill]),.c-teal>polygon:not([class]):not([fill]){fill:var(--ramp-teal-stroke)} +.c-teal>.th{fill:var(--ramp-teal-th)!important} .c-teal>.ts{fill:var(--ramp-teal-ts)!important} +.c-coral>rect,.c-coral>circle,.c-coral>ellipse{fill:var(--ramp-coral-fill);stroke:var(--ramp-coral-stroke);stroke-width:.5} +g.c-coral{color:var(--ramp-coral-stroke)} .c-coral>path:not([class]):not([fill]),.c-coral>polygon:not([class]):not([fill]){fill:var(--ramp-coral-stroke)} +.c-coral>.th{fill:var(--ramp-coral-th)!important} .c-coral>.ts{fill:var(--ramp-coral-ts)!important} +.c-pink>rect,.c-pink>circle,.c-pink>ellipse{fill:var(--ramp-pink-fill);stroke:var(--ramp-pink-stroke);stroke-width:.5} +g.c-pink{color:var(--ramp-pink-stroke)} .c-pink>path:not([class]):not([fill]),.c-pink>polygon:not([class]):not([fill]){fill:var(--ramp-pink-stroke)} +.c-pink>.th{fill:var(--ramp-pink-th)!important} .c-pink>.ts{fill:var(--ramp-pink-ts)!important} +.c-gray>rect,.c-gray>circle,.c-gray>ellipse{fill:var(--ramp-gray-fill);stroke:var(--ramp-gray-stroke);stroke-width:.5} +g.c-gray{color:var(--ramp-gray-stroke)} .c-gray>path:not([class]):not([fill]),.c-gray>polygon:not([class]):not([fill]){fill:var(--ramp-gray-stroke)} +.c-gray>.th{fill:var(--ramp-gray-th)!important} .c-gray>.ts{fill:var(--ramp-gray-ts)!important} +.c-blue>rect,.c-blue>circle,.c-blue>ellipse{fill:var(--ramp-blue-fill);stroke:var(--ramp-blue-stroke);stroke-width:.5} +g.c-blue{color:var(--ramp-blue-stroke)} .c-blue>path:not([class]):not([fill]),.c-blue>polygon:not([class]):not([fill]){fill:var(--ramp-blue-stroke)} +.c-blue>.th{fill:var(--ramp-blue-th)!important} .c-blue>.ts{fill:var(--ramp-blue-ts)!important} +.c-green>rect,.c-green>circle,.c-green>ellipse{fill:var(--ramp-green-fill);stroke:var(--ramp-green-stroke);stroke-width:.5} +g.c-green{color:var(--ramp-green-stroke)} .c-green>path:not([class]):not([fill]),.c-green>polygon:not([class]):not([fill]){fill:var(--ramp-green-stroke)} +.c-green>.th{fill:var(--ramp-green-th)!important} .c-green>.ts{fill:var(--ramp-green-ts)!important} +.c-amber>rect,.c-amber>circle,.c-amber>ellipse{fill:var(--ramp-amber-fill);stroke:var(--ramp-amber-stroke);stroke-width:.5} +g.c-amber{color:var(--ramp-amber-stroke)} .c-amber>path:not([class]):not([fill]),.c-amber>polygon:not([class]):not([fill]){fill:var(--ramp-amber-stroke)} +.c-amber>.th{fill:var(--ramp-amber-th)!important} .c-amber>.ts{fill:var(--ramp-amber-ts)!important} +.c-red>rect,.c-red>circle,.c-red>ellipse{fill:var(--ramp-red-fill);stroke:var(--ramp-red-stroke);stroke-width:.5} +g.c-red{color:var(--ramp-red-stroke)} .c-red>path:not([class]):not([fill]),.c-red>polygon:not([class]):not([fill]){fill:var(--ramp-red-stroke)} +.c-red>.th{fill:var(--ramp-red-th)!important} .c-red>.ts{fill:var(--ramp-red-ts)!important} +""" + +# --------------------------------------------------------------------------- +# Injected CSS — Base resets & interactive element styles +# --------------------------------------------------------------------------- + +BASE_STYLES = """ +* { box-sizing: border-box; margin: 0; font-family: var(--font-sans); } +html, body { overflow: hidden; } +body { background: transparent; color: var(--color-text-primary); line-height: 1.5; padding: 8px; } +svg { overflow: visible; } +svg text { fill: var(--color-text-primary); } +h1 { font-size: 22px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 12px; } +h2 { font-size: 18px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 8px; } +h3 { font-size: 16px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 6px; } +p { font-size: 14px; color: var(--color-text-secondary); margin-bottom: 8px; } +/* --- Pre-styled form elements --- + * Each rule is gated with :not([class]):not([style]) so the model + * opts in by emitting bare HTML. Adding either attribute is treated + * as opting out — the default suppresses and the model styles from + * scratch. Keeps token cost low for vanilla cases without locking + * the design space. + */ +button:not([class]):not([style]) { + background: transparent; border: 0.5px solid var(--color-border-secondary); + border-radius: var(--radius-md); padding: 6px 14px; font-size: 13px; + color: var(--color-text-primary); cursor: pointer; font-family: var(--font-sans); +} +button:not([class]):not([style]):hover { background: var(--color-bg-secondary); } + +input[type="text"]:not([class]):not([style]), +input[type="number"]:not([class]):not([style]), +input[type="email"]:not([class]):not([style]), +input[type="search"]:not([class]):not([style]), +input[type="password"]:not([class]):not([style]), +input[type="tel"]:not([class]):not([style]), +input[type="url"]:not([class]):not([style]), +input[type="date"]:not([class]):not([style]), +input[type="time"]:not([class]):not([style]), +input[type="datetime-local"]:not([class]):not([style]) { + background: var(--color-bg-primary); + border: 0.5px solid var(--color-border-tertiary); + border-radius: var(--radius-md); padding: 6px 10px; font-size: 13px; + color: var(--color-text-primary); font-family: var(--font-sans); + outline: none; transition: border-color 0.15s ease; +} +input[type="text"]:not([class]):not([style]):focus, +input[type="number"]:not([class]):not([style]):focus, +input[type="email"]:not([class]):not([style]):focus, +input[type="search"]:not([class]):not([style]):focus, +input[type="password"]:not([class]):not([style]):focus, +input[type="tel"]:not([class]):not([style]):focus, +input[type="url"]:not([class]):not([style]):focus, +input[type="date"]:not([class]):not([style]):focus, +input[type="time"]:not([class]):not([style]):focus, +input[type="datetime-local"]:not([class]):not([style]):focus { + border-color: var(--color-border-primary); +} + +/* Drop the type=number spinner — clashes with the field's borders. */ +input[type="number"]:not([class]):not([style]) { + -moz-appearance: textfield; appearance: textfield; +} +input[type="number"]:not([class]):not([style])::-webkit-outer-spin-button, +input[type="number"]:not([class]):not([style])::-webkit-inner-spin-button { + -webkit-appearance: none; margin: 0; +} + +textarea:not([class]) { + background: var(--color-bg-primary); + border: 0.5px solid var(--color-border-tertiary); + border-radius: var(--radius-md); padding: 8px 10px; font-size: 13px; + color: var(--color-text-primary); font-family: var(--font-sans); + outline: none; resize: vertical; min-height: 60px; + transition: border-color 0.15s ease; +} +textarea:not([class]):focus { border-color: var(--color-border-primary); } + +/* accent-color always applies, regardless of class/style — it's a + * tint property the model is highly unlikely to set themselves, and + * letting it ride keeps palette switches consistent even when the + * model adds inline width/max-width styling to the slider. */ +input[type="range"], input[type="checkbox"], input[type="radio"] { + accent-color: var(--accent); +} +input[type="range"]:not([class]):not([style]) { width: 100%; } + +input[type="checkbox"]:not([class]):not([style]), +input[type="radio"]:not([class]):not([style]) { + /* accent-color comes from the always-on rule above. */ + cursor: pointer; +} + +select:not([class]):not([style]) { + appearance: none; -webkit-appearance: none; -moz-appearance: none; + background-color: var(--color-bg-secondary); + background-image: var(--select-arrow); + background-repeat: no-repeat; + background-position: right 10px center; + border: 0.5px solid var(--color-border-tertiary); + border-radius: var(--radius-md); padding: 6px 28px 6px 10px; + font-size: 13px; color: var(--color-text-primary); font-family: var(--font-sans); + outline: none; cursor: pointer; +} +select:not([class]):not([style]):focus { border-color: var(--color-border-primary); } + +label:not([class]):not([style]) { + font-size: 13px; color: var(--color-text-primary); cursor: pointer; +} +fieldset:not([class]):not([style]) { + border: 0.5px solid var(--color-border-tertiary); + border-radius: var(--radius-md); padding: 12px; +} +legend:not([class]):not([style]) { + font-size: 12px; color: var(--color-text-secondary); padding: 0 6px; +} + +/* Validation error border — standard a11y attribute, no class needed. */ +input[aria-invalid="true"]:not([class]):not([style]), +textarea[aria-invalid="true"]:not([class]), +select[aria-invalid="true"]:not([class]):not([style]) { + border-color: var(--color-text-danger); +} + +/* Keyboard-only focus rings (accent outline). Mouse focus stays subtle. */ +button:not([class]):not([style]):focus-visible, +input:not([class]):not([style]):focus-visible, +textarea:not([class]):focus-visible, +select:not([class]):not([style]):focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; +} + +code { + font-family: var(--font-mono); font-size: 13px; background: var(--color-bg-tertiary); + padding: 2px 6px; border-radius: 4px; +} + +/* <kbd> — keyboard-key pill (cmd/ctrl/k style). */ +kbd:not([class]):not([style]) { + font-family: var(--font-mono); font-size: 12px; + background: var(--color-bg-secondary); + border: 0.5px solid var(--color-border-tertiary); + border-radius: 4px; padding: 1px 6px; + color: var(--color-text-primary); +} + +/* <hr> — flat divider matching the rest of the borders. */ +hr:not([class]):not([style]) { + border: none; + border-top: 0.5px solid var(--color-border-tertiary); + margin: 1.5rem 0; +} + +/* <details> / <summary> — themed disclosure with a bigger chevron. + * Container is an invisible rounded "wrapper" — the visible card- + * shape is the summary header itself. This way if a model adds its + * own summary background/border, the result is still single-card, + * not nested. Chevron is sized to be clearly visible. */ +details:not([class]):not([style]) { + margin: 12px 0; + border: 0.5px solid var(--color-border-tertiary); + border-radius: var(--radius-md); + overflow: hidden; +} +details:not([class]):not([style]) > summary { + cursor: pointer; list-style: none; user-select: none; + font-weight: 500; color: var(--color-text-primary); + background: var(--color-bg-secondary); + padding: 10px 14px 10px 34px; + position: relative; + transition: background-color 0.15s ease; +} +details:not([class]):not([style]) > summary:hover { + background: var(--color-bg-tertiary); +} +details:not([class]):not([style]) > summary::-webkit-details-marker { display: none; } +details:not([class]):not([style]) > summary::marker { content: ''; } +details:not([class]):not([style]) > summary::before { + content: '\\25B8'; /* ▸ */ + position: absolute; left: 12px; top: 50%; + transform: translateY(-50%); + transition: transform 0.15s ease; + color: var(--color-text-secondary); + font-size: 18px; + line-height: 1; +} +details[open]:not([class]):not([style]) > summary::before { + transform: translateY(-50%) rotate(90deg); +} +details[open]:not([class]):not([style]) > summary { + border-bottom: 0.5px solid var(--color-border-tertiary); +} +/* Margin (not padding) so children with their own bg inset properly. */ +details:not([class]):not([style]) > *:not(summary) { + margin: 12px 14px; +} + +blockquote:not([class]):not([style]) { + border-left: 4px solid var(--accent); + background: var(--color-bg-secondary); + padding: 12px 18px; + margin: 16px 0; + color: var(--color-text-secondary); + border-radius: var(--radius-md); +} +blockquote:not([class]):not([style]) > :last-child { margin-bottom: 0; } +blockquote:not([class]):not([style]) > :first-child { margin-top: 0; } + +/* <table> — flat data table, theme-matched borders, header pill, + * row hover, last-row borderless, no zebra (kept calm). For numeric + * columns, add align="right" or class="num" to <th>/<td>. */ +table:not([class]):not([style]) { + width: 100%; + border-collapse: collapse; + margin: 12px 0; + font-size: 13px; + color: var(--color-text-primary); + font-family: var(--font-sans); +} +table:not([class]):not([style]) caption { + text-align: left; + font-size: 13px; + font-weight: 500; + color: var(--color-text-secondary); + padding: 0 0 8px; + caption-side: top; +} +table:not([class]):not([style]) th { + text-align: left; + padding: 8px 12px; + /* Reset all sides so a model's `border:` shorthand can't leak through. */ + border: none; + border-bottom: 0.5px solid var(--color-border-secondary); + font-weight: 500; + font-size: 11px; + color: var(--color-text-secondary); + text-transform: uppercase; + letter-spacing: 0.04em; + background: var(--color-bg-secondary); + white-space: nowrap; +} +table:not([class]):not([style]) td { + padding: 10px 12px; + border: none; + border-bottom: 0.5px solid var(--color-border-tertiary); + vertical-align: top; +} +table:not([class]):not([style]) tr:last-child > td { + border-bottom: none; +} +table:not([class]):not([style]) tbody tr { + transition: background-color 0.1s ease; +} +table:not([class]):not([style]) tbody tr:hover { + background: var(--color-bg-secondary); +} +/* Numeric columns: opt-in via align="right" or class="num" on cells. */ +table:not([class]):not([style]) td[align="right"], +table:not([class]):not([style]) th[align="right"], +table:not([class]):not([style]) td.num, +table:not([class]):not([style]) th.num { + text-align: right; + font-variant-numeric: tabular-nums; +} + +mark:not([class]):not([style]) { + background: var(--ramp-amber-fill); + color: var(--ramp-amber-th); + padding: 0 4px; + border-radius: 3px; +} + +/* <dl> three modes — default stacked, data-layout="grid", data-layout="inline". + * data-layout is the explicit opt-in, so [data-layout] rules skip the class/style gate. */ +dl:not([class]):not([style]) { margin: 12px 0; } +dl:not([class]):not([style]) > dt { + font-weight: 500; + color: var(--color-text-primary); + font-size: 14px; + margin-top: 12px; +} +dl:not([class]):not([style]) > dt:first-child { margin-top: 0; } +dl:not([class]):not([style]) > dd { + margin: 4px 0 0; + font-size: 13px; + color: var(--color-text-secondary); +} + +/* `display: contents` on the optional wrapping div + dual selectors below + * tolerates both flat <dt><dd>… and <div><dt><dd></div>… markup. */ +dl[data-layout="grid"] { + display: grid; + grid-template-columns: max-content 1fr; + gap: 8px 16px; + align-items: baseline; + padding: 12px 16px; + border: 0.5px solid var(--color-border-tertiary); + border-radius: var(--radius-md); + background: var(--color-bg-secondary); + margin: 12px 0; +} +dl[data-layout="grid"] > div { display: contents; } +dl[data-layout="grid"] > dt, +dl[data-layout="grid"] > div > dt { + font-weight: 400; + color: var(--color-text-secondary); + font-size: 13px; + margin: 0; +} +dl[data-layout="grid"] > dd, +dl[data-layout="grid"] > div > dd { + margin: 0; + text-align: right; + color: var(--color-text-primary); + font-weight: 500; + font-size: 13px; +} + +/* data-layout="inline" — pill row. Each <dt>/<dd> pair wrapped in <div>. + * Same opt-in-via-attribute logic as grid above — no :not() gate. */ +dl[data-layout="inline"] { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 12px 0; +} +dl[data-layout="inline"] > div { + display: inline-flex; + align-items: baseline; + gap: 4px; + padding: 4px 10px; + border: 0.5px solid var(--color-border-tertiary); + border-radius: 999px; + font-size: 12px; + background: var(--color-bg-secondary); +} +dl[data-layout="inline"] > div > dt { + margin: 0; + font-weight: 400; + color: var(--color-text-secondary); + font-size: 12px; +} +dl[data-layout="inline"] > div > dt::after { + content: ":"; + margin-right: 2px; +} +dl[data-layout="inline"] > div > dd { + margin: 0; + font-weight: 500; + color: var(--color-text-primary); + font-size: 12px; +} + +#iv-dl-wrap{position:fixed;top:4px;right:4px;z-index:9999} +#iv-dl-btn{width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center; + opacity:0.3;border-color:var(--color-border-tertiary);background:var(--color-bg-primary)} +#iv-dl-btn:hover{opacity:0.9;background:var(--color-bg-secondary)} +#iv-dl-btn svg{width:14px;height:14px;stroke:var(--color-text-secondary);fill:none; + stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round} +/* --- Print --- + * overflow:hidden on html/body clips content in print (needed on screen + * for iframe sizing). Chart.js canvas scaling is handled by JS beforeprint + * handler in BODY_SCRIPTS — it directly mutates inline styles that CSS + * cannot reliably override in Chrome's print engine. + */ +@media print { + @page { margin: 12mm; } + html, body { overflow: visible !important; height: auto !important; + background: #fff !important; } + body { padding: 4px !important; } + #iv-dl-wrap { display: none !important; } + * { -webkit-print-color-adjust: exact; print-color-adjust: exact; } +} +""" + +# --------------------------------------------------------------------------- +# Injected JavaScript — theme detection (head), height reporting & bridges (body) +# --------------------------------------------------------------------------- +# Theme script runs in <head> before user content so CSS vars are resolved +# when model scripts read them at parse time. +# +# !! SRCDOC SAFETY !! Do NOT write the literal tokens <!-- , --> , +# <![CDATA[ , ]]> , <script> or </script> ANYWHERE in this body — +# not even inside JS comments. The iframe srcdoc's HTML5 tokenizer +# treats them as parser state changes regardless of JS context, and +# silently breaks the IIFE (see _assert_srcdoc_safe near the bottom +# of this file for the runtime guard). +THEME_DETECTION_SCRIPT = """ +<script> +(function() { + function detectTheme(root) { + return root.classList.contains('dark') + || root.getAttribute('data-theme') === 'dark' + || getComputedStyle(root).colorScheme === 'dark'; + } + + function applyTheme(isDark) { + var theme = isDark ? 'dark' : 'light'; + if (document.documentElement.getAttribute('data-theme') === theme) return; + document.documentElement.setAttribute('data-theme', theme); + if (window.Chart && Chart.instances) { + var styles = getComputedStyle(document.documentElement); + var textColor = styles.getPropertyValue('--color-text-secondary').trim(); + var gridColor = styles.getPropertyValue('--color-border-tertiary').trim(); + Chart.defaults.color = textColor; + Chart.defaults.borderColor = gridColor; + Object.values(Chart.instances).forEach(function(chart) { + Object.values(chart.options.scales || {}).forEach(function(scale) { + if (scale.ticks) scale.ticks.color = textColor; + if (scale.grid) scale.grid.color = gridColor; + }); + var legend = (chart.options.plugins || {}).legend; + if (legend && legend.labels) legend.labels.color = textColor; + chart.update(); + }); + } + } + + try { + var parentRoot = parent.document.documentElement; + applyTheme(detectTheme(parentRoot)); + new MutationObserver(function() { + applyTheme(detectTheme(parentRoot)); + }).observe(parentRoot, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + } catch(e) { + // No same-origin access — fall back to OS preference. + var mediaQuery = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)'); + if (mediaQuery) { + applyTheme(mediaQuery.matches); + mediaQuery.addEventListener('change', function(e) { applyTheme(e.matches); }); + } + } +})(); +</script> +""" + +# !! SRCDOC SAFETY !! Do NOT write the literal tokens <!-- , --> , +# <![CDATA[ , ]]> , <script> or </script> ANYWHERE in this body — +# not even inside JS comments. See THEME_DETECTION_SCRIPT for full rationale. +BODY_SCRIPTS = """ +<script> +// --- Height reporting --- +var _rh_last = 0; // last reported height +var _rh_consecutive = 0; // consecutive small-growth reports +var _rh_raf = 0; // rAF id for debouncing ResizeObserver + +function reportHeight() { + var body = document.body; + // Measure SVG overflow before the body collapse below — getBBox + // needs normal layout. + var svgOverflow = 0; + document.querySelectorAll('svg[viewBox]').forEach(function(svg) { + try { + var bbox = svg.getBBox(); + var viewBox = svg.viewBox.baseVal; + if (viewBox && viewBox.width > 0 && viewBox.height > 0) { + var overflow = bbox.y + bbox.height - (viewBox.y + viewBox.height); + if (overflow > 0) { + var scale = svg.getBoundingClientRect().width / viewBox.width; + svgOverflow += Math.ceil(overflow * scale); + } + } + } catch(e) {} + }); + + // Force height:auto on body + direct children — vh in an auto-sized + // iframe tracks iframe height, creating a feedback loop. + var savedBodyCss = body.style.cssText; + body.style.setProperty('height', 'auto', 'important'); + body.style.setProperty('overflow', 'visible', 'important'); + body.style.setProperty('display', 'block', 'important'); + var savedChildren = []; + Array.from(body.children).forEach(function(child) { + if (child.nodeType !== 1) return; + savedChildren.push({ el: child, css: child.style.cssText }); + child.style.setProperty('height', 'auto', 'important'); + child.style.setProperty('max-height', 'none', 'important'); + child.style.setProperty('min-height', '0', 'important'); + child.style.setProperty('overflow', 'visible', 'important'); + }); + + // Collapse any descendant with viewport-unit dimensions — 100vh + // resolves to our own reported height, so leaving it intact + // creates a feedback loop where body grows each cycle. + var savedVhUsers = []; + try { + var vhUsers = body.querySelectorAll( + '[style*="vh"], [style*="vw"], [style*="vmin"], [style*="vmax"]' + ); + for (var k = 0; k < vhUsers.length; k++) { + var vhEl = vhUsers[k]; + savedVhUsers.push({ el: vhEl, css: vhEl.style.cssText }); + vhEl.style.setProperty('min-height', '0', 'important'); + vhEl.style.setProperty('max-height', 'none', 'important'); + vhEl.style.setProperty('height', 'auto', 'important'); + } + } catch(e) {} + + var pageHeight = body.scrollHeight + svgOverflow; + body.style.cssText = savedBodyCss; + savedChildren.forEach(function(entry) { entry.el.style.cssText = entry.css; }); + for (var v = 0; v < savedVhUsers.length; v++) { + savedVhUsers[v].el.style.cssText = savedVhUsers[v].css; + } + + // Loop guard: 3+ consecutive small monotonic increases → stop. + var delta = pageHeight - _rh_last; + if (_rh_last > 0 && delta > 0 && delta < 50) { + _rh_consecutive++; + if (_rh_consecutive >= 3) return; + } else { + _rh_consecutive = 0; + } + + _rh_last = pageHeight; + parent.postMessage({ type: 'iframe:height', height: pageHeight }, '*'); +} +window.addEventListener('load', reportHeight); +window.addEventListener('resize', reportHeight); +// rAF-debounced ResizeObserver avoids tight synchronous loops. +new ResizeObserver(function() { + cancelAnimationFrame(_rh_raf); + _rh_raf = requestAnimationFrame(reportHeight); +}).observe(document.body); +// <details> toggle — ResizeObserver misses this in some browsers. +document.addEventListener('toggle', function() { + _rh_consecutive = 0; + setTimeout(reportHeight, 50); +}, true); +// Dynamic content swaps (innerHTML assignments, SPA-style updates). +var _rh_mutRaf = 0; +new MutationObserver(function() { + _rh_consecutive = 0; + cancelAnimationFrame(_rh_mutRaf); + _rh_mutRaf = requestAnimationFrame(reportHeight); +}).observe(document.body, { childList: true, subtree: true }); +// Click covers custom expand/collapse via style.display / class swaps. +document.addEventListener('click', function() { + _rh_consecutive = 0; + cancelAnimationFrame(_rh_mutRaf); + _rh_mutRaf = requestAnimationFrame(reportHeight); +}, true); + +// --- Post-render fixes (theme defaults, overlap prevention) --- +window.addEventListener('load', function() { + // Chart.js theme defaults + legend overflow prevention + if (window.Chart) { + var styles = getComputedStyle(document.documentElement); + var textColor = styles.getPropertyValue('--color-text-secondary').trim(); + var gridColor = styles.getPropertyValue('--color-border-tertiary').trim(); + Chart.defaults.color = textColor; + Chart.defaults.borderColor = gridColor; + Chart.defaults.plugins.legend.labels.color = textColor; + Chart.defaults.plugins.legend.maxHeight = 120; + Chart.defaults.plugins.legend.labels.boxWidth = 12; + Chart.defaults.plugins.legend.labels.font = { size: 11 }; + Object.values(Chart.instances || {}).forEach(function(chart) { + var legend = chart.options.plugins && chart.options.plugins.legend; + if (legend) { + legend.maxHeight = legend.maxHeight || 120; + if (legend.labels) { + legend.labels.boxWidth = legend.labels.boxWidth || 12; + } + } + chart.update(); + }); + } + + // De-overlap SVG axis labels only — add data-no-stagger on a <svg> + // to opt out. + document.querySelectorAll('svg').forEach(function(svg) { + if (svg.hasAttribute('data-no-stagger')) return; + var texts = Array.from(svg.querySelectorAll('text')); + if (texts.length < 4) return; + var items = []; + texts.forEach(function(textEl) { + var rect = textEl.getBoundingClientRect(); + if (rect.width < 1) return; + items.push({ el: textEl, rect: rect, cx: rect.left + rect.width / 2, cy: rect.top + rect.height / 2 }); + }); + if (items.length < 4) return; + // Only touch texts in a narrow y-band (axis labels). Diagrams with + // texts spread across the canvas are left alone. + var minY = Infinity, maxY = -Infinity; + items.forEach(function(item) { + if (item.cy < minY) minY = item.cy; + if (item.cy > maxY) maxY = item.cy; + }); + var ySpan = maxY - minY; + if (ySpan < 1) return; + // Pick the densest y-band (likely the axis row). + var bandSize = 30; + var bestBand = [], bestCount = 0; + items.forEach(function(anchor) { + var band = items.filter(function(item) { return Math.abs(item.cy - anchor.cy) < bandSize; }); + if (band.length > bestCount) { bestCount = band.length; bestBand = band; } + }); + if (bestBand.length < 3 || bestBand.length === items.length && ySpan > 60) return; + var groups = []; + bestBand.forEach(function(item) { + for (var i = 0; i < groups.length; i++) { + if (Math.abs(groups[i].cx - item.cx) < 15) { + groups[i].items.push(item); + return; + } + } + groups.push({ cx: item.cx, items: [item] }); + }); + if (groups.length < 3) return; + groups.sort(function(a, b) { return a.cx - b.cx; }); + var needsStagger = false; + for (var i = 0; i < groups.length - 1; i++) { + var maxRight = 0, minLeft = Infinity; + groups[i].items.forEach(function(item) { if (item.rect.right > maxRight) maxRight = item.rect.right; }); + groups[i+1].items.forEach(function(item) { if (item.rect.left < minLeft) minLeft = item.rect.left; }); + if (maxRight > minLeft - 2) { needsStagger = true; break; } + } + if (needsStagger) { + for (var i = 1; i < groups.length; i += 2) { + groups[i].items.forEach(function(item) { + var y = parseFloat(item.el.getAttribute('y') || 0); + item.el.setAttribute('y', String(y + 18)); + }); + } + } + }); + + setTimeout(reportHeight, 100); +}); + +// --- sendPrompt bridge (requires iframe Sandbox Allow Same Origin) --- +function sendPrompt(text) { + try { + // Open WebUI's native prompt-submit postMessage — queues if the + // model is mid-generation. + parent.postMessage({ type: 'input:prompt:submit', text: text }, '*'); + } catch(e) { /* iframe sandbox restriction */ } +} + +// --- Open link in parent window --- +function openLink(url) { + try { parent.window.open(url, '_blank'); } + catch(e) { window.open(url, '_blank'); } +} + +// --- navigator.vibrate silencer --- +// Chrome spams `[Intervention] Blocked call to navigator.vibrate…` on +// every call without a prior user gesture. Replace with a no-op so the +// block path never runs. +try { + if (typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate = function() { return false; }; + } +} catch(e) {} + +// --- Toast bridge --- +// Floating auto-dismissing top-right banner. kind = success/info/warn/error. +function toast(msg, kind) { + kind = kind || 'success'; + var color = kind === 'error' ? 'var(--color-text-danger)' + : kind === 'info' ? 'var(--color-text-info)' + : kind === 'warn' ? 'var(--color-text-warning)' + : 'var(--color-text-success)'; + var wrap = document.getElementById('iv-toast-wrap'); + if (!wrap) { + wrap = document.createElement('div'); + wrap.id = 'iv-toast-wrap'; + wrap.style.cssText = + 'position:fixed;top:4px;right:38px;z-index:9998;' + + 'display:flex;flex-direction:column;gap:4px;pointer-events:none;' + + 'max-width:280px;'; + document.body.appendChild(wrap); + } + var banner = document.createElement('div'); + banner.style.cssText = + 'padding:6px 12px;border-radius:var(--radius-md);' + + 'background:var(--color-bg-secondary);' + + 'border:0.5px solid var(--color-border-tertiary);' + + 'color:' + color + ';font-size:12px;line-height:1.4;' + + 'font-family:var(--font-sans);font-weight:500;' + + 'opacity:0;transform:translateY(-4px);transition:all 0.2s ease;' + + 'pointer-events:auto;white-space:nowrap;' + + 'overflow:hidden;text-overflow:ellipsis;'; + banner.textContent = String(msg == null ? '' : msg); + wrap.appendChild(banner); + requestAnimationFrame(function() { + banner.style.opacity = '1'; + banner.style.transform = 'none'; + }); + setTimeout(function() { + banner.style.opacity = '0'; + banner.style.transform = 'translateY(-4px)'; + setTimeout(function() { if (banner.parentNode) banner.parentNode.removeChild(banner); }, 220); + }, 2200); +} + +// --- copyText bridge --- +// Async Clipboard API with execCommand fallback (Open WebUI's iframe +// sandbox lacks allow-clipboard-write). Toast fires unconditionally — +// execCommand can silently fail and swallowing feedback leaves the user +// confused. silent=true suppresses the toast. +function copyText(text, silent) { + var value = String(text == null ? '' : text); + var label = (typeof _ivCopiedStr !== 'undefined' && + (_ivCopiedStr[_ivLang] || _ivCopiedStr.en)) || 'Copied'; + function fire() { if (!silent) try { toast(label, 'success'); } catch(e) {} } + + function legacy() { + try { + var textarea = document.createElement('textarea'); + textarea.value = value; + textarea.setAttribute('readonly', ''); + textarea.style.cssText = + 'position:fixed;left:-9999px;top:-9999px;opacity:0;'; + document.body.appendChild(textarea); + textarea.focus(); + textarea.select(); + try { textarea.setSelectionRange(0, value.length); } catch(e) {} + try { document.execCommand('copy'); } catch(e) {} + textarea.remove(); + } catch(e) {} + fire(); + } + + try { + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(value).then(fire, legacy); + return; + } + } catch(e) {} + legacy(); +} + +// --- saveState / loadState bridges --- +// parent.localStorage proxy scoped to the assistant message id — state +// persists across reloads but never leaks between chats / messages. +// Silent no-op if localStorage / parent is unreachable. +function _ivStatePrefix() { + try { + var frame = window.frameElement; + var msgEl = frame && frame.closest && frame.closest('[id^="message-"]'); + return 'iv-state:' + ((msgEl && msgEl.id) || 'global') + ':'; + } catch(e) { return 'iv-state:global:'; } +} +function saveState(key, value) { + try { + parent.localStorage.setItem( + _ivStatePrefix() + String(key), + JSON.stringify(value === undefined ? null : value) + ); + } catch(e) {} +} +function loadState(key, fallback) { + try { + var stored = parent.localStorage.getItem(_ivStatePrefix() + String(key)); + if (stored == null) return fallback === undefined ? null : fallback; + return JSON.parse(stored); + } catch(e) { return fallback === undefined ? null : fallback; } +} + +/*__CHIME_BLOCK__*/ + +// --- Print fix for Chart.js canvases --- +// Chart.js writes explicit pixel widths as inline styles that CSS +// max-width can't override in Chrome's print engine. Mutate inline +// styles before print, restore after. +(function() { + window.addEventListener('beforeprint', function() { + document.querySelectorAll('canvas').forEach(function(canvas) { + canvas.setAttribute('data-print-style', canvas.style.cssText); + canvas.style.setProperty('width', '100%', 'important'); + canvas.style.setProperty('max-width', '100%', 'important'); + canvas.style.setProperty('height', 'auto', 'important'); + var parentEl = canvas.parentElement; + if (parentEl) { + parentEl.setAttribute('data-print-style', parentEl.style.cssText); + parentEl.style.setProperty('width', '100%', 'important'); + parentEl.style.setProperty('max-width', '100%', 'important'); + } + }); + }); + window.addEventListener('afterprint', function() { + document.querySelectorAll('[data-print-style]').forEach(function(el) { + el.style.cssText = el.getAttribute('data-print-style'); + el.removeAttribute('data-print-style'); + }); + }); +})(); + +// --- Download visualization as self-contained HTML --- +var _ivLang = 'en'; +var _ivStr = { + // Required languages + en: 'Download as HTML', + de: 'Als HTML herunterladen', + cs: 'Stáhnout jako HTML', + hu: 'Letöltés HTML-ként', + hr: 'Preuzmi kao HTML', + pl: 'Pobierz jako HTML', + fr: 'Télécharger en HTML', + nl: 'Downloaden als HTML', + // Western & Southern European + es: 'Descargar como HTML', + pt: 'Baixar como HTML', + it: 'Scarica come HTML', + ca: 'Baixa com a HTML', + gl: 'Descargar como HTML', + eu: 'Deskargatu HTML gisa', + // Northern European + da: 'Download som HTML', + sv: 'Ladda ner som HTML', + no: 'Last ned som HTML', + fi: 'Lataa HTML-tiedostona', + is: 'Hlaða niður sem HTML', + // Eastern European & Slavic + sk: 'Stiahnuť ako HTML', + sl: 'Prenesi kot HTML', + sr: 'Преузми као HTML', + bs: 'Preuzmi kao HTML', + bg: 'Изтегли като HTML', + mk: 'Преземи како HTML', + uk: 'Завантажити як HTML', + ru: 'Скачать как HTML', + be: 'Спампаваць як HTML', + // Baltic + lt: 'Atsisiųsti kaip HTML', + lv: 'Lejupielādēt kā HTML', + et: 'Laadi alla HTML-ina', + // Other European + ro: 'Descarcă ca HTML', + el: 'Λήψη ως HTML', + sq: 'Shkarko si HTML', + // Middle Eastern + tr: 'HTML olarak indir', + az: 'HTML olaraq yüklə', + ar: 'تحميل كـ HTML', + + he: 'הורד כ-HTML', + // East & South Asian + zh: '下载为HTML', + ja: 'HTMLでダウンロード', + ko: 'HTML로 다운로드', + vi: 'Tải xuống dạng HTML', + th: 'ดาวน์โหลดเป็น HTML', + id: 'Unduh sebagai HTML', + ms: 'Muat turun sebagai HTML', + hi: 'HTML के रूप में डाउनलोड करें', + bn: 'HTML হিসেবে ডাউনলোড করুন', + // African + sw: 'Pakua kama HTML' +}; + +// Loader label (shown while waiting for the first content chunk). +var _ivLoadStr = { + en: 'Rendering visualization\u2026', + de: 'Visualisierung wird erstellt\u2026', + cs: 'Vykresluje se vizualizace\u2026', + hu: 'Vizualizáció renderelése\u2026', + hr: 'Iscrtavanje vizualizacije\u2026', + pl: 'Renderowanie wizualizacji\u2026', + fr: 'Rendu de la visualisation\u2026', + nl: 'Visualisatie renderen\u2026', + es: 'Renderizando visualización\u2026', + pt: 'Renderizando visualização\u2026', + it: 'Rendering della visualizzazione\u2026', + ca: 'Renderitzant visualització\u2026', + gl: 'Renderizando visualización\u2026', + eu: 'Bistaratzea errendatzen\u2026', + da: 'Gengiver visualisering\u2026', + sv: 'Renderar visualisering\u2026', + no: 'Gjengir visualisering\u2026', + fi: 'Renderöidään visualisointia\u2026', + is: 'Teiknar sjónræna framsetningu\u2026', + sk: 'Vykresľuje sa vizualizácia\u2026', + sl: 'Upodabljanje vizualizacije\u2026', + sr: 'Исцртавање визуализације\u2026', + bs: 'Iscrtavanje vizualizacije\u2026', + bg: 'Изчертаване на визуализацията\u2026', + mk: 'Исцртување на визуализацијата\u2026', + uk: 'Відображення візуалізації\u2026', + ru: 'Отрисовка визуализации\u2026', + be: 'Адмалёўка візуалізацыі\u2026', + lt: 'Atvaizduojama vizualizacija\u2026', + lv: 'Vizualizācijas renderēšana\u2026', + et: 'Visualiseeringu renderdamine\u2026', + ro: 'Randare vizualizare\u2026', + el: 'Απόδοση οπτικοποίησης\u2026', + sq: 'Duke renderuar vizualizimin\u2026', + tr: 'Görselleştirme oluşturuluyor\u2026', + az: 'Vizuallaşdırma hazırlanır\u2026', + ar: 'جارٍ عرض التصور\u2026', + he: 'מציג הדמיה\u2026', + zh: '正在渲染可视化\u2026', + ja: 'ビジュアライゼーションを描画中\u2026', + ko: '시각화 렌더링 중\u2026', + vi: 'Đang kết xuất hình ảnh\u2026', + th: 'กำลังแสดงผลการแสดงภาพ\u2026', + id: 'Merender visualisasi\u2026', + ms: 'Memaparkan visualisasi\u2026', + hi: 'विज़ुअलाइज़ेशन रेंडर हो रहा है\u2026', + bn: 'ভিজ্যুয়ালাইজেশন রেন্ডার হচ্ছে\u2026', + sw: 'Inarendi taswira\u2026' +}; + +// "Streaming visualization unavailable" title + body, shown only when +// the iframe cannot reach parent.document (Allow Same Origin disabled). +var _ivErrTitleStr = { + en: 'Streaming visualization unavailable', + de: 'Streaming-Visualisierung nicht verfügbar', + cs: 'Streamovaná vizualizace není dostupná', + hu: 'A streamelt vizualizáció nem érhető el', + hr: 'Streaming vizualizacija nije dostupna', + pl: 'Strumieniowa wizualizacja niedostępna', + fr: 'Visualisation en streaming indisponible', + nl: 'Streaming visualisatie niet beschikbaar', + es: 'Visualización en streaming no disponible', + pt: 'Visualização em streaming indisponível', + it: 'Visualizzazione in streaming non disponibile', + ca: 'Visualització en streaming no disponible', + gl: 'Visualización en streaming non dispoñíbel', + eu: 'Streaming bistaratzea ez dago erabilgarri', + da: 'Streaming-visualisering utilgængelig', + sv: 'Strömmande visualisering otillgänglig', + no: 'Streaming-visualisering utilgjengelig', + fi: 'Suoratoistettu visualisointi ei käytettävissä', + is: 'Streymandi sjónræn framsetning ekki tiltæk', + sk: 'Streamovaná vizualizácia nie je dostupná', + sl: 'Pretočna vizualizacija ni na voljo', + sr: 'Стриминг визуализација није доступна', + bs: 'Streaming vizualizacija nije dostupna', + bg: 'Поточната визуализация е недостъпна', + mk: 'Стриминг визуализација недостапна', + uk: 'Потокова візуалізація недоступна', + ru: 'Потоковая визуализация недоступна', + be: 'Струменевая візуалізацыя недаступная', + lt: 'Srautinė vizualizacija nepasiekiama', + lv: 'Straumētā vizualizācija nav pieejama', + et: 'Voogedastuse visualiseering pole saadaval', + ro: 'Vizualizarea în streaming indisponibilă', + el: 'Η ροή οπτικοποίησης δεν είναι διαθέσιμη', + sq: 'Vizualizimi i transmetimit i padisponueshëm', + tr: 'Akış görselleştirmesi kullanılamıyor', + az: 'Streaming vizualizasiyası mövcud deyil', + ar: 'التصور المتدفق غير متاح', + he: 'הדמיה בסטרימינג אינה זמינה', + zh: '流式可视化不可用', + ja: 'ストリーミングビジュアライゼーションは利用できません', + ko: '스트리밍 시각화를 사용할 수 없습니다', + vi: 'Hình ảnh trực quan phát trực tuyến không khả dụng', + th: 'การแสดงผลแบบสตรีมไม่พร้อมใช้งาน', + id: 'Visualisasi streaming tidak tersedia', + ms: 'Visualisasi strim tidak tersedia', + hi: 'स्ट्रीमिंग विज़ुअलाइज़ेशन अनुपलब्ध', + bn: 'স্ট্রিমিং ভিজ্যুয়ালাইজেশন অনুপলব্ধ', + sw: 'Taswira ya utiririshaji haipatikani' +}; + +// Confirmation toast shown after copyText() succeeds. +var _ivCopiedStr = { + en: 'Copied', de: 'Kopiert', cs: 'Zkopírováno', hu: 'Másolva', + hr: 'Kopirano', pl: 'Skopiowano', fr: 'Copié', nl: 'Gekopieerd', + es: 'Copiado', pt: 'Copiado', it: 'Copiato', ca: 'Copiat', + gl: 'Copiado', eu: 'Kopiatuta', + da: 'Kopieret', sv: 'Kopierat', no: 'Kopiert', fi: 'Kopioitu', + is: 'Afritað', + sk: 'Skopírované', sl: 'Kopirano', sr: 'Копирано', bs: 'Kopirano', + bg: 'Копирано', mk: 'Копирано', uk: 'Скопійовано', ru: 'Скопировано', + be: 'Скапіявана', + lt: 'Nukopijuota', lv: 'Nokopēts', et: 'Kopeeritud', + ro: 'Copiat', el: 'Αντιγράφηκε', sq: 'U kopjua', + tr: 'Kopyalandı', az: 'Kopyalandı', ar: 'تم النسخ', he: 'הועתק', + zh: '已复制', ja: 'コピーしました', ko: '복사됨', + vi: 'Đã sao chép', th: 'คัดลอกแล้ว', id: 'Disalin', ms: 'Disalin', + hi: 'कॉपी किया गया', bn: 'অনুলিপি করা হয়েছে', + sw: 'Imenakiliwa' +}; + +// Shown as a top-right toast when streaming completes and the +// visualization has finished rendering. Only appears if we actually +// witnessed live streaming — refreshes of completed messages stay silent. +var _ivDoneStr = { + en: 'Visualization ready', + de: 'Visualisierung bereit', + cs: 'Vizualizace připravena', + hu: 'Vizualizáció kész', + hr: 'Vizualizacija spremna', + pl: 'Wizualizacja gotowa', + fr: 'Visualisation prête', + nl: 'Visualisatie klaar', + es: 'Visualización lista', + pt: 'Visualização pronta', + it: 'Visualizzazione pronta', + ca: 'Visualització llesta', + gl: 'Visualización lista', + eu: 'Bistaratzea prest', + da: 'Visualisering klar', + sv: 'Visualisering klar', + no: 'Visualisering klar', + fi: 'Visualisointi valmis', + is: 'Sjónræn framsetning tilbúin', + sk: 'Vizualizácia pripravená', + sl: 'Vizualizacija pripravljena', + sr: 'Визуализација спремна', + bs: 'Vizualizacija spremna', + bg: 'Визуализацията е готова', + mk: 'Визуализацијата е подготвена', + uk: 'Візуалізація готова', + ru: 'Визуализация готова', + be: 'Візуалізацыя гатовая', + lt: 'Vizualizacija paruošta', + lv: 'Vizualizācija gatava', + et: 'Visualiseering valmis', + ro: 'Vizualizare gata', + el: 'Η οπτικοποίηση είναι έτοιμη', + sq: 'Vizualizimi gati', + tr: 'Görselleştirme hazır', + az: 'Vizuallaşdırma hazırdır', + ar: 'التصور جاهز', + he: 'ההדמיה מוכנה', + zh: '可视化已完成', + ja: 'ビジュアライゼーション完成', + ko: '시각화 완료', + vi: 'Hình ảnh đã sẵn sàng', + th: 'การแสดงภาพพร้อมแล้ว', + id: 'Visualisasi siap', + ms: 'Visualisasi sedia', + hi: 'विज़ुअलाइज़ेशन तैयार', + bn: 'ভিজ্যুয়ালাইজেশন প্রস্তুত', + sw: 'Taswira tayari' +}; + +// Export failure toast (PNG/SVG download dead-ended). +var _ivExportErrStr = { + en: 'Export failed', + de: 'Export fehlgeschlagen', + cs: 'Export se nezdařil', + hu: 'Az exportálás sikertelen', + hr: 'Izvoz nije uspio', + pl: 'Eksport nie powiódł się', + fr: 'Échec de l’exportation', + nl: 'Exporteren mislukt', + es: 'Error al exportar', + pt: 'Falha na exportação', + it: 'Esportazione non riuscita', + ca: 'Ha fallat l’exportació', + gl: 'Fallou a exportación', + eu: 'Esportazioak huts egin du', + da: 'Eksport mislykkedes', + sv: 'Exporten misslyckades', + no: 'Eksporten mislyktes', + fi: 'Vienti epäonnistui', + is: 'Útflutningur mistókst', + sk: 'Export zlyhal', + sl: 'Izvoz ni uspel', + sr: 'Извоз није успео', + bs: 'Izvoz nije uspio', + bg: 'Експортирането е неуспешно', + mk: 'Извезувањето не успеа', + uk: 'Не вдалося експортувати', + ru: 'Не удалось экспортировать', + be: 'Не ўдалося экспартаваць', + lt: 'Nepavyko eksportuoti', + lv: 'Neizdevās eksportēt', + et: 'Eksportimine ebaõnnestus', + ro: 'Exportul a eșuat', + el: 'Η εξαγωγή απέτυχε', + sq: 'Eksportimi dështoi', + tr: 'Dışa aktarma başarısız oldu', + az: 'İxrac uğursuz oldu', + ar: 'فشل التصدير', + he: 'הייצוא נכשל', + zh: '导出失败', + ja: 'エクスポートに失敗しました', + ko: '내보내기 실패', + vi: 'Xuất không thành công', + th: 'การส่งออกล้มเหลว', + id: 'Ekspor gagal', + ms: 'Eksport gagal', + hi: 'निर्यात विफल', + bn: 'এক্সপোর্ট ব্যর্থ হয়েছে', + sw: 'Imeshindwa kuhamisha' +}; + +// Inline script failed to parse and raw-source recovery dead-ended. +var _ivScriptErrStr = { + en: 'Visualization script error', + de: 'Fehler im Visualisierungsskript', + cs: 'Chyba skriptu vizualizace', + hu: 'Vizualizációs szkripthiba', + hr: 'Greška skripte vizualizacije', + pl: 'Błąd skryptu wizualizacji', + fr: 'Erreur de script de visualisation', + nl: 'Fout in visualisatiescript', + es: 'Error del script de visualización', + pt: 'Erro no script de visualização', + it: 'Errore nello script di visualizzazione', + ca: 'Error de l’script de visualització', + gl: 'Erro no script de visualización', + eu: 'Bistaratze-scriptaren errorea', + da: 'Fejl i visualiseringsscript', + sv: 'Fel i visualiseringsskript', + no: 'Feil i visualiseringsskript', + fi: 'Visualisointiskriptin virhe', + is: 'Villa í skriftu sjónrænnar framsetningar', + sk: 'Chyba skriptu vizualizácie', + sl: 'Napaka skripte vizualizacije', + sr: 'Грешка скрипте визуализације', + bs: 'Greška skripte vizualizacije', + bg: 'Грешка в скрипта на визуализацията', + mk: 'Грешка во скриптата на визуализацијата', + uk: 'Помилка скрипту візуалізації', + ru: 'Ошибка скрипта визуализации', + be: 'Памылка скрыпта візуалізацыі', + lt: 'Vizualizacijos scenarijaus klaida', + lv: 'Vizualizācijas skripta kļūda', + et: 'Visualiseeringu skripti viga', + ro: 'Eroare de script al vizualizării', + el: 'Σφάλμα σεναρίου οπτικοποίησης', + sq: 'Gabim në skriptin e vizualizimit', + tr: 'Görselleştirme betiği hatası', + az: 'Vizuallaşdırma skripti xətası', + ar: 'خطأ في نص التصور البرمجي', + he: 'שגיאת סקריפט ההדמיה', + zh: '可视化脚本错误', + ja: 'ビジュアライゼーションスクリプトのエラー', + ko: '시각화 스크립트 오류', + vi: 'Lỗi tập lệnh trực quan hóa', + th: 'ข้อผิดพลาดของสคริปต์การแสดงภาพ', + id: 'Kesalahan skrip visualisasi', + ms: 'Ralat skrip visualisasi', + hi: 'विज़ुअलाइज़ेशन स्क्रिप्ट त्रुटि', + bn: 'ভিজ্যুয়ালাইজেশন স্ক্রিপ্ট ত্রুটি', + sw: 'Hitilafu ya hati ya taswira' +}; + +var _ivErrBodyStr = { + en: 'Open User Settings \u2192 Interface, scroll down, and enable "Allow iframe same origin" to use streaming mode.', + de: 'Öffne Benutzereinstellungen \u2192 Oberfläche, scrolle nach unten und aktiviere „Allow iframe same origin" für den Streaming-Modus.', + cs: 'Otevřete Uživatelská nastavení \u2192 Rozhraní, sjeďte dolů a zapněte „Allow iframe same origin" pro režim streamování.', + hu: 'Nyissa meg a Felhasználói beállítások \u2192 Felület menüt, görgessen le, és kapcsolja be az „Allow iframe same origin" opciót a streamelési módhoz.', + hr: 'Otvorite Korisničke postavke \u2192 Sučelje, pomaknite se prema dolje i uključite „Allow iframe same origin" za streaming način.', + pl: 'Otwórz Ustawienia użytkownika \u2192 Interfejs, przewiń w dół i włącz „Allow iframe same origin" dla trybu strumieniowego.', + fr: 'Ouvrez Paramètres utilisateur \u2192 Interface, faites défiler vers le bas et activez « Allow iframe same origin » pour le mode streaming.', + nl: 'Open Gebruikersinstellingen \u2192 Interface, scrol omlaag en schakel "Allow iframe same origin" in voor streamingmodus.', + es: 'Abre Configuración de usuario \u2192 Interfaz, desplázate hacia abajo y activa "Allow iframe same origin" para el modo streaming.', + pt: 'Abra Configurações do usuário \u2192 Interface, role para baixo e ative "Allow iframe same origin" para o modo streaming.', + it: 'Apri Impostazioni utente \u2192 Interfaccia, scorri in basso e attiva "Allow iframe same origin" per la modalità streaming.', + ca: 'Obre Configuració d\u2019usuari \u2192 Interfície, desplaça\u2019t avall i activa "Allow iframe same origin" per al mode streaming.', + gl: 'Abre Configuración de usuario \u2192 Interface, desprázate cara abaixo e activa "Allow iframe same origin" para o modo streaming.', + eu: 'Ireki Erabiltzaile-ezarpenak \u2192 Interfazea, egin behera eta gaitu "Allow iframe same origin" streaming modua erabiltzeko.', + da: 'Åbn Brugerindstillinger \u2192 Grænseflade, rul ned, og aktivér "Allow iframe same origin" for streamingtilstand.', + sv: 'Öppna Användarinställningar \u2192 Gränssnitt, rulla ner och aktivera "Allow iframe same origin" för strömningsläge.', + no: 'Åpne Brukerinnstillinger \u2192 Grensesnitt, rull ned og aktiver "Allow iframe same origin" for streamingmodus.', + fi: 'Avaa Käyttäjäasetukset \u2192 Käyttöliittymä, vieritä alas ja ota "Allow iframe same origin" käyttöön suoratoistotilaa varten.', + is: 'Opnaðu Notandastillingar \u2192 Viðmót, skrunaðu niður og kveiktu á "Allow iframe same origin" fyrir streymisstillingu.', + sk: 'Otvorte Používateľské nastavenia \u2192 Rozhranie, posuňte sa nadol a zapnite „Allow iframe same origin" pre režim streamovania.', + sl: 'Odprite Uporabniške nastavitve \u2192 Vmesnik, pomaknite se navzdol in omogočite "Allow iframe same origin" za pretočni način.', + sr: 'Отворите Корисничка подешавања \u2192 Интерфејс, померите надоле и омогућите „Allow iframe same origin" за стриминг режим.', + bs: 'Otvorite Korisničke postavke \u2192 Sučelje, skrolajte prema dolje i uključite "Allow iframe same origin" za streaming mod.', + bg: 'Отворете Потребителски настройки \u2192 Интерфейс, превъртете надолу и активирайте „Allow iframe same origin" за поточен режим.', + mk: 'Отворете Кориснички поставки \u2192 Интерфејс, листајте надолу и овозможете „Allow iframe same origin" за стриминг режим.', + uk: 'Відкрийте Налаштування користувача \u2192 Інтерфейс, прокрутіть униз і ввімкніть «Allow iframe same origin» для потокового режиму.', + ru: 'Откройте Настройки пользователя \u2192 Интерфейс, прокрутите вниз и включите «Allow iframe same origin» для режима потоковой передачи.', + be: 'Адкрыйце Налады карыстальніка \u2192 Інтэрфейс, прагартайце ўніз і ўключыце «Allow iframe same origin» для струменевага рэжыму.', + lt: 'Atidarykite Naudotojo nustatymai \u2192 Sąsaja, slinkite žemyn ir įjunkite „Allow iframe same origin" srautiniam režimui.', + lv: 'Atveriet Lietotāja iestatījumi \u2192 Saskarne, ritiniet lejup un iespējojiet "Allow iframe same origin" straumēšanas režīmam.', + et: 'Ava Kasutaja seaded \u2192 Liides, keri alla ja luba „Allow iframe same origin" voogedastusrežiimi jaoks.', + ro: 'Deschide Setări utilizator \u2192 Interfață, derulează în jos și activează "Allow iframe same origin" pentru modul streaming.', + el: 'Ανοίξτε Ρυθμίσεις χρήστη \u2192 Διεπαφή, κυλήστε προς τα κάτω και ενεργοποιήστε το «Allow iframe same origin» για λειτουργία ροής.', + sq: 'Hapni Cilësimet e përdoruesit \u2192 Ndërfaqja, rrëshqitni poshtë dhe aktivizoni "Allow iframe same origin" për modalitetin e transmetimit.', + tr: 'Kullanıcı Ayarları \u2192 Arayüz\u2019ü açın, aşağı kaydırın ve akış modu için "Allow iframe same origin" seçeneğini etkinleştirin.', + az: 'İstifadəçi Ayarları \u2192 İnterfeys\u2019i açın, aşağı sürüşdürün və streaming rejimi üçün "Allow iframe same origin" seçimini aktivləşdirin.', + ar: 'افتح إعدادات المستخدم \u2190 الواجهة، مرر لأسفل وفعّل "Allow iframe same origin" لاستخدام وضع التدفق.', + he: 'פתח הגדרות משתמש \u2190 ממשק, גלול מטה והפעל את "Allow iframe same origin" למצב סטרימינג.', + zh: '打开 用户设置 \u2192 界面,向下滚动并启用"Allow iframe same origin"以使用流式模式。', + ja: 'ユーザー設定 \u2192 インターフェースを開き、下にスクロールして「Allow iframe same origin」を有効にするとストリーミングモードを使用できます。', + ko: '사용자 설정 \u2192 인터페이스를 열고 아래로 스크롤하여 "Allow iframe same origin"을 활성화하면 스트리밍 모드를 사용할 수 있습니다.', + vi: 'Mở Cài đặt người dùng \u2192 Giao diện, cuộn xuống và bật "Allow iframe same origin" để sử dụng chế độ phát trực tiếp.', + th: 'เปิดการตั้งค่าผู้ใช้ \u2192 อินเทอร์เฟซ เลื่อนลงและเปิดใช้งาน "Allow iframe same origin" เพื่อใช้โหมดสตรีม', + id: 'Buka Pengaturan Pengguna \u2192 Antarmuka, gulir ke bawah dan aktifkan "Allow iframe same origin" untuk mode streaming.', + ms: 'Buka Tetapan Pengguna \u2192 Antara Muka, tatal ke bawah dan dayakan "Allow iframe same origin" untuk mod strim.', + hi: 'उपयोगकर्ता सेटिंग्स \u2192 इंटरफ़ेस खोलें, नीचे स्क्रॉल करें और स्ट्रीमिंग मोड के लिए "Allow iframe same origin" सक्षम करें।', + bn: 'ব্যবহারকারী সেটিংস \u2192 ইন্টারফেস খুলুন, নিচে স্ক্রোল করুন এবং স্ট্রিমিং মোডের জন্য "Allow iframe same origin" সক্ষম করুন।', + sw: 'Fungua Mipangilio ya Mtumiaji \u2192 Kiolesura, sogeza chini na washa "Allow iframe same origin" kwa hali ya utiririshaji.' +}; + +(function() { + function detectLang() { + // 1. Pre-detected via __event_call__ (baked into HTML by the tool) + var pre = document.documentElement.getAttribute('data-iv-lang'); + if (pre && _ivStr[pre]) return pre; + // 2. Fallback: parent localStorage (needs same-origin) + try { + var stored = parent.localStorage.getItem('locale') + || parent.localStorage.getItem('language') + || parent.localStorage.getItem('i18nextLng'); + if (stored) { var primary = stored.split('-')[0].toLowerCase(); if (_ivStr[primary]) return primary; } + } catch(e) {} + // 3. Fallback: browser language (standalone HTML / no same-origin) + try { + var browserLang = (navigator.language || navigator.userLanguage || 'en').split('-')[0].toLowerCase(); + if (_ivStr[browserLang]) return browserLang; + } catch(e) {} + return 'en'; + } + _ivLang = detectLang(); + var downloadBtn = document.getElementById('iv-dl-btn'); + if (downloadBtn) downloadBtn.title = _ivStr[_ivLang] || _ivStr.en; + // Swap the server-baked English loader label for the detected locale. + var loadLabel = document.querySelector('.iv-loading-label'); + if (loadLabel) loadLabel.textContent = _ivLoadStr[_ivLang] || _ivLoadStr.en; +})(); + +// --------------------------------------------------------------------------- +// Download as self-contained HTML +// --------------------------------------------------------------------------- +// Desktop / Android: blob + <a download> + target="_blank" safety net +// (gracefully opens in a new tab if the iframe sandbox blocks downloads). +// iOS: NO target="_blank" (would strand PWA users on a blob page with no +// back button), setTimeout(0) deferral avoids a synchronous WebKit +// "Load failed" throw, and error listeners suppress the residual toast +// for 60s. iOS detection also catches iPadOS via MacIntel+touchpoints. +// --------------------------------------------------------------------------- + +var _ivIsIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) + || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1); + +// --------------------------------------------------------------------------- +// Download format menu (HTML / SVG / PNG) +// --------------------------------------------------------------------------- + +function _ivFirstSvg() { + var svgs = document.querySelectorAll('svg'); + for (var i = 0; i < svgs.length; i++) { + var svg = svgs[i]; + if (svg.ownerSVGElement) continue; // skip nested svg + var ancestor = svg.parentNode, inWrap = false; // skip the download icon itself + while (ancestor) { if (ancestor.id === 'iv-dl-wrap') { inWrap = true; break; } ancestor = ancestor.parentNode; } + if (inWrap) continue; + return svg; + } + return null; +} + +function _ivDlMenu(ev) { + if (ev) ev.stopPropagation(); + var menu = document.getElementById('iv-dl-menu'); + if (!menu) { _ivDownload(); return; } + if (menu.style.display !== 'none') { menu.style.display = 'none'; return; } + // SVG export only makes sense when the visualization contains an SVG. + // PNG is always available (vector rasterization or html2canvas screenshot). + var hasSvg = !!_ivFirstSvg(); + var items = menu.querySelectorAll('.iv-dl-item'); + for (var i = 0; i < items.length; i++) { + var label = items[i].textContent; + if (label === 'SVG') items[i].style.display = hasSvg ? 'block' : 'none'; + } + menu.style.display = 'block'; + var closer = function() { + menu.style.display = 'none'; + document.removeEventListener('click', closer, true); + }; + setTimeout(function() { document.addEventListener('click', closer, true); }, 0); +} + +function _ivBaseName() { + var name = (document.title || 'visualization').replace(/[<>:"\\/|?*]+/g, '-').replace(/\\s+/g, ' ').trim(); + if (!name) name = 'visualization'; + if (name.length > 200) name = name.substring(0, 200).trim(); + return name; +} + +function _ivSaveBlob(blob, fileName) { + var url = URL.createObjectURL(blob); + var triggerDownload = function() { + var link = document.createElement('a'); + link.style.display = 'none'; + link.href = url; + link.download = fileName; + if (!_ivIsIOS) link.target = '_blank'; + document.body.appendChild(link); + link.click(); + setTimeout(function() { link.remove(); URL.revokeObjectURL(url); }, 60000); + }; + if (_ivIsIOS) { setTimeout(triggerDownload, 0); } else { triggerDownload(); } +} + +function _ivResolvedBg() { + // Effective page background for exports: body, then html, then the + // detected theme (data-theme) so dark-mode exports stay dark. + var bg = ''; + try { + var bodyBg = window.getComputedStyle(document.body).backgroundColor; + if (bodyBg && bodyBg !== 'rgba(0, 0, 0, 0)' && bodyBg !== 'transparent') bg = bodyBg; + if (!bg) { + var htmlBg = window.getComputedStyle(document.documentElement).backgroundColor; + if (htmlBg && htmlBg !== 'rgba(0, 0, 0, 0)' && htmlBg !== 'transparent') bg = htmlBg; + } + } catch (e) {} + if (!bg) { + try { + var varBg = window.getComputedStyle(document.documentElement).getPropertyValue('--color-bg'); + if (varBg && varBg.trim()) bg = varBg.trim(); + } catch (e) {} + } + if (!bg) { + var isDark = (document.documentElement.getAttribute('data-theme') || '') === 'dark'; + bg = isDark ? '#1A1A1A' : '#ffffff'; + } + return bg; +} + +function _ivSerializedSvg(svg) { + // Inline computed styles so CSS-class based fills/strokes/fonts + // survive outside the document stylesheet. + var clone = svg.cloneNode(true); + var props = ['fill', 'fill-opacity', 'stroke', 'stroke-width', + 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin', 'opacity', + 'font-family', 'font-size', 'font-weight', 'font-style', + 'text-anchor', 'dominant-baseline', 'letter-spacing']; + var liveNodes = svg.querySelectorAll('*'); + var cloneNodes = clone.querySelectorAll('*'); + for (var i = 0; i < liveNodes.length && i < cloneNodes.length; i++) { + var computed; + try { computed = window.getComputedStyle(liveNodes[i]); } catch (e) { continue; } + var styleStr = ''; + for (var j = 0; j < props.length; j++) { + var value = computed.getPropertyValue(props[j]); + if (value && value !== 'normal' && value !== 'auto') styleStr += props[j] + ':' + value + ';'; + } + if (styleStr) cloneNodes[i].setAttribute('style', styleStr); + } + if (!clone.getAttribute('xmlns')) clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); + // Theme-matching background rect so dark-mode exports stay readable. + try { + var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); + var viewBox = (svg.viewBox && svg.viewBox.baseVal) || null; + rect.setAttribute('x', viewBox ? viewBox.x : 0); + rect.setAttribute('y', viewBox ? viewBox.y : 0); + rect.setAttribute('width', viewBox && viewBox.width ? viewBox.width : '100%'); + rect.setAttribute('height', viewBox && viewBox.height ? viewBox.height : '100%'); + rect.setAttribute('fill', _ivResolvedBg()); + rect.setAttribute('data-iv-bg', '1'); + clone.insertBefore(rect, clone.firstChild); + } catch (e) {} + return new XMLSerializer().serializeToString(clone); +} + +function _ivSvgSize(svg) { + var width = 0, height = 0; + var viewBox = svg.viewBox && svg.viewBox.baseVal; + if (viewBox && viewBox.width > 0) { width = viewBox.width; height = viewBox.height; } + if (!width || !height) { + var rect = svg.getBoundingClientRect(); + width = width || rect.width || 1200; + height = height || rect.height || 800; + } + return { w: Math.ceil(width), h: Math.ceil(height) }; +} + +// Terminal failure reporter — the fallback chain bottoms out here so a +// dead-end never leaves the user with a silent no-op. +function _ivExportError() { + try { + if (typeof toast !== 'function') return; + var msg = (typeof _ivExportErrStr !== 'undefined' && + (_ivExportErrStr[_ivLang] || _ivExportErrStr.en)) || 'Export failed'; + toast(msg, 'error'); + } catch (e) {} +} + +function _ivDownloadSVG() { + try { + var svg = _ivFirstSvg(); + if (!svg) { _ivExportError(); return; } + var xml = _ivSerializedSvg(svg); + _ivSaveBlob(new Blob([xml], {type: 'image/svg+xml;charset=utf-8'}), _ivBaseName() + '.svg'); + } catch (e) { _ivExportError(); } +} + +// onFail defaults to the terminal error toast so _ivSvgToPng is loop-free +// when used as the last link of the PNG chain; callers that still have a +// path left (e.g. the crisp-vector shortcut) pass _ivDomToPng instead. +function _ivSvgToPng(onFail) { + var fail = onFail || _ivExportError; + var svg = _ivFirstSvg(); + if (!svg) { fail(); return; } + var size = _ivSvgSize(svg); + var xml = _ivSerializedSvg(svg); + var img = new Image(); + img.onload = function() { + try { + var canvas = document.createElement('canvas'); + canvas.width = size.w * 2; // 2x for crisp rendering + canvas.height = size.h * 2; + var ctx = canvas.getContext('2d'); + ctx.fillStyle = _ivResolvedBg(); + ctx.fillRect(0, 0, canvas.width, canvas.height); + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + if (!canvas.toBlob) { fail(); return; } + canvas.toBlob(function(blob) { + if (blob) _ivSaveBlob(blob, _ivBaseName() + '.png'); + else fail(); + }, 'image/png'); + } catch (e) { fail(); } // tainted canvas / toBlob SecurityError + }; + img.onerror = function() { fail(); }; // malformed serialized SVG + img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml); +} + +function _ivHtml2Png() { + // Screenshot the full visualization via html2canvas. + // The CDN is permitted by the iframe CSP (script-src includes jsdelivr); + // no data leaves the iframe (connect-src stays 'none'). + var run = function() { + var dlWrap = document.getElementById('iv-dl-wrap'); + if (dlWrap) dlWrap.style.visibility = 'hidden'; + window.html2canvas(document.body, {backgroundColor: _ivResolvedBg(), scale: 2, logging: false}) + .then(function(canvas) { + if (dlWrap) dlWrap.style.visibility = ''; + if (!canvas.toBlob) { _ivSvgToPng(); return; } + canvas.toBlob(function(blob) { + if (blob) _ivSaveBlob(blob, _ivBaseName() + '.png'); + else _ivSvgToPng(); + }, 'image/png'); + }) + .catch(function() { + if (dlWrap) dlWrap.style.visibility = ''; + _ivSvgToPng(); + }); + }; + if (window.html2canvas) { run(); return; } + var scriptEl = document.createElement('script'); + scriptEl.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js'; + scriptEl.onload = run; + scriptEl.onerror = function() { _ivSvgToPng(); }; + document.head.appendChild(scriptEl); +} + +function _ivDomToPng() { + // Native-engine screenshot via SVG foreignObject. Unlike html2canvas this + // resolves CSS variables and modern color functions, so dark/light themes + // export exactly as rendered. Live canvases (Chart.js) are swapped for + // images; current input states (sliders) are frozen into the clone. + try { + var pageWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth, document.body.offsetWidth); + var pageHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.body.offsetHeight); + var clone = document.documentElement.cloneNode(true); + // Freeze live computed colors/opacity/transforms into the clone: + // SVG-as-image restarts CSS animations at frame 0 (fade-ins would + // export as opacity 0) and re-evaluates media queries (dark layouts + // would export light). Inlining the live values prevents both. + var PROPS = ['color', 'background-color', 'border-top-color', + 'border-right-color', 'border-bottom-color', 'border-left-color', + 'fill', 'stroke', 'box-shadow']; + var liveNodes = document.documentElement.querySelectorAll('*'); + var cloneNodes = clone.querySelectorAll('*'); + for (var n = 0; n < liveNodes.length && n < cloneNodes.length; n++) { + try { + var computed = window.getComputedStyle(liveNodes[n]); + cloneNodes[n].style.opacity = computed.opacity; + if (computed.visibility !== 'visible') cloneNodes[n].style.visibility = computed.visibility; + if (computed.transform && computed.transform !== 'none') cloneNodes[n].style.transform = computed.transform; + for (var pi = 0; pi < PROPS.length; pi++) { + var propValue = computed.getPropertyValue(PROPS[pi]); + if (propValue) cloneNodes[n].style.setProperty(PROPS[pi], propValue); + } + } catch (e) {} + } + var noAnimStyle = document.createElement('style'); + noAnimStyle.textContent = '* { animation: none !important; transition: none !important; }'; + var headEl = clone.querySelector('head'); + if (headEl) { headEl.appendChild(noAnimStyle); } else { clone.appendChild(noAnimStyle); } + var junkNodes = clone.querySelectorAll('#iv-dl-wrap, script'); + for (var i = 0; i < junkNodes.length; i++) { + if (junkNodes[i].parentNode) junkNodes[i].parentNode.removeChild(junkNodes[i]); + } + var liveCanvases = document.querySelectorAll('canvas'); + var cloneCanvases = clone.querySelectorAll('canvas'); + for (var j = 0; j < liveCanvases.length && j < cloneCanvases.length; j++) { + try { + var imgEl = document.createElement('img'); + imgEl.src = liveCanvases[j].toDataURL('image/png'); + var rect = liveCanvases[j].getBoundingClientRect(); + var styleStr = (cloneCanvases[j].getAttribute('style') || '') + ';width:' + rect.width + 'px;height:' + rect.height + 'px;'; + imgEl.setAttribute('style', styleStr); + if (cloneCanvases[j].getAttribute('class')) imgEl.setAttribute('class', cloneCanvases[j].getAttribute('class')); + cloneCanvases[j].parentNode.replaceChild(imgEl, cloneCanvases[j]); + } catch (e) {} + } + var liveInputs = document.querySelectorAll('input'); + var cloneInputs = clone.querySelectorAll('input'); + for (var k = 0; k < liveInputs.length && k < cloneInputs.length; k++) { + try { + cloneInputs[k].setAttribute('value', liveInputs[k].value); + if (liveInputs[k].checked) cloneInputs[k].setAttribute('checked', 'checked'); + } catch (e) {} + } + var bg = _ivResolvedBg(); + clone.style.background = bg; + var xml = new XMLSerializer().serializeToString(clone); + var svgWrapper = '<svg xmlns="http://www.w3.org/2000/svg" width="' + pageWidth + '" height="' + pageHeight + '">' + + '<foreignObject width="100%" height="100%">' + xml + '</foreignObject></svg>'; + var img = new Image(); + img.onload = function() { + var canvas = document.createElement('canvas'); + canvas.width = pageWidth * 2; + canvas.height = pageHeight * 2; + var ctx = canvas.getContext('2d'); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, canvas.width, canvas.height); + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + try { + canvas.toBlob(function(blob) { + if (blob) { _ivSaveBlob(blob, _ivBaseName() + '.png'); } else { _ivHtml2Png(); } + }, 'image/png'); + } catch (e) { _ivHtml2Png(); } + }; + img.onerror = function() { _ivHtml2Png(); }; + img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgWrapper); + } catch (e) { _ivHtml2Png(); } +} + +function _ivDownloadPNG() { + // Pure/dominant SVG: crisp vector rasterization. + // HTML or mixed layouts: native foreignObject screenshot (theme-faithful); + // html2canvas remains as a fallback (e.g. Safari foreignObject taint). + var svg = _ivFirstSvg(); + if (svg) { + try { + var rect = svg.getBoundingClientRect(); + var bodyWidth = document.body.scrollWidth || 1; + var bodyHeight = document.body.scrollHeight || 1; + // Crisp vector shortcut; if it fails, fall back to the DOM screenshot + // rather than dead-ending. + if ((rect.width * rect.height) / (bodyWidth * bodyHeight) >= 0.5) { _ivSvgToPng(_ivDomToPng); return; } + } catch (e) { _ivSvgToPng(_ivDomToPng); return; } + } + _ivDomToPng(); +} + +function _ivDownload() { + // Strip download button + overflow:hidden for standalone use. + var dlWrap = document.getElementById('iv-dl-wrap'); + if (dlWrap) dlWrap.remove(); + + // Serialize from a clone so we can relocate model-imported scripts + // without mutating the live iframe. enqueueScript appended each + // imported script tags to head for sequenced execution during streaming + // — but in a fresh standalone load, head scripts run BEFORE the body + // is parsed, so any getElementById('chart-canvas') etc. returns null. + // Move tagged scripts to the end of <body> so they execute after the + // canvases / DOM nodes they reference. + var docClone = document.documentElement.cloneNode(true); + var headClone = docClone.querySelector('head'); + var bodyClone = docClone.querySelector('body'); + if (headClone && bodyClone) { + var imported = headClone.querySelectorAll('script[data-iv-imported="1"]'); + for (var i = 0; i < imported.length; i++) { + bodyClone.appendChild(imported[i]); + } + } + var html = '<!DOCTYPE html>\\n' + docClone.outerHTML; + + if (dlWrap) document.body.appendChild(dlWrap); + html = html.replace('html, body { overflow: hidden; }', ''); + + var fileName = (document.title || 'visualization').replace(/[<>:"\\/|?*]+/g, '-').replace(/\\s+/g, ' ').trim(); + if (!fileName) fileName = 'visualization'; + // Cap at 200 chars to stay under the Windows 255-char filename limit. + if (fileName.length > 200) fileName = fileName.substring(0, 200).trim(); + fileName += '.html'; + + var blob = new Blob([html], {type: 'text/html;charset=utf-8'}); + var url = URL.createObjectURL(blob); + + if (_ivIsIOS) { + // iOS — deferred click + "Load failed" error suppression. + setTimeout(function() { + var _origOnerror = window.onerror; + window.onerror = function(msg) { + if (typeof msg === 'string' && msg.indexOf('Load failed') !== -1) return true; + if (_origOnerror) return _origOnerror.apply(this, arguments); + }; + var suppressLoadError = function(ev) { + var message = ev && (ev.message || (ev.reason && ev.reason.message) || ''); + if (message.indexOf('Load failed') !== -1) { ev.preventDefault(); ev.stopImmediatePropagation(); return true; } + }; + window.addEventListener('error', suppressLoadError, true); + window.addEventListener('unhandledrejection', suppressLoadError, true); + + var link = document.createElement('a'); + link.style.display = 'none'; + link.href = url; + link.download = fileName; + // No target="_blank" on iOS — strands PWA users on a blob page. + document.body.appendChild(link); + link.click(); + + // Restore original handlers after 60s. + setTimeout(function() { + window.onerror = _origOnerror; + window.removeEventListener('error', suppressLoadError, true); + window.removeEventListener('unhandledrejection', suppressLoadError, true); + URL.revokeObjectURL(url); + link.remove(); + }, 60000); + }, 0); + } else { + // Desktop / Android — straightforward blob download. + var link = document.createElement('a'); + link.href = url; + link.download = fileName; + // Safety net: new tab if the iframe sandbox blocks downloads. + link.target = '_blank'; + link.style.display = 'none'; + document.body.appendChild(link); + link.click(); + setTimeout(function() { link.remove(); URL.revokeObjectURL(url); }, 60000); + } +} +</script> +""" + + +# --------------------------------------------------------------------------- +# Happy chime on live-stream completion +# --------------------------------------------------------------------------- +# Injected into BODY_SCRIPTS via a /*__CHIME_BLOCK__*/ placeholder so the +# ``chime`` valve can strip it out entirely when disabled — no bytes +# shipped, not just a silent no-op. finalize() calls playDoneSound() inside +# a ``typeof playDoneSound === 'function'`` guard, so omission is safe. +# --------------------------------------------------------------------------- + +# !! SRCDOC SAFETY !! Do NOT write the literal tokens <!-- , --> , +# <![CDATA[ , ]]> , <script> or </script> ANYWHERE in this body — +# not even inside JS comments. See THEME_DETECTION_SCRIPT for full rationale. +CHIME_SCRIPT = """ +// --- Happy chime --- +// C-major arpeggio (C5 → E5 → G5) on sine oscillators with exponential +// decay. ~300 ms, gentle volume. Silent no-op if AudioContext is still +// suspended (no prior user gesture). +var _ivAudioCtx = null; +function playDoneSound() { + try { + var AudioCtx = window.AudioContext || window.webkitAudioContext; + if (!AudioCtx) return; + if (!_ivAudioCtx) _ivAudioCtx = new AudioCtx(); + var ctx = _ivAudioCtx; + if (ctx.state === 'suspended') { try { ctx.resume(); } catch(e) {} } + var now = ctx.currentTime; + var notes = [523.25, 659.25, 783.99]; // C5, E5, G5 + notes.forEach(function(freq, i) { + var osc = ctx.createOscillator(); + var gain = ctx.createGain(); + osc.type = 'sine'; + osc.frequency.value = freq; + var start = now + i * 0.09; + var duration = 0.35; + gain.gain.setValueAtTime(0.0001, start); + gain.gain.exponentialRampToValueAtTime(0.16, start + 0.015); + gain.gain.exponentialRampToValueAtTime(0.0001, start + duration); + osc.connect(gain).connect(ctx.destination); + osc.start(start); + osc.stop(start + duration + 0.02); + }); + } catch(e) {} +} +""" + +# --------------------------------------------------------------------------- +# STRICT-mode script — strip query params from openLink / window.open / +# <a href>. Supplementary hygiene only; the real exfil blocker is the +# CSP connect-src directive. Paths, fragments, and location.assign are +# not intercepted. +# --------------------------------------------------------------------------- + +# !! SRCDOC SAFETY !! Do NOT write the literal tokens <!-- , --> , +# <![CDATA[ , ]]> , <script> or </script> ANYWHERE in this body — +# not even inside JS comments. See THEME_DETECTION_SCRIPT for full rationale. +STRICT_SECURITY_SCRIPT = """ +<script> +(function() { + function stripParams(rawUrl) { + try { var parsed = new URL(rawUrl, location.href); parsed.search = ''; return parsed.toString(); } + catch(e) { return rawUrl; } + } + + // Override openLink to strip query/hash parameters + var _origOpenLink = window.openLink; + window.openLink = function(url) { + _origOpenLink(stripParams(url)); + }; + + // Override window.open to strip query parameters + var _origOpen = window.open; + window.open = function(url) { + arguments[0] = stripParams(url); + return _origOpen.apply(this, arguments); + }; + + // Strip params from all existing and future <a> tags + function sanitizeLinks(root) { + (root.querySelectorAll ? root : document).querySelectorAll('a[href]').forEach(function(anchor) { + anchor.href = stripParams(anchor.href); + }); + } + sanitizeLinks(document); + new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + mutation.addedNodes.forEach(function(node) { if (node.nodeType === 1) sanitizeLinks(node); }); + }); + }).observe(document.body, { childList: true, subtree: true }); +})(); +</script> +""" + +# --------------------------------------------------------------------------- +# STREAMING mode — text-marker observer (CodeBlock-free) +# --------------------------------------------------------------------------- +# Model emits plain-text @@@VIZ-START … @@@VIZ-END markers (NOT a code +# fence — that path routed through CodeMirror's virtualizer and lost +# content on scroll / refresh). Markdown renders them as ordinary +# paragraph/html tokens, so nothing we scan goes through CodeBlock. +# +# Observer loop: +# 1. Find enclosing message via frame.closest('[id^="message-"]'). +# 2. Read msg.textContent (skipping <details type="tool_calls"> etc). +# 3. Regex-extract the idx-th @@@VIZ-START … @@@VIZ-END block. +# 4. Safe-cut partial HTML, reconcile into #iv-render. +# 5. Walk the message DOM to hide the raw markers + between-marker +# content inline (display:none !important). +# +# idx comes from the embed container id "{messageId}-embeds-{N}", so +# multiple visualizations in the same message claim in order. +# +# Requires iframe Sandbox Allow Same Origin. +# --------------------------------------------------------------------------- + +# !! SRCDOC SAFETY !! Do NOT write the literal tokens <!-- , --> , +# <![CDATA[ , ]]> , <script> or </script> ANYWHERE in this body — +# not even inside JS comments. See THEME_DETECTION_SCRIPT for full rationale. +# This is the script that broke in 2.1.0–2.1.2 when a comment cleanup +# accidentally introduced literal <!-- and <script> inside JS comments. +STREAMING_OBSERVER_SCRIPT = """ +<script> +(function() { + 'use strict'; + // Markers must match SKILL.md. Chosen so markdown never treats them + // as a code fence (would put CodeMirror in the loop). + var START_MARK = '@@@VIZ-START'; + var END_MARK = '@@@VIZ-END'; + + // Stash the original text when we blank a node in place — wrapping + // breaks Svelte's tracked refs, but blanked nodes still need to + // surface the marker substring to the state machine. + // + // The store lives on the PARENT window so every visualizer iframe in + // the page shares it: on a multi-visualization message, a sibling + // embed must still see the original text of nodes we blanked (the + // END marker included), or its marker state machine desyncs and it + // mis-hides prose. Keys are parent-document text nodes, so entries + // die with the DOM (WeakMap). Falls back to a local store when the + // parent is unreachable (no same-origin — observer bails anyway). + var _ivOriginalText = null; + try { + var _sharedMap = parent.__ivChatOriginalText; + if (!_sharedMap || typeof _sharedMap.get !== 'function' || + typeof _sharedMap.set !== 'function' || typeof _sharedMap.has !== 'function') { + parent.__ivChatOriginalText = new parent.WeakMap(); + } + _ivOriginalText = parent.__ivChatOriginalText; + } catch(e) { + _ivOriginalText = (typeof WeakMap !== 'undefined') ? new WeakMap() : null; + } + // Blanked/trimmed-node registry (shared for the same reason) so the + // restore pass in hideMarkerRange can revive nodes that stop being + // marked. Companion WeakSet dedupes pushes across re-blank cycles. + var _ivBlankedNodes = null; + try { + var _sharedList = parent.__ivChatBlankedNodes; + if (!_sharedList || typeof _sharedList.push !== 'function' || + typeof _sharedList.splice !== 'function') { + parent.__ivChatBlankedNodes = new parent.Array(); + } + _ivBlankedNodes = parent.__ivChatBlankedNodes; + } catch(e) { _ivBlankedNodes = []; } + var _ivBlankedSet = null; + try { + var _sharedSet = parent.__ivChatBlankedSet; + if (!_sharedSet || typeof _sharedSet.has !== 'function' || + typeof _sharedSet.add !== 'function') { + parent.__ivChatBlankedSet = new parent.WeakSet(); + } + _ivBlankedSet = parent.__ivChatBlankedSet; + } catch(e) { + _ivBlankedSet = (typeof WeakSet !== 'undefined') ? new WeakSet() : null; + } + // Store entries are { orig, written }: `orig` is the model's text, + // `written` is what WE last wrote (empty string for a blank, the + // prose-only remainder for a trim). Legacy plain-string entries from + // older builds are read as { orig: entry, written: '' }. + function getEffectiveText(textNode) { + if (!textNode) return ''; + var value = textNode.nodeValue || ''; + if (!_ivOriginalText) return value; + var entry = null; + try { entry = _ivOriginalText.get(textNode); } catch(e) {} + if (entry == null) return value; + var orig = (typeof entry === 'object') ? entry.orig : entry; + var written = (typeof entry === 'object') ? (entry.written || '') : ''; + // Surface the original ONLY while the node still holds what we + // wrote — if Svelte overwrote it with fresh text, that text wins. + if (value === written || value === '') return orig || ''; + return value; + } + function _ivStash(textNode, current, written) { + if (!_ivOriginalText) return; + try { + var entry = _ivOriginalText.get(textNode); + if (entry && typeof entry === 'object') { + var prevWritten = entry.written || ''; + // Svelte handed the node new content since our last write — + // that becomes the new original (streaming growth on the node). + if (current !== prevWritten && current !== '') entry.orig = current; + entry.written = written; + } else if (typeof entry === 'string') { + _ivOriginalText.set(textNode, { orig: (current !== '' ? current : entry), written: written }); + } else { + _ivOriginalText.set(textNode, { orig: current, written: written }); + } + } catch(e) {} + } + function _ivRegisterBlanked(textNode) { + if (!_ivBlankedNodes) return; + if (_ivBlankedSet) { + try { + if (_ivBlankedSet.has(textNode)) return; + _ivBlankedSet.add(textNode); + } catch(e) {} + } + _ivBlankedNodes.push(textNode); + } + function blankPreserving(textNode) { + var current = textNode.nodeValue || ''; + if (current === '') return; // already blanked, idempotent no-op + _ivStash(textNode, current, ''); + try { textNode.nodeValue = ''; } catch(e) {} + _ivRegisterBlanked(textNode); + } + // Trim a node that MIXES prose and marker content down to its + // prose-only remainder ('Here is the chart: @@@VIZ-START' keeps + // 'Here is the chart: '). Blanking such a node would destroy the + // prose; hiding its block even more so. + function trimPreserving(textNode, kept) { + var current = textNode.nodeValue || ''; + if (current === kept) return; // already trimmed, idempotent + _ivStash(textNode, current, kept); + try { textNode.nodeValue = kept; } catch(e) {} + _ivRegisterBlanked(textNode); + } + // `+?` (not `*?`): require ≥1 body char so a freshly emitted + // @@@VIZ-START with no content yet doesn't match an empty capture + // and trip finalize("") via the idle timer. + var BLOCK_RE = /@@@VIZ-START\\n?([\\s\\S]+?)(?:\\n?@@@VIZ-END|$)/g; + // Reasoning is left alone unless the block itself lives there (lax match). + var _ivHideScansReasoning = false; + + // The DOM walker only skips tool/code (and reasoning, strict) detail + // blocks once Open WebUI has tokenised them, which needs the closing + // detail tag. While one is still streaming it is plain text, so its + // body (tool args/results, and the render_visualization embeds + // payload, a full copy of this script) leaks into the searchable + // text and the matcher can lock onto a decoy marker. Strip those + // ranges from the string too, mirroring the DOM filter: always + // tool/code, reasoning only on the strict pass. + function _ivStripDetailRanges(text, skipReasoning) { + if (!text || text.indexOf('<details') === -1) return text || ''; + var stripRe = skipReasoning + ? /type\\s*=\\s*"(?:tool_calls|code_execution|code_interpreter|reasoning)"/ + : /type\\s*=\\s*"(?:tool_calls|code_execution|code_interpreter)"/; + var out = '', i = 0; + while (i < text.length) { + var open = text.indexOf('<details', i); + if (open === -1) { out += text.slice(i); break; } + var tagEnd = text.indexOf('>', open); + if (tagEnd === -1) { + // Opening tag still streaming (large embeds payload). Drop the + // remainder if it is already a stripped type, else keep it. + out += stripRe.test(text.slice(open)) ? text.slice(i, open) : text.slice(i); + break; + } + if (!stripRe.test(text.slice(open, tagEnd + 1))) { + out += text.slice(i, tagEnd + 1); // kept type (reasoning, lax pass) + i = tagEnd + 1; + continue; + } + out += text.slice(i, open); // text before the stripped block + var depth = 1, j = tagEnd + 1; + while (j < text.length && depth > 0) { + var nextOpen = text.indexOf('<details', j); + var nextClose = text.indexOf('</details>', j); + if (nextClose === -1) { j = text.length; break; } // not closed, strip to end + if (nextOpen !== -1 && nextOpen < nextClose) { depth++; j = nextOpen + 8; } + else { depth--; j = nextClose + 10; } + } + i = j; + } + return out; + } + + // A real visualisation body always has at least one HTML element + // open tag. Text-only decoys (this script's regex source, or the + // skill example whose brackets are entity-escaped) do not, so we + // refuse to finalise on them and keep scanning for the real block. + function _ivLooksRenderable(html) { + return /<[a-zA-Z]/.test(html || ''); + } + + var renderArea = document.getElementById('iv-render'); + if (!renderArea) return; + + // Require same-origin access to parent — otherwise show a helpful notice. + var hasParentAccess = false; + try { void parent.document.body; hasParentAccess = true; } catch(e) {} + if (!hasParentAccess) { + // _ivLang / _ivErrTitleStr / _ivErrBodyStr come from BODY_SCRIPTS + // which runs before this observer script. + var _lang = (typeof _ivLang !== 'undefined' && _ivLang) || 'en'; + var errTitle = (typeof _ivErrTitleStr !== 'undefined' && + (_ivErrTitleStr[_lang] || _ivErrTitleStr.en)) || + 'Streaming visualization unavailable'; + var errBody = (typeof _ivErrBodyStr !== 'undefined' && + (_ivErrBodyStr[_lang] || _ivErrBodyStr.en)) || + 'Open User Settings \u2192 Interface, scroll down, and enable ' + + '"Allow iframe same origin" to use streaming mode.'; + function _esc(str) { + return String(str).replace(/&/g, '&').replace(/</g, '<') + .replace(/>/g, '>').replace(/"/g, '"'); + } + renderArea.innerHTML = + '<div style="padding:16px 18px;border:0.5px solid var(--color-border-tertiary);' + + 'border-radius:var(--radius-md);background:var(--color-bg-secondary);' + + 'color:var(--color-text-primary);font-size:13px;line-height:1.5;">' + + '<div style="font-weight:500;margin-bottom:6px;">' + _esc(errTitle) + '</div>' + + '<div style="color:var(--color-text-secondary);">' + _esc(errBody) + '</div></div>'; + return; + } + + // Message-level '-embeds-N' mounts carry the authoritative index; + // grouped and tool-call mounts map to the N-th pair by DOM position + // among the message's embed mounts (see determineIndex). + + var myMessage = null; + var myIndex = null; // this wrapper's position among embed siblings + var lastRawText = ''; + var lastSafeRendered = ''; + var finalizeTimer = null; + var finalized = false; + var finalizedText = null; + + function findMyMessage() { + if (myMessage && parent.document.contains(myMessage)) return myMessage; + try { + var frame = window.frameElement; + if (!frame) return null; + // chat-assistant wrapper holds both streaming-time buffer and + // settled content; response-content-container only populates on + // rehydrate. Toolbar / suggestions row are siblings, not + // descendants, so we won't scoop them up. + myMessage = (frame.closest && frame.closest('.chat-assistant')) + || (frame.closest && frame.closest('#response-content-container')) + || (frame.closest && frame.closest('[id^="message-"]')) + || null; + return myMessage; + } catch(e) { return null; } + } + + function determineIndex() { + if (myIndex !== null) return myIndex; + try { + var frame = window.frameElement; + if (!frame) return null; + // Message-level mounts ('-embeds-N') carry the authoritative index. + var embedContainer = frame.closest && frame.closest('[id*="-embeds-"]'); + if (embedContainer) { + var match = embedContainer.id.match(/-embeds-(\\d+)$/); + if (match) { myIndex = parseInt(match[1], 10); return myIndex; } + } + // Grouped ('-embed-N') and tool-call ('-tool-call-embed-N') mounts + // restart their index per container, and counting raw iframes picks + // up unrelated ones (YouTube previews). Resolve by DOM position + // among the message's embed mounts instead. + var msg = findMyMessage(); + if (msg) { + var mounts = msg.querySelectorAll('[id*="-embeds-"], [id*="-embed-"]'); + for (var i = 0, count = 0; i < mounts.length; i++) { + if (!/-embeds?-\\d+$/.test(mounts[i].id)) continue; + if (mounts[i].contains(frame)) { myIndex = count; return myIndex; } + count++; + } + } + } catch(e) {} + return null; + } + + // Concatenate searchable text, skipping reasoning / tool-result + // subtrees so our own result_context example markers (and any + // @@@VIZ markers the model wrote in chain-of-thought) don't trip + // the state machine. + // skipReasoning=true (strict): rejects reasoning subtrees too — + // this is the preferred pass, since it ignores planning markers + // a model may have written in chain-of-thought. + // skipReasoning=false (lax): scans reasoning. Used as fallback for + // providers that wrap the actual visible response inside + // <details type="reasoning"> (Bedrock-hosted Haiku 4.5). + // Mirrors the reasoning rejects of getSearchableText's strict pass. + function _ivIsReasoningNode(el) { + if (el.tagName === 'DETAILS' && el.getAttribute && + el.getAttribute('type') === 'reasoning') return true; + var id = el.id || ''; + if (id.indexOf('-detail-') !== -1 && + id.indexOf('tool') === -1 && id.indexOf('code') === -1) return true; + return /-\\d+-d(-|$)/.test(id); + } + + function getSearchableText(msg, skipReasoning) { + var out = ''; + try { + var walker = parent.document.createTreeWalker( + msg, NodeFilter.SHOW_TEXT, { + acceptNode: function(node) { + var ancestor = node.parentNode; + while (ancestor && ancestor !== msg) { + if (ancestor.nodeType === 1) { + // Markers inside code are documentation, not protocol: + // a fenced example must neither become the rendered + // block nor trip the hide state machine. cm-editor is + // Open WebUI's CodeMirror-rendered fence container. + if (ancestor.tagName === 'CODE' || ancestor.tagName === 'PRE') { + return NodeFilter.FILTER_REJECT; + } + try { + if (ancestor.classList && ancestor.classList.contains('cm-editor')) { + return NodeFilter.FILTER_REJECT; + } + } catch(e) {} + if (ancestor.tagName === 'DETAILS') { + var detailsType = ancestor.getAttribute && ancestor.getAttribute('type'); + if (detailsType === 'tool_calls' || + detailsType === 'code_execution' || detailsType === 'code_interpreter') { + return NodeFilter.FILTER_REJECT; + } + if (skipReasoning && detailsType === 'reasoning') { + return NodeFilter.FILTER_REJECT; + } + } + // '-detail-' covers both detail-id families: the grouped + // '-detail-group' markdown path and the output-items path + // ('{chatId}-{messageId}-detail-N-tool-call'). + var ancestorId = ancestor.id || ''; + if (ancestorId && ancestorId.indexOf('-detail-') !== -1) { + if (ancestorId.indexOf('tool') !== -1 || ancestorId.indexOf('code') !== -1) { + return NodeFilter.FILTER_REJECT; + } + if (skipReasoning) { + return NodeFilter.FILTER_REJECT; + } + } + // The content-markdown path renders ungrouped detail blocks + // without '-detail-' ids: tool calls as '-N-tc' ToolCallDisplay + // roots (never scanned); detail bodies get an id-less + // wrapper, but their textual children derive ids carrying + // a '-N-d-' segment (reasoning drafts; skipped strict). + if (ancestorId) { + if (/-\\d+-tc$/.test(ancestorId)) return NodeFilter.FILTER_REJECT; + if (skipReasoning && /-\\d+-d(-|$)/.test(ancestorId)) return NodeFilter.FILTER_REJECT; + } + } + ancestor = ancestor.parentNode; + } + return NodeFilter.FILTER_ACCEPT; + } + } + ); + var textNode; + while ((textNode = walker.nextNode())) out += getEffectiveText(textNode); + } catch(e) { return _ivStripDetailRanges(msg.textContent || '', skipReasoning); } + return _ivStripDetailRanges(out, skipReasoning); + } + + // Returns the regex match object for the idx-th block in `text`, or null. + function _ivMatchBlock(text, idx) { + BLOCK_RE.lastIndex = 0; + var match, count = 0; + while ((match = BLOCK_RE.exec(text)) !== null) { + if (count === idx) return match; + count++; + if (match.index === BLOCK_RE.lastIndex) BLOCK_RE.lastIndex++; + } + return null; + } + + // Strict pass first (skips reasoning); fall back to lax (scans + // reasoning) only when strict yields no match. This way planning + // markers a model wrote in chain-of-thought never win over a real + // response — but providers that wrap the entire visible response + // inside <details type="reasoning"> (Bedrock-routed Haiku 4.5) still + // surface their content via the lax fallback. + function _ivResolveBlock(idx) { + var msg = findMyMessage(); + if (!msg) return null; + var strict = _ivMatchBlock(getSearchableText(msg, true), idx); + if (strict !== null) { _ivHideScansReasoning = false; return strict; } + var lax = _ivMatchBlock(getSearchableText(msg, false), idx); + if (lax !== null) _ivHideScansReasoning = true; + return lax; + } + + function readSource() { + var idx = determineIndex(); + if (idx === null) idx = 0; + var match = _ivResolveBlock(idx); + return match ? match[1] : null; + } + + // Hide markers + between-marker content. Multi-pass walker, run + // every tick, idempotent and self-correcting. + // + // Pass 1 marks candidate text nodes with an OUTSIDE/INSIDE state + // machine (full markers, in-range nodes, and speculative partial + // marker tails still streaming in). + // + // Pass 2 hides a block ancestor ONLY when every non-whitespace + // text node inside it is marked. A container that also holds prose + // must never be display:none'd — Open WebUI 0.10+ renders raw html + // tokens as bare text nodes directly under the single div that + // wraps the whole message content, and unconditionally hiding that + // div nuked the entire response, prose included (issue #60). Marked + // nodes whose block fails the check are blanked in place instead + // (preserves Svelte's node refs). Text-free elements between the + // first and last marked nodes (markdown 'space' tokens render as + // empty margin divs) are swept too so the hidden source leaves no + // gap. Inline `display:none !important` survives Svelte re-renders. + // + // Pass 3 un-hides / un-blanks anything no longer marked, so a + // speculative partial hit (prose that transiently ends in '@@@') + // self-corrects on a later tick instead of staying hidden forever. + + function hideEl(el) { + if (!el || el.nodeType !== 1) return; + if (el.getAttribute('data-iv-chat-hidden') !== '1') { + el.setAttribute('data-iv-chat-hidden', '1'); + } + try { el.style.setProperty('display', 'none', 'important'); } catch(e) {} + } + + // Nearest ancestor that's a block-ish container — we prefer hiding + // block elements over inline ones so we don't leave empty block + // boxes visible. Stops at `stopAt` (the message root) — never hides + // the message itself. + function nearestBlockAncestor(el, stopAt) { + var BLOCK = { P:1, DIV:1, SECTION:1, ARTICLE:1, BLOCKQUOTE:1, + PRE:1, H1:1, H2:1, H3:1, H4:1, H5:1, H6:1, + UL:1, OL:1, LI:1, TABLE:1 }; + var cur = el; + while (cur && cur !== stopAt) { + if (cur.nodeType === 1 && BLOCK[cur.tagName]) return cur; + cur = cur.parentNode; + } + return null; + } + + // Length of the longest non-empty prefix of START_MARK (>= '@@@') + // that `text` ends with, or 0. Lets us hide a marker still streaming + // in char-by-char (e.g. "@@@V") before the full token matches — + // '@@@…' prefixes shared with a partial END_MARK are covered too. + function partialStartSuffixLength(text) { + for (var k = Math.min(text.length, START_MARK.length); k >= 3; k--) { + if (START_MARK.substr(0, k) === text.substr(text.length - k)) return k; + } + return 0; + } + + // Length of the longest suffix of `text` that is a prefix of END_MARK + // still streaming in, or 0. START fragments never trail a block body, + // so only END prefixes matter. Unlike the hide-side helper this has + // no minimum length: the paint strip is transient and self-corrects + // next frame, so even a lone trailing '@' is safe to withhold. + function partialEndSuffixLength(text) { + for (var k = Math.min(text.length, END_MARK.length); k >= 1; k--) { + if (END_MARK.substr(0, k) === text.substr(text.length - k)) return k; + } + return 0; + } + + // Order-aware scan of ONE text node. Walks marker occurrences in + // position order starting from `insideAtEntry`; returns the exit + // state plus the text lying OUTSIDE all marker ranges (the marker + // tokens themselves count as inside). Position order matters: a + // node reading '…@@@VIZ-END @@@VIZ-START…' must exit INSIDE, or the + // next visualization's body leaks into the chat as raw source. A + // stray END with no open range swallows just the marker token and + // stays OUTSIDE. + function scanNodeText(text, insideAtEntry) { + var kept = ''; + var pos = 0; + var inside = insideAtEntry; + while (pos < text.length) { + if (inside) { + var endIdx = text.indexOf(END_MARK, pos); + if (endIdx === -1) { pos = text.length; break; } + pos = endIdx + END_MARK.length; + inside = false; + } else { + var startIdx = text.indexOf(START_MARK, pos); + var strayEnd = text.indexOf(END_MARK, pos); + if (strayEnd !== -1 && (startIdx === -1 || strayEnd < startIdx)) { + kept += text.slice(pos, strayEnd); + pos = strayEnd + END_MARK.length; + continue; + } + if (startIdx === -1) { kept += text.slice(pos); break; } + kept += text.slice(pos, startIdx); + pos = startIdx + START_MARK.length; + inside = true; + } + } + return { inside: inside, kept: kept }; + } + + // Hidden text is always blanked in place, never wrapped in a hidden + // span: wrapping a text node breaks Svelte's tracked refs and stalls + // post-VIZ chunks. + function hideMarkerRange() { + var msg = findMyMessage(); + if (!msg) return; + var myFrame = window.frameElement; + + // Never hide our own iframe's container. + var myEmbedContainer = null; + try { myEmbedContainer = myFrame && myFrame.closest('[id*="-embeds-"], [id*="-embed-"]'); } + catch(e) {} + var embedsRoot = null; + try { embedsRoot = myFrame && myFrame.closest('[id$="-embeds-container"]'); } + catch(e) {} + + // Skip reasoning / tool-result subtrees (same rationale as + // getSearchableText). + var walker; + try { + walker = parent.document.createTreeWalker( + msg, NodeFilter.SHOW_TEXT, { + acceptNode: function(node) { + var ancestor = node.parentNode; + while (ancestor && ancestor !== msg) { + if (ancestor.nodeType === 1) { + // Same code-skip as getSearchableText: markers inside + // code/fences are documentation — never hide them or + // let them drive the state machine. + if (ancestor.tagName === 'CODE' || ancestor.tagName === 'PRE') { + return NodeFilter.FILTER_REJECT; + } + try { + if (ancestor.classList && ancestor.classList.contains('cm-editor')) { + return NodeFilter.FILTER_REJECT; + } + } catch(e) {} + if (ancestor.tagName === 'DETAILS') { + var detailsType = ancestor.getAttribute && ancestor.getAttribute('type'); + if (detailsType === 'tool_calls' || + detailsType === 'code_execution' || detailsType === 'code_interpreter') { + return NodeFilter.FILTER_REJECT; + } + } + if (!_ivHideScansReasoning && _ivIsReasoningNode(ancestor)) { + return NodeFilter.FILTER_REJECT; + } + // '-detail-' + tool/code covers both detail-id families + // (grouped markdown path and output-items path). + var ancestorId = ancestor.id || ''; + if (ancestorId && ancestorId.indexOf('-detail-') !== -1 && + (ancestorId.indexOf('tool') !== -1 || + ancestorId.indexOf('code') !== -1)) { + return NodeFilter.FILTER_REJECT; + } + // Content-path tool-call roots ('-N-tc') carry no 'tool' substring. + if (ancestorId && /-\\d+-tc$/.test(ancestorId)) { + return NodeFilter.FILTER_REJECT; + } + } + ancestor = ancestor.parentNode; + } + return NodeFilter.FILTER_ACCEPT; + } + } + ); + } catch(e) { return; } + + // ---- Pass 1: mark nodes via the OUTSIDE/INSIDE state machine ---- + // `segments` tracks runs of consecutively marked nodes (broken by + // any node with visible prose) so the element sweep below stays + // scoped to actual marker ranges and never reaches across the + // prose between two visualization pairs. + var inside = false; + var textNode; + var walked = []; + var hideNodes = []; + var hideNodeSet = (typeof WeakSet !== 'undefined') ? new WeakSet() : null; + // Nodes that MIX prose and marker content in one text node — they + // get trimmed to the prose remainder instead of blanked/hidden. + var partialTrims = []; + var partialSet = (typeof WeakSet !== 'undefined') ? new WeakSet() : null; + var segments = []; + var currentSegment = null; + function isMarked(node) { + if (hideNodeSet) return hideNodeSet.has(node); + return hideNodes.indexOf(node) !== -1; + } + function isTrimmed(node) { + if (partialSet) return partialSet.has(node); + for (var q = 0; q < partialTrims.length; q++) { + if (partialTrims[q].node === node) return true; + } + return false; + } + function markNode(node) { + hideNodes.push(node); + if (hideNodeSet) hideNodeSet.add(node); + if (!currentSegment) { + currentSegment = { first: node, last: node }; + segments.push(currentSegment); + } else { + currentSegment.last = node; + } + } + function trimNodeTo(node, kept) { + partialTrims.push({ node: node, kept: kept }); + if (partialSet) partialSet.add(node); + currentSegment = null; // visible prose breaks the sweep segment + } + + while ((textNode = walker.nextNode())) { + if (embedsRoot && embedsRoot.contains(textNode)) continue; + if (myEmbedContainer && myEmbedContainer.contains(textNode)) continue; + walked.push(textNode); + } + + // Last node with visible content. Open WebUI's fade streaming + // renders every word as `{word}{' '}`, appending a whitespace-only + // spacer node after each word, so the "still arriving" marker + // fragment is never the literal last node; skip trailing + // whitespace-only nodes or the growing '@@@VIZ' fragment stays + // visible on every marker arrival (#80). + var lastContentIdx = -1; + for (var lc = walked.length - 1; lc >= 0; lc--) { + if (getEffectiveText(walked[lc]).trim() !== '') { lastContentIdx = lc; break; } + } + // Fade-in token spans exist only while the message still streams; + // a finalize latched early (wrong or not) must not disable the + // speculative tail hide while new markers keep arriving. + var stillStreaming = false; + try { stillStreaming = !!msg.querySelector('.fade-in-token'); } catch(e) {} + + for (var w = 0; w < walked.length; w++) { + var node = walked[w]; + // getEffectiveText surfaces the original (pre-blank/pre-trim) + // text so already-processed nodes still match. + var text = getEffectiveText(node); + var scan = scanNodeText(text, inside); + inside = scan.inside; + + if (scan.kept !== text) { + // Node overlaps a marker range. Fully consumed -> hide it; + // mixed with prose -> trim to the prose-only remainder. + if (scan.kept.trim() === '') markNode(node); + else trimNodeTo(node, scan.kept); + continue; + } + + // Speculative partial marker tail: only the last streamed + // content node can be a marker still arriving char-by-char. + // Once neither the stream nor this embed is live, the gate + // closes: settled prose that legitimately ends in '@@@' must + // not be re-hidden on every tick, unrecoverably. + if ((!finalized || stillStreaming) && !inside && w === lastContentIdx) { + // Right-trim first: fade spans can merge the injected spacer + // into the same text node ('@@@VIZ-STAR '), which would defeat + // the suffix check. + var tailText = text.replace(/\\s+$/, ''); + var partialLen = partialStartSuffixLength(tailText); + if (partialLen > 0) { + var keptHead = tailText.slice(0, tailText.length - partialLen); + if (keptHead.trim() === '') markNode(node); + else trimNodeTo(node, keptHead); + continue; + } + } + + if (text.trim() !== '') currentSegment = null; + } + + // ---- Pass 2: pick hideable elements ---- + var toHideEls = []; + var toHideSet = (typeof WeakSet !== 'undefined') ? new WeakSet() : null; + function noteHidden(el) { + toHideEls.push(el); + if (toHideSet) toHideSet.add(el); + } + function isNotedHidden(el) { + if (toHideSet) return toHideSet.has(el); + return toHideEls.indexOf(el) !== -1; + } + var failedEls = []; + var failedSet = (typeof WeakSet !== 'undefined') ? new WeakSet() : null; + function noteFailed(el) { + failedEls.push(el); + if (failedSet) failedSet.add(el); + } + function isNotedFailed(el) { + if (failedSet) return failedSet.has(el); + return failedEls.indexOf(el) !== -1; + } + + // Structural safety: never collapse the message root, anything + // that owns an iframe (ours or a sibling embed's), or the embeds + // containers themselves. + function safeToHide(el) { + if (!el || el === msg) return false; + try { if (myFrame && el.contains(myFrame)) return false; } catch(e) {} + try { + if (el.tagName === 'IFRAME' || el.querySelector('iframe') !== null) return false; + } catch(e) { return false; } + if (el.id && String(el.id).indexOf('-embeds') !== -1) return false; + try { + if (embedsRoot && (el.contains(embedsRoot) || embedsRoot.contains(el))) return false; + } catch(e) {} + return true; + } + + // Content safety: every non-whitespace text node under `el` must + // be marked — a block holding ANY prose is never hidden wholesale. + function fullyMarked(el) { + try { + var check = parent.document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null); + var node; + while ((node = check.nextNode())) { + var value = getEffectiveText(node); + if (value === '' || value.trim() === '') continue; + if (!isMarked(node)) return false; + } + return true; + } catch(e) { return false; } + } + + var toBlankText = []; + for (var i = 0; i < hideNodes.length; i++) { + var block = nearestBlockAncestor(hideNodes[i].parentNode, msg); + if (block && isNotedHidden(block)) continue; + if (block && !isNotedFailed(block) && safeToHide(block) && fullyMarked(block)) { + noteHidden(block); + } else { + if (block && !isNotedFailed(block)) noteFailed(block); + // Block also holds prose (or an iframe) — can't hide it. + // Blank in place: nodeValue = '' preserves Svelte's refs. + toBlankText.push(hideNodes[i]); + } + } + + // Sweep text-free elements strictly inside each marked segment — + // markdown 'space' tokens render as empty margin divs that would + // otherwise leave a gap where the source was. Segment-scoped so an + // <hr>/<img> in the prose between two visualization pairs is never + // touched. (compareDocumentPosition bitmasks: 4 = FOLLOWING, + // 2 = PRECEDING.) + // Text-free is NOT content-free: images, rules, form controls and + // friends carry meaning without text nodes. Never sweep them (or + // anything containing them) — segments can legitimately span such + // an element when two pairs are separated only by, say, an image. + var CONTENT_EL = { IMG:1, SVG:1, HR:1, CANVAS:1, VIDEO:1, AUDIO:1, + PICTURE:1, OBJECT:1, EMBED:1, INPUT:1, BUTTON:1, + SELECT:1, TEXTAREA:1, IFRAME:1, MATH:1 }; + var CONTENT_EL_SELECTOR = 'img,svg,hr,canvas,video,audio,picture,' + + 'object,embed,input,button,select,textarea,iframe,math'; + if (segments.length > 0) { + var allEls; + try { allEls = msg.getElementsByTagName('*'); } catch(e) { allEls = []; } + for (var s = 0; s < allEls.length; s++) { + var candidate = allEls[s]; + if (isNotedHidden(candidate)) continue; + if ((candidate.textContent || '').trim() !== '') continue; + if (CONTENT_EL[String(candidate.tagName).toUpperCase()]) continue; + try { if (candidate.querySelector(CONTENT_EL_SELECTOR) !== null) continue; } + catch(e) { continue; } + if (!safeToHide(candidate)) continue; + for (var g = 0; g < segments.length; g++) { + var seg = segments[g]; + var within = false; + try { + within = !candidate.contains(seg.first) && + !candidate.contains(seg.last) && + (seg.first.compareDocumentPosition(candidate) & 4) !== 0 && + (seg.last.compareDocumentPosition(candidate) & 2) !== 0; + } catch(e) {} + if (within) { noteHidden(candidate); break; } + } + } + } + + // ---- Pass 3: apply, then self-correct stale hides / blanks ---- + // Un-hide first: elements we hid on an earlier tick that are no + // longer justified (partial-marker false positive, message edit, + // Svelte re-render shuffling content). + var previouslyHidden = []; + try { previouslyHidden = msg.querySelectorAll('[data-iv-chat-hidden="1"]'); } + catch(e) {} + for (var p = 0; p < previouslyHidden.length; p++) { + var hiddenEl = previouslyHidden[p]; + if (isNotedHidden(hiddenEl)) continue; + try { + hiddenEl.style.removeProperty('display'); + hiddenEl.removeAttribute('data-iv-chat-hidden'); + } catch(e) {} + } + + for (var h = 0; h < toHideEls.length; h++) hideEl(toHideEls[h]); + for (var k = 0; k < toBlankText.length; k++) blankPreserving(toBlankText[k]); + for (var t = 0; t < partialTrims.length; t++) { + trimPreserving(partialTrims[t].node, partialTrims[t].kept); + } + + // Restore nodes that are no longer marked or trimmed (speculative + // partials that turned out to be prose, message edits). Registry + // is shared across sibling iframes — only judge nodes inside OUR + // message; drop detached entries outright. + if (_ivBlankedNodes) { + for (var r = _ivBlankedNodes.length - 1; r >= 0; r--) { + var blanked = _ivBlankedNodes[r]; + var connected = false; + try { + if (!blanked) connected = false; + else if (typeof blanked.isConnected === 'boolean') { + connected = blanked.isConnected; + } else { + var ownerDoc = blanked.ownerDocument; + connected = !!(ownerDoc && ownerDoc.documentElement && + ownerDoc.documentElement.contains(blanked)); + } + } catch(e) {} + if (!connected) { + try { if (_ivBlankedSet) _ivBlankedSet.delete(blanked); } catch(e) {} + _ivBlankedNodes.splice(r, 1); + continue; + } + var inMyMsg = false; + try { inMyMsg = msg.contains(blanked); } catch(e) {} + if (!inMyMsg) continue; + if (isMarked(blanked) || isTrimmed(blanked)) continue; + // No longer ours to suppress: put the original back if the + // node still holds our write; if Svelte already overwrote it + // with fresh text, the fresh text wins — just drop the stash. + try { + var entry = _ivOriginalText ? _ivOriginalText.get(blanked) : null; + if (entry != null) { + var orig = (typeof entry === 'object') ? entry.orig : entry; + var written = (typeof entry === 'object') ? (entry.written || '') : ''; + var currentValue = blanked.nodeValue || ''; + if (typeof orig === 'string' && + (currentValue === written || currentValue === '')) { + blanked.nodeValue = orig; + } + } + } catch(e) {} + try { if (_ivOriginalText) _ivOriginalText.delete(blanked); } catch(e) {} + try { if (_ivBlankedSet) _ivBlankedSet.delete(blanked); } catch(e) {} + _ivBlankedNodes.splice(r, 1); + } + } + } + + // Returns the last index where the parser is in TEXT state (not + // mid-tag / mid-attr / mid-script / mid-CDATA). Browser auto-closes + // open tags on innerHTML assignment — depth doesn't matter. + var VOID_TAGS = {area:1,base:1,br:1,col:1,embed:1,hr:1,img:1,input:1, + link:1,meta:1,param:1,source:1,track:1,wbr:1}; + var RAW_TAGS = {script:1, style:1}; + + function findSafeCut(text) { + var i = 0, len = text.length; + var state = 'TEXT'; + var quote = 0; + var safeCut = 0; + var tagNameBuf = ''; + var tagNameEnd = false; + var inClosingTag = false; + var selfClosing = false; + var rawTag = ''; // active raw-text tag close-tag name + + while (i < len) { + var ch = text.charCodeAt(i); + + if (state === 'RAW') { + // Inside a raw-text element. Contents are NOT a safe cut — we + // have to wait for the full close tag before flushing, otherwise + // innerHTML would include partial JS/CSS. + var marker = '</' + rawTag; + if (text.substr(i, marker.length).toLowerCase() === marker) { + var end = text.indexOf('>', i + marker.length); + if (end === -1) break; + rawTag = ''; + state = 'TEXT'; + i = end + 1; + safeCut = i; + continue; + } + i++; continue; + } + + if (state === 'TEXT') { + if (ch === 60 /* < */) { + // The HTML-comment / CDATA opener tokens are built via + // string concatenation. Embedding the raw forms in source + // (even inside a JS comment) puts the enclosing srcdoc + // parser into script-data-escape mode and breaks the IIFE. + var CMT_OPEN = '<' + '!--'; + var CMT_CLOSE = '--' + '>'; + var CDATA_OPEN = '<' + '![CDATA['; + if (text.substr(i, 4) === CMT_OPEN) { + var ce = text.indexOf(CMT_CLOSE, i + 4); + if (ce === -1) break; + i = ce + 3; + safeCut = i; + continue; + } + if (text.substr(i, 9) === CDATA_OPEN) { + // CDATA close — literal would put srcdoc parser into + // script-data-escape mode; concatenate at runtime. + var ke = text.indexOf(']]' + '>', i + 9); + if (ke === -1) break; + i = ke + 3; + safeCut = i; + continue; + } + state = 'TAG'; + tagNameBuf = ''; tagNameEnd = false; + inClosingTag = false; selfClosing = false; + i++; continue; + } + i++; + safeCut = i; + continue; + } + + if (state === 'TAG') { + if (ch === 47 /* / */) { + if (tagNameBuf === '' && !tagNameEnd) { inClosingTag = true; i++; continue; } + selfClosing = true; i++; continue; + } + if (ch === 62 /* > */) { + var tagName = tagNameBuf.toLowerCase(); + if (!inClosingTag && !selfClosing && RAW_TAGS[tagName]) { + state = 'RAW'; rawTag = tagName; i++; continue; + } + state = 'TEXT'; i++; + safeCut = i; + continue; + } + if (ch === 32 || ch === 9 || ch === 10 || ch === 13) { + tagNameEnd = true; i++; state = 'ATTR_NAME'; continue; + } + if (!tagNameEnd) tagNameBuf += text.charAt(i); + i++; continue; + } + + if (state === 'ATTR_NAME') { + if (ch === 62) { + var tagName = tagNameBuf.toLowerCase(); + if (!inClosingTag && !selfClosing && RAW_TAGS[tagName]) { + state = 'RAW'; rawTag = tagName; i++; continue; + } + state = 'TEXT'; i++; + safeCut = i; + continue; + } + if (ch === 47) { selfClosing = true; i++; continue; } + if (ch === 61 /* = */) { state = 'ATTR_VAL_START'; i++; continue; } + i++; continue; + } + + if (state === 'ATTR_VAL_START') { + if (ch === 32 || ch === 9 || ch === 10 || ch === 13) { i++; continue; } + if (ch === 34) { quote = 34; state = 'ATTR_VAL_Q'; i++; continue; } + if (ch === 39) { quote = 39; state = 'ATTR_VAL_Q'; i++; continue; } + if (ch === 62) { state = 'ATTR_NAME'; continue; } + state = 'ATTR_VAL_U'; i++; continue; + } + + if (state === 'ATTR_VAL_Q') { + if (ch === quote) { state = 'ATTR_NAME'; i++; continue; } + i++; continue; + } + + if (state === 'ATTR_VAL_U') { + if (ch === 32 || ch === 9 || ch === 10 || ch === 13) { state = 'ATTR_NAME'; i++; continue; } + if (ch === 62) { state = 'ATTR_NAME'; continue; } + i++; continue; + } + } + return safeCut; + } + + // Incremental DOM reconciler — append-only, so existing elements + // stay put (no reflow, no animation re-trigger). Attributes are + // immutable between cuts (parser can't cut mid-tag). + + // Serializes script execution across the visualization — external + // scripts load async while inline scripts run sync on insertion, + // so we chain the insertions to enforce source order. + var _ivScriptChain = Promise.resolve(); + var _ivEnqueuedScripts = Object.create(null); + + // FNV-1a content hash, used to dedupe script bodies across + // reconciler branches that may re-encounter the same node. + function _ivHashScript(str) { + var hash = 2166136261; + for (var i = 0; i < str.length; i++) { + hash = (hash ^ str.charCodeAt(i)) >>> 0; + hash = Math.imul(hash, 16777619) >>> 0; + } + return hash.toString(36); + } + + function enqueueScript(incoming) { + var src = incoming.getAttribute && incoming.getAttribute('src'); + var code = incoming.textContent || ''; + + // Dedupe by src or content hash — reconciler may hit the same + // script twice across streaming/finalize branches. Re-execution + // would redeclare consts and double-wire listeners. + var key = src ? ('src:' + src) : ('code:' + code.length + ':' + _ivHashScript(code)); + if (_ivEnqueuedScripts[key]) return; + _ivEnqueuedScripts[key] = true; + + var attrs = []; + for (var a = 0; a < incoming.attributes.length; a++) { + attrs.push([incoming.attributes[a].name, incoming.attributes[a].value]); + } + // Each link in the chain is wrapped + .catch'd so a single bad + // script (model wrote invalid JS, attribute name has weird chars, + // appendChild's synchronous parse throws, etc.) can't kill the + // chain and stall every script that follows. + if (src) { + _ivScriptChain = _ivScriptChain.then(function() { + return new Promise(function(resolve) { + try { + var scriptEl = document.createElement('script'); + attrs.forEach(function(pair) { + try { scriptEl.setAttribute(pair[0], pair[1]); } catch(_){} + }); + // Tag for HTML export: _ivDownload moves these to end of body + // so they execute after the model's canvases / DOM nodes exist. + scriptEl.setAttribute('data-iv-imported', '1'); + scriptEl.onload = scriptEl.onerror = function() { resolve(); }; + document.head.appendChild(scriptEl); + } catch(e) { resolve(); } + }); + }).catch(function() {}); + } else { + _ivScriptChain = _ivScriptChain.then(function() { + try { + var scriptEl = document.createElement('script'); + attrs.forEach(function(pair) { + try { scriptEl.setAttribute(pair[0], pair[1]); } catch(_){} + }); + scriptEl.setAttribute('data-iv-imported', '1'); + scriptEl.textContent = code; + document.head.appendChild(scriptEl); + } catch(e) {} + }).catch(function() {}); + } + } + + // importNode preserves SVG namespaces. Scripts go through + // enqueueScript for source-order execution. + function importAndAppend(parent, incoming) { + var nodeType = incoming.nodeType; + if (nodeType === 3) { + parent.appendChild(document.createTextNode(incoming.textContent)); + return; + } + if (nodeType === 8) { + parent.appendChild(document.createComment(incoming.textContent)); + return; + } + if (nodeType !== 1) return; + var tagName = incoming.nodeName; + var el; + if (tagName === 'SCRIPT' || tagName === 'script') { + enqueueScript(incoming); + return; + } + // Shallow import preserves HTML/SVG namespace. + el = document.importNode(incoming, false); + parent.appendChild(el); + for (var i = 0; i < incoming.childNodes.length; i++) { + importAndAppend(el, incoming.childNodes[i]); + } + } + + function reconcile(existing, incoming) { + var existingChildren = existing.childNodes; + var incomingChildren = incoming.childNodes; + // Source declares this element as a leaf (no children); any children + // in the live DOM came from user scripts that target this element by + // id (d3.select(...).append('svg'), new vis.Network(container, ...), + // ECharts/Plotly/Vega painting into their target div, etc.). Trimming + // them would erase the chart, so leave the leaf alone. + if (incomingChildren.length === 0) return; + var i; + for (i = 0; i < incomingChildren.length; i++) { + var incomingChild = incomingChildren[i]; + var existingChild = existingChildren[i]; + if (!existingChild) { + importAndAppend(existing, incomingChild); + continue; + } + // Position mismatch — rare with append-only, but guard. + if (existingChild.nodeType !== incomingChild.nodeType || + (existingChild.nodeType === 1 && existingChild.nodeName !== incomingChild.nodeName)) { + existing.removeChild(existingChild); + var next = existingChildren[i] || null; + var holder = document.createDocumentFragment(); + importAndAppend(holder, incomingChild); + if (next) existing.insertBefore(holder, next); + else existing.appendChild(holder); + continue; + } + if (existingChild.nodeType === 3) { + if (existingChild.nodeValue !== incomingChild.nodeValue) existingChild.nodeValue = incomingChild.nodeValue; + continue; + } + if (existingChild.nodeType === 1) reconcile(existingChild, incomingChild); + } + // No outer trim — streaming source is append-only, so existing + // children beyond incomingChildren.length are script-added (D3 SVG, vis-network + // canvas/SVG, ECharts canvas, etc.). Removing them erases the chart + // mid-render even when the script targeted a non-leaf container. + } + + // withScripts=true materializes scripts (finalize path); false strips + // them during streaming. Regex source is concatenated so the raw + // open / close tokens never appear literally in this file. + var _ivOpen = '<' + 'script'; + var _ivClose = '<' + '\\/script>'; + var _ivStripPaired = new RegExp(_ivOpen + '[\\\\s\\\\S]*?' + _ivClose, 'gi'); + var _ivStripOpen = new RegExp(_ivOpen + '[\\\\s\\\\S]*$', 'i'); + // Strip doc-level tags that models sometimes wrap VIZ content in. + var _ivStripDocTags = new RegExp('<' + '!DOCTYPE[^>]*>|<' + '/?(?:html|head|body)[^>]*>', 'gi'); + + // Open WebUI's chat sanitizer strips <style> but keeps the inner CSS + // as text. Re-inflate consecutive bare CSS rules so the iframe can + // apply them. Strict pattern + ≥2 adjacent rules guards against + // accidental matches on JSON / object literals. + var _ivCssRule = /[A-Za-z@.#:*\\[\\]>+\\-,\\s_~()='"&]+\\{\\s*(?:[A-Za-z-]+\\s*:\\s*[^;{}<>]+;\\s*)+\\}/g; + function reinflateBareCSS(text) { + if (/<style[\\s>]/i.test(text)) return text; + _ivCssRule.lastIndex = 0; + var matches = [], match; + while ((match = _ivCssRule.exec(text)) !== null) { + matches.push({ start: match.index, end: _ivCssRule.lastIndex }); + if (match.index === _ivCssRule.lastIndex) _ivCssRule.lastIndex++; + } + if (matches.length < 2) return text; + // Group consecutive rules (separated by < 50 chars of whitespace) + var groups = [], current = null; + for (var i = 0; i < matches.length; i++) { + if (current && matches[i].start - current.end < 50) current.end = matches[i].end; + else { current = { start: matches[i].start, end: matches[i].end, count: 1 }; groups.push(current); } + if (current.start !== matches[i].start) current.count = (current.count || 1) + 1; + } + // Process from last to first to preserve indices + for (var g = groups.length - 1; g >= 0; g--) { + var group = groups[g]; + var slice = text.substring(group.start, group.end); + // Require multiple rules in the group + var braces = slice.match(/\\{/g); + if (!braces || braces.length < 2) continue; + text = text.substring(0, group.start) + '<style>' + slice + '</style>' + text.substring(group.end); + } + return text; + } + + function renderSafeInto(text, withScripts) { + var html = withScripts + ? text + : text.replace(_ivStripPaired, '').replace(_ivStripOpen, ''); + html = html.replace(_ivStripDocTags, ''); + html = reinflateBareCSS(html); + var temp = document.createElement('div'); + try { + temp.innerHTML = html; + } catch(e) { + // Fallback to full replace on any parse oddity. + renderArea.innerHTML = html; + return; + } + reconcile(renderArea, temp); + } + + // ---- Fade-in animation for newly-complete elements ------------------ + function markAndAnimate(root) { + var toAnimate = []; + function visit(node, top) { + if (!node || node.nodeType !== 1) return; + var isSvgChild = node.ownerSVGElement != null; + if ((top || isSvgChild || node.tagName === 'svg') && !node.hasAttribute('data-iv-faded')) { + node.setAttribute('data-iv-faded', '1'); + toAnimate.push(node); + } + if (node.tagName === 'svg') { + for (var child = node.firstElementChild; child; child = child.nextElementSibling) visit(child, false); + } + } + for (var child = root.firstElementChild; child; child = child.nextElementSibling) visit(child, true); + if (toAnimate.length === 0) return; + requestAnimationFrame(function() { + toAnimate.forEach(function(el) { el.classList.add('iv-fade-in'); }); + }); + } + + // ---- Height handling during streaming ------------------------------- + var heightRaf = 0; + function scheduleHeight() { + cancelAnimationFrame(heightRaf); + heightRaf = requestAnimationFrame(function() { + try { if (typeof reportHeight === 'function') reportHeight(); } catch(e) {} + }); + } + + // ---- Finalize: run scripts, final height nudge ---------------------- + + // Defensive post-finalize stripper. Catches marker leftovers and + // orphan close-tags from unbalanced model HTML that ended up in + // DOM regions the streaming-time hide skipped. Anchored on marker + // substrings (no false positives on prose) and skips <code>/<pre>. + function stripFinalizeArtifacts() { + var msg = findMyMessage(); + if (!msg) return; + var nodes = []; + try { + var walker = parent.document.createTreeWalker( + msg, NodeFilter.SHOW_TEXT, null + ); + var walkerNode; + while ((walkerNode = walker.nextNode())) nodes.push(walkerNode); + } catch(e) { return; } + + for (var i = 0; i < nodes.length; i++) { + var textNode = nodes[i]; + var value = textNode.nodeValue || ''; + if (!value) continue; + if (value.indexOf(START_MARK) === -1 && value.indexOf(END_MARK) === -1) continue; + // Skip code/pre AND anything hideMarkerRange already hid: the + // hide pass needs the marker text intact inside hidden blocks — + // stripping it there would make a later pass consider the block + // unjustified and un-hide the raw source. + var ancestor = textNode.parentNode, isProtected = false; + while (ancestor && ancestor !== msg) { + if (ancestor.nodeType === 1) { + if (ancestor.tagName === 'CODE' || ancestor.tagName === 'PRE') { + isProtected = true; break; + } + if (ancestor.getAttribute && + ancestor.getAttribute('data-iv-chat-hidden') === '1') { + isProtected = true; break; + } + if (!_ivHideScansReasoning && _ivIsReasoningNode(ancestor)) { + isProtected = true; break; + } + } + ancestor = ancestor.parentNode; + } + if (isProtected) continue; + var cleaned = value + .split(START_MARK).join('') + .split(END_MARK).join('') + .replace(/<\\/[a-z][a-z0-9]*\\s*>/gi, ''); + try { textNode.nodeValue = cleaned.replace(/^\\s+|\\s+$/g, '') ? cleaned : ''; } + catch(e) {} + } + } + + // ---- Raw-source recovery (issue #75) -------------------------------- + // The chat DOM is a lossy source: Open WebUI's citation machinery + // swallows bare numeric arrays like [21, 11, 4] (tokenised into a + // source chip, or regex-stripped when the model's Citations + // capability is off), leaving code the model never wrote (data:,). + // When an inline script fails to parse, finalize from the raw message + // text via the chats API instead. Retries cover live streams: content + // is only persisted once the response completes. + var _ivRecovery = 'idle'; // idle | pending | done | failed + + function _ivFetchRawContent(chatId, messageId, onDone) { + var token = null; + try { token = parent.localStorage.getItem('token'); } catch(e) {} + try { + // parent.fetch runs under the parent page's CSP, so this works + // even when the iframe's own connect-src is locked down. + parent.fetch('/api/v1/chats/' + encodeURIComponent(chatId), { + headers: token ? { 'Authorization': 'Bearer ' + token } : {} + }).then(function(res) { + return res.ok ? res.json() : null; + }).then(function(data) { + var msg = data && data.chat && data.chat.history && + data.chat.history.messages && data.chat.history.messages[messageId]; + onDone(msg && typeof msg.content === 'string' ? msg.content : null); + }, function() { onDone(null); }); + } catch(e) { onDone(null); } + } + + // This embed's block from raw message text. Fenced code is stripped + // first so a fenced example cannot shift the block ordinal. Only a + // closed block counts: an open-ended match means the save raced the + // stream. + function _ivBlockFromRaw(content) { + var text = content.replace(/```[\\s\\S]*?```/g, ''); + var idx = determineIndex(); + if (idx === null) idx = 0; + var match = _ivMatchBlock(_ivStripDetailRanges(text, true), idx); + if (match === null) match = _ivMatchBlock(_ivStripDetailRanges(text, false), idx); + if (!match || match[0].indexOf(END_MARK) === -1) return null; + return match[1]; + } + + // SyntaxError of the first inline classic script in `html` that fails + // to parse, else null. new Function is a parse check only (nothing + // runs); no CSP this tool emits blocks eval. Only a SyntaxError + // counts: anything else means we could not validate, not that the + // code is bad. + function _ivScriptParseError(html) { + var temp = document.createElement('div'); + try { temp.innerHTML = html.replace(_ivStripDocTags, ''); } catch(e) { return null; } + var scripts = temp.querySelectorAll('script'); + for (var i = 0; i < scripts.length; i++) { + var script = scripts[i]; + if (script.getAttribute('src')) continue; + var scriptType = script.getAttribute('type') || ''; + if (scriptType && scriptType.indexOf('javascript') === -1) continue; + try { new Function(script.textContent || ''); } + catch(err) { if (err && err.name === 'SyntaxError') return err; } + } + return null; + } + + function _ivChatContext() { + var chatId = null, messageId = null; + try { + var pathMatch = parent.location.pathname.match(/\\/c\\/([^\\/?#]+)/); + chatId = pathMatch ? pathMatch[1] : null; + var frame = window.frameElement; + var embedContainer = frame && frame.closest && frame.closest('[id*="-embeds-"]'); + var idMatch = embedContainer && embedContainer.id.match(/^(.+)-embeds-\\d+$/); + if (idMatch) { + messageId = idMatch[1]; + } else { + // The tool-response path mounts the iframe outside an embeds container. + var msgEl = frame && frame.closest && frame.closest('[id^="message-"]'); + if (msgEl) messageId = msgEl.id.slice('message-'.length); + } + } catch(e) {} + return { chatId: chatId, messageId: messageId }; + } + + function _ivStartRecovery(domText, scriptError) { + var ctx = _ivChatContext(); + var chatId = ctx.chatId, messageId = ctx.messageId, attempt = 0; + // The pending preview was diffed from the corrupt text, and + // reconcile never rewrites attributes on existing elements: render + // the final text from scratch (safe, no script has run yet). + function finalizeFresh(text) { + try { renderArea.innerHTML = ''; } catch(e) {} + finalize(text); + } + function fail(rawText, err) { + if (finalized) return; + _ivRecovery = 'failed'; // finalize toasts the error on live streams + try { console.error('iv[script] failed to parse', err || scriptError); } catch(e) {} + finalizeFresh(rawText || domText); + } + function attemptOnce() { + if (finalized) return; + _ivFetchRawContent(chatId, messageId, function(content) { + if (finalized) return; + var raw = content && _ivBlockFromRaw(content); + if (_ivLooksRenderable(raw)) { + var rawScriptError = _ivScriptParseError(raw); + if (!rawScriptError) { _ivRecovery = 'done'; finalizeFresh(raw); return; } + fail(raw, rawScriptError); // the model's own JS is bad; still render its authentic text + return; + } + setTimeout(attemptOnce, Math.min(1500 * ++attempt, 8000)); + }); + } + // Unsaved contexts (temporary chats, shared pages) can never + // recover; deferred so finalize is never re-entered synchronously. + if (!chatId || !messageId) { setTimeout(function() { fail(); }, 0); return; } + // Armed deadline, not a between-attempts check: a fetch that never + // settles must not strand the loader. Trailing prose can delay the + // save, hence the generous window. + setTimeout(function() { fail(); }, 90000); + attemptOnce(); + } + + function finalize(fullText) { + if (finalized) return; + if (!_ivLooksRenderable(fullText)) return; // never latch on a non-HTML decoy + if (_ivRecovery === 'pending') return; + // Recovery needs a closed block: a truncated stream (user stop, dead + // connection) has no END marker in the saved text either, so retrying + // could never succeed and would only delay this finalize. + if (_ivRecovery === 'idle' && isBlockClosed()) { + var scriptError = _ivScriptParseError(fullText); + if (scriptError) { + // Corrupt reconstruction (or bad model JS): keep the script-less + // preview up and try the raw text before executing anything. + _ivRecovery = 'pending'; + renderSafeInto(fullText, false); + markAndAnimate(renderArea); + scheduleHeight(); + _ivStartRecovery(fullText, scriptError); + return; + } + } + finalized = true; + finalizedText = fullText; + // withScripts=true so the reconciler materializes script tags. + renderSafeInto(fullText, true); + // Multi-shot self-heal — Svelte may flush chunks several seconds + // after finalize fires (slow networks, large messages, post-render + // re-hydrations), restoring text nodes we hid. Run once + // immediately, then every 1s for 30s; each run is idempotent and + // cheap. ORDER MATTERS: re-assert hiding BEFORE stripping — the + // stripper deletes marker text from visible nodes, and if it ran + // first on a freshly restored flush the hide pass would no longer + // find the markers and the raw source would stay visible. + try { hideMarkerRange(); } catch(e) {} + try { stripFinalizeArtifacts(); } catch(e) {} + var stripInterval = setInterval(function() { + try { hideMarkerRange(); } catch(e) {} + try { stripFinalizeArtifacts(); } catch(e) {} + _ivHealDirty = false; + }, 1000); + setTimeout(function() { clearInterval(stripInterval); }, 30000); + hideLoader(); + markAndAnimate(renderArea); + // Nudge the height reporter across layout settle. + scheduleHeight(); + setTimeout(scheduleHeight, 120); + setTimeout(scheduleHeight, 400); + // Done/failed announcement — only on live streams, not on rehydration. + if (wasStreaming) { + var failed = _ivRecovery === 'failed'; + try { + var table = failed ? _ivScriptErrStr : _ivDoneStr; + if (typeof toast === 'function') toast(table[_ivLang] || table.en, failed ? 'error' : 'success'); + } catch(e) {} + try { if (!failed && typeof playDoneSound === 'function') playDoneSound(); } catch(e) {} + } + } + + function isBlockClosed() { + var idx = determineIndex(); + if (idx === null) idx = 0; + var match = _ivResolveBlock(idx); + return !!match && match[0].indexOf(END_MARK) !== -1; + } + + // A finalize latched mid-stream can be wrong (a decoy block in + // chain-of-thought, extraction blinded by a transient DOM shape), + // and on the output-items rendering path reasoning carries no + // filterable anchor, so the settled DOM extraction can stay wrong + // too. The latch is therefore verified ONCE against the saved raw + // message text (where _ivBlockFromRaw strips the detail ranges) as + // soon as the save lands, and re-verified whenever the settled DOM + // extraction later changes shape. Whitespace-insensitive compares + // keep fade-spacer diffs from re-adopting cosmetically equal text. + var _ivRawVerified = false; + var _ivRefinalize = null; // null | 'checking' | last settle shape checked + function _ivShape(text) { return text.replace(/\\s+/g, ''); } + function refinalizeIfSettledDiffers() { + if (!finalized || _ivRecovery !== 'idle') return; + if (_ivRefinalize === 'checking') return; + var settled = readSource(); + var shape = settled === null ? '' : _ivShape(settled); + if (_ivRawVerified && + (settled === null || shape === _ivShape(finalizedText) || shape === _ivRefinalize)) { + return; + } + var ctx = _ivChatContext(); + if (!ctx.chatId || !ctx.messageId) { _ivRawVerified = true; _ivRefinalize = shape; return; } + _ivRefinalize = 'checking'; + var attempt = 0; + var dead = false; + // Armed deadline, not a between-attempts check: a fetch that never + // settles must not strand the 'checking' state. Expiry means the + // save was not fetchable yet, not that the latch was verified, so + // both flags stay unset and the next heal retries from scratch. + var deadlineTimer = setTimeout(function() { + dead = true; + if (_ivRefinalize === 'checking') _ivRefinalize = null; + }, 90000); + function finish(verified) { + clearTimeout(deadlineTimer); + _ivRefinalize = shape; + if (verified) _ivRawVerified = true; + } + function adopt(raw) { + // In-place adoption is only realm-safe while no script has run: + // re-evaluating a top-level const/let throws, and the code-keyed + // script dedupe would skip a byte-identical script after the + // canvas it drew was wiped. If the latched render executed + // scripts, reboot the iframe once instead: the fresh observer + // finalizes against the settled DOM in a clean realm. + // Split literal: the srcdoc guard forbids '<scr'+'ipt' in this string. + if (finalizedText.toLowerCase().indexOf('<scr' + 'ipt') !== -1) { + var frame = null; + try { frame = window.frameElement; } catch(e) {} + if (frame && frame.getAttribute('data-iv-refinalized') !== '1') { + try { + frame.setAttribute('data-iv-refinalized', '1'); + location.reload(); + return; + } catch(e) {} + } + return; // one reboot max; keep the current render + } + finalizedText = raw; + // Reconcile never rewrites attributes on existing elements: + // render the corrected text from scratch. + try { renderArea.innerHTML = ''; } catch(e) {} + renderSafeInto(raw, true); + markAndAnimate(renderArea); + scheduleHeight(); + } + function check() { + if (dead) return; + _ivFetchRawContent(ctx.chatId, ctx.messageId, function(content) { + if (dead) return; + if (!finalized || _ivRecovery !== 'idle') { finish(false); return; } + var raw = content ? _ivBlockFromRaw(content) : null; + if (raw === null) { + // The save lags the settle while trailing prose streams. + setTimeout(check, Math.min(1500 * ++attempt, 8000)); + return; + } + if (_ivShape(raw) === _ivShape(finalizedText)) { finish(true); return; } + if (!_ivLooksRenderable(raw) || _ivScriptParseError(raw)) { finish(true); return; } + finish(true); + adopt(raw); + }); + } + check(); + } + + // Tick skips its whole pipeline when the searchable text is + // unchanged. A childList mutation sets forceHide=true so Svelte + // rebuilds that preserve the text string still get re-hidden. + var lastMsgText = null; + var wasStreaming = false; + var firstSeenLen = null; + // Set by the mutation observers whenever the message subtree (or the + // chat body's child list) changes; gates the post-finalize self-heal + // so idle 400ms polls stay free. + var _ivHealDirty = false; + + function tick(forceHide) { + var msg = findMyMessage(); + if (!msg) return; + + if (finalized) { + // Post-finalize self-heal: the observers and the 400ms poll stay + // alive, and Svelte can flush restored text nodes long after + // finalize (late chunks, rehydration, branch switches). Only act + // when the message subtree actually mutated (cheap gate — no + // text walk on idle polls), and hide BEFORE stripping so the + // stripper never erases markers the hide pass still needs. + if (_ivHealDirty) { + try { hideMarkerRange(); } catch(e) {} + try { stripFinalizeArtifacts(); } catch(e) {} + try { refinalizeIfSettledDiffers(); } catch(e) {} + _ivHealDirty = false; + } + return; + } + + // Lax: tick on any text change, including reasoning-block edits + // (Bedrock-routed Haiku 4.5 streams the response inside reasoning). + var currentText = getSearchableText(msg, false); + var textChanged = currentText !== lastMsgText; + lastMsgText = currentText; + + // Live-stream detection by GROWTH — the first-seen searchable + // length never grows on refreshes of completed messages, so + // wasStreaming stays false and we don't fire the done toast/chime. + if (firstSeenLen === null) firstSeenLen = currentText.length; + else if (!wasStreaming && currentText.length > firstSeenLen) { + wasStreaming = true; + } + + if (textChanged || forceHide || stashDiverged()) hideMarkerRange(); + + // Source-dependent work only runs on actual changes. + if (!textChanged) return; + + var raw = readSource(); + if (raw === null) return; + if (raw === lastRawText) { + scheduleFinalize(raw); + return; + } + lastRawText = raw; + + var cut = findSafeCut(raw); + var safe = raw.substring(0, cut); + + // Never paint a trailing partial END marker ('@@@VIZ-' while END + // streams in): reconcile deliberately never trims surplus tail + // nodes (script-added charts live there), so painted marker text + // would survive finalize until reload (#80). + var tail = safe.replace(/\\s+$/, ''); + var partialEnd = partialEndSuffixLength(tail); + if (partialEnd > 0) { + safe = tail.slice(0, tail.length - partialEnd).replace(/\\s+$/, ''); + } + + if (safe !== lastSafeRendered && safe.length > 0) { + lastSafeRendered = safe; + renderSafeInto(safe, false); + markAndAnimate(renderArea); + scheduleHeight(); + } + + scheduleFinalize(raw); + } + + // getEffectiveText makes a Svelte restore of a blanked node invisible + // to the textChanged gate (effective text is the stashed original both + // before and after the restore), so detect restores directly: any + // registered node whose value no longer matches what we last wrote. + function stashDiverged() { + if (!_ivBlankedNodes || !_ivOriginalText) return false; + var msg = null; + try { msg = findMyMessage(); } catch(e) {} + if (!msg) return false; + for (var i = 0; i < _ivBlankedNodes.length; i++) { + var node = _ivBlankedNodes[i]; + var inMyMsg = false; + try { inMyMsg = node && msg.contains(node); } catch(e) {} + if (!inMyMsg) continue; + var entry = null; + try { entry = _ivOriginalText.get(node); } catch(e) {} + if (entry == null) continue; + var written = (typeof entry === 'object') ? (entry.written || '') : ''; + if ((node.nodeValue || '') !== written) return true; + } + return false; + } + + // Forces hideMarkerRange to re-run even when textContent is unchanged + // — Svelte can rebuild a text node without altering its string value. + function _ivHasChildListMutation(records) { + if (!records) return false; + for (var i = 0; i < records.length; i++) { + if (records[i] && records[i].type === 'childList') return true; + } + return false; + } + + // True when any mutation record touches OUR message subtree (or an + // ancestor of it — a wholesale rebuild mutates the parent's child + // list). Errs on true when the message can't be resolved. + function _ivRecordsTouchMyMessage(records) { + var msg = null; + try { msg = findMyMessage(); } catch(e) {} + if (!msg || !records) return true; + for (var i = 0; i < records.length; i++) { + var target = records[i] && records[i].target; + if (!target) continue; + try { + if (msg.contains(target) || target.contains(msg)) return true; + } catch(e) { return true; } + } + return false; + } + + function scheduleFinalize(raw) { + // Primary signal: @@@VIZ-END present → finalize instantly. + // Fallback: 30s of completely stable source (user stopped + // generation / model forgot END / network died). 30s is longer + // than any realistic inter-chunk stall (Gemini 3.1 Pro 200-token + // chunks, proxy buffering, etc) so we can't trip it mid-stream. + clearTimeout(finalizeTimer); + if (isBlockClosed() && _ivLooksRenderable(raw)) { finalize(raw); return; } + finalizeTimer = setTimeout(function() { + if (finalized) return; + var latest = readSource(); + if (latest === null) return; + if (!_ivLooksRenderable(latest)) return; + if (isBlockClosed() || latest === raw) { + finalize(latest); + } + }, 30000); + } + + // ---- Inject fade-in + loader CSS into our OWN document ------------- + (function injectFadeCss() { + var styleEl = document.createElement('style'); + styleEl.textContent = + '@keyframes iv-fade-in-kf {' + + ' from { opacity: 0; transform: translateY(2px); }' + + ' to { opacity: 1; transform: none; }' + + '}' + + '@keyframes iv-fade-in-svg-kf {' + + ' from { opacity: 0; } to { opacity: 1; }' + + '}' + + '#iv-render .iv-fade-in { animation: iv-fade-in-kf 500ms ease-out both; }' + + '#iv-render svg .iv-fade-in { animation: iv-fade-in-svg-kf 500ms ease-out both; }' + + // Three pulsing dots + label shown while waiting for content. + '@keyframes iv-pulse-kf {' + + ' 0%, 80%, 100% { opacity: 0.25; transform: scale(0.85); }' + + ' 40% { opacity: 1; transform: scale(1); }' + + '}' + + '.iv-loading {' + + ' display: flex; flex-direction: column; align-items: center;' + + ' justify-content: center; gap: 12px;' + + ' padding: 48px 20px; min-height: 120px;' + + ' color: var(--color-text-tertiary);' + + ' font-size: 12px; letter-spacing: 0.02em;' + + '}' + + '.iv-loading-dots { display: inline-flex; gap: 8px; }' + + '.iv-loading-dots span {' + + ' width: 8px; height: 8px; border-radius: 50%;' + + ' background: var(--color-text-tertiary);' + + ' animation: iv-pulse-kf 1.4s infinite ease-in-out both;' + + '}' + + '.iv-loading-dots span:nth-child(1) { animation-delay: -0.32s; }' + + '.iv-loading-dots span:nth-child(2) { animation-delay: -0.16s; }' + + '.iv-loading-label { opacity: 0.6; }'; + document.head.appendChild(styleEl); + })(); + + // #iv-loader is rendered server-side as a sibling below #iv-render; + // we only need to remove it on finalize. + function hideLoader() { + try { + var loader = document.getElementById('iv-loader'); + if (loader && loader.parentNode) loader.parentNode.removeChild(loader); + } catch(e) {} + } + + // Defense in depth: outer observer on parent.document.body sees new + // messages as chat scrolls / navigates; inner observer on our own + // message catches every streaming text mutation; 400ms poll is a + // safety net in case the observers miss anything. + var innerObserver = null; + function attachInnerObserver() { + if (innerObserver) return; + var msg = findMyMessage(); + if (!msg) return; + try { + innerObserver = new MutationObserver(function(records) { + _ivHealDirty = true; + try { tick(_ivHasChildListMutation(records)); } catch(e) {} + }); + innerObserver.observe(msg, { + childList: true, subtree: true, characterData: true + }); + } catch(e) {} + } + + function pollTick() { + try { tick(false); } catch(e) {} + try { attachInnerObserver(); } catch(e) {} + } + + // Each bootstrap step is independently guarded — any one of them + // failing must not prevent the polling timer from being installed. + // Without the timer the iframe goes silently dormant. + try { tick(false); } catch(e) {} + try { attachInnerObserver(); } catch(e) {} + try { + new MutationObserver(function(records) { + // childList touching OUR message can mean it was rebuilt + // wholesale — flag the self-heal for that case too. Scoped so a + // busy chat (other messages streaming) doesn't make every + // settled viz iframe re-walk its message on each flush. + var hasChildList = _ivHasChildListMutation(records); + if (hasChildList && _ivRecordsTouchMyMessage(records)) _ivHealDirty = true; + try { tick(hasChildList); } catch(e) {} + try { attachInnerObserver(); } catch(e) {} + }).observe(parent.document.body, { + childList: true, subtree: true, characterData: true + }); + } catch(e) {} + setInterval(pollTick, 400); +})(); +</script> +""" + + +# --------------------------------------------------------------------------- +# srcdoc safety guard +# +# Every constant listed in _IFRAME_EMBEDDED_SCRIPTS below is concatenated +# into an iframe's srcdoc. Once that srcdoc is parsed by the browser's +# HTML5 tokenizer, the script-data state machine is sensitive to the +# following literal byte sequences appearing ANYWHERE inside a script +# body (including inside JS comments and string literals): +# +# <!-- triggers "script data escape start" +# --> exits "script data escaped" +# <![CDATA[ same family of escape transitions +# ]]> same +# <script in escaped state, triggers "script data double escape start" +# </script> in double-escaped state, exits back to escaped — does +# NOT terminate the outer script +# +# When any of these appears inside a script body — even commented out — +# the outer script's actual `</script>` tag stops terminating the +# script. The IIFE then either never executes or executes incompletely, +# producing the silent failure mode we hit in 2.1.0–2.1.2 (every +# debugging path looks normal in isolation, but tick never runs). +# +# Always build these tokens via string concatenation in JS — never +# write them as literals, not even inside comments. The guard below +# raises at module load time so the plugin refuses to import if anyone +# ever reintroduces one. +_FORBIDDEN_SRCDOC_LITERALS = ( + "<!--", + "-->", + "<![CDATA[", + "]]>", + "<script", + "</script", +) + + +def _assert_srcdoc_safe(name: str, body: str) -> None: + """Refuse to load if `body` contains any HTML token that would + confuse the iframe srcdoc's script-data state machine. + + Each script body is allowed exactly ONE legitimate `<script>` and + one `</script>` — the wrapping tags themselves. Anything beyond + that count is a reintroduction of the bug fixed in 2.1.3. + """ + open_count = body.count("<script") + close_count = body.count("</script") + if open_count > 1 or close_count > 1: + raise RuntimeError( + f"Inline Visualizer: {name} contains an extra <script> or " + f"</script> literal (open={open_count}, close={close_count}). " + "These break HTML5 srcdoc parsing — build them via string " + "concatenation in JS instead." + ) + for tok in ("<!--", "-->", "<![CDATA[", "]]>"): + if tok in body: + raise RuntimeError( + f"Inline Visualizer: {name} contains a literal {tok!r}. " + "This puts the iframe srcdoc parser into script-data-escape " + "mode and silently breaks the IIFE. Concatenate it in JS " + "instead, even inside comments." + ) + + +_IFRAME_EMBEDDED_SCRIPTS = { + "THEME_DETECTION_SCRIPT": THEME_DETECTION_SCRIPT, + "BODY_SCRIPTS": BODY_SCRIPTS, + "CHIME_SCRIPT": CHIME_SCRIPT, + "STRICT_SECURITY_SCRIPT": STRICT_SECURITY_SCRIPT, + "STREAMING_OBSERVER_SCRIPT": STREAMING_OBSERVER_SCRIPT, +} +for _name, _body in _IFRAME_EMBEDDED_SCRIPTS.items(): + _assert_srcdoc_safe(_name, _body) + + +DOWNLOAD_BUTTON = ( + '<div id="iv-dl-wrap">' + '<button id="iv-dl-btn" onclick="_ivDlMenu(event)" title="Download">' + '<svg viewBox="0 0 16 16"><path d="M8 2v8M5 7l3 3 3-3"/><path d="M3 12h10"/></svg>' + "</button>" + '<div id="iv-dl-menu" style="display:none;position:absolute;right:0;top:30px;z-index:60;' + "background:rgba(28,30,34,.97);color:#fff;border:1px solid rgba(128,128,128,.35);" + "border-radius:8px;box-shadow:0 4px 14px rgba(0,0,0,.3);min-width:104px;" + 'overflow:hidden;font-size:12px;font-family:system-ui,sans-serif;">' + '<button class="iv-dl-item" onclick="_ivDownload()" style="display:block;width:100%;' + "padding:7px 14px;background:transparent;border:none;cursor:pointer;" + 'text-align:left;color:inherit;font:inherit;">HTML</button>' + '<button class="iv-dl-item" onclick="_ivDownloadSVG()" style="display:block;width:100%;' + "padding:7px 14px;background:transparent;border:none;cursor:pointer;" + 'text-align:left;color:inherit;font:inherit;">SVG</button>' + '<button class="iv-dl-item" onclick="_ivDownloadPNG()" style="display:block;width:100%;' + "padding:7px 14px;background:transparent;border:none;cursor:pointer;" + 'text-align:left;color:inherit;font:inherit;">PNG</button>' + "</div></div>" +) + + +# --------------------------------------------------------------------------- +# CSP generation per security level +# --------------------------------------------------------------------------- + +_KNOWN_CDNS = ( + "https://cdnjs.cloudflare.com" " https://cdn.jsdelivr.net" " https://unpkg.com" +) + +# The strict and balanced tags interpolate the (constant) CDN allowlist, so +# assemble them once at import instead of rebuilding the string on every render. +_CSP_STRICT = ( + '<meta http-equiv="Content-Security-Policy" content="' + f"default-src 'self'; " + f"script-src 'unsafe-inline' 'unsafe-eval' {_KNOWN_CDNS}; " + "style-src 'self' 'unsafe-inline'; " + "connect-src 'none'; " + "form-action 'none'; " + "img-src 'self' data: blob:; " + "font-src 'self' data:; " + "media-src 'self'; " + "object-src 'none'; " + "base-uri 'self'; " + '">' +) +_CSP_BALANCED = ( + '<meta http-equiv="Content-Security-Policy" content="' + f"default-src 'self'; " + f"script-src 'unsafe-inline' 'unsafe-eval' {_KNOWN_CDNS}; " + "style-src 'self' 'unsafe-inline'; " + "connect-src 'none'; " + "form-action 'none'; " + "img-src * data: blob:; " + "font-src 'self' data:; " + "media-src 'self'; " + "object-src 'none'; " + "base-uri 'self'; " + '">' +) + + +def _build_csp_tag(level: str) -> str: + """Return a <meta> CSP tag for the given security level, or empty string. + + 'unsafe-eval' is included because runtime expression compilers like + Vega / Vega-Lite use new Function() internally and fail under + strict CSP. 'unsafe-inline' is already present (inline scripts can + execute arbitrary code), so adding 'unsafe-eval' does not + meaningfully widen the attack surface — the real exfil blockers + (connect-src, form-action, img-src, object-src) remain intact. + """ + if level == "none": + return "" + + if level == "offline": + # STRICT minus the public CDN allowlist: nothing loads from + # outside the Open WebUI origin. 'self' replaces the CDN hosts + # so admins can serve pinned libraries from the instance's own + # /static directory (srcdoc iframes inherit the parent page's + # origin and base URL, so 'self' == the Open WebUI host and + # paths like /static/iv-libs/chart.umd.min.js resolve locally). + return ( + '<meta http-equiv="Content-Security-Policy" content="' + "default-src 'self'; " + "script-src 'unsafe-inline' 'unsafe-eval' 'self'; " + "style-src 'self' 'unsafe-inline'; " + "connect-src 'none'; " + "form-action 'none'; " + "img-src 'self' data: blob:; " + "font-src 'self' data:; " + "media-src 'self'; " + "object-src 'none'; " + "base-uri 'self'; " + '">' + ) + + if level == "strict": + return _CSP_STRICT + + # balanced: block outbound connections & forms, allow external images + return _CSP_BALANCED + + +def _build_html( + security_level: str = "strict", + title: str = "Visualization", + lang: str = "en", + chime: bool = True, +) -> str: + """Wrap the streaming visualization shell: empty render area + observer. + + The observer tails the parent chat DOM for an ``@@@VIZ-START`` … + ``@@@VIZ-END`` plain-text block in the assistant message and renders + its contents live into #iv-render. + """ + csp_tag = _build_csp_tag(security_level) + strict_script = ( + STRICT_SECURITY_SCRIPT if security_level in ("strict", "offline") else "" + ) + safe_title = ( + title.replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace('"', """) + ) + # Sanitize lang to a simple lowercase BCP-47 primary subtag. + # Split on '-' first so "zh-CN" → "zh", not "zhcn". + safe_lang = re.sub(r"[^a-z]", "", lang.split("-")[0].lower()[:5]) or "en" + + # Strip the chime script entirely when the valve is off — no bytes + # shipped, no defined playDoneSound in the iframe. finalize()'s + # typeof-function guard turns the missing definition into a no-op. + body_scripts = BODY_SCRIPTS.replace( + "/*__CHIME_BLOCK__*/", CHIME_SCRIPT if chime else "" + ) + + # Loader sits *below* the render area so content appears to flow + # downward toward the pulsing dots — like a cursor following a pen. + # The observer removes #iv-loader entirely on finalize(). + body_inner = ( + '<div id="iv-render"></div>\n' + '<div id="iv-loader" class="iv-loading" aria-live="polite">' + '<div class="iv-loading-dots"><span></span><span></span><span></span></div>' + '<div class="iv-loading-label">Rendering visualization\u2026</div>' + "</div>\n" + f"{DOWNLOAD_BUTTON}\n" + f"{body_scripts}" + f"{STREAMING_OBSERVER_SCRIPT}" + f"{strict_script}" + ) + + return ( + f'<!DOCTYPE html><html data-iv-lang="{safe_lang}" data-iv-build="{_IV_BUILD}"><head>' + f"<title>{safe_title}" + f"{csp_tag}" + f"" + f'' + f"{THEME_DETECTION_SCRIPT}" + f"\n{body_inner}\n" + ) + + +# --------------------------------------------------------------------------- +# Valves (user-configurable settings) +# --------------------------------------------------------------------------- + +# Developer reference for security levels: +# +# STRICT — Containment-oriented default. Blocks outbound fetch/XHR +# (connect-src 'none'), form submissions, external images, +# embedded objects, and base-URI hijacking. Injects a script +# that strips URL query parameters from link navigation as +# additional hygiene (query-only; does not cover path or +# fragment, and does not intercept location.assign/replace). +# Script execution within the visualization is intentionally +# allowed ('unsafe-inline' + CDN allowlist) — this is +# required for Chart.js, D3, and interactive visualizations. +# +# BALANCED — Same as STRICT but allows external image loading (img-src *). +# No URL parameter stripping. Note: img-src * permits +# tracking pixels — this is an accepted privacy tradeoff +# for visualizations that need external images. +# +# NONE — No CSP applied. Visualization can make arbitrary network +# requests. Use only for visualizations that fetch live API +# data (CORS restrictions still apply). +# +# OFFLINE — Nothing leaves the Open WebUI host. Same as STRICT but +# the public CDN hosts are dropped from script-src and +# 'self' is allowed instead, so chart libraries must be +# served by the Open WebUI instance itself (drop the pinned +# files under its /static directory — see the README +# section "Offline mode"). External scripts, images, fonts +# and media are all blocked; only same-origin, data: and +# blob: sources load. For air-gapped / privacy-hardened +# deployments. URL parameter stripping is applied like in +# STRICT. +# +# Limitations that apply to ALL levels: +# - Script execution is always permitted (required for core features). +# - When iframe Same-Origin is enabled at the platform level, JS inside +# the visualization can access the parent Open WebUI page. No CSP +# level can prevent this — it is controlled by the platform setting. + + +class Tools: + """Inline Visualizer — renders interactive HTML/SVG in chat. + + Security is controlled via the ``security_level`` valve, which applies + a Content Security Policy to the rendered iframe. Defaults to STRICT, + which blocks outbound network requests (fetch/XHR) and form submissions + while allowlisting three public script CDNs. OFFLINE additionally + drops the CDN allowlist for zero external connections (self-hosted + libraries under the instance's /static directory still load). + Script execution is always permitted — it is required for interactive + visualizations, Chart.js, and D3. See the developer reference above + for the full security model and its limitations. + """ + + class Valves(BaseModel): + security_level: Literal["strict", "balanced", "none", "offline"] = Field( + default="strict", + description="Strict (default): blocks outbound fetch/XHR, images, and forms; scripts always allowed (3 public CDNs allowlisted). Offline: like Strict but with ZERO external connections — even the CDNs are blocked; libraries self-hosted under Open WebUI's /static folder still load (see README). Balanced: like Strict but also allows external images. None: no restrictions.", + ) + chime: bool = Field( + default=True, + description="Play a soft three-note chime when a live-streamed visualization finishes. When off, the chime script is omitted from the iframe entirely (not shipped as a no-op).", + ) + + def __init__(self): + self.valves = self.Valves() + + async def visualize( + self, + title: str = "Visualization", + __event_call__=None, + __event_emitter__=None, + ): + """ + You need to call this tool before EVERY visualization you want to render. + What this tool does: visualize() mounts an iframe sandbox directly in the chat. + After this tool is called, the assistant must stream exactly one HTML/SVG visualization fragment between the plain-text delimiters @@@VIZ-START and @@@VIZ-END. + The sandbox renders that fragment live for the user. + + Use this tool ONLY for EXPLICIT visualization requests. + Do NOT use this tool proactively. Do NOT infer that a visualization would be helpful. + **If the user did not explicitly ask for a visual artifact, do not call visualize().** + Never use visualize() for ordinary assistant output. + The chat you are responding in has a full Markdown, LaTeX, KaTeX and Mermaid rendering engine. + Call visualize() ONLY when the user clearly and UNAMBIGUOUSLY, DIRECTLY, EXPLICITLY asked for a visual artifact (e.g. diagrams, charts, graphs, dashboards, illustrations, interactive explainers, etc.). + + IMPORTANT: + BEFORE CALLING THIS TOOL, YOU MUST: Call view_skill("visualize") FIRST. + You MUST call view_skill("visualize") first. + The visualize skill contains a mandatory handbook/tutorial with important rules for rendering, layout, SVG setup, chart patterns, colors, interactivity, and common failure points. + Never generate a visualization without reading the skill first. + + After calling this tool: + In the assistant message that follows, emit exactly one visualization block: + + @@@VIZ-START + + @@@VIZ-END + + Hard output rules: + - Use the delimiters exactly: @@@VIZ-START and @@@VIZ-END. + - Put each delimiter on its own line, and leave one empty line after @@@VIZ-END before any follow-up text. + - Emit exactly one @@@VIZ-START / @@@VIZ-END pair per tool call. + - Do not wrap the visualization in Markdown code fences. + - Do not use ```html, ```svg, ~~~, :::, or any other fenced block. + - Emit a fragment only: no , no , no , no . + - Structure the fragment as: + …all focus rings, checkboxes, and var(--accent) consumers go teal… + + +**To apply an accent color to a specific section**: set data-accent on any inner container to recolor just its subtree: + +
+ + +
+ + +**To apply an accent color to a single element**: set directly on an element to recolor just it: + + + + +Both light and dark themes are handled — accent values track per-theme ramp stops automatically, and foreground text color flips for legibility in dark mode. +No manual override needed. + +Pick an accent that matches the topic: green for finance/positive, red for warnings/critical actions, blue for informational dashboards, amber for attention/caution, etc. +Default to purple for neutral or multi-purpose visualizations. + +## Output rules + +These rules keep visuals clean, accessible, and consistent with the host UI: + +- **Flat design** — no gradients, drop shadows, blur, glow, or noise textures (the host UI is flat; matching it prevents visual jarring) +- **Prefer no emojis**, instead use CSS shapes or SVG paths for icons (emoji render inconsistently across platforms) +- **Sentence case** — all labels and headings +- **Round displayed numbers** — use Math.round, toLocaleString, or Intl.NumberFormat +- **Min font size 11px** — smaller becomes unreadable on most screens +- **Text weights** — 400 regular, 500 for emphasis only +- Keep long-form explanation in the prose response. Use concise labels, captions, legends, helper text, and short annotations inside the visual when they improve comprehension. +- **Build ambitiously when the topic supports it.** Treat each visualization like a small product surface, not a single static graphic. Combine multiple elements: a chart paired with a metric strip, a diagram with collapsible deep-dives, a comparison card with sliders that let the user explore tradeoffs. Use animation, hover, and click interactions where they help the reader notice or explore something — not for decoration. If the user asked for "a chart" and the topic naturally extends into a small dashboard, build the dashboard. Restraint is for cases where extra structure would distract; default to richness, not minimalism. + +--- + +## Design system + +### CSS variables (auto-injected — prefer these so light/dark mode just works) + +The tool injects theme-aware CSS variables that adapt to light/dark mode automatically. Use them by default for text, surface, and border colors; reach for a specific hex only when the design genuinely calls for a fixed color (a brand mark, a deliberate accent that shouldn't track the theme). + +| Token | Purpose | +|-------|---------| +| --color-text-primary | Main text | +| --color-text-secondary | Labels, muted text | +| --color-text-tertiary | Hints, placeholders | +| --color-text-info/success/warning/danger | Semantic text | +| --color-bg-primary | Main background | +| --color-bg-secondary | Cards, surfaces | +| --color-bg-tertiary | Page background | +| --color-border-tertiary | Default borders (0.15 alpha) | +| --color-border-secondary | Hover borders (0.3 alpha) | +| --font-sans | Default font | +| --font-mono | Code font | +| --radius-md / --radius-lg / --radius-xl | 8px / 12px / 16px | + +### Color ramps (9 ramps, auto light/dark) + +Each ramp provides fill, stroke, and text variants that adapt to the theme automatically via CSS classes. + +| Ramp | 50 (light fill) | 200 | 400 | 600 (light stroke) | 800 (light title) | +|------|------|------|------|------|------| +| purple | #EEEDFE | #AFA9EC | #7F77DD | #534AB7 | #3C3489 | +| teal | #E1F5EE | #5DCAA5 | #1D9E75 | #0F6E56 | #085041 | +| coral | #FAECE7 | #F0997B | #D85A30 | #993C1D | #712B13 | +| pink | #FBEAF0 | #ED93B1 | #D4537E | #993556 | #72243E | +| gray | #F1EFE8 | #B4B2A9 | #888780 | #5F5E5A | #444441 | +| blue | #E6F1FB | #85B7EB | #378ADD | #185FA5 | #0C447C | +| green | #EAF3DE | #97C459 | #639922 | #3B6D11 | #27500A | +| amber | #FAEEDA | #EF9F27 | #BA7517 | #854F0B | #633806 | +| red | #FCEBEB | #F09595 | #E24B4A | #A32D2D | #791F1F | + +### Chart dataset colors (use 400 stops) + +| Series | Color | Hex | +|--------|-------|-----| +| 1 | teal-400 | #1D9E75 | +| 2 | purple-400 | #7F77DD | +| 3 | coral-400 | #D85A30 | +| 4 | blue-400 | #378ADD | +| 5 | amber-400 | #BA7517 | + +For area/line fills, use same color at 20% opacity. + +--- + +## SVG setup + +If you want to build a beautiful SVG to be rendered inside the chat, follow these rules too: +Always use this SVG boilerplate: + + + + + + + + + +- viewBox width **always 680** — set H to **tightly fit** content (last element bottom + 40px). **Never oversize** — calculate the actual bottom of your last SVG element and add 40px. An SVG with content ending at y=180 must use H=220, not 500 +- Safe area: x=40 to x=640 +- Background transparent — host provides container + +### SVG classes (auto-injected) + +Drop these on SVG elements instead of writing inline fill, stroke, or +font-size. They track the theme automatically. + +| Class | What it is | When to use | +|-------|------------|-------------| +| .t | 14px primary-color text | Default for any visible label inside a node, axis tick, or callout. | +| .ts | 12px secondary-color text | Subtitles, captions, units (e.g. "users", "ms"), supporting text under a .t label. | +| .th | 14px primary text, 500 weight | Node titles, KPI numbers, anything that needs to read as "the headline" of a small region. | +| .box | Neutral rect — secondary bg, tertiary border | Default container for a labeled region. Use whenever you need a neutral chip / panel and don't have a semantic color. | +| .node | Cursor-pointer + hover opacity on a | Mark a as clickable. Pair with onclick="sendPrompt(...)" so a user can drill into the topic. | +| .arr | 1.5px stroke matching theme borders | Arrow lines and connectors. Combine with marker-end="url(#arrow)". | +| .leader | 0.5px dashed guide line | Pulling a label to a part of an illustration when the label can't sit on top of it. | +| .c-{ramp} | Sets fill/stroke + text colors on a whole from one of the 9 color ramps | Color a node by category — apply .c-teal (etc.) to a and its direct children pick up the matching ramp (not deeper descendants). Un-classed, un-filled / children (pie wedges, areas) take the ramp's series color; on a classed or filled mark, fill="currentColor" opts back in. | + +### Sizing text inside boxes + +Browsers don't auto-size SVG boxes to text. To pick a width, estimate +the rendered glyph width per character and size the box from the +longest line. + +- 14px text (.t, .th) → ~8 px / character +- 12px text (.ts) → ~7 px / character +- box_width = max(title_chars × 8, subtitle_chars × 7) + 24 (12 px padding each side) + +### Centering text in boxes + + defaults to dominant-baseline="alphabetic" — y is the text's +baseline, not its center, so a label placed at the vertical midpoint of +a box actually sits ~4 px too high. For text inside a node, callout, or +any rounded rect, add dominant-baseline="central" and put y at the +box midpoint. + +Keep the default (no dominant-baseline) for text that's *meant* to sit +on a baseline: axis tick labels (resting on the axis line), legend labels +(aligned to the swatch baseline), and anything where the bottom edge of +the glyphs is the visual anchor. Setting central on those will make +them look ~4 px low instead. + +--- + +## Diagram types + +### Flowchart — sequential steps, decisions + +- Max **4–5 nodes** per diagram — 6+ → decompose into overview + sub-flows +- Box spacing: 60px between boxes, 24px padding inside +- Single-line node: height 44px, two-line: 56px +- Arrows must not cross any box — use L-bends if needed +- Use marker-end="url(#arrow)" on arrow paths + +Single-line node: + + + + Label + + +Two-line node: + + + + Title + Subtitle + + +### Architecture — nested regions, layered systems + +For diagrams that show **what contains what**: services inside zones, +modules inside layers, components inside subsystems. The nesting itself +is the information — outer regions are the system, inner regions are +the parts. + +- Outermost container: rx=20–24, lightest ramp fill (the 50 stop), 0.5px stroke +- Inner regions: rx=8–12, a darker stop of the same ramp — or a different ramp when the inner region is semantically distinct (e.g. external service inside an internal cluster) +- 20px minimum padding between an inner region's bounds and its parent's edge +- Max 2–3 nesting levels — beyond that, decompose into a top-level overview plus sub-diagrams + +### Illustrative — explain a mechanism by drawing it + +For "how does this actually work" topics where the answer is spatial: +how light refracts through a prism, how a transformer attention head +weighs tokens, how a heat pump moves heat against a gradient. **Draw +the thing itself**, not a labeled diagram about it. + +- Shapes are freeform — paths, ellipses, polygons, curves — not just rounded rects +- Color encodes intensity or state, not category: warm ramps for active / hot / energized, cool ramps for calm / cold / passive, gray for neutral / inert +- Labels live outside the object connected via .leader lines — reserve a ~140px gutter on the side you'll label from +- Strongly prefer **interactive** illustrative diagrams: if the real system has a knob, a slider, or a phase, expose it. A prism with a draggable angle slider teaches refraction better than five static frames. + +--- + +## Charts (Chart.js) + +Load Chart.js in your HTML fragment: + + + +Setup pattern: + +
+ +
+ + +**Chart rules:** +- Wrap canvas in container with position: relative and explicit height — without it, maintainAspectRatio: false collapses the canvas to zero +- Always pass responsive: true, maintainAspectRatio: false in options — without maintainAspectRatio: false, Chart.js locks the canvas to a 2:1 aspect and ignores the container height; without responsive: true, it won't redraw when the iframe re-measures. You have to set them explicitly on every new Chart(...) call (Chart.js reads options at construction time, so there's no global default we could pre-set for you). +- Read CSS variables for text/border colors so the chart tracks the theme +- borderRadius: 4 on bars +- Line charts: tension: 0.3 for smooth curves +- Doughnut: cutout: '60%' — never use pie + +**Chart type selection:** + +| Data shape | Type | Notes | +|-----------|------|-------| +| Categories + values (a few items, comparable magnitudes) | **Bar** | Default for "compare values across labels". Switch to a horizontal bar (indexAxis: 'y') when labels are long, when there are 8+ categories, or when ranking is the point. | +| Time series, anything sampled at regular intervals | **Line** | tension: 0.3 for a natural curve. Stack multiple datasets when you're comparing trends, not when each line wanders independently — overlap gets unreadable past 4 lines. | +| Parts of a whole, ≤5 slices | **Doughnut** | Use cutout: '60%' so the empty middle can hold a total or label. Skip if the segments are very uneven (one slice >70%) — the small slices vanish; show a stacked bar instead. | +| Two continuous variables, looking for correlation | **Scatter** | Add a trend line if the relationship is the takeaway. For dense clouds, drop point opacity to 0.3–0.5 so density reads. | +| Stacked / cumulative composition over time | **Stacked bar / stacked area** | Bar when the buckets are discrete (months, segments); area when the underlying signal is continuous. | +| Single-value vs target / threshold | **Bar with reference line** or KPI card | A whole chart is overkill for one number — consider a metric card with a sparkline instead. | +| Multi-dimensional comparison (3–6 axes) | **Radar** | Only when the axes are genuinely commensurate — otherwise a small-multiples bar grid is clearer. | + +### Inline SVG charts (no library) + +Reach for inline SVG when the data is small, the shape is simple, or +you want the chart to share design with surrounding diagrams (matching +corner radii, palette, type). No script, no CDN — just shapes and text. +Reach for Chart.js when you need axes, tooltips, hover, animation, or +many series. + +**Good fits for inline SVG:** +- **Progress / completion bar** — a value rendered against a fixed track, often paired with a percentage label to its right +- **Ranking strip** — a small number of horizontal bars stacked vertically, each bar a different category color, sized by value +- **Sparkline** — a terse trend line with no axes that sits next to a number to give the number context +- **KPI donut / ring** — a single percentage rendered as a circle arc, with the number in the middle of the ring +- **Stacked composition row** — one horizontal bar split into colored segments to show parts of a whole, when a doughnut would feel heavy +- **Custom-shape charts** — anything where the chart shape is part of the metaphor (a thermometer for temperature, a battery for charge, a fuel gauge, a tide-line) + +**Theme consistency for inline SVG:** +- Use the .t / .ts / .th classes on for labels, captions, and headlines. + They pick up the theme's text colors and typography scale automatically. + Never set font-size or fill on label text manually unless you need a specific deviation. +- For neutral backgrounds (track behind a progress bar, empty slot in a ring), use fill="var(--color-bg-secondary)" so it blends into the surrounding card. +- For data colors, prefer the chart-dataset 400-stop hexes from the table above — they're calibrated to read on both light and dark backgrounds. + If you need a *whole group* recolored (rect + label + stroke together), wrap it in a (or any of the 9 ramp classes) and let the SVG class system handle fill + stroke + text in one shot. +- Keep stroke-widths to 0.5 px for chrome (axis lines, grid) and 1.5 px for data (lines, sparklines) — matches the 0.5 px borders the rest of the host UI uses, so the chart doesn't feel chunkier than its neighbors. +- Add opacity="0.85" on data fills — softens the color slightly so it sits comfortably next to text without overwhelming it. + +**Math hints for the less obvious shapes:** +- Donut arc length: circumference = 2 × π × r. To draw v% of the ring, set stroke-dasharray="{v×circumference/100} {circumference}" on the foreground circle, and transform="rotate(-90 cx cy)" so the arc starts at 12 o'clock instead of 3 o'clock. +- Bar widths in a viewBox="0 0 680 …": leave 40 px of margin on each side, giving a 600 px usable plot width. + +--- + +## Component patterns + +### Metric cards — KPI strip + +
+
+
Revenue
+
$3,870
+
▲ 12.4%
+
+ +
+ +Pair with a chart below for a compact dashboard. Add a tiny inline-SVG +sparkline under each value if the trend matters. + +### Comparison layout — two paths side by side + +
+
+
Monolith
+
+
Deploy unit
1 service
+
Latency
Low (in-process)
+
Scaling
Vertical
+
+
+
+
Microservices
+
+
Deploy unit
N services
+
Latency
Higher (network)
+
Scaling
Horizontal per service
+
+
+
+ +### Interactive explainer — slider drives output + + +
+ + + +The pattern generalises: every interactive element binds an input listener, recomputes a value, and writes it to a result node. +Pair with an inline SVG that re-draws on every input change for a "live diagram". + +### Tabs — a piece of UI users already know + + +
+ + + +
+
…
+ + + + + + + +Persist the active tab with saveState/loadState so it survives reloads. + +**Charts in inactive tabs render at 0×0.** Plotly, ECharts, and vis-network all measure their container at init time. +If that container is inside a hidden / display:none panel, they paint into a zero-size canvas and stay blank even after the tab becomes visible. +Two workarounds, pick one: + +1. **Lazy-init**: only call Plotly.newPlot / echarts.init / new vis.Network the first time its tab is shown (track a tabInit[id] flag in the handler). +2. **Resize on show**: init everything up front (so data is ready), then in showTab call the right resize hook for whichever lib is in that tab. + Note the API differs per library — c.resize() does not work for all of them: + + // ECharts: instance.resize() + echartsInstance.resize(); + // Plotly: pass the container element, no .resize() on the chart + Plotly.Plots.resize(document.getElementById('plotly-container')); + // vis-network: redraw + fit — the instance has no .resize() + networkInstance.redraw(); + networkInstance.fit(); + // Chart.js: instance.resize() — but Chart.js auto-resizes on + // container size change so usually nothing needed. + + Skip the resize call for D3 / Vega-Lite / inline SVG — they paint declaratively into the SVG namespace and aren't bothered by hidden parents. + +### Step-through walkthrough — guided narrative +A "Next ▶" button advances through a sequence of stages, each with its own caption and (optionally) a different highlighted region of the same diagram. +Useful for explaining algorithms, processes, or any topic where the order matters more than the totals. + + +
Click Next to begin.
+ + + + +--- + +## sendPrompt bridge — conversational diagrams + +sendPrompt(text) is the function that makes visualizations conversational. When called, it injects the given text into the chat input field and submits it — exactly as if the user had typed and sent it themselves. The model then receives that message and responds normally, creating a feedback loop between the visual and the conversation. + +This is what separates a static diagram from an **exploration interface**. A user sees a system architecture diagram, clicks on the "Load Balancer" node, and the model receives "Tell me more about the load balancer — how does it distribute traffic across the backend services?" as a user message. The model then responds with details, and could even generate a *new* sub-diagram showing the load balancer internals. The user never had to type anything — they just clicked. + +### Why this matters + +Without sendPrompt, interactive elements inside the iframe are isolated — they can toggle visibility, animate, or filter data, but they can never talk back to the model. The user sees a cool diagram but has to manually type follow-up questions. With sendPrompt, every clickable element becomes a conversation starter. The diagram itself becomes a navigation interface for the topic. + +### Writing good sendPrompt text + +The text you pass to sendPrompt becomes the user's message to the model. Write it as a natural follow-up question — conversational, specific, and referencing the context of the diagram: + +**Good prompt text** (specific, contextual, references the diagram): +- "Explain the attention mechanism — how does it decide which tokens to focus on?" +- "Break down the CI/CD pipeline stage. What tools are typically used here?" +- "Show me a more detailed diagram of the data processing layer" +- "What happens when the load balancer detects a failed backend node?" +- "Compare the pros and cons of the monolith vs microservices approach shown here" + +### Usage patterns + +Simple patterns — single-click sendPrompt on a node or button: +- **Drill-down**: onclick="sendPrompt('Explain the API gateway — what does it handle?')" on a diagram node +- **Quiz answer**: onclick="sendPrompt('I chose B: O(n log n). Am I right? Explain why.')" on answer buttons +- **Guided exploration**: onclick="sendPrompt('Show me a more advanced example with edge cases.')" on a "Go deeper →" button +- **Comparison**: onclick="sendPrompt('Compare REST vs GraphQL — when should I use each?')" on one of two nodes + +**Form / preference collector** — gather multiple user selections, then send them all at once. Use local JS to track choices (button highlights, state object) and a submit button that composes a sendPrompt from the collected answers: + + + +

What's your style?

+

Pace

+ + + + +

Focus

+ + + + + + +This pattern is powerful because the model receives a structured summary of all user preferences in one message. Use local JS for the selection UI (instant feedback), then sendPrompt only on final submit. + +### When to use sendPrompt vs local JS: +| User action | Use | Why | +|------------|-----|-----| +| Learn more about a component | sendPrompt | Model gives a contextual explanation | +| Explore a stage / drill down | sendPrompt | Model can generate a sub-diagram | +| Submit answers or preferences | sendPrompt | Model evaluates or personalizes | +| Toggle views, adjust sliders | Local JS | Instant feedback, no reasoning needed | +| Filter/sort data | Local JS | Instant response, no model needed | + +--- + +## Interactivity by default + +Build dashboards, charts, graphs, interactive functions, animated sections, moving objects, expandable detail sections, cards, copyable text elements and more. If the topic allows and it makes sense for the topic, build complex and visually stunning elements. + +Visualizations should feel alive and polished — not static images dumped into chat. Build interfaces that invite interaction: + +- **Expandable sections** — use collapsible
elements or JS-toggled sections so users can explore at their own pace without overwhelming them upfront +- **Hover effects** — nodes, buttons, and cards should respond to hover (the .node class adds this for SVG elements; for HTML, use :hover styles) +- **Smooth transitions** — add transition: all 0.2s ease to interactive elements for a polished feel +- **Active states** — when a user selects an option or clicks a tab, make the selection visually clear with your own .active class or distinct styling +- **Progressive disclosure** — show a clean overview first, let the user click to reveal detail (tabs, accordions, or sendPrompt for model-powered drill-down) + +**The goal is to build something that feels like a real app component embedded in chat with reactivity, sections and extra elements** — not a screenshot. If the visualization has multiple facets, give the user controls to explore them. If it has hierarchical information, let them expand and collapse. If it has data, let them sort or filter. + +--- + +## openLink bridge — opening URLs from visualizations + +openLink(url) opens a URL in a new browser tab from within the visualization iframe. Normal links inside an iframe can behave unpredictably (opening inside the iframe, being blocked by sandbox restrictions, etc.). This function handles that by opening the link in the parent window instead. + + + +Or in SVG: + + + + View source ↗ + + +Use openLink for external references, documentation links, or source code links. Unlike sendPrompt, this navigates away from the chat — use it when the user needs to access an external resource, not when they need the model to explain something. + +--- + +## copyText + toast bridges — feedback on user actions + +copyText(text) copies text to the system clipboard and automatically shows a localized "Copied" toast in the top-right corner of the iframe. Works from HTTPS and HTTP origins (falls back to execCommand('copy') if the async Clipboard API is blocked). Use this on "Copy" buttons inside interactive visualizations — data tables, code snippets, shareable values. + + + +toast(message, kind) shows a small auto-dismissing banner inside the iframe. kind is optional and controls the text color: 'success' (green, default), 'info' (blue), 'warn' (amber), 'error' (red). Use it for status notifications inside long-running interactive tools — "Calculation done", "Invalid input", etc. + + + +Toasts auto-dismiss after ~2.2 s and stack vertically if fired in quick succession. + +--- + +## saveState + loadState bridges — persistent interactive state + +saveState(key, value) and loadState(key, fallback) proxy parent.localStorage with a key prefix scoped to **this assistant message**. State survives page reloads and tab switches, but two different chats (or different messages in the same chat) each get their own independent state — no cross-contamination. + + + +Use it for: selected tabs, picked chart range, hidden/shown layers, theme overrides, collapsed sections — anything the user would expect to be remembered when they re-open the chat. + +Values are JSON-serialized. If localStorage is blocked (private browsing, sandboxed), both functions silently no-op and loadState returns fallback. + +--- + +## CDN libraries + +The CSP allowlists three CDN hosts for scripts only: any script served from them +loads, CDN stylesheets and fonts are blocked, so inline any CSS a library needs. + +Allowed hosts: +- cdnjs.cloudflare.com — widest coverage +- cdn.jsdelivr.net — npm / GitHub backed, supports minor-version pinning +- unpkg.com — npm mirror + +Common picks: + +| Library | Why reach for it | Example loader | +|---------|------------------|----------------| +| **Chart.js** | Bar / line / doughnut / scatter with animation out of the box | | +| **D3.js** | Custom data-driven SVG (force graphs, arcs, maps, non-standard charts) | | +| **Vega-Lite** | Declarative grammar of graphics — feed it a JSON spec, it draws the chart | | +| **ECharts** | Rich interactive dashboards, advanced chart types | | +| **Plotly** | Scientific / 3D plots, statistical charts | | +| **vis-network** | Force-directed network / node-link graphs | (the **standalone** UMD bundle — exposes vis.Network *and* vis.DataSet. The bare vis-network.min.js on cdnjs is the *peer* build and requires vis-data loaded separately, otherwise new vis.DataSet(...) throws vis is not defined.) | +| **Tone.js / Wavesurfer** | Audio synthesis, waveform visualisation | | + +Anything else on those three CDNs is fair game — apexcharts, d3-force, +konva, flatpickr, etc. Pick whatever fits the topic. + +--- + +## Library init + +Two patterns to follow when using a CDN library: + +### 1 · Wrap a Chart.js canvas in a fixed-height container + +maintainAspectRatio: false makes Chart.js use the container's height. +If the canvas has no intrinsic height (e.g. inside a flex column without a height set), it collapses to zero and nothing draws: + +
+ +
+ + +### 2 · Source order matters + +Put external + +