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: stop later code spans changing whether an earlier one is escaped (#9028)

Daniel Han8b033a120b02
diff --git a/studio/frontend/src/lib/latex.ts b/studio/frontend/src/lib/latex.ts
index ccccccbbe43..0baf4f00f4d 100644
--- a/studio/frontend/src/lib/latex.ts
+++ b/studio/frontend/src/lib/latex.ts
@@ -19,41 +19,69 @@
const CURRENCY_REGEX =
/(?<![\\$])\$(?!\$)(?=\d+(?:,\d{3})*(?:\.\d+)?[KMBkmb]?(?:\s|$|[^a-zA-Z\d]))/g;
+/**
+ * Union of two span lists, each ascending by start (overlap within a list is
+ * fine, non-ascending input silently drops spans). The sorted, non-overlapping
+ * result is the shape `isInRegion`'s binary search needs.
+ */
+function mergeRegions(
+ left: ReadonlyArray<readonly [number, number]>,
+ right: ReadonlyArray<readonly [number, number]>,
+): Array<[number, number]> {
+ const merged: Array<[number, number]> = [];
+ let leftIndex = 0;
+ let rightIndex = 0;
+ while (leftIndex < left.length || rightIndex < right.length) {
+ const takeLeft =
+ rightIndex >= right.length ||
+ (leftIndex < left.length && left[leftIndex][0] <= right[rightIndex][0]);
+ const next = takeLeft ? left[leftIndex++] : right[rightIndex++];
+ const last = merged[merged.length - 1];
+ if (last && next[0] < last[1]) {
+ if (next[1] > last[1]) {
+ last[1] = next[1];
+ }
+ continue;
+ }
+ merged.push([next[0], next[1]]);
+ }
+ return merged;
+}
+
/**
* Find code-block regions (``` ... ```, ~~~ ... ~~~, and ` ... `) to skip.
- * Returns a sorted array of [start, end] index pairs.
+ * Returns a sorted, non-overlapping array of [start, end] index pairs.
*/
function findCodeBlockRegions(content: string): Array<[number, number]> {
- const regions: Array<[number, number]> = [];
-
// Fenced code blocks: ```...``` and ~~~...~~~ (both are code in GFM)
+ const fenced: Array<[number, number]> = [];
const fencedRe = /```[\s\S]*?```|~~~[\s\S]*?~~~/g;
let match: RegExpExecArray | null;
while ((match = fencedRe.exec(content)) !== null) {
- regions.push([match.index, match.index + match[0].length]);
+ fenced.push([match.index, match.index + match[0].length]);
}
// Inline code: `...`, skipped when inside a fenced block. Both loops yield
// ascending matches, so walk the fenced list with a cursor rather than
// rescanning it per match (was quadratic on code-heavy text).
- const fencedCount = regions.length;
+ const inline: Array<[number, number]> = [];
const inlineRe = /`[^`\n]+`/g;
let fencedIndex = 0;
while ((match = inlineRe.exec(content)) !== null) {
const start = match.index;
const end = start + match[0].length;
- while (fencedIndex < fencedCount && regions[fencedIndex][1] <= start) {
+ while (fencedIndex < fenced.length && fenced[fencedIndex][1] <= start) {
fencedIndex += 1;
}
- const fenced = fencedIndex < fencedCount ? regions[fencedIndex] : null;
- if (!(fenced && start >= fenced[0] && end <= fenced[1])) {
- regions.push([start, end]);
+ const block = fencedIndex < fenced.length ? fenced[fencedIndex] : null;
+ if (!(block && start >= block[0] && end <= block[1])) {
+ inline.push([start, end]);
}
}
- // Sort by start position for binary search.
- regions.sort((a, b) => a[0] - b[0]);
- return regions;
+ // An inline span can CONTAIN a fence (`` `~~~a~~~ $5` ``); that overlap made
+ // the binary search land on the inner span and miss the outer one.
+ return mergeRegions(fenced, inline);
}
/**
@@ -179,8 +207,8 @@ function hasInlineMathCloser(
offset: number,
mathRegions: Array<[number, number]>,
): boolean {
- const MAX_SPAN = 200;
- const limit = Math.min(content.length, offset + 1 + MAX_SPAN);
+ const maxSpan = 200;
+ const limit = Math.min(content.length, offset + 1 + maxSpan);
for (let i = offset + 1; i < limit; i++) {
const c = content[i];
if (c === "\n") return false;
diff --git a/studio/frontend/tests/latex-code-regions.test.ts b/studio/frontend/tests/latex-code-regions.test.ts
new file mode 100644
index 00000000000..e4987e35f09
--- /dev/null
+++ b/studio/frontend/tests/latex-code-regions.test.ts
@@ -0,0 +1,80 @@
+// 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 assert from "node:assert/strict";
+import test from "node:test";
+
+import { preprocessLaTeX } from "../src/lib/latex.ts";
+
+test("currency inside inline code survives unrelated later code spans", () => {
+ // An inline span containing a `~~~...~~~` pair used to yield overlapping
+ // spans, so the binary search hit the inner one and missed the outer.
+ const span = "`~~~a~~~ $5`";
+ assert.equal(preprocessLaTeX(span), span);
+
+ for (const trailer of [
+ "\n\n`x`",
+ "\n\n`x`\n\n`y`",
+ "\n\n`x`\n\n`y`\n\n`z`",
+ ]) {
+ assert.equal(
+ preprocessLaTeX(`${span}${trailer}`),
+ `${span}${trailer}`,
+ `currency inside inline code was rewritten by ${JSON.stringify(trailer)}`,
+ );
+ }
+});
+
+test("a code span's own text decides its escaping, whatever follows it", () => {
+ // Appending an unrelated code span must never change an earlier one.
+ const heads = [
+ "`~~~a~~~ $5`",
+ "`~~~ $5 ~~~`",
+ "`a ``` b $5`",
+ "`plain $5 here`",
+ "```\nfenced $5\n```",
+ "~~~\nfenced $5\n~~~",
+ "`~~~a~~~ \\(x\\)`",
+ ];
+ for (const head of heads) {
+ const alone = preprocessLaTeX(head);
+ for (let count = 1; count <= 4; count += 1) {
+ const trailer = "\n\n`t`".repeat(count);
+ assert.equal(
+ preprocessLaTeX(`${head}${trailer}`),
+ `${alone}${trailer}`,
+ `${JSON.stringify(head)} changed after ${count} trailing span(s)`,
+ );
+ }
+ }
+});
+
+test("LaTeX inside inline code stays literal whatever follows it", () => {
+ // The same lookup guards `convertLatexDelimiters`.
+ const span = "`~~~a~~~ \\(x\\)`";
+ assert.equal(preprocessLaTeX(span), span);
+ assert.equal(preprocessLaTeX(`${span}\n\n\`x\``), `${span}\n\n\`x\``);
+});
+
+test("ordinary code spans and fences are unchanged", () => {
+ // Nothing that was already non-overlapping may move.
+ const cases: [string, string][] = [
+ ["`costs $5`", "`costs $5`"],
+ ["`costs $5`\n\n`x`", "`costs $5`\n\n`x`"],
+ ["```\ncosts $5\n```", "```\ncosts $5\n```"],
+ ["```\ncosts $5\n```\n\n`x`", "```\ncosts $5\n```\n\n`x`"],
+ ["a `b` c `d` e", "a `b` c `d` e"],
+ ["costs $5 outside", "costs \\$5 outside"],
+ ["costs $5 outside\n\n`x`", "costs \\$5 outside\n\n`x`"],
+ ["```\n`inner`\n```", "```\n`inner`\n```"],
+ ["`\\(x\\)` and \\(y\\)", "`\\(x\\)` and $y$"],
+ ["```\n\\(x\\)\n```\n\nthen \\(y\\)", "```\n\\(x\\)\n```\n\nthen $y$"],
+ ];
+ for (const [input, expected] of cases) {
+ assert.equal(
+ preprocessLaTeX(input),
+ expected,
+ `changed for ${JSON.stringify(input)}`,
+ );
+ }
+});