This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-11 15:34:33 +09:00
1 parent 3f26c03330
commit e46920dcc7
18 files changed
+1146 -12

No files matched your search

+1
View File
@@ -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
@@ -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'}
+16 -3
View File
@@ -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'
+17 -3
View File
@@ -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
+1 -1
View File
@@ -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']},
}
+4
View File
@@ -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])
@@ -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}
</div>
{/if}
{:else if displayItem.type === 'visualization'}
<VisualizationToolCall
call={displayItem.call}
result={displayItem.result}
{chatId}
{messageId}
messageDone={done}
{allowEmbeds}
{compactPreview}
resolvable={!!chatId && !!messageId && (save || allowToolApproval)}
resolving={resolvingCallId === (displayItem.call.call_id ?? displayItem.call.id)}
onResolve={(approved) =>
resolveToolCall(displayItem.call.call_id ?? displayItem.call.id ?? '', approved)}
/>
{:else if displayItem.type === 'image'}
<Image src={displayItem.src} alt={$i18n.t('Generated Image')} />
{:else if displayItem.type === 'detail_group'}
@@ -0,0 +1,326 @@
<script lang="ts">
import { getContext, onDestroy } from 'svelte';
import { get } from 'svelte/store';
import { chatId as activeChatId, config, settings } from '$lib/stores';
import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
import ToolCallDisplay from '$lib/components/common/ToolCallDisplay.svelte';
import { buildToolCallToken, getToolResultText, type OutputItem } from './structuredOutput';
import {
createVisualizationArgumentDecoder,
parseVisualizationArguments,
type VisualizationArguments
} from '$lib/utils/visualizations/arguments';
import { getVisualizationVendor, visualizationDocument } from '$lib/utils/visualizations/frame';
export let call: OutputItem;
export let result: OutputItem | undefined = undefined;
export let chatId = '';
export let messageId = '';
export let messageDone = false;
export let allowEmbeds = false;
export let compactPreview = false;
export let resolvable = false;
export let resolving = false;
export let onResolve: (approved: boolean) => void = () => {};
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
const decoder = createVisualizationArgumentDecoder();
let ready = false,
initialized = false;
let runtimeError = '',
frameRevision = 0,
generation = 0,
submittedKey = '';
let port: MessagePort | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
let latest: {
source: string;
args: VisualizationArguments | null;
accepted: boolean;
execute: boolean;
};
let confirmationText = '',
showConfirmation = false;
let confirmCall: ((accept: boolean) => void) | undefined;
function acceptedResult(item: OutputItem | undefined) {
try {
return (
item?.status === 'completed' && JSON.parse(getToolResultText(item)).status === 'accepted'
);
} catch {
return false;
}
}
$: raw =
typeof call.arguments === 'string' ? call.arguments : JSON.stringify(call.arguments ?? {});
$: decoded = decoder.update(raw);
$: args = parseVisualizationArguments(call.arguments);
$: source = args?.html ?? decoded.html;
$: accepted = acceptedResult(result);
$: enabled = allowEmbeds && !compactPreview;
$: execute = $settings?.iframeSandboxAllowScripts ?? true;
$: finalKey = accepted && args ? JSON.stringify([args.html, args.libraries, execute]) : '';
$: if (submittedKey && submittedKey !== finalKey) {
submittedKey = '';
frameRevision++;
}
$: token = buildToolCallToken(call, result ? { [call.call_id ?? call.id ?? '']: result } : {});
$: needsToolDetails =
['pending', 'queued', 'requires_approval', 'failed', 'rejected', 'incomplete'].includes(
call.status ?? ''
) || result?.status === 'failed';
$: title = args?.title ?? decoded.title ?? $i18n.t('Visualization');
$: srcdoc = visualizationDocument($config?.ui?.iframe_csp ?? '');
$: queue(source, args, accepted, execute, ready);
$: if (ready) sendContext($i18n.language);
function context(language = $i18n.language) {
return {
theme: document.documentElement.classList.contains('dark') ? 'dark' : 'light',
textScale:
getComputedStyle(document.documentElement).getPropertyValue('--app-text-scale').trim() ||
'1',
language: language || document.documentElement.lang || navigator.language,
direction: $i18n.dir?.() ?? document.documentElement.dir ?? 'ltr',
reducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches
};
}
function sendContext(language?: string) {
port?.postMessage({ type: 'context', context: context(language) });
}
function queue(
source: string,
args: VisualizationArguments | null,
accepted: boolean,
execute: boolean,
ready: boolean
) {
latest = { source, args, accepted, execute };
if (!ready) return;
if (accepted && args) {
clearTimeout(timer);
timer = undefined;
void flush();
} else if (!timer) {
timer = setTimeout(() => {
timer = undefined;
void flush();
}, 100);
}
}
async function flush() {
if (!ready || !port || !latest) return;
const current = generation;
const channel = port;
const { source, args, accepted, execute } = latest;
if (!accepted || !args) {
channel.postMessage({ type: 'preview', html: source });
return;
}
const key = JSON.stringify([args.html, args.libraries, execute]);
if (submittedKey === key) return;
submittedKey = key;
try {
const chartSource =
execute && args.libraries?.includes('chartjs')
? await getVisualizationVendor('chartjs')
: undefined;
if (generation !== current || submittedKey !== key) return;
channel.postMessage({
type: 'finalize',
html: args.html,
chartSource,
executeScripts: execute
});
} catch (error) {
if (generation === current) runtimeError = String(error);
}
}
function requestMessage(
data: { requestId: string; text: string },
channel: MessagePort,
current: number
) {
const reply = (sent: boolean) => {
if (generation === current)
channel.postMessage({ type: 'send-message-result', requestId: data.requestId, sent });
};
if (
!initialized ||
!execute ||
confirmCall ||
get(activeChatId) !== chatId ||
typeof data.requestId !== 'string' ||
data.requestId.length > 80 ||
typeof data.text !== 'string' ||
!data.text.trim() ||
data.text.length > 16000
) {
reply(false);
return;
}
confirmationText = data.text;
showConfirmation = true;
confirmCall = (accept) => {
showConfirmation = false;
confirmCall = undefined;
const sent = accept && current === generation && get(activeChatId) === chatId;
if (sent) window.postMessage({ type: 'input:prompt:submit', text: data.text }, window.origin);
reply(sent);
};
}
function mountFrame(node: HTMLIFrameElement) {
const current = ++generation;
ready = false;
initialized = false;
runtimeError = '';
submittedKey = '';
let connected = false,
loads = 0;
let reportedHeight = 1;
const resize = () => {
node.style.height = `${Math.max(1, reportedHeight)}px`;
};
const timeout = setTimeout(() => {
if (!ready && generation === current)
runtimeError = $i18n.t('Visualization could not start.');
}, 10000);
const receiveHandshake = async (event: MessageEvent) => {
if (
event.source !== node.contentWindow ||
event.data?.type !== 'visualization:connect-ready' ||
connected
)
return;
connected = true;
const channel = new MessageChannel();
port = channel.port1;
channel.port1.onmessage = (event) => {
if (generation !== current) return;
const data = event.data;
if (data?.type === 'ready') {
clearTimeout(timeout);
ready = true;
} else if (data?.type === 'initialized') initialized = true;
else if (
data?.type === 'height' &&
typeof data.value === 'number' &&
Number.isFinite(data.value)
) {
reportedHeight = data.value;
resize();
} else if (data?.type === 'error') runtimeError = String(data.message).slice(0, 500);
else if (data?.type === 'send-message') requestMessage(data, channel.port1, current);
};
node.contentWindow?.postMessage({ type: 'visualization:connect' }, '*', [channel.port2]);
try {
const purifierSource = await getVisualizationVendor('purifier');
if (generation === current)
channel.port1.postMessage({ type: 'init', purifierSource, context: context() });
} catch (error) {
if (generation === current) runtimeError = String(error);
}
};
const onLoad = () => {
if (++loads > 1) {
port?.close();
ready = false;
confirmCall?.(false);
runtimeError = $i18n.t('Visualization stopped after navigation.');
}
};
node.addEventListener('load', onLoad);
window.addEventListener('message', receiveHandshake);
const observer = new MutationObserver(() => sendContext());
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class', 'dir', 'lang', 'style']
});
const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
const onMotion = () => sendContext();
motion.addEventListener('change', onMotion);
const unsubscribe = activeChatId.subscribe((id) => {
if (id !== chatId) confirmCall?.(false);
});
resize();
return {
destroy() {
confirmCall?.(false);
generation++;
port?.close();
port = undefined;
ready = false;
initialized = false;
submittedKey = '';
clearTimeout(timeout);
clearTimeout(timer);
timer = undefined;
observer.disconnect();
unsubscribe();
motion.removeEventListener('change', onMotion);
node.removeEventListener('load', onLoad);
window.removeEventListener('message', receiveHandshake);
}
};
}
onDestroy(() => confirmCall?.(false));
</script>
<section class="my-1 min-w-0" aria-label={title} data-visualization-call={call.call_id ?? call.id}>
<div class="mb-0.5 text-xs font-medium">{title}</div>
{#if needsToolDetails}
<div>
<ToolCallDisplay
attributes={token.attributes}
resultContent={token.text}
{resolvable}
{resolving}
{onResolve}
/>
</div>
{/if}
{#if enabled}
{#key `${chatId}:${messageId}:${frameRevision}`}
<iframe
use:mountFrame
{srcdoc}
{title}
sandbox="allow-scripts"
referrerpolicy="no-referrer"
class="block w-full border-0"
></iframe>
{/key}
{/if}
{#if runtimeError || decoded.malformed}
<p role="status" class="mt-1 text-xs text-red-600 dark:text-red-400">
{runtimeError || $i18n.t('Visualization arguments are incomplete or invalid.')}
</p>
{:else if enabled && !initialized}
<p role="status" class="mt-1 text-xs text-gray-500">
{messageDone && !accepted
? $i18n.t('Visualization incomplete.')
: accepted
? $i18n.t('Preparing visualization…')
: $i18n.t('Drawing preview…')}
</p>
{:else if enabled && !execute}
<p class="mt-1 text-xs text-gray-500">{$i18n.t('Interactive scripts are disabled.')}</p>
{/if}
</section>
{#if showConfirmation}
<ConfirmDialog
bind:show={showConfirmation}
title={$i18n.t('Confirm Prompt from Embed')}
on:confirm={() => confirmCall?.(true)}
on:cancel={() => confirmCall?.(false)}
>
<div class="whitespace-pre-wrap">{confirmationText}</div>
</ConfirmDialog>
{/if}
@@ -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<string, { tool_id: string; tool_type: string }>;
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<string, OutputItem>) {
export function buildToolCallToken(
item: OutputItem,
toolOutputByCallId: Record<string, OutputItem>
) {
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) {
@@ -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<string, boolean> = {};
export let capabilities: Record<string, boolean> = {};
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 @@
<ModelSettingToggle
label={toolLabels[key].label}
description={toolLabels[key].description}
checked={builtinTools[key] !== false}
checked={builtinTools[key] ?? key !== 'visualizations'}
{disabled}
on:change={(e) => setBuiltinTool(key, e.detail)}
/>
@@ -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": "",
+1
View File
@@ -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',
+223
View File
@@ -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<string, string> = {};
let keys = new Set<string>();
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<string, string> = {
'"': '"',
'\\': '\\',
'/': '/',
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 };
}
};
}
+75
View File
@@ -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<string> {
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;
}
+40
View File
@@ -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 = `<!doctype html><html><head><meta charset="utf-8"><style>${styles}</style></head><body><main id="visualization-root" inert></main><script>${safeCode}</script></body></html>`;
html = injectCsp(html, VISUALIZATION_CSP);
return additionalCsp ? injectCsp(html, additionalCsp) : html;
}
const sources = new Map<string, Promise<string>>();
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)!;
}
+267
View File
@@ -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<string, { update: (mode: 'none') => 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<string, (value: { sent: boolean }) => 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<HTMLTemplateElement>(
'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' }, '*');
}
+42
View File
@@ -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) || source.startsWith('<![CDATA[', cursor)) {
const cdata = source.startsWith('<![CDATA[', cursor);
const end = source.indexOf(cdata ? ']]>' : '-->', 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('</' + tag[1] + '\\s*>', '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;
}
+4
View File
@@ -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'