From e46920dcc73d5e0edec0679d5323e19bf1c61410 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Wed, 11 Nov 2026 15:34:33 +0900 Subject: [PATCH] refac --- backend/open_webui/tools/builtin.py | 1 + backend/open_webui/tools/visualizations.py | 63 ++++ backend/open_webui/utils/middleware.py | 19 +- backend/open_webui/utils/tool_calling.py | 20 +- backend/open_webui/utils/tool_search.py | 2 +- backend/open_webui/utils/tools.py | 4 + .../Messages/StructuredOutputRenderer.svelte | 15 + .../Messages/VisualizationToolCall.svelte | 326 ++++++++++++++++++ .../chat/Messages/structuredOutput.ts | 34 +- .../workspace/Models/BuiltinTools.svelte | 12 +- src/lib/i18n/locales/en-US/translation.json | 10 + src/lib/utils/ui-visibility.ts | 1 + src/lib/utils/visualizations/arguments.ts | 223 ++++++++++++ src/lib/utils/visualizations/dispatch.ts | 75 ++++ src/lib/utils/visualizations/frame.ts | 40 +++ src/lib/utils/visualizations/runtime.ts | 267 ++++++++++++++ src/lib/utils/visualizations/safeCut.ts | 42 +++ vite.config.ts | 4 + 18 files changed, 1146 insertions(+), 12 deletions(-) create mode 100644 backend/open_webui/tools/visualizations.py create mode 100644 src/lib/components/chat/Messages/VisualizationToolCall.svelte create mode 100644 src/lib/utils/visualizations/arguments.ts create mode 100644 src/lib/utils/visualizations/dispatch.ts create mode 100644 src/lib/utils/visualizations/frame.ts create mode 100644 src/lib/utils/visualizations/runtime.ts create mode 100644 src/lib/utils/visualizations/safeCut.ts diff --git a/backend/open_webui/tools/builtin.py b/backend/open_webui/tools/builtin.py index dba05e4ad5..ec79e105b9 100644 --- a/backend/open_webui/tools/builtin.py +++ b/backend/open_webui/tools/builtin.py @@ -63,6 +63,7 @@ from open_webui.routers.memories import ( ) from open_webui.routers.retrieval import search_web as _search_web from open_webui.socket.main import close_changed_note_documents, sio +from open_webui.tools.visualizations import render_visualization # noqa: F401 — re-exported from open_webui.tools.knowledge_fs import kb_exec # noqa: F401 — re-exported from open_webui.utils.access_control.files import has_access_to_note_files from open_webui.utils.chat_id import is_saved_chat_id diff --git a/backend/open_webui/tools/visualizations.py b/backend/open_webui/tools/visualizations.py new file mode 100644 index 0000000000..a93cfaab2b --- /dev/null +++ b/backend/open_webui/tools/visualizations.py @@ -0,0 +1,63 @@ +"""The visualization tool validates source; only the isolated browser frame executes it.""" + +from typing import Literal + +MAX_HTML_BYTES = 256 * 1024 + + +async def render_visualization( + title: str, + html: str, + libraries: list[Literal['chartjs']] | None = None, +) -> dict: + """Render an interactive chart, SVG diagram, calculator, or explainer inline in chat. + + Use proactively when a visual helps the user understand or explore the answer, + even when they have not explicitly asked for a visualization. Good uses include + comparisons, trends, mechanisms, and exploring how inputs change an outcome. + Prefer plain text for simple facts or short answers. Put the entire visualization + in html; write explanation in normal messages. HTML/SVG previews + appear progressively. Scripts run once, after the complete call is accepted. + Default to a lean, compact, flat inline design: concise labels, restrained spacing, + readable text, and only useful controls. Use regular font weight almost everywhere; + use medium (500) sparingly and never heavier weights. Prefer flat layouts to cards. + Inherit the default body text size (0.90625rem, matching chat) for normal text + and labels; do not shrink body text to make a layout compact. + Use rem for CSS typography, spacing, radii, and dimensions; use responsive widths. + Prefer 0.25–0.5rem gaps and padding, with 0.75rem only between distinct sections. + Keep labels close to controls and trim heading, paragraph, and list margins. + Avoid fixed-pixel styling and empty space. + The chat displays title above the visual; avoid repeating it in html. Avoid hero + headers, introductory copy, decorative gradients/shadows, oversized typography, + and nested cards unless requested. + Let content determine height; use the chat's scrolling, not internal scroll areas. + Emit a fragment: styles first, visible content next, classic inline scripts last. + Use addEventListener, not onclick attributes or DOMContentLoaded. No external + scripts, imports, fetch, frames, or parent-page access are available. + Request libraries=["chartjs"] to get window.Chart (no script URL needed). + Wrap each canvas in .chart-container; use responsive:true, maintainAspectRatio:false. + Buttons, inputs, tables, and details have built-in styling. Use CSS variables + --owui-background, --owui-surface, --owui-text, --owui-muted, --owui-border, + --owui-accent. Include accessible labels and responsive layouts; avoid vh heights. + window.openwebui.context supplies theme, language, direction, reducedMotion. + Listen for openwebui:contextchange for custom canvas theme updates. + await openwebui.sendMessage(text) requests a user-confirmed follow-up and returns + {sent:boolean}. Never assume access to chat history, credentials, or storage. + + :param title: Short accessible title, 1–160 characters. + :param html: Self-contained HTML/SVG/CSS/JavaScript fragment, at most 256 KiB UTF-8. + :param libraries: Omit or use [] for native HTML/SVG, or ["chartjs"] for charts. + """ + if not isinstance(title, str) or not 1 <= len(title.strip()) <= 160: + return {'error': 'title must contain 1–160 characters'} + if not isinstance(html, str) or not html.strip(): + return {'error': 'html must be a nonempty string'} + try: + size = len(html.encode('utf-8')) + except UnicodeEncodeError: + return {'error': 'html must contain valid Unicode'} + if size > MAX_HTML_BYTES: + return {'error': 'html exceeds the 256 KiB limit'} + if libraries is not None and libraries not in ([], ['chartjs']): + return {'error': 'libraries must be [] or ["chartjs"]'} + return {'status': 'accepted'} diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index fd653df6d7..ec0d0c3b9a 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -166,7 +166,7 @@ from open_webui.utils.tool_calling import ( final_answer_payload, prepare_tool_call, recover_tool_calls, - set_tool_call_visibility, + set_tool_call_metadata, split_tool_calls, tool_repetition_error, ) @@ -4704,7 +4704,7 @@ async def streaming_chat_response_handler(response, ctx): def full_output(): for item in output: - set_tool_call_visibility(item, metadata.get('tools', {})) + set_tool_call_metadata(item, metadata.get('tools', {})) if is_message_continuation(): return [ *prior_output[:-1], @@ -4924,7 +4924,7 @@ async def streaming_chat_response_handler(response, ctx): response_data.get('item') or {}, *((response_data.get('response') or {}).get('output') or []), ]: - set_tool_call_visibility(item, metadata.get('tools', {})) + set_tool_call_metadata(item, metadata.get('tools', {})) if response_data.get('type', '').endswith('.delta'): await queue_pending_delta_data( response_data, @@ -5258,6 +5258,7 @@ async def streaming_chat_response_handler(response, ctx): if item.get('type') == 'function_call' } + tool_name_changed = False for tc in response_tool_calls: call_id = tc.get('id') or output_id('fc') tc['id'] = call_id @@ -5266,6 +5267,7 @@ async def streaming_chat_response_handler(response, ctx): output_index, item = output_by_call_id[call_id] if func.get('name', item.get('name', '')) != item.get('name'): stream_size = 0 + tool_name_changed = True item['name'] = func.get('name', item.get('name', '')) item['arguments'] = func.get('arguments', item.get('arguments', '')) item['status'] = 'in_progress' @@ -5317,6 +5319,17 @@ async def streaming_chat_response_handler(response, ctx): } ) + if tool_name_changed: + # A late tool name can select a native renderer. Flush deltas + # before the full snapshot so arguments are not appended twice. + await flush_pending_delta_data() + await event_emitter( + { + 'type': 'chat:completion', + 'data': {'output': full_output(), 'flush': True}, + } + ) + data = None delta_type = 'tool_call' diff --git a/backend/open_webui/utils/tool_calling.py b/backend/open_webui/utils/tool_calling.py index 44ea110a81..46eab2f5d6 100644 --- a/backend/open_webui/utils/tool_calling.py +++ b/backend/open_webui/utils/tool_calling.py @@ -93,9 +93,23 @@ def strip_tool_approval_prompt(prompt): return _TOOL_APPROVAL_PROMPT_RE.sub('', prompt) if prompt else prompt -def set_tool_call_visibility(item, tools): - """Copy trusted tool visibility metadata onto display output, without changing execution.""" - if item.get('type') == 'function_call' and tools.get(item.get('name'), {}).get('hidden') is True: +def set_tool_call_metadata(item, tools): + """Copy application-owned display metadata, never trusting provider annotations.""" + if item.get('type') != 'function_call': + return + tool = tools.get(item.get('name'), {}) + for field, source in (('tool_id', 'tool_id'), ('tool_type', 'type')): + item.pop(field, None) + if tool.get(source): + item[field] = tool[source] + item.pop('tool_targets', None) + if tool.get('type') == 'builtin' and tool.get('tool_id') == 'builtin:call_tool': + item['tool_targets'] = { + name: {'tool_id': target['tool_id'], 'tool_type': target['type']} + for name, target in tools.items() + if target.get('type') == 'builtin' and target.get('tool_id') and not target.get('hidden') + } + if tool.get('hidden') is True: item['hidden'] = True diff --git a/backend/open_webui/utils/tool_search.py b/backend/open_webui/utils/tool_search.py index 170b532390..ca34a603de 100644 --- a/backend/open_webui/utils/tool_search.py +++ b/backend/open_webui/utils/tool_search.py @@ -181,7 +181,7 @@ def split_tool_call_batches(calls: list[dict], tools: dict[str, dict]) -> list[d expanded.append( { **call, - 'id': call_id if index == 0 else f'call_{uuid4().hex[:24]}', + 'id': call_id if index == 0 else f'{call_id}:{index}', 'function': {'name': CALL_TOOL_NAME, 'arguments': JSONCodec.dumps(entry)}, 'provider_batch': {**batch, 'tool_name': entry['tool_name']}, } diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py index ce6cf423f7..6359b3e8de 100644 --- a/backend/open_webui/utils/tools.py +++ b/backend/open_webui/utils/tools.py @@ -79,6 +79,7 @@ from open_webui.tools.builtin import ( read_memory_path, replace_memory_content, replace_note_content, + render_visualization, search_calendar_events, search_channel_messages, search_channels, @@ -720,6 +721,9 @@ async def get_builtin_tools( 'type': 'builtin', } + if is_builtin_tool_enabled('visualizations', False): + builtin_functions.append(render_visualization) + # Time utilities - available for date calculations if is_builtin_tool_enabled('time'): builtin_functions.extend([get_current_timestamp, calculate_timestamp]) diff --git a/src/lib/components/chat/Messages/StructuredOutputRenderer.svelte b/src/lib/components/chat/Messages/StructuredOutputRenderer.svelte index 498bdad42b..f1e05bd915 100644 --- a/src/lib/components/chat/Messages/StructuredOutputRenderer.svelte +++ b/src/lib/components/chat/Messages/StructuredOutputRenderer.svelte @@ -5,6 +5,7 @@ import Image from '$lib/components/common/Image.svelte'; import ToolCallDisplay from '$lib/components/common/ToolCallDisplay.svelte'; import ToolOutputFile from './ToolOutputFile.svelte'; + import VisualizationToolCall from './VisualizationToolCall.svelte'; import { resolveChatMessageToolCall } from '$lib/apis/chats'; import { settings } from '$lib/stores'; import { toast } from 'svelte-sonner'; @@ -132,6 +133,20 @@ {displayItem.text} {/if} + {:else if displayItem.type === 'visualization'} + + resolveToolCall(displayItem.call.call_id ?? displayItem.call.id ?? '', approved)} + /> {:else if displayItem.type === 'image'} {$i18n.t('Generated {:else if displayItem.type === 'detail_group'} diff --git a/src/lib/components/chat/Messages/VisualizationToolCall.svelte b/src/lib/components/chat/Messages/VisualizationToolCall.svelte new file mode 100644 index 0000000000..8179c6e24c --- /dev/null +++ b/src/lib/components/chat/Messages/VisualizationToolCall.svelte @@ -0,0 +1,326 @@ + + +
+
{title}
+ {#if needsToolDetails} +
+ +
+ {/if} + {#if enabled} + {#key `${chatId}:${messageId}:${frameRevision}`} + + {/key} + {/if} + + {#if runtimeError || decoded.malformed} +

+ {runtimeError || $i18n.t('Visualization arguments are incomplete or invalid.')} +

+ {:else if enabled && !initialized} +

+ {messageDone && !accepted + ? $i18n.t('Visualization incomplete.') + : accepted + ? $i18n.t('Preparing visualization…') + : $i18n.t('Drawing preview…')} +

+ {:else if enabled && !execute} +

{$i18n.t('Interactive scripts are disabled.')}

+ {/if} +
+ +{#if showConfirmation} + confirmCall?.(true)} + on:cancel={() => confirmCall?.(false)} + > +
{confirmationText}
+
+{/if} diff --git a/src/lib/components/chat/Messages/structuredOutput.ts b/src/lib/components/chat/Messages/structuredOutput.ts index e361b9b994..1d864fcc16 100644 --- a/src/lib/components/chat/Messages/structuredOutput.ts +++ b/src/lib/components/chat/Messages/structuredOutput.ts @@ -1,4 +1,5 @@ import { encode } from 'html-entities'; +import { getDispatchedVisualizationPreviews } from '$lib/utils/visualizations/dispatch'; export type OutputContentPart = { type?: string; @@ -15,6 +16,9 @@ export type OutputItem = { display_labels?: { running?: string; completed?: string }; status?: string; hidden?: boolean; + tool_id?: string; + tool_type?: string; + tool_targets?: Record; arguments?: unknown; content?: OutputContentPart[]; summary?: OutputContentPart[] | string; @@ -50,6 +54,7 @@ export type OutputDetailToken = { }; export type OutputDisplayItem = + | { type: 'visualization'; id: string; call: OutputItem; result?: OutputItem } | { type: 'message'; id: string; @@ -152,7 +157,7 @@ function getReasoningText(item: OutputItem): string { return getTextFromParts(summary ?? item.content ?? []); } -function getToolResultText(item?: OutputItem): string { +export function getToolResultText(item?: OutputItem): string { return (item?.output ?? []) .filter((part) => part?.type !== 'input_image') .map((part) => { @@ -209,7 +214,10 @@ function getInlineFileFromToolOutput(callItem?: OutputItem, resultItem?: OutputI : result; } -function buildToolCallToken(item: OutputItem, toolOutputByCallId: Record) { +export function buildToolCallToken( + item: OutputItem, + toolOutputByCallId: Record +) { const callId = item.call_id ?? item.id ?? ''; const resultItem = toolOutputByCallId[callId]; const status = String(item.status ?? ''); @@ -412,6 +420,11 @@ export function buildOutputDisplayItems(output: OutputItem[] = []): OutputDispla return; } + for (const call of getDispatchedVisualizationPreviews(item)) { + flushDetails(); + displayItems.push({ type: 'visualization', id: `visualization:${call.call_id}`, call }); + } + if (isHiddenToolCall(item)) { return; } @@ -439,6 +452,23 @@ export function buildOutputDisplayItems(output: OutputItem[] = []): OutputDispla return; } + if ( + item.type === 'function_call' && + item.tool_type === 'builtin' && + item.tool_id === 'builtin:render_visualization' && + (item.call_id || item.id) + ) { + flushDetails(); + const callId = item.call_id ?? item.id!; + displayItems.push({ + type: 'visualization', + id: `visualization:${callId}`, + call: item, + result: toolOutputByCallId[callId] + }); + return; + } + if (item.type && GROUPABLE_OUTPUT_TYPES.has(item.type)) { const token = buildDetailToken(item, index === output.length - 1, toolOutputByCallId); if (token) { diff --git a/src/lib/components/workspace/Models/BuiltinTools.svelte b/src/lib/components/workspace/Models/BuiltinTools.svelte index ad0d833d5a..8b9797f180 100644 --- a/src/lib/components/workspace/Models/BuiltinTools.svelte +++ b/src/lib/components/workspace/Models/BuiltinTools.svelte @@ -10,6 +10,10 @@ let toolLabels; $: toolLabels = { + visualizations: { + label: $i18n.t('settings.admin.models.builtinTools.visualizations.label'), + description: $i18n.t('settings.admin.models.builtinTools.visualizations.description') + }, time: { label: $i18n.t('settings.admin.models.builtinTools.time.label'), description: $i18n.t('settings.admin.models.builtinTools.time.description') @@ -107,11 +111,13 @@ export let builtinTools: Record = {}; export let capabilities: Record = {}; export let disabled = false; - $: enabledTools = allTools.filter((key) => builtinTools[key] !== false); + $: enabledTools = allTools.filter((key) => builtinTools[key] ?? key !== 'visualizations'); const setBuiltinTool = (tool: keyof typeof toolLabels, checked: boolean) => { builtinTools = { ...builtinTools }; - if (checked) { + if (tool === 'visualizations') { + builtinTools[tool] = checked; + } else if (checked) { delete builtinTools[tool]; } else { builtinTools[tool] = false; @@ -153,7 +159,7 @@ setBuiltinTool(key, e.detail)} /> diff --git a/src/lib/i18n/locales/en-US/translation.json b/src/lib/i18n/locales/en-US/translation.json index eb6e90f742..983ea65c61 100644 --- a/src/lib/i18n/locales/en-US/translation.json +++ b/src/lib/i18n/locales/en-US/translation.json @@ -1,4 +1,14 @@ { + "Interactive scripts are disabled.": "Interactive scripts are disabled.", + "Drawing preview…": "Drawing preview…", + "Preparing visualization…": "Preparing visualization…", + "Visualization incomplete.": "Visualization incomplete.", + "Visualization arguments are incomplete or invalid.": "Visualization arguments are incomplete or invalid.", + "Visualization stopped after navigation.": "Visualization stopped after navigation.", + "Visualization could not start.": "Visualization could not start.", + "Visualization": "Visualization", + "settings.admin.models.builtinTools.visualizations.label": "Visualizations", + "settings.admin.models.builtinTools.visualizations.description": "Render interactive diagrams, charts, and explainers inside chat", "- usage not recorded": "- usage not recorded", "- usage not recorded · * partial usage": "- usage not recorded · * partial usage", "-1 for no limit, or a positive integer for a specific limit": "", diff --git a/src/lib/utils/ui-visibility.ts b/src/lib/utils/ui-visibility.ts index e01203ce60..b8702ee4cb 100644 --- a/src/lib/utils/ui-visibility.ts +++ b/src/lib/utils/ui-visibility.ts @@ -37,6 +37,7 @@ export const CONTROL_LABELS = { 'model_editor.tools.automations': 'settings.admin.models.builtinTools.automations.label', 'model_editor.tools.calendar': 'settings.admin.models.builtinTools.calendar.label', 'model_editor.tools.subagents': 'settings.admin.models.builtinTools.subagents.label', + 'model_editor.tools.visualizations': 'settings.admin.models.builtinTools.visualizations.label', 'model_editor.tools.skills': 'settings.admin.models.builtinTools.skills.label', 'model_editor.tools.tools': 'settings.admin.models.builtinTools.tools.label', 'chat.capture': 'Capture', diff --git a/src/lib/utils/visualizations/arguments.ts b/src/lib/utils/visualizations/arguments.ts new file mode 100644 index 0000000000..af4d4c3d92 --- /dev/null +++ b/src/lib/utils/visualizations/arguments.ts @@ -0,0 +1,223 @@ +export const MAX_HTML_BYTES = 256 * 1024; +const MAX_ARGUMENT_CHARS = 2 * 1024 * 1024; + +export type VisualizationArguments = { + title: string; + html: string; + libraries?: Array<'chartjs'>; +}; + +export function parseVisualizationArguments(raw: unknown): VisualizationArguments | null { + try { + const value = typeof raw === 'string' ? JSON.parse(raw) : raw; + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const { title, html, libraries } = value; + if (typeof title !== 'string' || !title.trim() || [...title.trim()].length > 160) return null; + if ( + typeof html !== 'string' || + !html.trim() || + new TextEncoder().encode(html).length > MAX_HTML_BYTES + ) + return null; + if ( + libraries != null && + (!Array.isArray(libraries) || libraries.length > 1 || libraries.some((l) => l !== 'chartjs')) + ) + return null; + return { title, html, libraries: libraries ?? [] }; + } catch { + return null; + } +} + +// Only root string values are exposed. Incomplete JSON is never repaired or executed. +export function createStringFieldDecoder(names: readonly string[], partialNames = names) { + let previous = '', + cursor = 0, + key = '', + value = ''; + let stack: string[] = []; + let stage: 'key' | 'colon' | 'value' | 'comma' = 'key'; + let stringRole: 'key' | 'value' | 'skip' | null = null; + let started = false, + ended = false, + malformed = false; + let fields: Record = {}; + let keys = new Set(); + const reset = () => { + previous = ''; + cursor = 0; + key = ''; + value = ''; + stack = []; + stage = 'key'; + stringRole = null; + started = false; + ended = false; + malformed = false; + fields = {}; + keys = new Set(); + }; + return { + reset, + update(snapshot: string) { + if (!snapshot.startsWith(previous)) reset(); + previous = snapshot; + if (snapshot.length > MAX_ARGUMENT_CHARS) malformed = true; + while (cursor < snapshot.length && !malformed) { + const c = snapshot[cursor]; + if (stringRole) { + if (c === '"') { + if (stringRole === 'key') { + key = value; + if (keys.has(key)) { + malformed = true; + break; + } + keys.add(key); + stage = 'colon'; + } else if (stringRole === 'value') { + if (names.includes(key)) fields[key] = value; + stage = 'comma'; + } + stringRole = null; + cursor++; + continue; + } + if (c.charCodeAt(0) < 32) { + malformed = true; + break; + } + let decoded = c; + if (c === '\\') { + if (cursor + 1 >= snapshot.length) break; + const escape = snapshot[cursor + 1]; + if (escape === 'u') { + if (cursor + 6 > snapshot.length) break; + const hex = snapshot.slice(cursor + 2, cursor + 6); + if (!/^[\da-f]{4}$/i.test(hex)) { + malformed = true; + break; + } + decoded = String.fromCharCode(parseInt(hex, 16)); + cursor += 6; + } else { + const escapes: Record = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + }; + if (!(escape in escapes)) { + malformed = true; + break; + } + decoded = escapes[escape]; + cursor += 2; + } + } else cursor++; + if (stringRole !== 'skip') value += decoded; + continue; + } + if (/\s/.test(c)) { + cursor++; + continue; + } + if (ended) { + malformed = true; + break; + } + if (!started) { + if (c !== '{') { + malformed = true; + break; + } + started = true; + stack.push(c); + cursor++; + continue; + } + if (c === '"') { + stringRole = + stack.length === 1 + ? stage === 'key' + ? 'key' + : stage === 'value' + ? 'value' + : null + : 'skip'; + if (!stringRole) { + malformed = true; + break; + } + value = ''; + cursor++; + continue; + } + if (stack.length === 1) { + if (c === ':' && stage === 'colon') { + stage = 'value'; + cursor++; + continue; + } + if (c === ',' && stage === 'comma') { + stage = 'key'; + cursor++; + continue; + } + if (c === '}' && (stage === 'comma' || stage === 'key')) { + stack.pop(); + ended = true; + cursor++; + continue; + } + if (stage !== 'value' || names.includes(key)) { + malformed = true; + break; + } + if (c !== '[' && c !== '{') { + const match = /^(?:true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?=\s*[,}])/.exec( + snapshot.slice(cursor) + ); + if (!match) break; + cursor += match[0].length; + stage = 'comma'; + continue; + } + stage = 'comma'; + } + if (c === '[' || c === '{') stack.push(c); + else if (c === ']' || c === '}') { + if (stack.pop() !== (c === ']' ? '[' : '{')) { + malformed = true; + break; + } + } + cursor++; + } + const partial = + stringRole === 'value' && partialNames.includes(key) + ? { [key]: value.replace(/[\uD800-\uDBFF]$/, '') } + : {}; + const current = { ...fields, ...partial }; + return { values: current, malformed }; + } + }; +} + +export function createVisualizationArgumentDecoder() { + const decoder = createStringFieldDecoder(['title', 'html']); + return { + reset: decoder.reset, + update(snapshot: string) { + const { values, malformed } = decoder.update(snapshot); + const html = values.html ?? ''; + const invalid = malformed || new TextEncoder().encode(html).length > MAX_HTML_BYTES; + return { title: values.title, html: invalid ? '' : html, malformed: invalid }; + } + }; +} diff --git a/src/lib/utils/visualizations/dispatch.ts b/src/lib/utils/visualizations/dispatch.ts new file mode 100644 index 0000000000..d378b8e751 --- /dev/null +++ b/src/lib/utils/visualizations/dispatch.ts @@ -0,0 +1,75 @@ +import { createStringFieldDecoder } from './arguments'; +import type { OutputItem } from '$lib/components/chat/Messages/structuredOutput'; + +// Slice complete or still-streaming members without interpreting braces inside JSON strings. +function* callEntries(source: string): Generator { + const batch = /^\s*\{\s*"calls"\s*:\s*\[/.exec(source); + if (!batch) { + yield source; // Original single-call dispatcher format. + return; + } + let start = -1, + depth = 0, + quoted = false; + for (let index = batch[0].length; index < source.length; index++) { + const char = source[index]; + if (quoted) { + if (char === '\\') index++; + else if (char === '"') quoted = false; + continue; + } + if (char === '"') quoted = true; + else if (char === '{') { + if (depth++ === 0) start = index; + } else if (char === '}') { + if (--depth === 0) { + yield source.slice(start, index + 1); + start = -1; + } + if (depth < 0) return; + } else if (depth === 0 && !/[\s,]/.test(char)) return; + } + if (start !== -1) yield source.slice(start); +} + +export function getDispatchedVisualizationPreviews(item: OutputItem): OutputItem[] { + const callId = item.call_id ?? item.id; + if ( + item.type !== 'function_call' || + item.tool_type !== 'builtin' || + item.tool_id !== 'builtin:call_tool' || + !callId || + !item.tool_targets + ) + return []; + const source = + typeof item.arguments === 'string' ? item.arguments : JSON.stringify(item.arguments ?? {}); + const previews: OutputItem[] = []; + let index = 0; + for (const entry of callEntries(source)) { + const { values, malformed } = createStringFieldDecoder( + ['tool_name', 'params'], + ['params'] + ).update(entry); + const id = index === 0 ? callId : `${callId}:${index}`; + index++; + const target = item.tool_targets[values.tool_name]; + if ( + malformed || + target?.tool_type !== 'builtin' || + target.tool_id !== 'builtin:render_visualization' || + typeof values.params !== 'string' + ) + continue; + previews.push({ + type: 'function_call', + id, + call_id: id, + name: values.tool_name, + ...target, + arguments: values.params, + status: item.status === 'completed' ? 'in_progress' : item.status + }); + } + return previews; +} diff --git a/src/lib/utils/visualizations/frame.ts b/src/lib/utils/visualizations/frame.ts new file mode 100644 index 0000000000..467132ca3d --- /dev/null +++ b/src/lib/utils/visualizations/frame.ts @@ -0,0 +1,40 @@ +import { base } from '$app/paths'; +import { injectCsp } from '$lib/utils/csp'; +import { findSafeCut } from './safeCut'; +import { visualizationRuntime } from './runtime'; + +export const VISUALIZATION_CSP = + "default-src 'none'; script-src 'unsafe-inline'; script-src-attr 'none'; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'none'; font-src 'none'; media-src 'none'; frame-src 'none'; object-src 'none'; worker-src 'none'; base-uri 'none'; form-action 'none'"; + +const styles = ` +:root{color-scheme:light;--owui-background:#fff;--owui-surface:#f5f5f5;--owui-text:#171717;--owui-muted:#737373;--owui-border:#e5e5e5;--owui-accent:#2563eb;font:calc(1rem * var(--owui-text-scale,1))/1.4 system-ui,sans-serif;color:var(--owui-text);background:var(--owui-background)} +:root[data-theme=dark]{color-scheme:dark;--owui-background:#171717;--owui-surface:#262626;--owui-text:#f5f5f5;--owui-muted:#a3a3a3;--owui-border:#404040;--owui-accent:#60a5fa} +*{box-sizing:border-box}h1,h2,h3,h4,h5,h6,strong,b,th{font-weight:500}h1,h2,h3,h4,h5,h6,p,ul,ol,figure{margin:0.25rem 0}ul,ol{padding-inline-start:1.25rem}body{margin:0;padding:0;font-size:0.90625rem}#visualization-root{display:flow-root;min-width:0}svg{max-width:100%;height:auto}button,input,select,textarea{font:inherit;color:inherit}button,input,select,textarea,summary{accent-color:var(--owui-accent)}button,input,select,textarea{border:0.0625rem solid var(--owui-border);border-radius:0.375rem;padding:0.1875rem 0.375rem;background:var(--owui-surface)}button,summary{cursor:pointer}button:hover{filter:brightness(.95)}label{display:block;margin:0.25rem 0}input[type=range]{width:100%;padding:0}table{border-collapse:collapse;width:100%}th,td{text-align:start;border-bottom:0.0625rem solid var(--owui-border);padding:0.25rem 0.375rem}details{padding:0.25rem 0}:focus-visible{outline:0.125rem solid var(--owui-accent);outline-offset:0.1875rem}.chart-container{position:relative;width:100%;min-width:0;height:15rem}:root[data-reduced-motion=true] *{animation:none!important;transition:none!important} +`; + +export function visualizationDocument(additionalCsp = '') { + // Only trusted code is serialized here; generated content travels over the port. + const code = `(${visualizationRuntime.toString()})(${findSafeCut.toString()});`; + const safeCode = code.replace(/<\/script/gi, '<\\/script'); + let html = `
`; + html = injectCsp(html, VISUALIZATION_CSP); + return additionalCsp ? injectCsp(html, additionalCsp) : html; +} + +const sources = new Map>(); +export function getVisualizationVendor(name: 'purifier' | 'chartjs') { + const file = name === 'purifier' ? 'purify.min.js' : 'chart.umd.min.js'; + if (!sources.has(file)) { + const promise = fetch(`${base}/visualizations/${file}`) + .then(async (response) => { + if (!response.ok) throw new Error('Visualization library could not load.'); + return response.text(); + }) + .catch((error) => { + sources.delete(file); + throw error; + }); + sources.set(file, promise); + } + return sources.get(file)!; +} diff --git a/src/lib/utils/visualizations/runtime.ts b/src/lib/utils/visualizations/runtime.ts new file mode 100644 index 0000000000..9dd6b28cf5 --- /dev/null +++ b/src/lib/utils/visualizations/runtime.ts @@ -0,0 +1,267 @@ +// This function is serialized into the opaque iframe. Keep it independent of module globals. +export function visualizationRuntime(safeCut: (source: string) => number) { + type Context = { + theme: string; + language: string; + direction: string; + reducedMotion: boolean; + textScale: string; + }; + const win = window as typeof window & { + DOMPurify: { sanitize: (source: string, options: object) => DocumentFragment }; + Chart?: { + defaults: { color: () => string; borderColor: () => string }; + instances: Record void }>; + }; + openwebui: { + context: Context; + sendMessage: (text: string) => Promise<{ sent: boolean }>; + }; + }; + const root = document.getElementById('visualization-root')!; + let port: MessagePort | undefined; + let initialized = false, + initializing = false, + prepared = false; + let heightFrame = 0, + lastHeight = 0, + requestSequence = 0; + const requests = new Map void>(); + const send = (data: object) => port?.postMessage(data); + const fail = (message: string) => send({ type: 'error', message: String(message).slice(0, 500) }); + + function appendScript(source: string, placeholder?: Element) { + const script = document.createElement('script'); + script.textContent = source; + if (placeholder) placeholder.replaceWith(script); + else document.head.append(script); + } + + function contextChanged(context: Context) { + win.openwebui.context = Object.freeze({ ...context }); + document.documentElement.dataset.theme = context.theme; + document.documentElement.style.setProperty('--owui-text-scale', context.textScale); + document.documentElement.lang = context.language; + document.documentElement.dir = context.direction; + document.documentElement.dataset.reducedMotion = String(context.reducedMotion); + if (win.Chart) { + // Chart.js copies scale defaults at construction; callbacks keep those copies theme-aware. + win.Chart.defaults.color = () => + getComputedStyle(document.documentElement).getPropertyValue('--owui-muted').trim(); + win.Chart.defaults.borderColor = () => + getComputedStyle(document.documentElement).getPropertyValue('--owui-border').trim(); + for (const chart of Object.values(win.Chart.instances)) chart.update('none'); + } + window.dispatchEvent( + new CustomEvent('openwebui:contextchange', { detail: win.openwebui.context }) + ); + } + + win.openwebui = { + context: { + theme: 'light', + language: 'en', + direction: 'ltr', + reducedMotion: false, + textScale: '1' + }, + sendMessage(text) { + if ( + !initialized || + requests.size || + typeof text !== 'string' || + !text.trim() || + text.length > 16000 + ) { + return Promise.resolve({ sent: false }); + } + const requestId = String(++requestSequence); + return new Promise((resolve) => { + requests.set(requestId, resolve); + send({ type: 'send-message', requestId, text }); + }); + } + }; + + function scheduleHeight() { + if (heightFrame) return; + heightFrame = requestAnimationFrame(() => { + heightFrame = 0; + let bottom = Math.max(root.getBoundingClientRect().bottom, root.scrollHeight); + for (const svg of root.querySelectorAll('svg')) { + try { + const box = svg.getBBox(); + const matrix = svg.getScreenCTM(); + if (matrix) + bottom = Math.max( + bottom, + new DOMPoint(box.x + box.width, box.y + box.height).matrixTransform(matrix).y + ); + } catch { + /* Hidden SVGs have no bounding box. */ + } + } + const height = Math.ceil(bottom + window.scrollY); + if (height !== lastHeight && Number.isFinite(height)) { + lastHeight = height; + send({ type: 'height', value: height }); + } + }); + } + + function prepare(source: string, final: boolean) { + const doc = new DOMParser().parseFromString(source, 'text/html'); + const scripts: string[] = []; + // Only placeholders created here may select executable source. + for (const node of doc.querySelectorAll('[data-owui-script]')) + node.removeAttribute('data-owui-script'); + for (const script of doc.querySelectorAll('script')) { + if (final) { + const type = (script.getAttribute('type') ?? '').trim().toLowerCase(); + if ( + script.hasAttribute('src') || + script.hasAttribute('href') || + script.hasAttribute('xlink:href') || + !['', 'text/javascript', 'application/javascript'].includes(type) + ) { + throw new Error('Use classic inline scripts and bundled libraries only.'); + } + const placeholder = doc.createElement('template'); + placeholder.dataset.owuiScript = String(scripts.length); + scripts.push(script.textContent ?? ''); + script.replaceWith(placeholder); + } else script.remove(); + } + const head = Array.from( + doc.head.querySelectorAll('style, template[data-owui-script]'), + (node) => node.outerHTML + ).join(''); + const fragment = win.DOMPurify.sanitize(head + doc.body.innerHTML, { + RETURN_DOM_FRAGMENT: true, + FORCE_BODY: true, // Retain leading styles and script placeholders in the fragment. + USE_PROFILES: { html: true, svg: true, svgFilters: true }, + ADD_TAGS: ['style'], + FORBID_TAGS: [ + 'script', + 'iframe', + 'object', + 'embed', + 'base', + 'meta', + 'link', + 'form', + 'foreignObject' + ], + FORBID_ATTR: ['srcdoc', 'autofocus', 'target', 'download'] + }); + // Navigation is not a capability of the generated fragment. + for (const anchor of fragment.querySelectorAll('a')) { + anchor.removeAttribute('href'); + anchor.removeAttribute('xlink:href'); + } + return { fragment, scripts }; + } + + function reconcile(existing: Node, incoming: Node) { + const wanted = Array.from(incoming.childNodes); + for (let index = 0; index < wanted.length; index++) { + const next = wanted[index]; + const old = existing.childNodes[index]; + if (!old) { + existing.appendChild(next.cloneNode(true)); + continue; + } + if ( + old.nodeType !== next.nodeType || + old.nodeName !== next.nodeName || + (old instanceof Element && + next instanceof Element && + (old.namespaceURI !== next.namespaceURI || old.id !== next.id)) + ) { + existing.replaceChild(next.cloneNode(true), old); + continue; + } + if (old.nodeType === Node.TEXT_NODE || old.nodeType === Node.COMMENT_NODE) { + if (old.nodeValue !== next.nodeValue) old.nodeValue = next.nodeValue; + } else if (old instanceof Element && next instanceof Element) { + for (const attr of Array.from(old.attributes)) + if (!next.hasAttributeNS(attr.namespaceURI, attr.localName)) + old.removeAttributeNS(attr.namespaceURI, attr.localName); + for (const attr of Array.from(next.attributes)) + if (old.getAttributeNS(attr.namespaceURI, attr.localName) !== attr.value) + old.setAttributeNS(attr.namespaceURI, attr.name, attr.value); + reconcile(old, next); + } + } + while (existing.childNodes.length > wanted.length) existing.lastChild?.remove(); + } + + function receive(event: MessageEvent) { + const data = event.data; + try { + if (data?.type === 'init' && !prepared) { + appendScript(data.purifierSource); + if (!win.DOMPurify) throw new Error('Visualization sanitizer could not load.'); + prepared = true; + contextChanged(data.context); + send({ type: 'ready' }); + } else if (data?.type === 'context' && prepared) { + contextChanged(data.context); + } else if (data?.type === 'preview' && prepared && !initialized && !initializing) { + const { fragment } = prepare(data.html.slice(0, safeCut(data.html)), false); + reconcile(root, fragment); + scheduleHeight(); + } else if (data?.type === 'finalize' && prepared && !initialized && !initializing) { + initializing = true; + const { fragment, scripts } = prepare(data.html, true); + reconcile(root, fragment); + if (data.executeScripts) { + if (data.chartSource) { + appendScript(data.chartSource); + if (!win.Chart) throw new Error('Chart.js could not load.'); + contextChanged(win.openwebui.context); + } + // Set before running user code so its callbacks can use the bridge. + initialized = true; + root.inert = false; + // Keep currentScript and sibling/container lookups consistent with the authored HTML. + for (const placeholder of root.querySelectorAll( + 'template[data-owui-script]' + )) { + appendScript(scripts[Number(placeholder.dataset.owuiScript)], placeholder); + } + } + initialized = true; + initializing = false; + send({ type: 'initialized' }); + scheduleHeight(); + } else if (data?.type === 'send-message-result') { + requests.get(data.requestId)?.({ sent: data.sent === true }); + requests.delete(data.requestId); + } + } catch (error) { + initializing = false; + fail(error instanceof Error ? error.message : 'Visualization failed.'); + } + } + + function connect(event: MessageEvent) { + if ( + event.source !== parent || + event.data?.type !== 'visualization:connect' || + !event.ports[0] || + port + ) + return; + port = event.ports[0]; + port.onmessage = receive; + window.removeEventListener('message', connect); + } + window.addEventListener('message', connect); + window.addEventListener('error', (event) => fail(event.message)); + window.addEventListener('unhandledrejection', (event) => fail(String(event.reason))); + new ResizeObserver(scheduleHeight).observe(root); + document.addEventListener('toggle', scheduleHeight, true); + window.addEventListener('resize', scheduleHeight); + parent.postMessage({ type: 'visualization:connect-ready' }, '*'); +} diff --git a/src/lib/utils/visualizations/safeCut.ts b/src/lib/utils/visualizations/safeCut.ts new file mode 100644 index 0000000000..2fa49f7e95 --- /dev/null +++ b/src/lib/utils/visualizations/safeCut.ts @@ -0,0 +1,42 @@ +// Buffer incomplete markup rather than asking the browser to repair partial attributes or CSS. +export function findSafeCut(source: string): number { + let cursor = 0, + safe = 0; + while (cursor < source.length) { + if (source[cursor] === '&') { + const tail = source.slice(cursor); + if (/^&(?:#[xX]?[\da-f]*|[a-z\d]*)$/i.test(tail)) break; + } + if (source[cursor] !== '<') { + safe = ++cursor; + continue; + } + if (source.startsWith('', cursor + (cdata ? 9 : 4)); + if (end < 0) break; + cursor = safe = end + 3; + continue; + } + let end = cursor + 1, + quote = ''; + for (; end < source.length; end++) { + const c = source[end]; + if (quote) { + if (c === quote) quote = ''; + } else if (c === '"' || c === "'") quote = c; + else if (c === '>') break; + } + if (end === source.length) break; + const tag = /^<\s*(script|style|textarea|title)(?=[\s/>])/i.exec(source.slice(cursor, end + 1)); + if (tag) { + const close = new RegExp('', 'gi'); + close.lastIndex = end + 1; + const match = close.exec(source); + if (!match) break; + end = match.index + match[0].length - 1; + } + cursor = safe = end + 1; + } + return safe; +} diff --git a/vite.config.ts b/vite.config.ts index 2d57e48e68..fc520821d0 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -15,6 +15,10 @@ export default defineConfig({ sveltekit(), viteStaticCopy({ targets: [ + { src: 'node_modules/chart.js/dist/chart.umd.min.js', dest: 'visualizations' }, + { src: 'node_modules/dompurify/dist/purify.min.js', dest: 'visualizations' }, + { src: 'node_modules/chart.js/LICENSE.md', dest: 'licenses/visualizations/chartjs' }, + { src: 'node_modules/dompurify/LICENSE', dest: 'licenses/visualizations/dompurify' }, { src: 'src/lib/encryption/vendor/THIRD_PARTY_LICENSES.txt', dest: 'licenses/encryption'