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: stop an unterminated code fence re-repairing itself on every chunk (#9517)
Daniel Han5d76c4f21f42
diff --git a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.tsindex 96c37928e5b..e2a1a671f5c 100644--- a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts@@ -18,6 +18,31 @@ const ROLLBACK_BLOCKS = 8;// full-document path is +73% at 32,768 and +1.6% at 8,192. 8,192 characters is// still around 1,300 words of slack, well beyond a marker a later line closes.const STALLED_TAIL_CHARACTERS = 8_192;+// remend repairs the trailing incomplete construct, but it reaches that+// decision with whole-string passes: one walks the text once per `[` looking+// for an unterminated link, another escapes comparison operators line by line.+// Inside an unterminated fence every such character is literal and every pass+// declines, so those walks cost the length of the fence and change nothing. The+// fence also lexes into a single block, so `candidateCount` in update() is 0,+// nothing is ever retained, and the tail grows with the fence: appending one+// chunk then costs O(fence) and a reply costs the square of it. Repair the head+// plus a window of the fence body instead, and splice the untouched middle back+// in. The window carries the last line and the line before it, which is all the+// trailing repairs read.+const OPEN_FENCE_REPAIR_WINDOW = 4_096;+// A plain two-line probe. When remend leaves the head alone with ordinary text+// after it, no marker is pending for it to close, so it cannot append anything+// beyond the window either. Without it a marker left open before the fence gets+// its closer at the wrong offset.+//+// Its verdict is a property of the HEAD, while remend decides from the whole+// string, so on its own it is not enough: text later in the body can flip a+// global parity the probe assumed and revive a marker it cleared. The body+// marker refusal below is what closes that gap, and the two only work together.+const OPEN_FENCE_PROBE = "\nq\n";+// An index can only be resolved once the two characters after it are known, so+// the scan keeps that many back from the live edge and re-reads them.+const FENCE_SCAN_MARGIN = 2;// Balanced marker prefixes preserve the whole-document facts that remend uses// to decide how an incomplete tail should close, without changing parity.const MULTILINE_KATEX_CONTEXT = "$$\n$$\n\n";@@ -558,17 +583,180 @@ const emphasisContext = (context: RetainedContext): string => {// Taking the context as a value lets a candidate commit be priced before it is// applied, which the repeated-Markdown check in update() needs.-function repairTail(tail: string, context: RetainedContext): string {- const prefix =+function repairContextPrefix(context: RetainedContext): string {+ return (emphasisContext(context) +singleAsteriskContext(context) +- (context.multilineKatex ? MULTILINE_KATEX_CONTEXT : "");+ (context.multilineKatex ? MULTILINE_KATEX_CONTEXT : "")+ );+}++function repairTail(tail: string, context: RetainedContext): string {+ const prefix = repairContextPrefix(context);if (!prefix) {return remend(tail);}return remend(prefix + tail).slice(prefix.length);}+// Where remend believes a fence is open. It toggles on any ``` run, wherever on+// the line that run sits, and a backslash escapes the backtick after it, so this+// deliberately mirrors remend rather than CommonMark: a mid-line ``` closes the+// fence for remend and must close it here too.+type OpenFenceState = {+ index: number;+ fenceOpen: boolean;+ bodyStart: number;+ // The FIRST ` $ or ~ in the current fence body, or -1. Its mere presence+ // disqualifies the splice, so only whether one exists ever matters; the index+ // is kept because it reads better in a test than a bare boolean.+ //+ // remend does not have one notion of "inside a fence"; it has at least three,+ // and they disagree. `isWithinCodeBlock` walks the text and honours a+ // backslash before a backtick, the emphasis counters toggle on ``` without+ // honouring it, and the inline-code repair just counts /```/g. An escaped+ // \``` or a ```` run flips the last of those and not the first. The opener+ // that stands in for the elided text can only reproduce all three when the+ // elided part holds none of the characters any of them counts.+ //+ // The first such character, not the last: a marker sitting in the window+ // would otherwise mask an earlier one sitting in the elided middle, which is+ // the half that matters. First is also monotone, so it costs nothing to keep.+ firstBodyMarker: number;+};++const initialOpenFenceState = (): OpenFenceState => ({+ index: 0,+ fenceOpen: false,+ bodyStart: -1,+ firstBodyMarker: -1,+});++function advanceOpenFence(+ state: OpenFenceState,+ text: string,+ limit: number,+): OpenFenceState {+ let { index, fenceOpen, bodyStart, firstBodyMarker } = state;+ while (index < limit) {+ const character = text[index];+ if (character === "\\" && text[index + 1] === "`") {+ // Escaped for `isWithinCodeBlock`, not for the passes that only count+ // ``` runs, so the backtick still counts as a marker.+ if (fenceOpen && firstBodyMarker < 0) {+ firstBodyMarker = index + 1;+ }+ index += 2;+ continue;+ }+ if (+ character === "`" &&+ text[index + 1] === "`" &&+ text[index + 2] === "`"+ ) {+ fenceOpen = !fenceOpen;+ bodyStart = fenceOpen ? index + 3 : -1;+ firstBodyMarker = -1;+ index += 3;+ continue;+ }+ if (+ fenceOpen &&+ firstBodyMarker < 0 &&+ (character === "`" || character === "$" || character === "~")+ ) {+ firstBodyMarker = index;+ }+ index += 1;+ }+ return { index, fenceOpen, bodyStart, firstBodyMarker };+}++// Carries the scan across updates so a growing tail costs the characters that+// arrived, not the characters it holds. Any text that is not an extension of the+// last one rescans from the start, which is what a commit or a rewrite hands it.+class OpenFenceTracker {+ private text = "";+ private resolved = initialOpenFenceState();++ // Where the open fence's body starts and where its first marker sits, or null+ // when the whole-tail repair applies.+ spliceBounds(+ text: string,+ ): { bodyStart: number; firstBodyMarker: number } | null {+ if (!hasPrefix(text, this.text)) {+ this.resolved = initialOpenFenceState();+ }+ const limit = Math.max(0, text.length - FENCE_SCAN_MARGIN);+ if (limit > this.resolved.index) {+ this.resolved = advanceOpenFence(this.resolved, text, limit);+ }+ this.text = text;+ const live = advanceOpenFence(this.resolved, text, text.length);+ if (!live.fenceOpen) {+ return null;+ }+ return {+ bodyStart: live.bodyStart,+ firstBodyMarker: live.firstBodyMarker,+ };+ }+}++// A head the probe found inert contributes nothing but "a fence is open", which+// one opener reproduces. Standing in for it keeps the repair off the head as+// well as off the elided body.+const OPEN_FENCE_SYNTHETIC_HEAD = "```\n";++// The spliced repair, or null when it cannot be shown to match repairTail. All+// four refusals fall back to repairing the whole tail:+//+// a body still shorter than the window has nothing to elide;+// a final line longer than the window leaves no line boundary to cut on,+// which is the only place the splice can start without changing what the+// trailing repairs read;+// a PRECEDING line longer than the window puts the cut on the newline that+// ends it, so the window holds the final line alone. remend's setext repair+// reads exactly one line back, and the synthetic opener standing in for it+// is never blank, so a whitespace-only line elided that way turns a tail+// ending in `-`, `--`, `=` or `==` into one carrying a zero-width space+// that repairing the whole tail does not add, and that the copy button+// would then put on the clipboard;+// a ` $ or ~ ANYWHERE in the body, elided or retained, is a character one of+// remend's fence notions counts, and the opener cannot stand in for it.+//+// The last one deliberately covers the retained window and not just the elided+// middle, because the probe that licenses the opener reads the head ALONE while+// remend decides from the whole string. An escaped \``` in the window flips the+// global triple-run parity, so the whole-tail repair closes an unmatched inline+// backtick that sits before the opener and the spliced output does not; a `$$`+// there moves the math parity the other way. Neither is reachable from a+// refusal on the cut, since the probe runs before the cut is chosen. Keeping+// the body free of all three characters is what makes the probe's verdict a+// property of the whole tail rather than of the head it was handed.+function repairOpenFenceTail(+ tail: string,+ bodyStart: number,+ firstBodyMarker: number,+): string | null {+ const cut = tail.indexOf("\n", tail.length - OPEN_FENCE_REPAIR_WINDOW);+ if (+ cut < 0 ||+ cut + 1 <= bodyStart ||+ tail.indexOf("\n", cut + 1) < 0 ||+ firstBodyMarker >= 0+ ) {+ return null;+ }+ const repaired = remend(OPEN_FENCE_SYNTHETIC_HEAD + tail.slice(cut + 1));+ if (!hasPrefix(repaired, OPEN_FENCE_SYNTHETIC_HEAD)) {+ return null;+ }+ return (+ tail.slice(0, cut + 1) + repaired.slice(OPEN_FENCE_SYNTHETIC_HEAD.length)+ );+}+const advanceContext = (context: RetainedContext,parity: RepairParity,@@ -727,6 +915,9 @@ export class IncrementalMarkdownCache {private committedLength = 0;private commitPoints: CommitPoint[] = [];private context = createRetainedContext();+ private fenceTracker = new OpenFenceTracker();+ private openFenceHead: string | null = null;+ private openFenceHeadInert = false;private fullDocumentMode = false;private lastMarkdown: string | null = null;private droppedRetainedBlocks = false;@@ -757,6 +948,28 @@ export class IncrementalMarkdownCache {return { markdown, parseMarkdownIntoBlocks: this.parseMarkdownIntoBlocks };}+ // The repair of a tail sitting inside an open fence, or null to repair the+ // whole tail as before. The head is everything the repair would have to keep:+ // once the probe shows remend leaves it alone, it holds nothing that could+ // change the repair of the body, and it stays fixed until the fence closes,+ // so the probe is paid once per fence rather than once per chunk.+ private repairOpenFence(): string | null {+ const bounds = this.fenceTracker.spliceBounds(this.tail);+ if (bounds === null) {+ return null;+ }+ const head =+ repairContextPrefix(this.context) + this.tail.slice(0, bounds.bodyStart);+ if (head !== this.openFenceHead) {+ this.openFenceHead = head;+ const probed = head + OPEN_FENCE_PROBE;+ this.openFenceHeadInert = remend(probed) === probed;+ }+ return this.openFenceHeadInert+ ? repairOpenFenceTail(this.tail, bounds.bodyStart, bounds.firstBodyMarker)+ : null;+ }+private resetIncrementalState(markdown: string): void {this.droppedRetainedBlocks ||= this.committedBlocks.length > 0;this.source = markdown;@@ -885,7 +1098,8 @@ export class IncrementalMarkdownCache {this.updateTail(markdown);- const repaired = repairTail(this.tail, this.context);+ const repaired =+ this.repairOpenFence() ?? repairTail(this.tail, this.context);// Streamdown deliberately turns a repaired document containing footnotes// into one block so definitions can resolve references anywhere in thediff --git a/studio/frontend/tests/streaming-open-fence-repair.test.ts b/studio/frontend/tests/streaming-open-fence-repair.test.tsnew file mode 100644index 00000000000..1452564ee31--- /dev/null+++ b/studio/frontend/tests/streaming-open-fence-repair.test.ts@@ -0,0 +1,248 @@+// 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 remend from "remend";++import { IncrementalMarkdownCache } from "../src/components/assistant-ui/streaming-render-schedule.ts";++/**+ * A fence that has opened and not yet closed pins the cache: the whole fence+ * lexes into one block, so no prefix is ever retained and the live tail grows+ * with the fence. Repairing that tail is worse than linear -- remend walks the+ * whole string once per `[`, and code is dense in brackets -- so appending one+ * chunk used to cost the length of the fence.+ *+ * Two things have to hold for the shortcut that fixes it: the repaired text is+ * the text the whole-tail repair would have produced, and the work per chunk no+ * longer grows with the fence.+ */++const codeLine = (index: number) =>+ `def step_${index}(x, y=${index}):\n z = [item for item in range(${index})] # note\n return {'z': z, 'x': x * y}\n`;++function fenceBody(lines: number): string {+ let body = "";+ for (let index = 0; index < lines; index += 1) {+ body += codeLine(index);+ }+ return body;+}++// Comfortably past OPEN_FENCE_REPAIR_WINDOW, so the cut cannot land inside it.+const OVERLONG_BLANK_LINE = 6_000;++const tailOf = (cache: IncrementalMarkdownCache): string =>+ (cache as unknown as { tail: string }).tail;++const contextOf = (cache: IncrementalMarkdownCache): Record<string, unknown> =>+ (cache as unknown as { context: Record<string, unknown> }).context;++/**+ * Stream `text` in fixed chunks and assert every frame renders the Markdown the+ * whole-tail repair would have rendered.+ *+ * After update() the cache's own tail is the text its return value repaired,+ * whether or not that update retained a block, so `remend(tail)` is the+ * reference render. It is only the reference while the retained context carries+ * no marker prefix, which the assertion below holds these replies to.+ */+function assertRepairMatches(text: string, chunk = 192): void {+ const cache = new IncrementalMarkdownCache();+ const ends: number[] = [];+ for (let end = chunk; end < text.length; end += chunk) {+ ends.push(end);+ }+ // The last frame is fed exactly, not at whatever multiple of the chunk size+ // happens to land near it. Several of the divergences this file exists to+ // catch only show on a tail that ends on a specific character.+ ends.push(text.length);+ for (const end of ends) {+ const render = cache.update(text.slice(0, end));+ const context = contextOf(cache);+ assert.equal(+ context.bold || context.singleAsterisk || context.singleUnderscore,+ false,+ "reply must not need a marker context for remend(tail) to be the reference",+ );+ assert.equal(+ render.markdown,+ remend(tailOf(cache)),+ `frame at ${end} characters diverged from the whole-tail repair`,+ );+ }+}++test("an unterminated fence repairs to the whole-tail result", () => {+ assertRepairMatches(`Here is the code.\n\n\`\`\`python\n${fenceBody(180)}`);+});++test("a fence that closes and reopens repairs to the whole-tail result", () => {+ const text = `Intro paragraph one.\n\nIntro paragraph two.\n\n\`\`\`python\n${fenceBody(70)}\`\`\`\n\nProse between the fences.\n\n\`\`\`js\n${fenceBody(70)}\`\`\`\n\nClosing prose.\n`;+ assertRepairMatches(text);+});++test("CRLF inside an unterminated fence repairs to the whole-tail result", () => {+ const text = `Intro.\r\n\r\n\`\`\`python\r\n${fenceBody(110).replace(/\n/g, "\r\n")}`;+ assertRepairMatches(text);+});++test("a tilde fence keeps the whole-tail repair", () => {+ assertRepairMatches(`Intro.\n\n~~~python\n${fenceBody(110)}`);+});++test("a nested longer fence repairs to the whole-tail result", () => {+ assertRepairMatches(+ `Intro.\n\n\`\`\`\`markdown\n\`\`\`python\n${fenceBody(110)}`,+ );+});++test("display math inside an open fence keeps the whole-tail repair", () => {+ assertRepairMatches(`Intro.\n\n\`\`\`text\n$$\n${fenceBody(90)}`);+});++test("a marker left open before the fence keeps the whole-tail repair", () => {+ assertRepairMatches(`Intro **bold\n\n\`\`\`python\n${fenceBody(110)}`);+});++/**+ * A whitespace-only line longer than the repair window, then a tail that looks+ * like a setext underline.+ *+ * The window is cut at the first line boundary at or after its start, so a+ * preceding line this long puts the cut on the newline that ENDS it and leaves+ * the window holding the final line alone. remend's setext repair reads exactly+ * one line back, and the opener that stands in for the head is never blank, so+ * the elided blank line used to become a non-blank one and the repair appended a+ * zero-width space the whole-tail repair does not add -- a hidden character in+ * rendered code, and on the clipboard behind the copy button.+ *+ * Reported on unslothai/unsloth#9517 as review item 3836360429.+ */+for (const filler of [" ", "\t"]) {+ for (const underline of ["-", "--", "=", "=="]) {+ const label = JSON.stringify(filler);+ test(`a ${label} line longer than the window before ${underline} keeps the whole-tail repair`, () => {+ const blank = filler.repeat(OVERLONG_BLANK_LINE);+ assertRepairMatches(+ `Here is the code.\n\n\`\`\`python\nx = 1\n${blank}\n${underline}`,+ );+ });+ }+}++/**+ * A ` $ or ~ inside the part of the fence body that the window elides.+ *+ * remend has at least three notions of "inside a fence" and they disagree: the+ * escape-aware walk behind `isWithinCodeBlock`, the emphasis counters that+ * toggle on ``` without honouring a backslash, and the inline-code repair that+ * just counts /```/g. An escaped \``` or a ```` run flips some and not others,+ * so the opener that stands in for the elided text cannot reproduce them all+ * once the elided part carries one of those characters, and the repair appends+ * a stray closer the whole-tail repair does not add.+ *+ * These two are the shrunk reproducers, kept verbatim: the shape needs a stray+ * backtick before the fence, a longer opener, and an escaped fence inside it,+ * so a tidier-looking case silently stops covering the bug.+ */+test("an escaped fence in the elided body keeps the whole-tail repair", () => {+ assertRepairMatches(+ `a\`\n\n\`\`\`\`md\n\\\`\`\`\n${"ab".repeat(3000)}\n===\n`,+ );+});++test("an escaped fence before two overlong lines keeps the whole-tail repair", () => {+ assertRepairMatches(+ `- a\n- b\n\n\`\`\`\`md\n\\\`\`\`\n* * *\n${" ".repeat(5000)}\n${"x".repeat(5000)}\n\`tick\n`,+ );+});++// Built by concatenation, not escapes: a backslash followed by a triple-backtick+// run is exactly the sequence this bug needs, and writing it inside a template+// literal produced three ESCAPED backticks instead, which is a different string+// and quietly stopped covering the case.+const BACKTICK = String.fromCharCode(96);+const ESCAPED_FENCE = `\\${BACKTICK}${BACKTICK}${BACKTICK}`;+const DANGLING_INLINE_BACKTICK = `${BACKTICK}\n\n`;+const FENCE_OPENER = `${BACKTICK}${BACKTICK}${BACKTICK}\n`;++/**+ * An unmatched inline backtick BEFORE the opener, and a marker in the part of+ * the window the splice RETAINS rather than elides.+ *+ * The probe that licenses the opener standing in for the head reads the head+ * alone, and it runs before the cut is chosen. remend decides from the whole+ * string: an escaped \``` later in the body flips the global triple-run parity,+ * so repairing the whole tail closes the head's dangling backtick while the+ * spliced output, whose synthetic head never had one, does not. A `$$` there+ * moves the math parity the other way and the splice appends where the whole+ * tail does not. Neither is reachable from a refusal on the cut, which is why+ * the body-marker refusal covers the retained window and not just the middle.+ *+ * Reported on unslothai/unsloth#9517 as review item 3836846709.+ */+for (const [name, windowText] of [+ ["an escaped fence", `${ESCAPED_FENCE} more`],+ ["display math", "$$odd"],+ // A `~~` here does NOT reproduce and is deliberately absent: a case that+ // passes on the broken code documents nothing and reads as coverage.+] as const) {+ test(`${name} in the retained window keeps the whole-tail repair`, () => {+ assertRepairMatches(+ `${DANGLING_INLINE_BACKTICK}${FENCE_OPENER}${"x".repeat(OVERLONG_BLANK_LINE)}\n${windowText}\n`,+ );+ });+}++test("a fence that never closes stays live and is never committed away", () => {+ const text = `Intro.\n\n\`\`\`python\n${fenceBody(300)}`;+ const cache = new IncrementalMarkdownCache();+ let render = cache.update(text.slice(0, 64));+ for (let end = 128; end < text.length; end += 128) {+ render = cache.update(text.slice(0, end));+ }+ render = cache.update(text);+ const blocks = render.parseMarkdownIntoBlocks(render.markdown);+ assert.equal(blocks.join(""), remend(text));+});++/**+ * A complexity test, not a timing test. remend decides where a construct ends+ * with `substring` probes whose receiver is the whole string, so charging every+ * probe its receiver's length prices a repair at the length of what it was+ * given. Doubling the fence must roughly double that bill, which is what a+ * per-chunk cost independent of the fence looks like. Before this shortcut the+ * same doubling multiplied it by about 16.+ */+function repairCharacters(text: string, chunk = 256): number {+ const realSubstring = String.prototype.substring;+ let counted = 0;+ String.prototype.substring = function counting(+ this: string,+ start: number,+ end?: number,+ ): string {+ counted += this.length;+ return realSubstring.call(this, start, end);+ } as unknown as typeof realSubstring;+ try {+ const cache = new IncrementalMarkdownCache();+ for (let end = chunk; end <= text.length; end += chunk) {+ cache.update(text.slice(0, end));+ }+ } finally {+ String.prototype.substring = realSubstring;+ }+ return counted;+}++test("appending to an open fence does not cost the length of the fence", () => {+ const short = repairCharacters(`Intro.\n\n\`\`\`python\n${fenceBody(180)}`);+ const long = repairCharacters(`Intro.\n\n\`\`\`python\n${fenceBody(360)}`);+ assert.ok(+ long < short * 3,+ `doubling the fence multiplied the repair by ${(long / short).toFixed(1)}`,+ );+});